path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/us/jwf/aoc/graph/Graph.kt
|
jasonwyatt
| 318,073,137
| false
| null |
package us.jwf.aoc.graph
class Graph<NodeData> {
private val _nodes = mutableSetOf<Node<NodeData>>()
private val _edges = mutableSetOf<Edge<NodeData>>()
private val edgesByOrigin = mutableMapOf<Node<NodeData>, List<Edge<NodeData>>>()
val nodes: Set<Node<NodeData>>
get() = _nodes
val edges: Set<Edge<NodeData>>
get() = _edges
fun addNode(node: NodeData) {
_nodes.add(Node(node))
}
fun edgesForNode(node: Node<NodeData>): List<Edge<NodeData>> = edgesByOrigin[node] ?: emptyList()
// Note: Assumes two edges connecting the same nodes in the same direction are different.
fun addEdge(from: NodeData, to: NodeData, weight: Double = 0.0) {
val fromNode = Node(from).also { _nodes.add(it) }
val toNode = Node(to).also { _nodes.add(it) }
val edge = Edge(fromNode, toNode, weight)
_edges.add(edge)
edgesByOrigin.compute(fromNode) { _, value ->
if (value == null) listOf(edge)
else value + listOf(edge)
}
}
/**
* Returns a set of connected subgraphs.
*
* When this graph is fully-connected, returns a single-element.
*/
fun toSubgraphs(): Set<Graph<NodeData>> {
val result = mutableSetOf<Graph<NodeData>>()
val nodesToTraverse = nodes.toMutableSet()
while (nodesToTraverse.isNotEmpty()) {
val subgraph = Graph<NodeData>()
fun traverse(node: Node<NodeData>) {
edgesByOrigin[node]?.asSequence()
?.forEach { (from, to, weight) ->
if (!nodesToTraverse.remove(to)) return@forEach
subgraph.addEdge(from.data, to.data, weight)
traverse(to)
}
}
val root = nodesToTraverse.first().also { nodesToTraverse.remove(it) }
subgraph.addNode(root.data)
traverse(root)
result.add(subgraph)
}
return result
}
/**
* Applies the visitor pattern to traverse the graph from a given start point.
*
* The [visitor] is responsible for saying whether or not traversal should continue to the
* provided node's children.
*/
fun traverseFrom(node: NodeData, visitor: (NodeData, Double) -> Boolean) {
traverseFrom(Node(node), 0.0) { visited, weight -> visitor(visited.data, weight) }
}
/**
* Finds the minimum spanning tree of the graph by Prim's algorithm.
*/
fun findMSTKruskal(): Graph<NodeData> {
val result = Graph<NodeData>()
val firstNode = nodes.first()
val visited = mutableSetOf<Node<NodeData>>()
val weights = nodes.associateWithTo(mutableMapOf()) { Double.POSITIVE_INFINITY }
weights[firstNode] = 0.0
while (visited.size < nodes.size) {
val current = weights.entries
.asSequence()
.filter { it.key !in visited }
.minByOrNull { it.value }!!.key
}
return result
}
private fun traverseFrom(
node: Node<NodeData>,
weight: Double,
visitor: (Node<NodeData>, Double) -> Boolean
) {
if (!visitor(node, weight)) return
edgesByOrigin[node]?.forEach { traverseFrom(it.to, it.weight, visitor) }
}
override fun toString() = "Graph(nodes=${_nodes.size}, edges=${edgesByOrigin.values})"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Graph<*>) return false
if (_nodes != other._nodes) return false
if (_edges != other._edges) return false
return true
}
override fun hashCode(): Int {
var result = _nodes.hashCode()
result = 31 * result + _edges.hashCode()
return result
}
}
data class Node<T>(val data: T) {
override fun toString() = data.toString()
}
data class Edge<T>(val from: Node<T>, val to: Node<T>, val weight: Double) {
override fun toString() = "$from -${if (weight != 0.0) "($weight)-" else ""}> $to"
}
| 0
|
Kotlin
|
0
| 0
|
60282b121bec6b845a74507960934a03a9153178
| 3,724
|
AdventOfCode-Kotlin
|
Apache License 2.0
|
src/main/kotlin/therealfarfetchd/retrocomputers/common/item/ReadonlyDisk.kt
|
Darkstrumn
| 131,374,601
| true
|
{"Kotlin": 369119, "Assembly": 52301, "Shell": 2306, "GLSL": 1113}
|
package therealfarfetchd.retrocomputers.common.item
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.util.NonNullList
import therealfarfetchd.quacklib.common.api.util.IView
import therealfarfetchd.retrocomputers.common.api.IFloppy
import therealfarfetchd.retrocomputers.common.api.RCCreativeTab
import therealfarfetchd.retrocomputers.common.api.item.IFloppyProvider
import java.io.InputStream
import java.util.*
/**
* Created by marco on 24.06.17.
*/
class ReadonlyDisk(vararg val streams: () -> InputStream?) : Item(), IFloppyProvider {
init {
maxStackSize = 1
hasSubtypes = true
maxDamage = 0
creativeTab = RCCreativeTab
}
override fun showDurabilityBar(stack: ItemStack?): Boolean = false
override fun getSubItems(tab: CreativeTabs?, items: NonNullList<ItemStack>?) {
if (tab == creativeTab && items != null) streams.indices.forEach {
items += ItemStack(this, 1, it)
}
}
override fun getUnlocalizedName(stack: ItemStack?): String = "$unlocalizedName.${stack?.metadata}"
override fun invoke(stack: ItemStack): IFloppy = Floppy(streams[stack.metadata])
private class Floppy(val stream: () -> InputStream?) : IFloppy {
override val uniqueId: UUID = UUID(0, 0)
override var label: String
get() = "System Disk"
set(value) {}
override fun trim() {}
override val sector: IView<Short, List<Byte>?> = object : IView<Short, List<Byte>?> {
override fun get(k: Short): List<Byte>? {
val stream = stream()
return stream?.let {
val skipped = it.skip(k * 128L)
val ret = if (skipped != k * 128L) null else {
val data = ByteArray(128)
if (stream.read(data) != 128) null else data.toList()
}
it.close()
ret
}
}
override fun set(k: Short, v: List<Byte>?) {}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9c5f4d614eb7af91dec06400a658b0c6eb9fb656
| 1,944
|
HCTM
|
MIT License
|
app/src/test/java/nl/jovmit/friends/domain/post/InMemoryPostCatalogTest.kt
|
mitrejcevski
| 336,415,632
| false
|
{"Kotlin": 122711}
|
package i.herman.domain.post
class InMemoryPostCatalogTest : PostCatalogContract() {
override fun postCatalogWith(
vararg availablePosts: Post
): PostCatalog {
return InMemoryPostCatalog(
availablePosts = availablePosts.toMutableList()
)
}
}
| 2
|
Kotlin
|
7
| 32
|
7fe7a87f6948e9e7590dfadcb8d1cd35c096a753
| 291
|
friends
|
Apache License 2.0
|
testing/src/main/java/com/adjectivemonk2/pixels/testing/DispatcherParameterResolver.kt
|
Sripadmanabans
| 300,346,280
| false
| null |
package com.adjectivemonk2.pixels.testing
import kotlinx.coroutines.cancel
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.ParameterContext
import org.junit.jupiter.api.extension.ParameterResolver
public class DispatcherParameterResolver :
ParameterResolver,
BeforeEachCallback,
AfterEachCallback {
private var dispatcher: TestDispatcher? = null
override fun supportsParameter(
parameterContext: ParameterContext,
extensionContext: ExtensionContext?
): Boolean {
return parameterContext.parameter.type == TestDispatcher::class.java
}
override fun resolveParameter(
parameterContext: ParameterContext?,
extensionContext: ExtensionContext?
): Any {
return dispatcher!!
}
override fun beforeEach(context: ExtensionContext?) {
dispatcher = StandardTestDispatcher()
}
override fun afterEach(context: ExtensionContext?) {
dispatcher!!.cancel()
dispatcher = null
}
}
| 0
|
Kotlin
|
0
| 1
|
b3b1b56a8c422fdabd3c23618c003a6a1bfad01b
| 1,193
|
Pixels
|
Apache License 2.0
|
app/src/main/java/com/maku/pombe/latestfeature/LatestFragmentViewModel.kt
|
ma-za-kpe
| 373,888,998
| false
| null |
package com.maku.pombe.latestfeature
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.maku.logging.Logger
import com.maku.pombe.common.data.cache.model.cachedLatest.CachedLatest
import com.maku.pombe.common.domain.model.NetworkException
import com.maku.pombe.common.domain.model.NetworkUnavailableException
import com.maku.pombe.common.domain.model.NoDrinksException
import com.maku.pombe.common.domain.model.latest.LatestDrink
import com.maku.pombe.common.domain.model.shared.Details
import com.maku.pombe.common.domain.model.shared.Ingredients
import com.maku.pombe.common.presentation.Event
import com.maku.pombe.common.presentation.model.latest.UILatestDrinkDetails
import com.maku.pombe.common.presentation.model.mappers.UiLatestDrinkDetailsMapper
import com.maku.pombe.common.presentation.model.mappers.UiLatestDrinkMapper
import com.maku.pombe.common.utils.createExceptionHandler
import com.maku.pombe.latestfeature.domain.usecases.GetLatestDrinkById
import com.maku.pombe.latestfeature.domain.usecases.GetLatestDrinks
import com.maku.pombe.latestfeature.domain.usecases.RequestLatestDrinksList
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LatestFragmentViewModel @Inject constructor(
private val getLatestDrinkById: GetLatestDrinkById,
private val getLatestDrinks: GetLatestDrinks,
private val requestLatestDrinksList: RequestLatestDrinksList,
private val uiLatestDrinkMapper: UiLatestDrinkMapper,
private val uiLatestDrinkDetailsMapper: UiLatestDrinkDetailsMapper,
private val compositeDisposable: CompositeDisposable
): ViewModel() {
val state: LiveData<LatestDrinkViewState> get() = _state
private val _state = MutableLiveData<LatestDrinkViewState>()
init {
_state.value = LatestDrinkViewState()
subscribeToPombeDbUpdates()
}
private fun subscribeToPombeDbUpdates() {
getLatestDrinks()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ onNewPombeList(it) },
{ onFailure(it) }
)
.addTo(compositeDisposable)
}
private fun onNewPombeList(drink: List<LatestDrink>) {
_state.value = state.value!!.copy( loading = true)
val latestDrinks = drink.map { uiLatestDrinkMapper.mapToView(it) }
// TODO: add updates at value while inserting into room db
// This ensures that new items are added below the already existing ones, thus avoiding
// repositioning of items that are already visible, as it can provide for a confusing UX. A
// nice alternative to this would be to add an "updatedAt" field to the Room entities, so
// that we could actually order them by something that we completely control.
val currentList = state.value!!.drinks
val newLatest = latestDrinks.subtract(currentList)
val updatedList = currentList + newLatest
_state.value = state.value!!.copy( loading = false, drinks = updatedList)
}
fun onEvent(event: LatestDrinkEvent, id: String = "") { // id is optional
when(event) {
is LatestDrinkEvent.RequestLatestDrinksList ->
loadLatestDrinks()
is LatestDrinkEvent.RequestLatestDrinkById ->
loadLatestDrinkById(id)
}
}
private fun loadLatestDrinkById(id: String) {
getLatestDrinkById(id)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ onDrinkById(it) },
{ onFailure(it) }
)
.addTo(compositeDisposable)
}
private fun onDrinkById(drink: CachedLatest?) {
_state.value = state.value!!.copy( loading = true)
val drinkById = uiLatestDrinkDetailsMapper.mapToView(drink!!)
_state.value = state.value!!.copy( loading = false, drinkById = drinkById)
}
private fun loadLatestDrinks() {
if (state.value!!.drinks.isEmpty()) {
loadDrinks()
}
}
private fun loadDrinks() {
_state.value = state.value!!.copy( loading = true)
val errorMessage = "Failed to fetch pombes"
val exceptionHandler = viewModelScope.createExceptionHandler(errorMessage){
onFailure(it)
}
viewModelScope.launch(exceptionHandler) {
delay(3000)
requestLatestDrinksList()
// request drinks!
_state.value = state.value!!.copy( loading = false)
}
}
private fun onFailure(failure: Throwable) {
when (failure) {
is NetworkException,
is NetworkUnavailableException -> {
_state.value = state.value!!.copy(
loading = false,
failure = Event(failure)
)
}
is NoDrinksException -> {
_state.value = state.value!!.copy(
failure = Event(failure)
)
}
}
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| 18
|
Kotlin
|
2
| 5
|
e62294e8e5a25774f5955aa3565f62c4ff589cd5
| 5,478
|
Pombe
|
The Unlicense
|
src/jvmTest/kotlin/examples/game/TiledTileSetTest.kt
|
AndreasHefti
| 387,557,032
| false
| null |
package examples.game
import com.inari.firefly.DesktopApp
import com.inari.firefly.core.Engine
import com.inari.firefly.core.Entity
import com.inari.firefly.core.api.BlendMode
import com.inari.firefly.core.api.ShapeType
import com.inari.firefly.game.tile.tiled_binding.TiledTileSet
import com.inari.firefly.graphics.shape.EShape
import com.inari.firefly.graphics.sprite.ESprite
import com.inari.firefly.graphics.text.EText
import com.inari.firefly.graphics.text.Font
import com.inari.firefly.graphics.view.ETransform
import com.inari.firefly.graphics.view.View
import com.inari.firefly.physics.animation.EAnimation
import com.inari.firefly.physics.animation.IntFrameAnimation
import com.inari.firefly.physics.animation.IntFrameAnimationControl
fun main() {
DesktopApp("TiledTileSetTest", 800, 600, debug = true) {
val tiledTileSetAsset = TiledTileSet {
name = "TiledTileSetTestAsset"
resourceName = "tiled_tileset_example/tiled_tileset.json"
}
View {
autoActivation = true
name = "testView"
bounds(0, 0, 800, 600)
zoom = 1f
}
TiledTileSet.load(tiledTileSetAsset)
TiledTileSet.activate(tiledTileSetAsset)
val offset = 50
var x = 0
var y = 0
TiledTileSet[tiledTileSetAsset].tiles.forEach {
Entity {
autoActivation = true
withComponent(ETransform) {
viewRef("testView")
position( offset + x * 64,offset + y * 64)
}
withComponent(ESprite) {
spriteIndex = it.spriteTemplate.spriteIndex
blendMode = it.blendMode ?: BlendMode.NONE
tintColor(it.tintColor ?: tintColor)
}
it.contactMask?.apply {
val list = mutableListOf<Float>()
for (y in 0 until 16) {
for (x in 0 until 16) {
if (this.getBit(x, y)) {
list.add(16f + x)
list.add(16f + y)
}
}
}
this@Entity.withComponent(EShape) {
type = ShapeType.POINT
color1(1f, 0f, 0f , 1f)
vertices = list.toFloatArray()
}
}
it.animationData?.apply {
this@Entity.withComponent(EAnimation) {
IntFrameAnimationControl
withAnimation(IntFrameAnimation) {
animatedProperty = ESprite.PropertyAccessor.SPRITE_INDEX
looping = true
timeline = this@apply.frames.toArray()
animationController(IntFrameAnimationControl)
}
}
}
}
x++
if (x >= 10) {
x = 0
y++
}
}
Entity {
autoActivation = true
withComponent(ETransform) {
viewRef("testView")
position( 50,300)
}
withComponent(EText) {
fontRef(Font[Engine.SYSTEM_FONT])
text.append("Blue: Tile-Sprite\nRed: Collision-Map\nLeft-Bottom-Corner: Tile-Animation")
}
}
}
}
| 5
|
Kotlin
|
0
| 11
|
f56999f0dc6aea344611be34f097bd96cfd94d60
| 3,547
|
flyko-lib
|
Apache License 2.0
|
src/main/kotlin/dsl/wiremock/request/body/BasePathBodyPattern.kt
|
valentin-goncharov
| 447,352,842
| false
|
{"Kotlin": 208558}
|
/*-
* ========================LICENSE_START=================================
* Wiremock Kotlin DSL
* %%
* Copyright (C) 2022 <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.
* =========================LICENSE_END==================================
*/
package dsl.wiremock.request.body
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.matching.StringValuePattern
import dsl.wiremock.WireMockDSL
abstract class BasePathBodyPattern : StringValueRequestBodyPattern, PathValuePattern {
protected val matchingPathPattern: (String, StringValuePattern) -> StringValuePattern
constructor(
scope: RequestBodyScope,
matchingPathPattern: (String, StringValuePattern) -> StringValuePattern
): super(scope) {
this.matchingPathPattern = matchingPathPattern
}
constructor(
pattern: RequestBodyPattern,
matchingPathPattern: (String, StringValuePattern) -> StringValuePattern
): super(pattern) {
this.matchingPathPattern = matchingPathPattern
}
@WireMockDSL
override infix fun equalTo(str: String): JunctionableBodyPattern {
modifyPattern(matchingPathPattern(this.currentValue, WireMock.equalTo(str)))
return this
}
@WireMockDSL
override infix fun contains(str: String): JunctionableBodyPattern {
modifyPattern(matchingPathPattern(this.currentValue, WireMock.containing(str)))
return this
}
@WireMockDSL
override infix fun matches(str: String): JunctionableBodyPattern {
modifyPattern(matchingPathPattern(this.currentValue, WireMock.matching(str)))
return this
}
@WireMockDSL
override infix fun doesNotMatch(str: String): JunctionableBodyPattern {
modifyPattern(matchingPathPattern(this.currentValue, WireMock.notMatching(str)))
return this
}
}
| 2
|
Kotlin
|
0
| 0
|
ad0aac9ce014a6f53c51c0e1aedb846414358b8d
| 2,583
|
wiremock-kotlin-dsl
|
Apache License 2.0
|
coil-core/src/commonMain/kotlin/coil3/request/RequestDelegate.kt
|
coil-kt
| 201,684,760
| false
|
{"Kotlin": 955603, "Shell": 2360, "JavaScript": 209}
|
package coil3.request
import coil3.annotation.MainThread
import kotlinx.coroutines.CancellationException
internal interface RequestDelegate {
/** Throw a [CancellationException] if this request should be cancelled before starting. */
@MainThread
fun assertActive() {}
/** Register all lifecycle observers. */
@MainThread
fun start() {}
/** Called when this request's job is cancelled or completes successfully/unsuccessfully. */
@MainThread
fun complete() {}
/** Cancel this request's job and clear all lifecycle observers. */
@MainThread
fun dispose() {}
}
| 39
|
Kotlin
|
626
| 9,954
|
9b3f851b2763b4c72a3863f8273b8346487b363b
| 612
|
coil
|
Apache License 2.0
|
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectSettingsTracker.kt
|
hieuprogrammer
| 284,920,751
| false
| null |
// Copyright 2000-2019 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 com.intellij.openapi.externalSystem.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.EXTERNAL
import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesProviderImpl
import com.intellij.openapi.externalSystem.autoimport.changes.FilesChangesListener
import com.intellij.openapi.externalSystem.util.calculateCrc
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LocalTimeCounter.currentTime
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.util.concurrent.Executor
import java.util.concurrent.atomic.AtomicReference
@ApiStatus.Internal
class ProjectSettingsTracker(
private val project: Project,
private val projectTracker: AutoImportProjectTracker,
private val backgroundExecutor: Executor,
private val projectAware: ExternalSystemProjectAware,
private val parentDisposable: Disposable
) {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
private val status = ProjectStatus(debugName = "Settings ${projectAware.projectId.readableName}")
private val settingsFilesCRC = AtomicReference(emptyMap<String, Long>())
private val applyChangesOperation = AnonymousParallelOperationTrace(debugName = "Apply changes operation")
private fun collectSettingsFiles() = projectAware.settingsFiles + settingsFilesCRC.get().keys
private fun calculateSettingsFilesCRC(): Map<String, Long> {
val localFileSystem = LocalFileSystem.getInstance()
return projectAware.settingsFiles
.mapNotNull { localFileSystem.findFileByPath(it) }
.map { it.path to calculateCrc(it) }
.toMap()
}
private fun calculateCrc(file: VirtualFile): Long {
val fileDocumentManager = FileDocumentManager.getInstance()
val document = fileDocumentManager.getCachedDocument(file)
if (document != null) return document.calculateCrc(project, file)
return file.calculateCrc(project)
}
fun isUpToDate() = status.isUpToDate()
fun getModificationType() = status.getModificationType()
private fun hasChanges(newSettingsFilesCRC: Map<String, Long>): Boolean {
val oldSettingsFilesCRC = settingsFilesCRC.get()
if (newSettingsFilesCRC.size != oldSettingsFilesCRC.size) return true
return newSettingsFilesCRC.any { it.value != oldSettingsFilesCRC[it.key] }
}
/**
* Usually all crc hashes must be previously calculated
* => this apply will be fast
* => collisions is a rare thing
*/
private fun applyChanges() {
applyChangesOperation.startTask()
submitSettingsFilesRefresh {
submitSettingsFilesCRCCalculation { newSettingsFilesCRC ->
settingsFilesCRC.set(newSettingsFilesCRC)
status.markSynchronized(currentTime())
applyChangesOperation.finishTask()
}
}
}
/**
* Applies changes for newly registered files
* Needed to cases: tracked files are registered during project reload
*/
private fun applyUnknownChanges() {
applyChangesOperation.startTask()
submitSettingsFilesRefresh {
submitSettingsFilesCRCCalculation { newSettingsFilesCRC ->
settingsFilesCRC.updateAndGet { newSettingsFilesCRC + it }
if (!hasChanges(newSettingsFilesCRC)) {
status.markSynchronized(currentTime())
}
applyChangesOperation.finishTask()
}
}
}
fun refreshChanges() {
submitSettingsFilesRefresh {
submitSettingsFilesCRCCalculation { newSettingsFilesCRC ->
when (hasChanges(newSettingsFilesCRC)) {
true -> status.markDirty(currentTime(), EXTERNAL)
else -> status.markReverted(currentTime())
}
projectTracker.scheduleChangeProcessing()
}
}
}
fun getState() = State(status.isDirty(), settingsFilesCRC.get().toMap())
fun loadState(state: State) {
if (state.isDirty) status.markDirty(currentTime(), EXTERNAL)
settingsFilesCRC.set(state.settingsFiles.toMap())
}
private fun isAsyncAllowed() = projectTracker.isAsyncChangesProcessing
private fun submitSettingsFilesRefresh(callback: () -> Unit = {}) {
invokeLater {
val fileDocumentManager = FileDocumentManager.getInstance()
fileDocumentManager.saveAllDocuments()
submitSettingsFilesCollection { settingsPaths ->
val localFileSystem = LocalFileSystem.getInstance()
val settingsFiles = settingsPaths.map { File(it) }
localFileSystem.refreshIoFiles(settingsFiles, isAsyncAllowed(), false, callback)
}
}
}
private fun submitSettingsFilesCollection(action: (Set<String>) -> Unit) {
if (!isAsyncAllowed()) {
action(collectSettingsFiles())
return
}
ReadAction.nonBlocking<Set<String>> { collectSettingsFiles() }
.expireWith(parentDisposable)
.finishOnUiThread(ModalityState.defaultModalityState(), action)
.submit(backgroundExecutor)
}
private fun submitSettingsFilesCRCCalculation(action: (Map<String, Long>) -> Unit) {
if (!isAsyncAllowed()) {
action(calculateSettingsFilesCRC())
return
}
ReadAction.nonBlocking<Map<String, Long>> { calculateSettingsFilesCRC() }
.expireWith(parentDisposable)
.finishOnUiThread(ModalityState.defaultModalityState(), action)
.submit(backgroundExecutor)
}
private fun invokeLater(action: () -> Unit) {
val application = ApplicationManager.getApplication()
if (!isAsyncAllowed()) {
application.invokeAndWait(action)
}
else {
application.invokeLater(action, { Disposer.isDisposed(parentDisposable) })
}
}
fun beforeApplyChanges(listener: () -> Unit) = applyChangesOperation.beforeOperation(listener)
fun afterApplyChanges(listener: () -> Unit) = applyChangesOperation.afterOperation(listener)
init {
val projectRefreshListener = object : ExternalSystemProjectRefreshListener {
override fun beforeProjectRefresh() {
applyChangesOperation.startTask()
applyChanges()
}
override fun afterProjectRefresh(status: ExternalSystemRefreshStatus) {
applyUnknownChanges()
applyChangesOperation.finishTask()
}
}
projectAware.subscribe(projectRefreshListener, parentDisposable)
}
init {
AsyncFilesChangesProviderImpl(backgroundExecutor, ::collectSettingsFiles)
.subscribe(ProjectSettingsListener(), parentDisposable)
}
data class State(var isDirty: Boolean = true, var settingsFiles: Map<String, Long> = emptyMap())
private inner class ProjectSettingsListener : FilesChangesListener {
private var hasRelevantChanges = false
override fun onFileChange(path: String, modificationStamp: Long, modificationType: ModificationType) {
hasRelevantChanges = true
logModificationAsDebug(path, modificationStamp, modificationType)
if (applyChangesOperation.isOperationCompleted()) {
status.markModified(currentTime(), modificationType)
}
else {
status.markDirty(currentTime(), modificationType)
}
}
override fun init() {
hasRelevantChanges = false
}
override fun apply() {
if (hasRelevantChanges) {
submitSettingsFilesCRCCalculation { newSettingsFilesCRC ->
if (!hasChanges(newSettingsFilesCRC)) {
status.markReverted(currentTime())
}
projectTracker.scheduleChangeProcessing()
}
}
}
private fun logModificationAsDebug(path: String, modificationStamp: Long, type: ModificationType) {
if (LOG.isDebugEnabled) {
val projectPath = projectAware.projectId.externalProjectPath
val relativePath = FileUtil.getRelativePath(projectPath, path, '/') ?: path
LOG.debug("File $relativePath is modified at ${modificationStamp} as $type")
}
}
}
}
| 1
| null |
2
| 2
|
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 8,573
|
intellij-community
|
Apache License 2.0
|
shapes/src/main/java/shapes/feature/presentation/stats/StatisticsViewState.kt
|
rahulsainani
| 198,700,715
| false
| null |
package shapes.feature.presentation.stats
sealed class StatisticsViewState {
object Empty : StatisticsViewState()
data class Content(val items: List<StatisticsItemEntity>) : StatisticsViewState()
}
| 0
|
Kotlin
|
0
| 8
|
962f33454933317205b93e9f2552d704766cffc3
| 207
|
shapes
|
Apache License 2.0
|
wire-library/wire-moshi-adapter/src/test/java/com/squareup/wire/MoshiPersonTest.kt
|
square
| 12,274,147
| false
| null |
package com.squareup.wire
import com.squareup.moshi.Moshi
import org.assertj.core.api.Assertions.assertThat
import org.junit.Ignore
import org.junit.Test
import com.squareup.wire.protos.person.java.Person as JavaPerson
import com.squareup.wire.protos.person.kotlin.Person as KotlinPerson
class MoshiPersonTest {
/**
* When we encounter an explicit null in the JSON, we discard it. As a consequence we won't
* overwrite a non-null value with null which could happen in malformed JSON that repeats a value.
*/
@Test
fun javaClobberNonNullWithNull() {
val personWithName = moshi.adapter(JavaPerson::class.java)
.fromJson("""{"id":1,"name":"Jo","email":"<EMAIL>"}""")
assertThat(personWithName!!.email).isEqualTo("<EMAIL>")
val personWithNameClobberedWithNull = moshi.adapter(JavaPerson::class.java)
.fromJson("""{"id":1,"name":"Jo","email":"<EMAIL>","email":null}""")
assertThat(personWithNameClobberedWithNull!!.email).isEqualTo("<EMAIL>")
}
@Test @Ignore("The adapter doesn't support idiomatic Kotlin yet.")
fun kotlinClobberNonNullWithNull() {
val personWithName = moshi.adapter(KotlinPerson::class.java)
.fromJson("""{"id":1,"name":"Jo","email":"<EMAIL>"}""")
assertThat(personWithName!!.email).isEqualTo("<EMAIL>")
val personWithNameClobberedWithNull = moshi.adapter(KotlinPerson::class.java)
.fromJson("""{"id":1,"name":"Jo","email":"<EMAIL>","email":null}""")
assertThat(personWithNameClobberedWithNull!!.email).isEqualTo("<EMAIL>")
}
// Uncomment when #997 is fixed.
// @Test
// fun javaInteropKotlinClobberNonNullWithNull() {
// val personWithName = moshi.adapter(JavaInteropKotlinPerson::class.java)
// .fromJson("{\"id\":1,\"name\":\"Jo\",\"email\":\"<EMAIL>\"}")
// assertThat(personWithName!!.email).isEqualTo("<EMAIL>")
//
// val personWithNameClobberedWithNull = moshi.adapter(JavaInteropKotlinPerson::class.java)
// .fromJson("{\"id\":1,\"name\":\"Jo\",\"email\":\"<EMAIL>\",\"email\":null}")
// assertThat(personWithNameClobberedWithNull!!.email).isEqualTo("<EMAIL>")
// }
companion object {
private val moshi = Moshi.Builder()
.add(WireJsonAdapterFactory())
.build()
}
}
| 138
| null |
506
| 3,650
|
de1651027879d285bdc41f0647a7fa7ceb604e58
| 2,232
|
wire
|
Apache License 2.0
|
src/main/kotlin/com/expediagroup/openworld/sdk/core/plugin/logging/OpenWorldLoggerFactory.kt
|
ExpediaGroup
| 527,522,338
| false
| null |
/*
* Copyright (C) 2022 Expedia, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.sdk.core.plugin.logging
import org.slf4j.LoggerFactory
internal object ExpediaGroupLoggerFactory {
fun getLogger(clazz: Class<*>) = ExpediaGroupLogger(LoggerFactory.getLogger(clazz))
}
| 4
| null |
5
| 5
|
7a0e003376a38bc9676669b6e769a0a16070a833
| 813
|
openworld-sdk-java-core
|
Apache License 2.0
|
DittoPresenceDegradationReporter/src/main/java/live/ditto/presencedegradationreporter/theme/Color.kt
|
getditto
| 596,719,336
| false
|
{"Kotlin": 140033}
|
package live.ditto.presencedegradationreporter.theme
import androidx.compose.ui.graphics.Color
val screenBackground = Color(0xFFF1EBEB)
val dashboardSuccess = Color(0xFFB1F3B4)
val dashboardError = Color(0xFFF8ACAC)
val dashboardCardConnected = Color(0xFF549B58)
val dashboardCardNotConnected = Color(0xFFA55757)
| 27
|
Kotlin
|
1
| 6
|
fc87cdb7194937220e096cb1b7d41d7b78500dbb
| 315
|
DittoAndroidTools
|
MIT License
|
ktor-server/src/main/kotlin/org/diploma/data/responses/BasicResponse.kt
|
k-arabadzhiev
| 515,181,907
| false
|
{"Kotlin": 309983}
|
package org.diploma.data.responses
import kotlinx.serialization.Serializable
@Serializable
data class BasicResponse(
val status: String? = null,
val message: String,
)
| 0
|
Kotlin
|
0
| 0
|
e69e22d6aabffb3b4afe54cf9ef6a92007d5beb5
| 178
|
Roommates
|
MIT License
|
arranger-runtime/src/test/java/dev/mkeeda/arranger/runtime/SimpleMarkupTextParserTest.kt
|
mkeeda
| 565,651,877
| false
| null |
package dev.mkeeda.arranger.runtime
import com.google.common.truth.Truth.assertThat
import dev.mkeeda.arranger.runtime.node.HeadingLevel
import dev.mkeeda.arranger.runtime.node.HeadingNode
import dev.mkeeda.arranger.runtime.node.LinkNode
import dev.mkeeda.arranger.runtime.node.MarkupTextNode
import dev.mkeeda.arranger.runtime.node.ParagraphNode
import dev.mkeeda.arranger.runtime.node.RootNode
import dev.mkeeda.arranger.runtime.node.TextNode
import org.junit.Test
class SimpleMarkupTextParserTest {
private fun doTest(markupText: String, expectedNode: MarkupTextNode) {
val parser = SimpleMarkupTextParser()
val actualNode = parser.parse(markupText)
assertThat(actualNode).isEqualTo(expectedNode)
}
@Test
fun oneText() {
doTest(
markupText = "This is a pen.",
expectedNode = RootNode(
listOf(
ParagraphNode(
listOf(
TextNode("This is a pen."),
)
),
)
)
)
}
@Test
fun twoParagraph() {
doTest(
markupText = """
This is a pen.
That is a cup.
""".trimIndent(),
expectedNode = RootNode(
listOf(
ParagraphNode(
listOf(
TextNode("This is a pen."),
)
),
ParagraphNode(
listOf(
TextNode("That is a cup."),
)
),
)
)
)
}
@Test
fun link() {
doTest(
markupText = """
before text [link](https://example.com) after text
""".trimIndent(),
expectedNode = RootNode(
listOf(
ParagraphNode(
listOf(
TextNode("before text "),
LinkNode(url = "https://example.com", text = "link"),
TextNode(" after text"),
)
),
)
)
)
}
@Test
fun heading() {
doTest(
markupText = """
# h1
## h2
### h3
""".trimIndent(),
expectedNode = RootNode(
listOf(
HeadingNode(title = "h1", level = HeadingLevel.H1),
HeadingNode(title = "h2", level = HeadingLevel.H2),
HeadingNode(title = "h3", level = HeadingLevel.H3),
)
)
)
}
@Test
fun mixSyntax() {
doTest(
markupText = """
# My profile
Hello world. I am a arranger. My profile is this [link](https://example.com).
""".trimIndent(),
expectedNode = RootNode(
listOf(
HeadingNode(title = "My profile", level = HeadingLevel.H1),
ParagraphNode(
listOf(
TextNode("Hello world. I am a arranger. My profile is this "),
LinkNode(url = "https://example.com", text = "link"),
TextNode("."),
)
)
)
)
)
}
}
| 1
|
Kotlin
|
0
| 0
|
ecafaba025c993e3b8eb1a7b8ae7c5149b8f3a77
| 3,569
|
arranger
|
Apache License 2.0
|
karibu-testing-v10/src/main/kotlin/com/github/mvysny/kaributesting/v10/Utils.kt
|
thigg
| 287,500,252
| true
|
{"Gradle Kotlin DSL": 14, "Java Properties": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 5, "Markdown": 10, "INI": 1, "YAML": 1, "Java": 8, "Kotlin": 115, "Groovy": 40, "JavaScript": 9, "JSON": 3}
|
package com.github.mvysny.kaributesting.v10
import elemental.json.Json
import elemental.json.JsonArray
import elemental.json.JsonObject
import elemental.json.JsonValue
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
import java.net.URL
import kotlin.test.expect
fun Serializable.serializeToBytes(): ByteArray = ByteArrayOutputStream().use { it -> ObjectOutputStream(it).writeObject(this); it }.toByteArray()
inline fun <reified T: Serializable> ByteArray.deserialize(): T = ObjectInputStream(inputStream()).readObject() as T
inline fun <reified T: Serializable> T.serializeDeserialize() = serializeToBytes().deserialize<T>()
val IntRange.size: Int get() = (endInclusive + 1 - start).coerceAtLeast(0)
/**
* Expects that [actual] list of objects matches [expected] list of objects. Fails otherwise.
*/
fun <T> expectList(vararg expected: T, actual: ()->List<T>) = expect(expected.toList(), actual)
/**
* Parses the contents of given URL as a Json.
*/
internal fun URL.readJson(): JsonObject = Json.parse(readText())
/**
* Adds a [value] at the end of the array.
*/
fun JsonArray.add(value: JsonValue) {
set(length(), value)
}
/**
* Returns the major JVM version, e.g. 6 for Java 1.6, 8 for Java 8, 11 for Java 11 etc.
*/
val jvmVersion: Int get() = System.getProperty("java.version").parseJvmVersion()
/**
* Returns the major JVM version, 1 for 1.1, 2 for 1.2, 3 for 1.3, 4 for 1.4, 5
* for 1.5 etc.
*/
internal fun String.parseJvmVersion(): Int {
// taken from https://stackoverflow.com/questions/2591083/getting-java-version-at-runtime
val version: String = removePrefix("1.").takeWhile { it.isDigit() }
return version.toInt()
}
| 0
| null |
0
| 0
|
86709b25fc9c53688fc44940d2d9271ad3b0922b
| 1,748
|
karibu-testing
|
Apache License 2.0
|
core/src/main/kotlin/sift/core/api/GenericsParser.kt
|
junkdog
| 561,870,959
| false
| null |
package sift.core.api
import sift.core.asm.signature.ArgType
import sift.core.asm.signature.MetaType
import sift.core.asm.signature.TypeSignature
import sift.core.dsl.Classes
import sift.core.dsl.Signature
import sift.core.dsl.Type
import sift.core.stringWriter
internal fun explodeTypeFromSignature(
context: Signature,
signature: String,
synthesize: Boolean,
f: Classes.() -> Unit
) {
// we'll only evaluate nodes leading to T
fun containsT(sig: GenericType) = sig.flatten().any { it.constraint is TypeName.TypeT }
val sig = parseGenericType(signature.replace(" ", ""))
// require T in signature
require(containsT(sig)) {
"Signature must contain a type parameter T: $signature"
}
// T can only occur once
require(sig.flatten().count { it.constraint is TypeName.TypeT } == 1) {
"Type parameter T must only occur once: $signature"
}
fun recurse(dsl: Signature, self: GenericType) {
when (self.constraint) {
is TypeName.TypeT -> {
dsl.explodeType(synthesize, f)
}
is TypeName.SimpleName -> {
dsl.filter(Regex("^.+\\.${self.constraint.name}\$"))
self.arguments
.filter(::containsT)
.forEach { arg -> dsl.typeArgument(arg.index) { recurse(this, arg) } }
}
is TypeName.Any -> {
self.arguments
.filter(::containsT)
.forEach { arg -> dsl.typeArgument(arg.index) { recurse(this, arg) } }
}
}
}
recurse(context, sig)
}
internal fun parseSignature(signature: String): TypeSignature {
return parseGenericType(signature.replace(" ", "")).signature
}
private fun parseGenericType(
signature: String
): GenericType = GenericsParser(signature).parseType(0)
private sealed interface TypeName {
data class SimpleName(val name: String) : TypeName {
override fun toString(): String = name
}
object TypeT : TypeName {
override fun toString(): String = "T"
}
object Any : TypeName {
override fun toString(): String = "_"
}
companion object {
fun from(s: String): TypeName = when (s) {
"_" -> Any
"T" -> TypeT
else -> SimpleName(s)
}
}
}
private class GenericType(val index: Int, val constraint: TypeName, val arguments: MutableList<GenericType>) {
override fun toString(): String = when (arguments.size) {
0 -> constraint.toString()
else -> "${constraint}<${arguments.joinToString(", ")}>"
}
fun flatten(): List<GenericType> = listOf(this) + arguments.flatMap { it.flatten() }
val signature: TypeSignature
get() {
val args = arguments.map(GenericType::signature).toMutableList()
return TypeSignature(ArgType.Plain(Type.from(constraint.toString())), 0, MetaType.Class, args)
}
}
private class GenericsParser(val input: String) {
private var index = 0
fun parseType(index: Int): GenericType {
val name = parseTypeName()
val arguments = mutableListOf<GenericType>()
if (at('<')) {
consume('<')
arguments += parseTypeArguments()
consume('>')
}
return GenericType(index, name, arguments)
}
private fun consume(): Char = input[index++]
private fun consume(c: Char) {
if (!at(c)) {
error("Expected character '$c' at index $index")
}
index++
}
private fun parseTypeName(): TypeName = TypeName.from(stringWriter {
while (!(eol || at('<') || at('>') || at(','))) {
append(consume())
}
})
private fun parseTypeArguments(): List<GenericType> {
val arguments = mutableListOf<GenericType>()
var index = 0
while (!at('>')) {
arguments.add(parseType(index++))
if (at(',')) {
consume(',')
}
}
return arguments
}
private fun at(check: Char) = input.length > index && input[index] == check
private val eol: Boolean
get() = input.length <= index
}
| 5
| null |
0
| 56
|
b486fe82fc07d85355311c13160a9fadc2f65831
| 4,226
|
sift
|
MIT License
|
navigation/src/main/java/com/parimatch/navigation/screen/ScreenContract.kt
|
parimatch-tech
| 509,548,833
| false
| null |
package com.parimatch.navigation.screen
import android.os.Bundle
/**
* The first parameter stands for the argument type, the second for the related information type.
* Restrictions for the argument type are the same as for [Bundle].
* todo : separate through inheritance
* todo : make arg parameter constrained by Serializable
*/
public interface ScreenContract <A: Any, I: Any>
/**
* [Reason](https://discuss.kotlinlang.org/t/allow-bounds-on-typealias-type-parameters/16028) why there are no more aliases.
*/
public interface BlankScreenContract : ScreenContract<Unit, Unit>
| 0
|
Kotlin
|
0
| 0
|
a074b34e86a18884982b515d228faa26d04e2f21
| 586
|
priroda
|
Apache License 2.0
|
skin_cancer_app/android/app/src/main/kotlin/com/kmadstudio/skincancerapp/MainActivity.kt
|
bahkali
| 345,211,600
| false
|
{"Jupyter Notebook": 115947, "Dart": 5710, "Swift": 404, "Kotlin": 133, "Objective-C": 38}
|
package com.kmadstudio.skincancerapp
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Jupyter Notebook
|
0
| 0
|
0a0a825c354f3b4d5cf24a3a9d5011052b5a515f
| 133
|
SkinCancerClassifier
|
MIT License
|
src/main/kotlin/com/examplemod/ExampleMod.kt
|
butterfriez
| 568,274,715
| false
| null |
import com.butter.commands.MainCommand
import com.butter.config.Config
import com.butter.config.PersistentData
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiScreen
import net.minecraftforge.client.ClientCommandHandler
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.fml.common.Mod
import net.minecraftforge.fml.common.ModMetadata
import net.minecraftforge.fml.common.event.FMLInitializationEvent
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.common.gameevent.TickEvent
import java.io.File
@Mod(
modid = "bobomb",
name = "Bob-Omb Overlay",
version = "1.0",
useMetadata = true,
clientSideOnly = true
)
class BombOmb {
@Mod.EventHandler
fun preInit(event: FMLPreInitializationEvent) {
metadata = event.modMetadata
val directory = File(event.modConfigurationDirectory, event.modMetadata.modId)
directory.mkdirs()
configDirectory = directory
persistentData = PersistentData.load()
config = Config
}
@Mod.EventHandler
fun onInit(event: FMLInitializationEvent) {
ClientCommandHandler.instance.registerCommand(MainCommand())
listOf(
this
).forEach(MinecraftForge.EVENT_BUS::register)
}
@SubscribeEvent
fun onTick(event: TickEvent.ClientTickEvent) {
if (event.phase != TickEvent.Phase.START || currentGui == null) return
mc.displayGuiScreen(currentGui)
currentGui = null
}
companion object {
val mc: Minecraft = Minecraft.getMinecraft()
var currentGui: GuiScreen? = null
lateinit var configDirectory: File
lateinit var config: Config
lateinit var persistentData: PersistentData
lateinit var metadata: ModMetadata
}
}
| 0
|
Kotlin
|
0
| 0
|
e1a865a87305dc780b582e917e6c9acef2e066d4
| 1,906
|
mixin-testing
|
The Unlicense
|
app/src/main/java/com/heig/yfitops/ui/components/list/song/SongView.kt
|
Alessandro-AP
| 488,206,391
| false
| null |
package com.heig.yfitops.ui.components.list.song
import android.annotation.SuppressLint
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import com.heig.yfitops.viewmodels.MainViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
* Representing the View of the Song List
*/
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun SongView(playlistID: String, mainViewModel: MainViewModel) {
CoroutineScope(Dispatchers.IO).launch {
mainViewModel.updatePlaylist(playlistID)
}
val list by mainViewModel.mediaItems.observeAsState()
list?.data?.let { SongList(it, mainViewModel) }
}
| 0
|
Kotlin
|
0
| 2
|
15be1734b3f1e7f13c5ef015f74a1df81cef1695
| 783
|
Yfi-Tops
|
MIT License
|
subprojects/org.compiere.crm/test/kotlin/org/compiere/crm/test/BPartnerTests.kt
|
idempiere-micro-archive
| 140,256,677
| false
| null |
package org.compiere.crm.test
import org.compiere.crm.*
import org.compiere.model.I_C_BPartner
import org.junit.Test
import org.idempiere.common.db.CConnection
import org.idempiere.common.db.Database
import org.idempiere.common.util.CLogger
import org.idempiere.common.util.DB
import org.idempiere.common.util.Env
import org.idempiere.common.util.Ini
import pg.org.compiere.db.DB_PostgreSQL
import java.util.Random
import kotlin.test.assertEquals
// generates random string with small letters of a given length
fun randomString(length: Int): String {
// helper extension function to generate random string based on a set
fun ClosedRange<Char>.randomString(length: Int) =
(1..length)
.map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
.joinToString("")
return ('a'..'z').randomString(length)
}
class BPartnerTests : BaseProcessTest() {
@Test
fun `loading saving finding business partner work`() {
Ini.getIni().isClient = false
CLogger.getCLogger(BPartnerTests::class.java)
Ini.getIni().properties
val db = Database()
db.setDatabase(DB_PostgreSQL())
DB.setDBTarget(CConnection.get(null))
DB.isConnected()
val ctx = Env.getCtx()
val AD_CLIENT_ID = 11
val AD_CLIENT_ID_s = AD_CLIENT_ID.toString()
ctx.setProperty(Env.AD_CLIENT_ID, AD_CLIENT_ID_s )
Env.setContext(ctx, Env.AD_CLIENT_ID, AD_CLIENT_ID_s )
val AD_USER_ID = 104
val AD_USER_ID_s = AD_USER_ID.toString()
ctx.setProperty(Env.AD_USER_ID, AD_USER_ID_s )
Env.setContext(ctx, Env.AD_USER_ID, AD_USER_ID_s )
val id = 118
val partner = MBPartner.get( Env.getCtx(), id )
assertEquals( id, partner.c_BPartner_ID)
assertEquals( "JoeBlock", partner.value)
assertEquals( "Joe Block", partner.name)
val partner2 : I_C_BPartner = partner as I_C_BPartner
val newValue = "JoeBlock*"
partner2.setValue( newValue )
partner2.save()
val partner3 = MBPartner.get( Env.getCtx(), id )
assertEquals( id, partner3.c_BPartner_ID)
assertEquals( newValue, partner3.value)
assertEquals( "Joe Block", partner3.name)
partner2.setValue( "JoeBlock" )
partner2.save()
val newPartner = MBPartner.getTemplate(ctx, AD_CLIENT_ID)
val name = "Test "+ randomString(10)
newPartner.setName(name)
val value = "t-"+ randomString(5)
newPartner.setValue(value)
newPartner.save()
val defaultCountry = MCountry.getDefault(ctx)
val defaultRegion = MRegion.getDefault(ctx)
val location = MLocation( defaultCountry, defaultRegion )
location.save()
val partnerLocation = MBPartnerLocation( newPartner )
partnerLocation.c_Location_ID = location.c_Location_ID
partnerLocation.save()
val newPartner2 = MBPartner.get( Env.getCtx(), newPartner.c_BPartner_ID )
assertEquals( 1, newPartner2.locations.count() )
newPartner.delete(true)
location.delete(true)
}
}
| 1
| null |
1
| 1
|
a5c09f37d68950b458cf23ce4a2c50e98c50ea2c
| 3,155
|
idempiere-micro
|
MIT License
|
src/main/kotlin/uk/co/placona/eventsbot/hawkeye/HawkeyeService.kt
|
mplacona
| 120,651,533
| false
| null |
package uk.co.placona.eventsbot.hawkeye
import io.reactivex.Observable
import io.reactivex.Single
import org.springframework.cache.annotation.Cacheable
import retrofit2.http.GET
import retrofit2.http.Query
import uk.co.placona.eventsbot.models.HawkeyeCountryResponse
import uk.co.placona.eventsbot.models.HawkeyeEventResponse
import uk.co.placona.eventsbot.models.HawkeyeTagResponse
interface HawkeyeService {
// All Green events
@GET("/api/events?viewModel.includeNoAssignedAttendees=false&viewModel.statusId=3&viewModel.pageSize=1000&viewModel.sort=start")
fun getEventsByCountry(
@Query("viewModel.startDate") startDate: String,
@Query("viewModel.country") country: String,
@Query("api_key") apiKey: String)
: Observable<HawkeyeEventResponse>
@GET("/api/events?viewModel.includeNoAssignedAttendees=false&viewModel.statusId=3&viewModel.pageSize=1000&viewModel.sort=start")
fun getEventsByTag(
@Query("viewModel.startDate") startDate: String,
@Query("viewModel.eventTagIds") tag: String,
@Query("api_key") apiKey: String)
: Observable<HawkeyeEventResponse>
@GET("/api/tags?pageSize=1000")
@Cacheable("tags")
fun getTags(@Query("api_key") apiKey: String) : Observable<HawkeyeTagResponse>
@GET("/api/countries?pageSize=1000")
@Cacheable("countries")
fun getCountries(@Query("api_key") apiKey: String) : Observable<HawkeyeCountryResponse>
}
| 0
|
Kotlin
|
1
| 2
|
aad5486986ef5c14e580ac3b33bc87fa5c5abbaf
| 1,483
|
EventsBot
|
Apache License 2.0
|
app/src/main/java/com/crossbowffs/quotelock/data/modules/Modules.kt
|
Yubyf
| 60,074,817
| false
| null |
package com.crossbowffs.quotelock.data.modules
import com.crossbowffs.quotelock.data.api.QuoteModule
import com.crossbowffs.quotelock.data.modules.brainyquote.BrainyQuoteQuoteModule
import com.crossbowffs.quotelock.data.modules.collections.CollectionsQuoteModule
import com.crossbowffs.quotelock.data.modules.custom.CustomQuoteModule
import com.crossbowffs.quotelock.data.modules.fortune.FortuneQuoteModule
import com.crossbowffs.quotelock.data.modules.freakuotes.FreakuotesQuoteModule
import com.crossbowffs.quotelock.data.modules.hitokoto.HitokotoQuoteModule
import com.crossbowffs.quotelock.data.modules.jinrishici.JinrishiciQuoteModule
import com.crossbowffs.quotelock.data.modules.libquotes.LibquotesQuoteModule
import com.crossbowffs.quotelock.data.modules.natune.NatuneQuoteModule
import com.crossbowffs.quotelock.data.modules.wikiquote.WikiquoteQuoteModule
object Modules {
private val sModules: MutableMap<String, QuoteModule> = LinkedHashMap()
init {
addLocalModule(HitokotoQuoteModule())
addLocalModule(WikiquoteQuoteModule())
addLocalModule(JinrishiciQuoteModule())
addLocalModule(FreakuotesQuoteModule())
addLocalModule(NatuneQuoteModule())
addLocalModule(BrainyQuoteQuoteModule())
addLocalModule(LibquotesQuoteModule())
addLocalModule(FortuneQuoteModule())
addLocalModule(CustomQuoteModule())
addLocalModule(CollectionsQuoteModule())
}
private fun addLocalModule(module: QuoteModule) {
val className = module::class.qualifiedName ?: ""
sModules[className] = module
}
private fun getModule(className: String): QuoteModule {
val module = sModules[className]
return module ?: throw ModuleNotFoundException("Module not found for class: $className")
}
fun values(): List<QuoteModule> {
return ArrayList(sModules.values)
}
operator fun get(className: String): QuoteModule = getModule(className)
operator fun contains(className: String): Boolean = sModules.containsKey(className)
}
| 8
| null |
3
| 79
|
7e82ba2c535ed6f68a81c762805038f2b8bf0e4f
| 2,060
|
QuoteLockX
|
MIT License
|
cellular/src/main/java/com/fa/cellular/enums/Ellipsize.kt
|
furkanayaz
| 714,965,102
| false
|
{"Kotlin": 32976}
|
package com.fa.cellular.enums
enum class Ellipsize(val code: Int) {
NONE(code = 0),
START(code = 1),
MIDDLE(code = 2),
END(code = 3),
MARQUEE(code = 4),
}
| 0
|
Kotlin
|
0
| 7
|
61740028dfd010e78882f0a1139d293215b9a348
| 175
|
Cellular-Table-Layout
|
Apache License 2.0
|
src/main/kotlin/novah/cli/command/BuildCommand.kt
|
stackoverflow
| 255,379,925
| false
| null |
/**
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package novah.cli.command
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import novah.cli.Deps
import novah.cli.DepsProcessor
import novah.data.Err
import novah.main.CompilationError
import novah.main.Compiler
import novah.main.Options
import java.io.File
import kotlin.system.exitProcess
class BuildCommand : CliktCommand(name = "build", help = "compile the project described by the `novah.json` file") {
private val alias by option(
"-a", "--alias",
help = "Alias to turn on"
)
private val check by option(
"-c", "--check",
help = "just check the code for errors, but don't generate code"
).flag(default = false)
private val verbose by option(
"-v", "--verbose",
help = "print information about the process"
).flag(default = false)
private val devMode by option(
"-d", "--dev",
help = "run the compiler in dev mode: no optimizations will be applied and some errors will be warnings."
).flag(default = false)
override fun run() {
val depsRes = DepsProcessor.readNovahFile()
if (depsRes is Err) {
echo(depsRes.err, false)
return
}
val deps = depsRes.unwrap()
val al = alias ?: DepsProcessor.defaultAlias
build(al, deps, verbose, devMode, check, ::echo, ::echo)
}
companion object {
fun build(
alias: String,
deps: Deps,
verbose: Boolean,
devMode: Boolean,
check: Boolean,
echo: (String) -> Unit,
echoErr: (String, Boolean) -> Unit
) {
val classpath = getClasspath(alias, "classpath", echoErr) ?: return
val sourcepath = getClasspath(alias, "sourcepath", echoErr) ?: return
val out = deps.output ?: DepsProcessor.defaultOutput
val javaPaths = File(".cpcache/$alias.javasourcepath")
if (javaPaths.exists()) {
val paths = javaPaths.readText(Charsets.UTF_8).split(File.pathSeparator).toSet()
if (paths.isNotEmpty()) {
if (!runJavac(paths, alias, out)) {
echoErr("Failed to compile java sources", true)
exitProcess(-1)
}
}
}
val compiler = Compiler.new(emptySequence(), classpath, sourcepath, Options(verbose, devMode))
try {
val warns = compiler.run(File(out), check)
Compiler.printWarnings(warns, echo)
echo("Success")
} catch (_: CompilationError) {
val allErrs = compiler.errors()
Compiler.printErrors(allErrs, echoErr)
echoErr("Failure", true)
exitProcess(1)
}
}
private fun runJavac(paths: Set<String>, alias: String, out: String): Boolean {
val argsfile = File(".cpcache/$alias.argsfile")
val sources = mutableSetOf<String>()
paths.forEach { path ->
File(path).walkTopDown().forEach { file ->
if (file.extension == "java") {
sources += file.absolutePath
}
}
}
if (sources.isEmpty()) return true
val srcFile = File.createTempFile("novahsources", null)
srcFile.writeText(sources.joinToString(" "))
val cmd = "javac @${argsfile.path} -d $out @${srcFile.path}"
val exit = RunCommand.runCommand(cmd)
return exit == 0
}
fun getClasspath(alias: String, type: String, echo: (String, Boolean) -> Unit): String? {
val cp = File(".cpcache/$alias.$type")
if (!cp.exists()) {
if (alias == DepsProcessor.defaultAlias) {
echo("No classpath found. Run the `deps` command first to generate a classpath", true)
} else {
echo(
"No classpath found for alias $alias. Run the `deps` command first to generate a classpath",
true
)
}
return null
}
return cp.readText(Charsets.UTF_8)
}
}
}
| 0
|
Kotlin
|
1
| 9
|
f3f2b12e178c5288197f6c6d591e8d304f5baf5d
| 5,014
|
novah
|
Apache License 2.0
|
feature-staking-impl/src/main/java/jp/co/soramitsu/feature_staking_impl/presentation/payouts/detail/di/PayoutDetailsModule.kt
|
soramitsu
| 278,060,397
| false
| null |
package jp.co.soramitsu.feature_staking_impl.presentation.payouts.detail.di
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import jp.co.soramitsu.common.address.AddressIconGenerator
import jp.co.soramitsu.common.di.viewmodel.ViewModelKey
import jp.co.soramitsu.common.di.viewmodel.ViewModelModule
import jp.co.soramitsu.common.resources.ResourceManager
import jp.co.soramitsu.feature_account_api.presenatation.actions.ExternalAccountActions
import jp.co.soramitsu.feature_staking_impl.domain.StakingInteractor
import jp.co.soramitsu.feature_staking_impl.presentation.StakingRouter
import jp.co.soramitsu.feature_staking_impl.presentation.payouts.detail.PayoutDetailsViewModel
import jp.co.soramitsu.feature_staking_impl.presentation.payouts.model.PendingPayoutParcelable
@Module(includes = [ViewModelModule::class])
class PayoutDetailsModule {
@Provides
@IntoMap
@ViewModelKey(PayoutDetailsViewModel::class)
fun provideViewModel(
interactor: StakingInteractor,
router: StakingRouter,
payout: PendingPayoutParcelable,
addressIconGenerator: AddressIconGenerator,
externalAccountActions: ExternalAccountActions.Presentation,
resourceManager: ResourceManager
): ViewModel {
return PayoutDetailsViewModel(
interactor,
router,
payout,
addressIconGenerator,
externalAccountActions,
resourceManager
)
}
@Provides
fun provideViewModelCreator(
fragment: Fragment,
viewModelFactory: ViewModelProvider.Factory
): PayoutDetailsViewModel {
return ViewModelProvider(fragment, viewModelFactory).get(PayoutDetailsViewModel::class.java)
}
}
| 3
| null |
15
| 55
|
756c1fea772274ad421de1b215a12bf4e2798d12
| 1,878
|
fearless-Android
|
Apache License 2.0
|
android/lib_common/src/main/java/uk/ac/cam/energy/common/execution/ExecutionLog.kt
|
lambdapioneer
| 650,185,708
| false
|
{"Kotlin": 153164, "Jupyter Notebook": 92840, "Rust": 15505, "Python": 13604, "C++": 3065, "OpenSCAD": 2520, "Shell": 639, "Dockerfile": 551}
|
package uk.ac.cam.energy.common.execution
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import uk.ac.cam.energy.common.mkdirIfNotExists
import uk.ac.cam.energy.common.monotonicMs
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayDeque
/** idempotent */
fun getScenarioBasename(scenarioFileName: String) =
scenarioFileName.replace(".scenario", "")
fun getLogCsvFilename(scenarioName: String, timeRefMs: Long): String {
val dateString = getLogDateString(timeRefMs)
return "${scenarioName}_${dateString}_android.csv"
}
fun getTraceCsvFilename(scenarioName: String, timeRefMs: Long): String {
val dateString = getLogDateString(timeRefMs)
return "${scenarioName}_${dateString}_trace.csv"
}
fun ensureLogsDir(context: Context): File {
val dir = File(context.filesDir, "logs")
dir.mkdirIfNotExists()
return dir
}
private fun getLogDateString(timeRefMs: Long) =
SimpleDateFormat("yyyyMMdd_HHmm", Locale.US).format(Date(timeRefMs))
data class LogEntry(
val operation: String,
val ts_ms: Double,
val te_ms: Double,
val debug: String
)
class ExecutionLog(private val scenarioName: String) {
private val entries = ArrayDeque<LogEntry>(128)
fun log(entry: LogEntry) {
entries.add(entry)
}
fun syncToDisk(context: Context, startRealtimeMs: Long) {
val file = File(
ensureLogsDir(context),
getLogCsvFilename(getScenarioBasename(scenarioName), startRealtimeMs)
)
Log.d("ExecutionLog", "syncToDisk $file")
// ensure file and header
if (file.createNewFile()) {
FileWriter(file).use { fw ->
BufferedWriter(fw).use { bw ->
bw.write("scenario,operation,ts,te,debug\n")
}
}
}
// append data
val append = true
FileWriter(file, append).use { fw ->
BufferedWriter(fw).use { bw ->
for (entry in entries) {
val row = String.format(
"%s,%s,%.6f,%.6f,%s\n",
scenarioName,
entry.operation,
entry.ts_ms / 1000.0, // file uses seconds
entry.te_ms / 1000.0, // file uses seconds
entry.debug
)
bw.write(row)
}
}
}
}
}
@SuppressLint("StaticFieldLeak")
private var singleton: Tracer? = null
fun getTracer(): Tracer {
singleton?.also { return it }
synchronized(Tracer::class.java) {
singleton?.also { return it }
singleton = Tracer()
return singleton!!
}
}
class Tracer {
// for timekeeping relative to the ExecutionLog
private var isInit = false
private var _timeRefMs = 0.0
private var scenarioName: String? = null
private var traces = ArrayList<Pair<Double, String>>(1024)
fun trace(s: String) {
trace(nowMs(), s)
}
fun trace(t: Double, s: String) {
traces.add(Pair(t, s))
}
fun init(scenarioName: String?, timeRefMs: Double) {
isInit = true
setScenarioName(scenarioName)
traces.clear()
_timeRefMs = timeRefMs
}
private fun setScenarioName(name: String?) {
scenarioName = name
}
private fun nowMs(): Double {
val nowMs = monotonicMs()
if (!isInit) throw IllegalStateException("notinit")//init(scenarioName = null, timeRefMs = nowMs)
return nowMs - _timeRefMs
}
fun syncToDisk(context: Context, startRealtimeMs: Long) {
if (scenarioName == null) return
val file = File(
ensureLogsDir(context),
getTraceCsvFilename(getScenarioBasename(scenarioName!!), startRealtimeMs)
)
Log.d("Tracer", "syncToDisk $file")
// ensure file and header
if (!file.exists()) {
FileWriter(file).use { fw ->
BufferedWriter(fw).use { bw ->
bw.write("time,event\n")
}
}
}
// append data
val append = true
FileWriter(file, append).use { fw ->
BufferedWriter(fw).use { bw ->
for (trace in traces) {
val row = String.format(
"%.6f,%s\n",
trace.first / 1000.0, // file uses seconds
trace.second
)
bw.write(row)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
2bd0df00f68a149ed61801d45f1a9396673daab8
| 4,720
|
powering-privacy
|
MIT License
|
app/src/main/java/com/marvelousportal/activities/adapter/DetailCharactersAdapter.kt
|
ibhavikmakwana
| 123,120,686
| false
| null |
package com.marvelousportal.activities.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.marvelousportal.R
import com.marvelousportal.activities.DetailActivity
import com.marvelousportal.models.Result
import com.marvelousportal.utils.Constant
import kotlinx.android.synthetic.main.layout_list_items.view.*
import java.util.*
/**
* Created by <NAME> on 1/30/2018.
*/
class DetailCharactersAdapter(context: Context, characters: List<Result>) : RecyclerView.Adapter<DetailCharactersAdapter.ItemViewHolder>() {
private var mResult: List<Result>? = ArrayList()
private var mContext: Context? = null
init {
mResult = characters
mContext = context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder? {
val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_list_items, parent, false)
return ItemViewHolder(view)
}
@SuppressLint("SimpleDateFormat", "SetTextI18n")
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val resultInfo = mResult?.get(position)
holder.charName.text = resultInfo?.name
val path = resultInfo?.thumbnail?.path + "." + resultInfo?.thumbnail?.extension
Log.i("PATH", path)
Glide.with(mContext).load(path).into(holder.charImage)
holder.rootLayout.setOnClickListener {
DetailActivity.launchActivity(mContext!!, resultInfo?.id!!, Constant.CHARACTERS)
}
}
override fun getItemCount(): Int {
return mResult!!.size
}
inner class ItemViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
var charName = itemView.tv_list_name_title!!
var charImage = itemView.iv_list_name_image!!
var rootLayout = itemView.row_root_list!!
}
fun setUserList(character: List<Result>?) {
mResult = character
notifyDataSetChanged()
}
}
| 0
|
Kotlin
|
3
| 5
|
3a2ae78847aaab4fc5027e261efd46e718c9a31d
| 2,174
|
MarvelousPortal
|
MIT License
|
module-book-reader/src/main/java/io/legado/app/service/help/CheckSource.kt
|
LinXueyuanStdio
| 332,099,365
| false
|
{"Gradle": 10, "Java Properties": 3, "Shell": 1, "Text": 2, "Ignore List": 5, "Batchfile": 1, "Markdown": 16, "INI": 3, "Proguard": 4, "JSON": 7, "XML": 357, "Kotlin": 478, "Java": 6, "HTML": 3, "JavaScript": 9, "CSS": 6, "robots.txt": 1, "SVG": 1}
|
package io.legado.app.service.help
import android.content.Context
import android.content.Intent
import io.legado.app.App
import io.legado.app.R
import io.legado.app.constant.IntentAction
import io.legado.app.data.entities.BookSource
import io.legado.app.data.entities.SearchBook
import io.legado.app.help.coroutine.Coroutine
import io.legado.app.model.webBook.WebBook
import io.legado.app.service.CheckSourceService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import org.jetbrains.anko.toast
import kotlin.coroutines.CoroutineContext
class CheckSource(val source: BookSource) {
companion object {
var keyword = "我的"
fun start(context: Context, sources: List<BookSource>) {
if (sources.isEmpty()) {
context.toast(R.string.non_select)
return
}
val selectedIds: ArrayList<String> = arrayListOf()
sources.map {
selectedIds.add(it.bookSourceUrl)
}
Intent(context, CheckSourceService::class.java).let {
it.action = IntentAction.start
it.putExtra("selectIds", selectedIds)
context.startService(it)
}
}
fun stop(context: Context) {
Intent(context, CheckSourceService::class.java).let {
it.action = IntentAction.stop
context.startService(it)
}
}
}
fun check(
scope: CoroutineScope,
context: CoroutineContext,
onNext: (sourceUrl: String) -> Unit
): Coroutine<*> {
val webBook = WebBook(source)
val variableBook = SearchBook(origin = source.bookSourceUrl)
return webBook
.searchBook(keyword, scope = scope, context = context, variableBook = variableBook)
.timeout(60000L)
.onError(Dispatchers.IO) {
source.addGroup("失效")
App.db.bookSourceDao().update(source)
}.onSuccess(Dispatchers.IO) {
source.removeGroup("失效")
App.db.bookSourceDao().update(source)
}.onFinally(Dispatchers.IO) {
onNext(source.bookSourceUrl)
}
}
}
| 1
| null |
1
| 1
|
1131fe5d2c16c15adfa12111cfac0fda080a50dc
| 2,242
|
TimeCatModule-BookReader
|
Apache License 2.0
|
libnavui-maneuver/src/main/java/com/mapbox/navigation/ui/maneuver/ManeuverProcessor.kt
|
liangxiaohit
| 383,684,199
| true
|
{"Kotlin": 3195469, "Java": 94102, "Python": 11580, "Makefile": 6255, "Shell": 1686}
|
package com.mapbox.navigation.ui.maneuver
import com.mapbox.api.directions.v5.models.BannerComponents
import com.mapbox.api.directions.v5.models.BannerInstructions
import com.mapbox.api.directions.v5.models.BannerText
import com.mapbox.api.directions.v5.models.DirectionsRoute
import com.mapbox.api.directions.v5.models.RouteLeg
import com.mapbox.navigation.base.formatter.DistanceFormatter
import com.mapbox.navigation.base.trip.model.RouteProgress
import com.mapbox.navigation.core.internal.utils.isSameRoute
import com.mapbox.navigation.ui.maneuver.model.Component
import com.mapbox.navigation.ui.maneuver.model.DelimiterComponentNode
import com.mapbox.navigation.ui.maneuver.model.ExitComponentNode
import com.mapbox.navigation.ui.maneuver.model.ExitNumberComponentNode
import com.mapbox.navigation.ui.maneuver.model.Lane
import com.mapbox.navigation.ui.maneuver.model.LaneIndicator
import com.mapbox.navigation.ui.maneuver.model.LegToManeuvers
import com.mapbox.navigation.ui.maneuver.model.Maneuver
import com.mapbox.navigation.ui.maneuver.model.PrimaryManeuver
import com.mapbox.navigation.ui.maneuver.model.RoadShieldComponentNode
import com.mapbox.navigation.ui.maneuver.model.SecondaryManeuver
import com.mapbox.navigation.ui.maneuver.model.StepDistance
import com.mapbox.navigation.ui.maneuver.model.StepIndexToManeuvers
import com.mapbox.navigation.ui.maneuver.model.SubManeuver
import com.mapbox.navigation.ui.maneuver.model.TextComponentNode
import com.mapbox.navigation.ui.utils.internal.ifNonNull
import java.util.UUID
internal object ManeuverProcessor {
fun process(action: ManeuverAction): ManeuverResult {
return when (action) {
is ManeuverAction.GetManeuverListWithRoute -> {
processManeuverList(
action.route,
action.routeLeg,
action.maneuverState,
action.distanceFormatter
)
}
is ManeuverAction.GetManeuverList -> {
processManeuverList(
action.routeProgress,
action.maneuverState,
action.distanceFormatter
)
}
}
}
private fun processManeuverList(
route: DirectionsRoute,
routeLeg: RouteLeg? = null,
maneuverState: ManeuverState,
distanceFormatter: DistanceFormatter,
): ManeuverResult.GetManeuverList {
if (!route.isSameRoute(maneuverState.route)) {
maneuverState.route = route
maneuverState.allManeuvers.clear()
maneuverState.roadShields.clear()
try {
createManeuverList(route, maneuverState, distanceFormatter)
} catch (exception: RuntimeException) {
return ManeuverResult.GetManeuverList.Failure(exception.message)
}
}
return try {
val allManeuverList = readManeuverListWith(maneuverState.allManeuvers, routeLeg)
ManeuverResult.GetManeuverList.Success(allManeuverList)
} catch (exception: RuntimeException) {
ManeuverResult.GetManeuverList.Failure(exception.message)
}
}
private fun processManeuverList(
routeProgress: RouteProgress,
maneuverState: ManeuverState,
distanceFormatter: DistanceFormatter
): ManeuverResult.GetManeuverListWithProgress {
return try {
val route = routeProgress.route
val routeLeg = routeProgress.currentLegProgress?.routeLeg
val stepIndex = routeProgress.currentLegProgress?.currentStepProgress?.stepIndex
val currentInstructionIndex =
routeProgress.currentLegProgress?.currentStepProgress?.instructionIndex
val stepDistanceRemaining =
routeProgress.currentLegProgress?.currentStepProgress?.distanceRemaining?.toDouble()
when {
routeLeg == null -> {
return ManeuverResult.GetManeuverListWithProgress.Failure(
"routeLeg is null"
)
}
stepIndex == null -> {
return ManeuverResult.GetManeuverListWithProgress.Failure(
"stepIndex is null"
)
}
currentInstructionIndex == null -> {
return ManeuverResult.GetManeuverListWithProgress.Failure(
"instructionIndex is null"
)
}
stepDistanceRemaining == null -> {
return ManeuverResult.GetManeuverListWithProgress.Failure(
"distanceRemaining is null"
)
}
else -> {
if (!route.isSameRoute(maneuverState.route)) {
maneuverState.route = route
maneuverState.allManeuvers.clear()
maneuverState.roadShields.clear()
createManeuverList(route, maneuverState, distanceFormatter)
}
val legToManeuvers = routeLeg.findIn(maneuverState.allManeuvers)
val stepsToManeuvers = legToManeuvers.stepIndexToManeuvers
val stepToManeuvers = stepIndex.findIn(stepsToManeuvers)
val indexOfStepToManeuvers = stepsToManeuvers.indexOf(stepToManeuvers)
updateDistanceRemainingForCurrentManeuver(
stepToManeuvers,
currentInstructionIndex,
stepDistanceRemaining
)
val filteredList = createFilteredList(
currentInstructionIndex,
indexOfStepToManeuvers,
stepsToManeuvers
)
ManeuverResult.GetManeuverListWithProgress.Success(filteredList)
}
}
} catch (exception: Exception) {
ManeuverResult.GetManeuverListWithProgress.Failure(exception.message)
}
}
private fun createManeuverList(
route: DirectionsRoute,
maneuverState: ManeuverState,
distanceFormatter: DistanceFormatter
) {
ifNonNull(route.legs()) { routeLegs ->
routeLegs.forEach { routeLeg ->
ifNonNull(routeLeg?.steps()) { steps ->
val stepList = mutableListOf<StepIndexToManeuvers>()
for (stepIndex in 0..steps.lastIndex) {
steps[stepIndex].bannerInstructions()?.let { bannerInstruction ->
val maneuverList = mutableListOf<Maneuver>()
bannerInstruction.forEach { banner ->
maneuverList.add(transformToManeuver(banner, distanceFormatter))
}
val stepIndexToManeuvers = StepIndexToManeuvers(
stepIndex,
maneuverList
)
stepList.add(stepIndexToManeuvers)
} ?: throw RuntimeException("LegStep should have valid banner instructions")
}
maneuverState.allManeuvers.add(LegToManeuvers(routeLeg, stepList))
} ?: throw RuntimeException("RouteLeg should have valid steps")
}
} ?: throw RuntimeException("Route should have valid legs")
if (maneuverState.allManeuvers.isEmpty()) {
throw RuntimeException("Maneuver list could not be created")
}
}
private fun readManeuverListWith(
list: List<LegToManeuvers>,
routeLeg: RouteLeg? = null
): List<Maneuver> {
if (list.isEmpty()) {
throw RuntimeException("List of LegToManeuvers cannot be empty")
}
val maneuverList = mutableListOf<Maneuver>()
when (routeLeg == null) {
true -> {
list[0].stepIndexToManeuvers.forEach { stepIndexToManeuver ->
maneuverList.addAll(stepIndexToManeuver.maneuverList)
}
}
else -> {
list.find { item -> item.routeLeg == routeLeg }?.let { legToManeuver ->
legToManeuver.stepIndexToManeuvers.forEach { stepIndexToManeuver ->
maneuverList.addAll(stepIndexToManeuver.maneuverList)
}
} ?: throw RuntimeException("$routeLeg passed is different")
}
}
if (maneuverList.isEmpty()) {
throw RuntimeException("Maneuver list not found corresponding to $routeLeg")
}
return maneuverList
}
private fun RouteLeg.findIn(legs: List<LegToManeuvers>): LegToManeuvers {
return legs.find {
it.routeLeg == this
} ?: throw RuntimeException("Could not find the $this")
}
private fun Int.findIn(steps: List<StepIndexToManeuvers>): StepIndexToManeuvers {
return steps.find {
it.stepIndex == this
} ?: throw RuntimeException("Could not find the $this")
}
private fun updateDistanceRemainingForCurrentManeuver(
stepToManeuvers: StepIndexToManeuvers,
currentInstructionIndex: Int,
stepDistanceRemaining: Double
) {
stepToManeuvers.maneuverList[currentInstructionIndex].stepDistance.distanceRemaining =
stepDistanceRemaining
}
private fun createFilteredList(
currentInstructionIndex: Int,
indexOfStepToManeuvers: Int,
stepsToManeuvers: List<StepIndexToManeuvers>
): List<Maneuver> {
val list = mutableListOf<Maneuver>()
for (i in indexOfStepToManeuvers..stepsToManeuvers.lastIndex) {
if (i == indexOfStepToManeuvers &&
stepsToManeuvers[i].maneuverList.size > 1
) {
list.addAll(
stepsToManeuvers[i].maneuverList.subList(
currentInstructionIndex,
stepsToManeuvers[i].maneuverList.size
)
)
} else {
list.addAll(stepsToManeuvers[i].maneuverList)
}
}
return list
}
private fun transformToManeuver(
bannerInstruction: BannerInstructions,
distanceFormatter: DistanceFormatter
): Maneuver {
val primaryManeuver = getPrimaryManeuver(bannerInstruction.primary())
val secondaryManeuver = getSecondaryManeuver(bannerInstruction.secondary())
val subManeuver = getSubManeuverText(bannerInstruction.sub())
val laneGuidance = getLaneGuidance(bannerInstruction)
val totalStepDistance = bannerInstruction.distanceAlongGeometry()
val stepDistance = StepDistance(distanceFormatter, totalStepDistance, null)
return Maneuver(
primaryManeuver,
stepDistance,
secondaryManeuver,
subManeuver,
laneGuidance
)
}
private fun getPrimaryManeuver(bannerText: BannerText): PrimaryManeuver {
val bannerComponentList = bannerText.components()
return when (!bannerComponentList.isNullOrEmpty()) {
true -> {
PrimaryManeuver
.Builder()
.id(UUID.randomUUID().toString())
.text(bannerText.text())
.type(bannerText.type())
.degrees(bannerText.degrees())
.modifier(bannerText.modifier())
.drivingSide(bannerText.drivingSide())
.componentList(createComponents(bannerComponentList))
.build()
}
else -> {
PrimaryManeuver.Builder().build()
}
}
}
private fun getSecondaryManeuver(bannerText: BannerText?): SecondaryManeuver? {
val bannerComponentList = bannerText?.components()
return when (!bannerComponentList.isNullOrEmpty()) {
true -> {
SecondaryManeuver
.Builder()
.id(UUID.randomUUID().toString())
.text(bannerText.text())
.type(bannerText.type())
.degrees(bannerText.degrees())
.modifier(bannerText.modifier())
.drivingSide(bannerText.drivingSide())
.componentList(createComponents(bannerComponentList))
.build()
}
else -> {
null
}
}
}
private fun getSubManeuverText(bannerText: BannerText?): SubManeuver? {
bannerText?.let { subBanner ->
if (subBanner.type() != null && subBanner.text().isNotEmpty()) {
val bannerComponentList = subBanner.components()
return when (!bannerComponentList.isNullOrEmpty()) {
true -> {
SubManeuver
.Builder()
.id(UUID.randomUUID().toString())
.text(bannerText.text())
.type(bannerText.type())
.degrees(bannerText.degrees())
.modifier(bannerText.modifier())
.drivingSide(bannerText.drivingSide())
.componentList(createComponents(bannerComponentList))
.build()
}
else -> {
null
}
}
}
}
return null
}
private fun getLaneGuidance(bannerInstruction: BannerInstructions): Lane? {
val subBannerText = bannerInstruction.sub()
val primaryBannerText = bannerInstruction.primary()
return subBannerText?.let { subBanner ->
if (subBanner.type() == null && subBanner.text().isEmpty()) {
val bannerComponentList = subBanner.components()
return ifNonNull(bannerComponentList) { list ->
val laneIndicatorList = mutableListOf<LaneIndicator>()
list.forEach {
val directions = it.directions()
val active = it.active()
if (!directions.isNullOrEmpty() && active != null) {
laneIndicatorList.add(
LaneIndicator
.Builder()
.isActive(active)
.directions(directions)
.build()
)
}
}
// TODO: This is a fallback solution. Remove this and add all active_directions
// to LaneIndicator() once directions have migrated all customers to valhalla
Lane
.Builder()
.allLanes(laneIndicatorList)
.activeDirection(primaryBannerText.modifier())
.build()
}
}
null
}
}
private fun createComponents(
bannerComponentList: List<BannerComponents>
): List<Component> {
val componentList = mutableListOf<Component>()
bannerComponentList.forEach { component ->
when {
component.type() == BannerComponents.EXIT -> {
val exit = ExitComponentNode
.Builder()
.text(component.text())
.build()
componentList.add(Component(BannerComponents.EXIT, exit))
}
component.type() == BannerComponents.EXIT_NUMBER -> {
val exitNumber = ExitNumberComponentNode
.Builder()
.text(component.text())
.build()
componentList.add(Component(BannerComponents.EXIT_NUMBER, exitNumber))
}
component.type() == BannerComponents.TEXT -> {
val text = TextComponentNode
.Builder()
.text(component.text())
.abbr(component.abbreviation())
.abbrPriority(component.abbreviationPriority())
.build()
componentList.add(Component(BannerComponents.TEXT, text))
}
component.type() == BannerComponents.DELIMITER -> {
val delimiter = DelimiterComponentNode
.Builder()
.text(component.text())
.build()
componentList.add(Component(BannerComponents.DELIMITER, delimiter))
}
component.type() == BannerComponents.ICON -> {
val roadShield = RoadShieldComponentNode
.Builder()
.text(component.text())
.shieldUrl(component.imageBaseUrl())
.build()
componentList.add(Component(BannerComponents.ICON, roadShield))
}
}
}
return componentList
}
}
| 0
| null |
0
| 0
|
02f5fb7db8113a776c0382e7d4c9dbffe9348ceb
| 17,645
|
mapbox-navigation-android
|
Apache License 2.0
|
src/main/kotlin/github/ioannuwu/lexerutils/utils.kt
|
IoaNNUwU
| 675,036,715
| false
| null |
package github.ioannuwu.lexerutils
/**
* fun *.splitWithSplitter() can be used for optimal performance
*/
fun String.splitWithPattern(
vararg patterns: Pattern
): List<String> {
val string = this
val splitter = Splitter.withPattern(*patterns)
return splitter.split(string)
}
/**
* fun *.splitWithSplitter() can be used for optimal performance
*/
fun CharSequence.splitWithPattern(
vararg patterns: Pattern
) : List<String> {
val charSequence = this
val splitter = Splitter.withPattern(*patterns)
return splitter.split(charSequence)
}
/**
* fun *.splitWithSplitter() can be used for optimal performance
*/
fun Sequence<Char>.splitWithPattern(
vararg patterns: Pattern
): List<String> {
val charSequence = this
val splitter = Splitter.withPattern(*patterns)
return splitter.split(charSequence)
}
/**
* fun *.splitWithSplitter() can be used for optimal performance
*/
fun CharArray.splitWithPattern(
vararg patterns: Pattern
): List<String> {
val charArray = this
val splitter = Splitter.withPattern(*patterns)
return splitter.split(charArray)
}
/**
* fun *.splitWithSplitter() can be used for optimal performance
*/
fun Array<Char>.splitWithPattern(
vararg patterns: Pattern
): List<String> {
val charArray = this
val splitter = Splitter.withPattern(*patterns)
return splitter.split(charArray)
}
fun String.splitWithSplitter(
splitter: Splitter
): List<String> {
val string = this
return splitter.split(string)
}
fun CharSequence.splitWithSplitter(
splitter: Splitter
) : List<String> {
val charSequence = this
return splitter.split(charSequence)
}
fun Sequence<Char>.splitWithSplitter(
splitter: Splitter
): List<String> {
val charSequence = this
return splitter.split(charSequence)
}
fun CharArray.splitWithSplitter(
splitter: Splitter
): List<String> {
val charArray = this
return splitter.split(charArray)
}
fun Array<Char>.splitWithSplitter(
splitter: Splitter
): List<String> {
val charArray = this
return splitter.split(charArray)
}
| 0
|
Kotlin
|
0
| 1
|
e96544d79986f427d5b2672d7d0ef868811b0cd5
| 2,112
|
lexer-utils
|
MIT License
|
app/src/main/java/com/example/tictrac/domain/di/DomainModule.kt
|
rostikbalagurak
| 151,734,221
| false
| null |
package com.example.tictrac.domain.di
import com.example.tictrac.domain.boundaries.api.UsersAPI
import com.example.tictrac.domain.boundaries.repository.UserRepository
import com.example.tictrac.domain.usecase.UsersInteractor
import com.example.tictrac.domain.usecase.impl.DefaultUsersInteractor
import dagger.Module
import dagger.Provides
@Module
class DomainModule {
@Provides
fun usersInteractory(userRepository: UserRepository, usersAPI: UsersAPI): UsersInteractor {
return DefaultUsersInteractor(userRepository, usersAPI)
}
}
| 0
|
Kotlin
|
0
| 1
|
ca786503de7fe6eb9a81b9e2c31443c15ea95e76
| 552
|
android-clean-architecture
|
MIT License
|
snsLogin/src/main/java/com/manta/snslogin/login/twitter/TwitterLogin.kt
|
bso112
| 529,804,604
| false
| null |
package com.manta.snslogin.login.twitter
import android.app.Activity
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.*
import com.manta.snslogin.FirebaseUserData
import com.manta.snslogin.login.google.GoogleAuthUtil
import com.manta.snslogin.util.toSafe
internal object TwitterLogin {
fun login(
activity: Activity,
onSuccess: (firebaseUserData: FirebaseUserData) -> Unit,
onFailure: (String) -> Unit
) {
val provider = OAuthProvider.newBuilder("twitter.com")
val firebaseAuth = FirebaseAuth.getInstance()
val pendingResultTask: Task<AuthResult>? = firebaseAuth.pendingAuthResult
if (pendingResultTask != null) {
pendingResultTask
.addOnSuccessListener(
OnSuccessListener { authResult ->
handleAuthResult(authResult, onSuccess, onFailure)
})
.addOnFailureListener {
onFailure(it.message.toSafe())
}
} else {
firebaseAuth
.startActivityForSignInWithProvider(activity, provider.build())
.addOnSuccessListener { authResult ->
handleAuthResult(authResult, onSuccess, onFailure)
}
.addOnFailureListener {
onFailure(it.message.toSafe())
}
}
}
fun logOut(){
FirebaseAuth.getInstance().signOut()
}
private fun handleAuthResult(authResult : AuthResult, onSuccess: (firebaseUserData: FirebaseUserData) -> Unit, onFailure: (String) -> Unit){
val user = authResult.user ?: run {
onFailure("Fail to sign in with firebase")
return
}
user.getIdToken(true).addOnSuccessListener { result ->
if (result.token != null && result.token.toSafe().isNotBlank()) {
FirebaseUserData(
email = user.email.toSafe(),
idToken = result.token.toSafe(),
displayName = user.displayName.toSafe(),
phoneNumber = user.phoneNumber.toSafe(),
photoUrl = user.photoUrl.toString(),
isEmailVerified = user.isEmailVerified.toSafe(),
isAnonymous = user.isAnonymous.toSafe(),
providerId = user.providerId,
uid = user.uid
).also {
onSuccess(it)
}
} else {
onFailure("invalid firebase token")
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
a74d900ce78203fc3f66cf9854d380979a5515af
| 2,678
|
SnsLogin
|
The Unlicense
|
m31/src/main/java/ir/farsroidx/m31/AndromedaViewStateViewModel.kt
|
riazati75
| 706,246,252
| false
|
{"Kotlin": 142934}
|
@file:Suppress("unused")
package ir.farsroidx.m31
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
abstract class AndromedaViewStateViewModel <VS: Any> : AndromedaViewModel() {
private var _onViewStateChange: (VS) -> Unit = {}
private var _lifecycleOwner: LifecycleOwner? = null
private val _viewStateChange = MutableLiveData<VS>()
val viewStateChange: LiveData<VS> = _viewStateChange
internal fun setOnViewStateChanged(lifecycleOwner: LifecycleOwner, onChange: (VS) -> Unit) {
_lifecycleOwner = lifecycleOwner
_onViewStateChange = onChange
}
protected suspend fun setViewState(viewState: VS) {
_lifecycleOwner?.let {
doInMain {
if (it.lifecycle.currentState != Lifecycle.State.DESTROYED) {
_onViewStateChange( viewState )
} else {
// TODO: Nothing to change =====================================================
}
}
}
}
protected fun setLiveViewState(viewState: VS) {
_viewStateChange.value = viewState
}
protected fun postLiveViewState(viewState: VS) {
_viewStateChange.postValue(viewState)
}
}
| 0
|
Kotlin
|
0
| 0
|
304fdfe080619f6e6e87a3293d8ed31c1ee9c889
| 1,322
|
andromeda
|
Apache License 2.0
|
basic-feature/src/main/java/eu/krzdabrowski/starter/basicfeature/data/local/dao/RocketDao.kt
|
rashed-imam
| 584,109,324
| false
| null |
package eu.krzdabrowski.starter.basicfeature.data.local.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import eu.krzdabrowski.starter.basicfeature.data.local.model.RocketCached
import kotlinx.coroutines.flow.Flow
@Dao
interface RocketDao {
@Query("SELECT * FROM RocketCached")
fun getRockets(): Flow<List<RocketCached>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun saveRockets(rockets: List<RocketCached>)
}
| 0
|
Kotlin
|
0
| 1
|
7c9ecff7ef03bfc0dc3517d2327cf01c5525cb99
| 521
|
AndroidStater
|
MIT License
|
app/src/main/java/phocidae/mirounga/leonina/servicios/GestorUUID.kt
|
poximan
| 711,693,982
| false
|
{"Kotlin": 392827}
|
package phocidae.mirounga.leonina.servicios
import android.provider.Settings
import phocidae.mirounga.leonina.activity.MainActivity
import phocidae.mirounga.leonina.exception.UUIDRepetidoExcepcion
import java.util.UUID
class GestorUUID {
companion object {
private val resolveitor = MainActivity.resolver
private var actual: UUID = UUID.randomUUID()
private var ultimo: UUID = UUID.randomUUID()
fun obtenerAndroidID(): String {
val androidID = Settings.Secure.getString(resolveitor, Settings.Secure.ANDROID_ID)
return androidID + "@" + android.os.Build.MANUFACTURER + "-" + android.os.Build.MODEL
}
fun obtenerUUID(): UUID {
actual = UUID.randomUUID()
if (actual != ultimo)
ultimo = actual
else
throw UUIDRepetidoExcepcion()
return ultimo
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3f4940db61831e03b4ea82155a0c26bbb2fc6eb0
| 917
|
harenkaren
|
MIT License
|
app/src/main/java/com/fulldive/wallet/interactors/chains/grpc/GrpcInteractor.kt
|
imversed
| 473,994,295
| true
|
{"Java": 9874648, "Kotlin": 515378}
|
package com.fulldive.wallet.interactors.chains.grpc
import com.fulldive.wallet.di.modules.DefaultInteractorsModule
import com.fulldive.wallet.extensions.*
import com.fulldive.wallet.interactors.chains.StationInteractor
import com.fulldive.wallet.models.BaseChain
import com.fulldive.wallet.rx.AppSchedulers
import com.joom.lightsaber.ProvidedBy
import cosmos.base.v1beta1.CoinOuterClass
import cosmos.staking.v1beta1.Staking
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.reactivex.Completable
import io.reactivex.Single
import tendermint.p2p.Types
import wannabit.io.cosmostaion.dao.Account
import wannabit.io.cosmostaion.utils.WLog
import javax.inject.Inject
@ProvidedBy(DefaultInteractorsModule::class)
class GrpcInteractor @Inject constructor(
private val grpcRepository: GrpcRepository,
private val stationInteractor: StationInteractor
) {
fun update(account: Account, chain: BaseChain): Completable {
return Completable
.mergeArray(
updateBondedValidators(chain).subscribeOn(AppSchedulers.io()),
updateUnbondedValidators(chain).subscribeOn(AppSchedulers.io()),
updateUnbondingValidators(chain).subscribeOn(AppSchedulers.io())
)
.andThen(
Completable.mergeArray(
updateAccount(chain, account).subscribeOn(AppSchedulers.io()),
updateDelegations(chain, account).subscribeOn(AppSchedulers.io()),
updateUndelegations(chain, account).subscribeOn(AppSchedulers.io()),
updateRewards(chain, account).subscribeOn(AppSchedulers.io()),
)
)
.andThen(updateAdditional(chain, account))
.andThen(updateValidators(chain))
.andThen(updateNodeInfo(chain))
.flatMapCompletable { nodeInfo ->
Completable
.mergeArray(
stationInteractor
.updateStationParams(
chain,
nodeInfo.network
)
.subscribeOn(AppSchedulers.io())
.doOnError { error ->
WLog.e(error.message)
error.printStackTrace()
}
.onErrorComplete(),
stationInteractor
.updateIbcPaths(
chain,
nodeInfo.network
)
.doOnError { error ->
WLog.e(error.message)
error.printStackTrace()
}
.onErrorComplete()
.subscribeOn(AppSchedulers.io()),
stationInteractor
.updateIbcTokens(
chain,
nodeInfo.network
)
.doOnError { error ->
WLog.e(error.message)
error.printStackTrace()
}
.onErrorComplete()
.subscribeOn(AppSchedulers.io()),
updateMintScanAssets(chain).subscribeOn(AppSchedulers.io())
)
}
}
fun updateBondedValidators(chain: BaseChain): Completable {
return grpcRepository.updateValidators(
chain,
Staking.BondStatus.BOND_STATUS_BONDED,
DEFAULT_LIMIT
)
}
fun updateUnbondedValidators(chain: BaseChain): Completable {
return grpcRepository.updateValidators(
chain,
Staking.BondStatus.BOND_STATUS_UNBONDED,
DEFAULT_LIMIT
)
}
fun updateUnbondingValidators(chain: BaseChain): Completable {
return grpcRepository.updateValidators(
chain,
Staking.BondStatus.BOND_STATUS_UNBONDING,
DEFAULT_LIMIT
)
}
fun updateAccount(chain: BaseChain, account: Account): Completable {
return grpcRepository.updateAccount(chain, account.address)
.onErrorComplete { error ->
((error as? StatusRuntimeException)?.status?.code == Status.Code.NOT_FOUND)
.apply {
ifTrue {
WLog.e(error.message)
}
}
}
}
fun updateDelegations(chain: BaseChain, account: Account): Completable {
return grpcRepository.updateDelegations(chain, account.address)
}
fun updateUndelegations(chain: BaseChain, account: Account): Completable {
return grpcRepository.updateUndelegations(chain, account.address)
}
fun updateRewards(chain: BaseChain, account: Account): Completable {
return grpcRepository.updateRewards(chain, account.address)
}
fun updateNodeInfo(chain: BaseChain): Single<Types.NodeInfo> {
return grpcRepository
.requestNodeInfo(chain)
.flatMap { nodeInfo ->
grpcRepository
.setNodeInfo(chain, nodeInfo)
.toSingleDefault(nodeInfo)
}
}
fun requestBalances(chain: BaseChain, address: String): Single<List<CoinOuterClass.Coin>> {
return grpcRepository.requestBalance(chain, address)
}
private fun updateValidators(chain: BaseChain): Completable {
return Single
.zip(
grpcRepository.getTopValidators(),
grpcRepository.getOtherValidators(),
::concat
)
.flatMap { validators ->
grpcRepository
.setAllValidators(chain, validators)
.toSingleDefault(validators)
}
.flatMap { validators ->
Single
.zip(
grpcRepository.getDelegations(),
grpcRepository.getUndelegations(),
::combine
)
.flatMap { (delegations, undelegations) ->
singleCallable {
validators.mapNotNull { validator ->
validator.takeIf {
delegations.any { it.delegation.validatorAddress == validator.operatorAddress }
|| undelegations.any { it.validatorAddress == validator.operatorAddress }
}
}
}
}
}
.flatMapCompletable { myValidators ->
grpcRepository.setMyValidators(chain, myValidators)
}
}
private fun updateMintScanAssets(chain: BaseChain): Completable {
return grpcRepository.updateMintScanAssets(chain)
.doOnError { error ->
WLog.e(error.message)
error.printStackTrace()
}
.onErrorComplete()
}
private fun updateMintScanCw20Assets(chain: BaseChain, account: Account): Completable {
return grpcRepository
.updateMintScanCw20Assets()
.flatMapCompletable { cw20Assets ->
cw20Assets.map { assets ->
assets
.takeIf {
chain.mintScanChainName.isNotEmpty() && assets.chain.equals(
chain.mintScanChainName,
ignoreCase = true
)
}
.letOr(
{
grpcRepository
.requestCw20Balance(
chain,
account,
assets.contract_address
)
.map { balance ->
assets.amount = balance
assets
}
},
{
Single.just(assets)
}
)
}
.let { Single.concat(it) }
.toList()
.flatMapCompletable(grpcRepository::setCw20Assets)
}
}
private fun updateAdditional(chain: BaseChain, account: Account): Completable {
return when (chain) {
BaseChain.COSMOS_MAIN -> {
grpcRepository.updateGravityDex(chain)
}
BaseChain.IOV_MAIN -> Completable.mergeArray(
grpcRepository.updateStarNameFees(),
grpcRepository.updateStarNameConfig()
)
BaseChain.OSMOSIS_MAIN -> {
grpcRepository.updateOsmosisPools()
}
BaseChain.JUNO_MAIN -> {
updateMintScanCw20Assets(chain, account)
}
BaseChain.KAVA_MAIN -> Completable.mergeArray(
grpcRepository.updateKavaMarketPrice(),
grpcRepository.updateKavaIncentiveParam(),
grpcRepository.updateKavaIncentiveReward(account.address)
)
else -> Completable.complete()
}
}
companion object {
private const val DEFAULT_LIMIT = 300
}
}
| 0
|
Java
|
0
| 2
|
5fddbefcdc6acf7cadb6f7a7ab2edccee9f57851
| 9,876
|
imversed-wallet-android
|
MIT License
|
app/src/main/java/nl/jovmit/roboapp/login/common/CoroutineViewModel.kt
|
mitrejcevski
| 181,701,148
| false
| null |
package nl.jovmit.roboapp.login.common
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
abstract class CoroutineViewModel(
private val dispatchers: CoroutineDispatchers
) : ViewModel(), CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = dispatchers.ui + job
override fun onCleared() {
job.cancel()
super.onCleared()
}
}
| 1
| null |
1
| 15
|
731e128fd5a588b66e2c5f2a7fe34812f7bc11c2
| 515
|
roboapp
|
Apache License 2.0
|
api/src/main/kotlin/com/nebrija/pushit/api/security/domain/exception/JwtTokenInvalidException.kt
|
n01rdev
| 729,900,246
| false
|
{"Kotlin": 53053, "Dockerfile": 365}
|
package com.nebrija.pushit.api.security.domain.exception
class JwtTokenInvalidException : RuntimeException("JWT token is not valid")
| 0
|
Kotlin
|
1
| 0
|
dbafb47675b317be9e8c6ce65944451f99b60cc1
| 133
|
push-it-api
|
MIT License
|
android/app/src/encryption/java/net/yangkx/mmkv/MMKVInitializer.kt
|
yangkx-1024
| 674,122,195
| false
|
{"Rust": 97603, "Kotlin": 33019, "Swift": 29993, "Shell": 6290, "Dockerfile": 3045, "C": 2489}
|
package net.yangkx.mmkv
import android.content.Context
import net.yangkx.mmkv.log.LogLevel
object MMKVInitializer {
fun init(context: Context) {
val dir = context.getDir("mmkv", Context.MODE_PRIVATE)
MMKV.initialize(dir.absolutePath, "88C51C536176AD8A8EE4A06F62EE897E")
MMKV.setLogLevel(LogLevel.DEBUG)
}
}
| 2
|
Rust
|
1
| 13
|
ade37f41b8b9b1d1606f0ca7abc04cc56b156ba5
| 340
|
MMKV
|
Apache License 2.0
|
app/src/main/java/com/starts/movieguide/Ext.kt
|
ZhaoSiBo
| 278,286,809
| false
| null |
package com.starts.movieguide
import android.content.res.Resources
import android.content.res.TypedArray
import android.graphics.Color
/**
*文件描述:.
*作者:Created by Administrator on 2020/8/28.
*版本号:1.0
*/
fun getMaterialColor(resources: Resources, index:Int):Int {
val colors = resources.obtainTypedArray(R.array.mdcolor_300);
val returnColor = colors.getColor(index % colors.length(), Color.BLACK);
colors.recycle();
return returnColor
}
| 0
|
Kotlin
|
0
| 1
|
0b663068a9eb1df32f76f60272d2bc3579e47196
| 462
|
MovieGuide
|
MIT License
|
app/src/main/java/com/rarilabs/rarime/util/parseASN1Rsa.kt
|
rarimo
| 775,551,013
| false
|
{"Kotlin": 1036626, "Java": 86126, "C++": 17305, "C": 5321, "CMake": 1262}
|
package com.rarilabs.rarime.util
import java.security.interfaces.RSAPublicKey
import java.security.spec.RSAPublicKeySpec
import java.math.BigInteger
import java.security.KeyFactory
fun parseASN1RsaManually(data: ByteArray): RSAPublicKey {
var offset = 0
// Parse the top-level SEQUENCE
if (data[offset] != 0x30.toByte()) {
throw IllegalArgumentException("Invalid data: expected SEQUENCE at offset $offset")
}
offset += 1
val (seqLength, seqLengthOffset) = readAsn1Length(data, offset)
offset = seqLengthOffset
val seqEnd = offset + seqLength
// Parse AlgorithmIdentifier SEQUENCE
if (data[offset] != 0x30.toByte()) {
throw IllegalArgumentException("Invalid data: expected SEQUENCE at offset $offset")
}
offset += 1
val (algIdLength, algIdOffset) = readAsn1Length(data, offset)
offset = algIdOffset + algIdLength
// Parse BIT STRING
if (data[offset] != 0x03.toByte()) {
throw IllegalArgumentException("Invalid data: expected BIT STRING at offset $offset")
}
offset += 1
val (bitStringLength, bitStringOffset) = readAsn1Length(data, offset)
offset = bitStringOffset
// Skip the unused bits byte
val unusedBits = data[offset].toInt()
if (unusedBits != 0) {
throw IllegalArgumentException("Unsupported unused bits: $unusedBits")
}
offset += 1
// Extract the public key bytes
val pubKeyBytes = data.copyOfRange(offset, offset + (bitStringLength - 1))
offset = 0 // Reset offset for public key bytes
// Parse the public key SEQUENCE
if (pubKeyBytes[offset] != 0x30.toByte()) {
throw IllegalArgumentException("Invalid data: expected SEQUENCE at offset $offset")
}
offset += 1
val (pubKeySeqLength, pubKeySeqOffset) = readAsn1Length(pubKeyBytes, offset)
offset = pubKeySeqOffset
// Parse modulus INTEGER
if (pubKeyBytes[offset] != 0x02.toByte()) {
throw IllegalArgumentException("Invalid data: expected INTEGER (modulus) at offset $offset")
}
offset += 1
val (modulusLength, modulusOffset) = readAsn1Length(pubKeyBytes, offset)
offset = modulusOffset
val modulusBytes = pubKeyBytes.copyOfRange(offset, offset + modulusLength)
offset += modulusLength
// Parse exponent INTEGER
if (pubKeyBytes[offset] != 0x02.toByte()) {
throw IllegalArgumentException("Invalid data: expected INTEGER (exponent) at offset $offset")
}
offset += 1
val (exponentLength, exponentOffset) = readAsn1Length(pubKeyBytes, offset)
offset = exponentOffset
val exponentBytes = pubKeyBytes.copyOfRange(offset, offset + exponentLength)
// Construct BigIntegers
val modulus = BigInteger(1, modulusBytes)
val exponent = BigInteger(1, exponentBytes)
// Output the modulus and exponent
println("Modulus: $modulus")
println("Exponent (decimal): $exponent")
return createRSAPublicKey(modulus, exponent)
}
fun readAsn1Length(data: ByteArray, offset: Int): Pair<Int, Int> {
var idx = offset
var length = data[idx].toInt() and 0xFF
idx += 1
if (length > 127) {
val numLengthBytes = length and 0x7F
length = 0
for (i in 0 until numLengthBytes) {
length = (length shl 8) or (data[idx].toInt() and 0xFF)
idx += 1
}
}
return Pair(length, idx)
}
fun createRSAPublicKey(modulus: BigInteger, exponent: BigInteger): RSAPublicKey {
// Create an RSAPublicKeySpec with the modulus and exponent
val publicKeySpec = RSAPublicKeySpec(modulus, exponent)
// Get a KeyFactory for RSA
val keyFactory = KeyFactory.getInstance("RSA")
// Generate the public key from the key specification
val publicKey = keyFactory.generatePublic(publicKeySpec) as RSAPublicKey
return publicKey
}
| 1
|
Kotlin
|
0
| 5
|
c92dd78d59c40a09370acaded9ea5b01e80dc10d
| 3,820
|
rarime-android-app
|
MIT License
|
src/main/kotlin/io/sc3/goodies/enderstorage/EnderStorageBaseCommand.kt
|
SwitchCraftCC
| 529,969,303
| false
|
{"Kotlin": 275965, "Java": 16573}
|
package io.sc3.goodies.enderstorage
import com.mojang.brigadier.Command
import com.mojang.brigadier.context.CommandContext
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType
import io.sc3.goodies.ScGoodies.modId
import io.sc3.goodies.enderstorage.EnderStorageProvider.EnderStorageInventory
import io.sc3.goodies.util.parseDyeArg
import io.sc3.goodies.util.parseUserArg
import net.minecraft.server.command.ServerCommandSource
import net.minecraft.text.Text.translatable
abstract class EnderStorageBaseCommand(val private: Boolean) : Command<ServerCommandSource> {
fun getFrequency(ctx: CommandContext<ServerCommandSource>): Frequency {
val user = if (private) parseUserArg(ctx, "user") else null
return Frequency(
owner = user?.id,
ownerName = user?.name,
left = parseDyeArg(ctx, "left"),
middle = parseDyeArg(ctx, "middle"),
right = parseDyeArg(ctx, "right")
)
}
fun getInventory(ctx: CommandContext<ServerCommandSource>): Pair<EnderStorageInventory, Frequency> {
val frequency = getFrequency(ctx)
// Don't create the inventory if it doesn't exist, error instead
val inv = EnderStorageProvider.getInventory(ctx.source.server, frequency, create = false)
?: throw NO_FREQUENCY.create()
return inv to frequency
}
companion object {
val NO_FREQUENCY = SimpleCommandExceptionType(translatable("block.$modId.ender_storage.not_found"))
}
}
| 14
|
Kotlin
|
10
| 9
|
d06fac1d69664b5141ef7f91fbc2ca71e2b9c1c2
| 1,450
|
sc-goodies
|
MIT License
|
app/src/main/java/com/soyvictorherrera/bdates/modules/eventList/data/datasource/JSONArrayExtensions.kt
|
VictorHerreraO
| 442,241,064
| false
| null |
package com.soyvictorherrera.bdates.modules.eventList.data.datasource
import org.json.JSONArray
fun JSONArray.forEach(action: (Any) -> Unit) {
for (i in 0 until this.length()) {
action(this.get(i))
}
}
| 4
|
Kotlin
|
0
| 0
|
6892e1c0c2cbc31bdfcd3fd62a2d90d3e10c2497
| 220
|
bdates
|
MIT License
|
app/src/main/java/com/kasuminotes/ui/theme/Color.kt
|
chilbi
| 399,723,451
| false
| null |
package com.kasuminotes.ui.theme
import androidx.compose.material.Colors
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
val PrimaryColor = Color(0xFF5F96F5)
val PrimaryVariantColor = Color(0xFF5B88E6)
val SecondaryColor = Color(0xFFF55F96)
val SecondaryVariantColor = Color(0xFFF2397E)
val ImmersiveSysUi = Color(0x33000000)
val ShadowColor = Color(0x775E6FA2)
val LightPlace = Color(0xFFE0E0E0)
val DarkPlace = Color(0xFF3F3F3F)
val BorderColor = Color(0x335E6FA2)
val UniqueColor = Color(0xFFD34BEF)
val Positive = Color(0xFF0097A7)
val Negative = Color(0xFFE64A19)
val LightError = Color(0xFFFFCDD2)
val DarkError = Color(0xFFE53935)
val LightWarning = Color(0xFFFFE082)
val DarkWarning = Color(0xFFFFA000)
val LightInfo = Color(0xFFB3E5FC)
val DarkInfo = Color(0xFF039BE5)
val LightSuccess = Color(0xFFA5D6A7)
val DarkSuccess = Color(0xFF388E3C)
val Colors.place: Color
get() = if (isLight) LightPlace else DarkPlace
val Colors.selected: Color
get() = if (isLight) LightWarning else DarkWarning
val GrayFilter by lazy {
ColorFilter.colorMatrix(
ColorMatrix().apply {
setToSaturation(0f)
}
)
}
val LightColorPalette = lightColors(
primary = PrimaryColor,
primaryVariant = PrimaryVariantColor,
secondary = SecondaryColor,
secondaryVariant = SecondaryVariantColor,
// background = Color.White,
// surface = Color.White,
// error = Color(0xFFB00020),
onPrimary = Color.White,
onSecondary = Color.White,
// onBackground = Color.Black,
// onSurface = Color.Black,
// onError = Color.White
)
val DarkColorPalette = darkColors(
primary = PrimaryColor,
primaryVariant = PrimaryVariantColor,
secondary = SecondaryColor,
secondaryVariant = SecondaryVariantColor,
// background = Color(0xFF121212),
// surface = Color(0xFF121212),
// error = Color(0xFFCF6679),
onPrimary = Color.White,
onSecondary = Color.White,
// onBackground = Color.White,
// onSurface = Color.White,
// onError = Color.Black
)
val Int.rankRarity: Int
get() = when {
this > 23 -> 8
this > 20 -> 7
this > 17 -> 6
this > 10 -> 5
this > 6 -> 4
this > 3 -> 3
this > 1 -> 2
else -> 1
}
data class RarityColors(
val highLight: Color,
val light: Color,
val middle: Color,
val dark: Color,
val deepDark: Color
)
object RaritiesColors {
private val r8: RarityColors by lazy {
RarityColors(
highLight = Color(0xFFFFEEAA),
light = Color(0xFFFF6339),
middle = Color(0xFFFFA819),
dark = Color(0xFFFF6611),
deepDark = Color(0xFFB03010)
)
}
private val r7: RarityColors by lazy {
RarityColors(
highLight = Color(0xFF67DE9A),
light = Color(0xFF21D673),
middle = Color(0xFF00c660),
dark = Color(0xFF106241),
deepDark = Color(0xFF224444)
)
}
private val r6: RarityColors by lazy {
RarityColors(
highLight = Color(0xFFFCA7A7),
light = Color(0xFFEF6778),
middle = Color(0xFFEB5252),
dark = Color(0xFFE12648),
deepDark = Color(0xFF614048)
)
}
private val r5: RarityColors by lazy {
RarityColors(
highLight = Color(0xFFF4B0FF),
light = Color(0xFFCC77FF),
middle = Color(0xFFD086F1),
dark = Color(0xFF9F4AF4),
deepDark = Color(0xFF474769)
)
}
private val r4: RarityColors by lazy {
RarityColors(
highLight = Color(0xFFFFEE99),
light = Color(0xFFFAE276),
middle = Color(0xFFFDCA64),
dark = Color(0xFFEFAB34),
deepDark = Color(0xFF665544)
)
}
private val r3: RarityColors by lazy {
RarityColors(
highLight = Color(0xFFFFFFFF),
light = Color(0xFFD6E7F7),
middle = Color(0xFFC1C1D2),
dark = Color(0xFFABABCD),
deepDark = Color(0xFF555577)
)
}
private val r2: RarityColors by lazy {
RarityColors(
highLight = Color(0xFFFFD5B3),
light = Color(0xFFFFBB99),
middle = Color(0xFFFA9461),
dark = Color(0xFFCD7845),
deepDark = Color(0xFF774433)
)
}
private val r1: RarityColors by lazy {
RarityColors(
highLight = Color(0xFF88DDFF),
light = Color(0xFF51BDF6),
middle = Color(0xFF7FB0EA),
dark = Color(0xFF4882DC),
deepDark = Color(0xFF3B6EB2)
)
}
fun getRarityColors(rankRarity: Int): RarityColors = when (rankRarity) {
8 -> r8
7 -> r7
6 -> r6
5 -> r5
4 -> r4
3 -> r3
2 -> r2
else -> r1
}
}
| 0
|
Kotlin
|
0
| 0
|
9f06b7e33c0aa5f615688a49716f70cf022ed4ff
| 5,082
|
KasumiNotes
|
Apache License 2.0
|
library/src/main/java/io/github/chenfei0928/view/Choreographer.kt
|
chenfei0928
| 130,954,695
| false
|
{"Kotlin": 938893, "Java": 336337}
|
package io.github.chenfei0928.view
import android.os.Build
import android.view.Choreographer
import androidx.annotation.RequiresApi
/**
* @author chenfei()
* @date 2022-07-06 18:54
*/
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
inline fun Choreographer.postFrameCallbackDelayed(
delayMillis: Long, crossinline block: (Long) -> Unit
) {
postFrameCallbackDelayed({ block(it) }, delayMillis)
}
| 0
|
Kotlin
|
0
| 7
|
7171bfa3022cd9d4b2a26e3f1329a31ce008dfec
| 405
|
Util
|
MIT License
|
compiler/testData/writeFlags/hidden/propertySetter.kt
|
JakeWharton
| 99,388,807
| true
| null |
// IGNORE_BACKEND: JVM_IR
class MyClass() {
@Deprecated("hidden", level = DeprecationLevel.HIDDEN)
var test: Int
get() = 0
set(value) {}
}
// TESTED_OBJECT_KIND: function
// TESTED_OBJECTS: MyClass, setTest
// FLAGS: ACC_SYNTHETIC, ACC_PUBLIC, ACC_FINAL, ACC_DEPRECATED
| 179
|
Kotlin
|
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 295
|
kotlin
|
Apache License 2.0
|
src/jvmMain/kotlin/com/outsidesource/oskitcompose/systemui/KMPWindowInfo.desktop.kt
|
outsidesource
| 607,444,788
| false
|
{"Kotlin": 303688}
|
package com.outsidesource.oskitcompose.systemui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.input.pointer.PointerKeyboardModifiers
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.unit.IntSize
@OptIn(ExperimentalComposeUiApi::class)
@Composable
actual fun rememberKMPWindowInfo(): KMPWindowInfo {
val windowInfo = LocalWindowInfo.current
return remember(windowInfo) {
object : KMPWindowInfo {
override val isWindowFocused: Boolean
get() = windowInfo.isWindowFocused
override val keyboardModifiers: PointerKeyboardModifiers
get() = windowInfo.keyboardModifiers
override val containerSize: IntSize
get() = windowInfo.containerSize
}
}
}
| 0
|
Kotlin
|
1
| 6
|
1944fbf21f17ea550a79d44c52cbf67363125694
| 898
|
OSKit-Compose-KMP
|
MIT License
|
gradle/plugins/src/main/kotlin/io/github/droidkaigi/confsched2022/primitive/KotlinSerializationPlugin.kt
|
DroidKaigi
| 517,191,221
| false
| null |
package io.github.droidkaigi.confsched2022.primitive
import org.gradle.api.Plugin
import org.gradle.api.Project
@Suppress("unused")
class KotlinSerializationPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
with(pluginManager) {
apply("org.jetbrains.kotlin.plugin.serialization")
}
}
}
}
| 49
| null |
201
| 491
|
f0ae974c7862e3ff4d70c4841d93ea64bff11ce1
| 385
|
conference-app-2022
|
Apache License 2.0
|
tempest2-testing-internal/src/main/kotlin/app/cash/tempest2/testing/internal/TestUtils.kt
|
cashapp
| 270,829,467
| false
| null |
/*
* Copyright 2021 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.tempest2.testing.internal
import app.cash.tempest2.testing.TestTable
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient
import software.amazon.awssdk.enhanced.dynamodb.TableSchema
import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest
import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient
import software.amazon.awssdk.services.dynamodb.DynamoDbClient
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput
import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsAsyncClient
import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient
import java.net.ServerSocket
import java.net.URI
fun pickRandomPort(): Int {
ServerSocket(0).use { socket -> return socket.localPort }
}
private val AWS_CREDENTIALS_PROVIDER = StaticCredentialsProvider.create(
AwsBasicCredentials.create("key", "secret")
)
fun connect(port: Int): DynamoDbClient {
return DynamoDbClient.builder()
// The values that you supply for the AWS access key and the Region are only used to name
// the database file.
.credentialsProvider(AWS_CREDENTIALS_PROVIDER)
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:$port"))
.build()
}
fun connectAsync(port: Int): DynamoDbAsyncClient {
return DynamoDbAsyncClient.builder()
// The values that you supply for the AWS access key and the Region are only used to name
// the database file.
.credentialsProvider(AWS_CREDENTIALS_PROVIDER)
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:$port"))
.build()
}
fun connectToStreams(port: Int): DynamoDbStreamsClient {
return DynamoDbStreamsClient.builder()
// The values that you supply for the AWS access key and the Region are only used to name
// the database file.
.credentialsProvider(AWS_CREDENTIALS_PROVIDER)
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:$port"))
.build()
}
fun connectToStreamsAsync(port: Int): DynamoDbStreamsAsyncClient {
return DynamoDbStreamsAsyncClient.builder()
// The values that you supply for the AWS access key and the Region are only used to name
// the database file.
.credentialsProvider(AWS_CREDENTIALS_PROVIDER)
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:$port"))
.build()
}
fun DynamoDbClient.createTable(
table: TestTable
) {
val enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(this)
.build()
var tableRequest = CreateTableEnhancedRequest.builder()
// Provisioned throughput needs to be specified when creating the table. However,
// DynamoDB Local ignores your provisioned throughput settings. The values that you specify
// when you call CreateTable and UpdateTable have no effect. In addition, DynamoDB Local
// does not throttle read or write activity.
.provisionedThroughput(
ProvisionedThroughput.builder().readCapacityUnits(1L).writeCapacityUnits(1L).build()
)
.build()
tableRequest = table.configureTable(tableRequest)
enhancedClient.table(table.tableName, TableSchema.fromClass(table.tableClass.java))
.createTable(tableRequest)
}
| 14
|
Kotlin
|
14
| 62
|
f96cebd6323f97adfc0afda5ec2a476787a90966
| 4,032
|
tempest
|
Apache License 2.0
|
android/feature/setting/src/main/java/com/jaino/setting/SettingFragment.kt
|
pknu-wap
| 615,959,763
| false
| null |
package com.jaino.setting
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.jaino.common.model.UiEvent
import com.jaino.common.navigation.AppNavigator
import com.jaino.common.widget.ErrorDialog
import com.jaino.setting.databinding.FragmentSettingBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
@AndroidEntryPoint
class SettingFragment : Fragment() {
@Inject
lateinit var appNavigator: AppNavigator
private var _binding: FragmentSettingBinding? = null
private val binding
get() = requireNotNull(_binding) { "binding object is not initialized" }
private val viewModel : SettingViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DataBindingUtil.inflate(inflater, R.layout.fragment_setting, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewModelStates()
initButtons()
observeData()
}
private fun initViewModelStates(){
viewModel.getNickname()
}
private fun initButtons(){
binding.settingBackButton.setOnClickListener {
navigateToHome()
}
binding.settingAccountCardView.setOnClickListener {
navigateToAccount()
}
binding.settingProfileCardView.setOnClickListener {
navigateToProfile()
}
binding.historyCardView.setOnClickListener {
navigateToHistory()
}
}
private fun initNicknameColor(){
val text = binding.settingNicknameTitle.text
val spannable = SpannableStringBuilder(text)
spannable.setSpan(
ForegroundColorSpan(Color.BLACK),
text.length - 15, text.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
binding.settingNicknameTitle.text = spannable
}
private fun observeData(){
viewModel.settingUiEvent.flowWithLifecycle(viewLifecycleOwner.lifecycle)
.onEach {
when(it){
is UiEvent.Failure ->{
showErrorDialog(it.error)
}
is UiEvent.Success -> { }
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
viewModel.nicknameState.flowWithLifecycle(viewLifecycleOwner.lifecycle)
.onEach {
if(it.isNotEmpty()){
initNicknameColor()
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
}
private fun showErrorDialog(error: Throwable){
ErrorDialog(
requireContext(),
error = error,
onRetryButtonClick = {
viewModel.getNickname()
}
).show()
}
private fun navigateToHome(){
findNavController().navigate("BeJuRyu://feature/home".toUri())
}
private fun navigateToAccount(){
startActivity(appNavigator.navigateToAccount())
}
private fun navigateToProfile(){
findNavController().navigate(
R.id.action_settingFragment_to_profileFragment
)
}
private fun navigateToHistory(){
findNavController().navigate(
R.id.action_settingFragment_to_historyFragment
)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 1
|
Kotlin
|
3
| 9
|
f2144cb5f19d0617b146b94fcc3058f330f2df41
| 4,242
|
2023_1_WAT_BeJuRyu
|
MIT License
|
src/main/kotlin/pl/komorowskidev/kotlinrest/InitApplication.kt
|
komorowskidev
| 312,876,443
| false
| null |
package pl.komorowskidev.kotlinrest
import org.apache.logging.log4j.LogManager
import org.springframework.stereotype.Component
import pl.komorowskidev.kotlinrest.db.services.AccountTypeService
import pl.komorowskidev.kotlinrest.db.services.CustomerService
import pl.komorowskidev.kotlinrest.db.services.DbService
import pl.komorowskidev.kotlinrest.db.services.TransactionService
import pl.komorowskidev.kotlinrest.file.FileLoader
import pl.komorowskidev.kotlinrest.properties.DataFilePathName
import pl.komorowskidev.kotlinrest.util.converters.AccountTypeConverter
import pl.komorowskidev.kotlinrest.util.converters.CustomerConverter
import pl.komorowskidev.kotlinrest.util.converters.TransactionConverter
import java.io.IOException
@Component
class InitApplication(
dbService: DbService,
private val dataFilePathName: DataFilePathName,
private val accountTypeConverter: AccountTypeConverter,
private val customerConverter: CustomerConverter,
private val transactionConverter: TransactionConverter,
private val fileLoader: FileLoader,
private val accountTypeService: AccountTypeService,
private val customerService: CustomerService,
private val transactionService: TransactionService) {
companion object {
private val logger = LogManager.getLogger()
}
init {
dbService.clearDataBase()
try {
loadExampleData()
} catch(e: IOException) {
logger.error("File not found. {}", e.message)
}
dbService.removeTemporaryCollection("account-type")
dbService.removeTemporaryCollection("customer")
}
@Throws(IOException::class)
private fun loadExampleData(){
fileLoader.load(
dataFilePathName.accountTypes,
accountTypeConverter,
accountTypeService)
fileLoader.load(
dataFilePathName.customers,
customerConverter,
customerService)
fileLoader.load(
dataFilePathName.transactions,
transactionConverter,
transactionService)
}
}
| 0
|
Kotlin
|
0
| 0
|
201470cda10f026b151ba17a5a8d94ceeb85a6ac
| 2,127
|
kotlin-rest
|
MIT License
|
app/src/main/java/com/sayaradz/views/activities/LoginActivity.kt
|
sayaradz
| 170,285,633
| false
| null |
package com.sayaradz.views.activities
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import com.facebook.*
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FacebookAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.sayaradz.R
import com.sayaradz.viewModels.UserViewModel
import kotlinx.android.synthetic.main.activity_login.*
import org.json.JSONException
/**
* A login screen that offers login via google/facebook.
**/
class LoginActivity : AppCompatActivity() {
private val rcSignIn: Int = 555
private var fb: Int = 1
private lateinit var mGoogleSignInClient: GoogleSignInClient
private lateinit var mAuth: FirebaseAuth
private var mUserViewModel: UserViewModel? = null
private lateinit var progressBar: ProgressBar
private lateinit var callbackManager: CallbackManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
mAuth = FirebaseAuth.getInstance()
setupUI()
}
private fun setupUI() {
progressBar = this.progressBar1
button_facebook_login_copy.setOnClickListener {
buttonFacebookLogin.performClick()
}
buttonFacebookLogin.setOnClickListener {
signInFacebook()
progressBar.visibility = View.VISIBLE
loading_background.visibility = View.VISIBLE
}
configureGoogleSignIn()
google_btn.setOnClickListener {
signInGoogle()
progressBar.visibility = View.VISIBLE
loading_background.visibility = View.VISIBLE
}
}
// ------------------------------ FACEBOOK LOGIN -------------------------------//
private fun signInFacebook() {
fb = 0
callbackManager = CallbackManager.Factory.create()
buttonFacebookLogin.setReadPermissions("email", "public_profile")
buttonFacebookLogin.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
Log.d("", "facebook:onSuccess:$loginResult")
handleFacebookAccessToken(loginResult.accessToken)
graphLoginRequest(loginResult.accessToken)
}
override fun onCancel() {
progressBar.visibility = View.GONE
loading_background.visibility = View.GONE
Toast.makeText(this@LoginActivity, "facebook Login annulé", Toast.LENGTH_SHORT).show()
}
override fun onError(error: FacebookException) {
progressBar.visibility = View.GONE
loading_background.visibility = View.GONE
Toast.makeText(this@LoginActivity, "facebook Login erreur!", Toast.LENGTH_SHORT).show()
}
})
}
// Method to access Facebook User Data.
private fun graphLoginRequest(accessToken: AccessToken) {
val graphRequest = GraphRequest.newMeRequest(
accessToken
) { jsonObject, _ ->
try {
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val editor = prefs.edit()
editor.putString("fullName", jsonObject.getString("name"))
editor.putString(
"profilePicLink",
"https://graph.facebook.com/${jsonObject.getString("id")}/picture?type=large"
)
editor.putString("address", jsonObject.getString("email"))
editor.apply()
} catch (e: JSONException) {
e.printStackTrace()
}
}
val bundle = Bundle()
bundle.putString(
"fields",
"id,name,link,email,gender,last_name,first_name,locale,timezone,updated_time,verified"
)
graphRequest.parameters = bundle
graphRequest.executeAsync()
}
private fun handleFacebookAccessToken(token: AccessToken) {
Log.d("tag", "handleFacebookAccessToken:$token")
val credential = FacebookAuthProvider.getCredential(token.token)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
startActivity(MainActivity.getLaunchIntent(this))
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInWithCredential:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show()
}
}
}
// ------------------------------ END FACEBOOK LOGIN -------------------------------//
// --------------------------- START GOOGLE LOGIN -------------------------------//
private fun configureGoogleSignIn() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
}
private fun signInGoogle() {
fb = 1
val signInIntent = mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent, rcSignIn)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (fb == 0) callbackManager.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == rcSignIn) {
Log.e("Tag", "Discover: " + data!!.getParcelableExtra("googleSignInStatus"))
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)
firebaseAuthWithGoogle(account!!)
} catch (e: ApiException) {
progressBar.visibility = View.GONE
loading_background.visibility = View.GONE
// Google Sign In failed, update UI appropriately
Log.w("Login", "Google sign in failed", e)
Toast.makeText(this, "Auth Failed", Toast.LENGTH_LONG).show()
// ...
}
}
}
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
Log.d("", "firebaseAuthWithGoogle:" + acct.id!!)
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d("", "signInWithCredential:success")
val user = mAuth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w("", "signInWithCredential:failure", task.exception)
Toast.makeText(this, "Auth Failed", Toast.LENGTH_LONG).show()
updateUI(null)
}
// ...
}
}
private fun updateUI(user: FirebaseUser?) {
if (user != null) {
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val editor = prefs.edit()
editor.putString("fullName", user.displayName)
editor.putString("profilePicLink", user.photoUrl.toString())
editor.putString("address", user.email)
editor.putString("id", user.uid)
editor.apply()
mUserViewModel = UserViewModel(user.email!!, user.uid, "")
progressBar.visibility = View.GONE
loading_background.visibility = View.GONE
startActivity(MainActivity.getLaunchIntent(this))
finish()
}
}
// ------------------------------ END GOOGLE LOGIN -------------------------------//
override fun onStart() {
super.onStart()
val currentUser = mAuth.currentUser
updateUI(currentUser)
}
companion object {
fun getLaunchIntent(from: Context) = Intent(from, LoginActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
}
}
| 0
|
Kotlin
|
1
| 2
|
15d54c6e9c959fafdd84703dbf63ae9245aa08ce
| 9,314
|
sayaradz_android
|
MIT License
|
android/app/src/main/kotlin/com/example/jluquebarberia_appreservas/MainActivity.kt
|
iamlolo-dev
| 469,640,108
| false
|
{"Dart": 17227, "Swift": 404, "Kotlin": 143, "Objective-C": 38}
|
package com.example.jluquebarberia_appreservas
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
1b3f3b3b74be31ac5f3baf97d7c75422aecc010f
| 143
|
APPReservas_JLuqueBarberia
|
Apache License 2.0
|
src/main/kotlin/dev/rmcmk/gspm/gradle/module/GradleModule.kt
|
rmcmk
| 750,875,199
| false
|
{"Kotlin": 23605}
|
package dev.rmcmk.gradle.gmvmb
import org.gradle.tooling.model.GradleModuleVersion
import org.gradle.tooling.model.Model
import java.io.Serializable
/**
* Represents a serializable Gradle module.
*
* @author <NAME> <<EMAIL>>
*/
interface GradleModule : Model, Serializable {
/** The absolute path to the module. */
val path: String
/** The version of the module. */
val version: GradleModuleVersion
/** The child modules of this module. */
val children: List<GradleModule>
}
/**
* The default implementation of [GradleModule].
*
* @author <NAME> <<EMAIL>>
*/
data class DefaultGradleModule(
override val path: String,
override val version: GradleModuleVersion,
override val children: List<GradleModule>,
) : GradleModule
| 0
|
Kotlin
|
0
| 1
|
81c435da12872aa163c67b9d84bd7dc4b068f51a
| 770
|
gspm
|
MIT License
|
app/src/main/java/org/bidon/demoapp/MainActivity.kt
|
bidon-io
| 654,165,570
| false
|
{"Kotlin": 1049134, "Java": 2186}
|
package org.bidon.demoapp
import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Pets
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.fragment.app.FragmentActivity
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import kotlinx.coroutines.launch
import org.bidon.demoapp.navigation.NavigationGraph
import org.bidon.demoapp.theme.AppTheme
import org.bidon.demoapp.ui.SdkSettings
import org.bidon.demoapp.ui.TestModeKey
import org.bidon.demoapp.ui.settings.TestModeInfo
class MainActivity : FragmentActivity() {
@RequiresApi(Build.VERSION_CODES.Q)
@OptIn(ExperimentalPermissionsApi::class, ExperimentalMaterialApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val coroutineScope = rememberCoroutineScope()
val modalSheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
confirmStateChange = { it != ModalBottomSheetValue.HalfExpanded },
skipHalfExpanded = true,
)
AppTheme {
val navController = rememberNavController()
LocalContext.current.getSharedPreferences("app_test", Context.MODE_PRIVATE).let {
TestModeInfo.isTesMode.value = it.getBoolean(TestModeKey, false)
}
ModalBottomSheetLayout(
modifier = Modifier,
sheetState = modalSheetState,
sheetShape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp),
sheetContent = {
SdkSettings()
}
) {
Box(
modifier = Modifier
.fillMaxSize()
) {
Column {
NavigationGraph(
navController = navController,
)
}
FloatingActionButton(
modifier = Modifier
.safeDrawingPadding()
.align(Alignment.BottomEnd)
.padding(24.dp),
onClick = {
coroutineScope.launch { modalSheetState.show() }
},
containerColor = MaterialTheme.colorScheme.primary,
shape = CircleShape,
) {
Icon(
imageVector = Icons.Rounded.Pets,
contentDescription = "Add FAB",
tint = Color.White,
)
}
// Box(
// modifier = Modifier
// .size(100.dp)
// .background(Color.Red)
// )
// Box(
// modifier = Modifier
// .size(100.dp)
// .background(Color.Red)
// .align(Alignment.BottomEnd)
// )
}
}
}
val permissionsState = rememberMultiplePermissionsState(
permissions = listOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
)
)
LaunchedEffect(key1 = Unit, block = {
permissionsState.permissions
.firstOrNull { !it.status.isGranted }
?.launchPermissionRequest()
})
}
}
}
@Composable
fun HideSystemBars() {
val context = LocalContext.current
DisposableEffect(Unit) {
val window = (context as Activity).window
val insetsController = WindowCompat.getInsetsController(window, window.decorView)
insetsController.apply {
hide(WindowInsetsCompat.Type.statusBars())
hide(WindowInsetsCompat.Type.navigationBars())
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
onDispose {
insetsController.apply {
show(WindowInsetsCompat.Type.statusBars())
show(WindowInsetsCompat.Type.navigationBars())
// systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_DEFAULT
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ac4906b014f0901fd2ce2a3e593ef9d777cb0edc
| 6,404
|
bidon_sdk_android
|
Apache License 2.0
|
core/src/main/java/com/bruno13palhano/core/network/model/CategoryNet.kt
|
bruno13palhano
| 670,001,130
| false
|
{"Kotlin": 1392940}
|
package com.bruno13palhano.core.network.model
import com.bruno13palhano.core.model.Model
import com.squareup.moshi.Json
data class CategoryNet(
@Json(name = "id") override val id: Long,
@Json(name = "category") val category: String,
@Json(name = "timestamp") override val timestamp: String,
) : Model(id = id, timestamp = timestamp)
| 0
|
Kotlin
|
0
| 2
|
bffdfff8cc2ee93114a9b01821ba22d959a6a781
| 347
|
shop-dani-management
|
MIT License
|
app/src/main/java/com/ebf/instant/data/network/auth/datasources/AuthStateUserDataSource.kt
|
vinceglb
| 417,691,337
| false
|
{"Kotlin": 120689, "TypeScript": 10921, "JavaScript": 728}
|
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.data.signin.datasources
import com.google.samples.apps.iosched.shared.data.signin.AuthenticatedUserInfoBasic
import com.google.samples.apps.iosched.shared.result.Result
import kotlinx.coroutines.flow.Flow
/**
* Listens to an Authentication state data source that emits updates on the current user.
*
* @see FirebaseAuthStateUserDataSource
*/
interface AuthStateUserDataSource {
/**
* Returns an observable of the [AuthenticatedUserInfoBasic].
*/
fun getBasicUserInfo(): Flow<Result<AuthenticatedUserInfoBasic?>>
}
| 77
|
Kotlin
|
6259
| 76
|
c9f7ef097daecc26437873f01027aab74c3891b7
| 1,181
|
Instant
|
MIT License
|
cinescout/movies/data/remote/tmdb/src/commonMain/kotlin/cinescout/movies/data/remote/tmdb/mapper/TmdbMovieVideosMapper.kt
|
4face-studi0
| 280,630,732
| false
| null |
package cinescout.movies.data.remote.tmdb.mapper
import cinescout.common.model.TmdbVideo
import cinescout.common.model.TmdbVideoId
import cinescout.movies.data.remote.tmdb.model.GetMovieVideos
import cinescout.movies.domain.model.MovieVideos
import org.koin.core.annotation.Factory
@Factory
internal class TmdbMovieVideosMapper {
fun toMovieVideos(videos: GetMovieVideos.Response) = MovieVideos(
movieId = videos.movieId,
videos = videos.videos.map(::toVideo)
)
private fun toVideo(video: GetMovieVideos.Response.Video): TmdbVideo {
val resolution = when {
video.size < 1080 -> TmdbVideo.Resolution.SD
video.size == 1080 -> TmdbVideo.Resolution.FHD
video.size == 2160 -> TmdbVideo.Resolution.UHD
else -> throw IllegalArgumentException("Unknown video resolution: ${video.size}")
}
val site = when (video.site) {
"YouTube" -> TmdbVideo.Site.YouTube
else -> throw IllegalArgumentException("Unknown video site: ${video.site}")
}
val type = when (video.type) {
"Behind the Scenes" -> TmdbVideo.Type.BehindTheScenes
"Bloopers" -> TmdbVideo.Type.Bloopers
"Clip" -> TmdbVideo.Type.Clip
"Featurette" -> TmdbVideo.Type.Featurette
"Teaser" -> TmdbVideo.Type.Teaser
"Trailer" -> TmdbVideo.Type.Trailer
else -> throw IllegalArgumentException("Unknown video type: ${video.type}")
}
return TmdbVideo(
id = TmdbVideoId(video.id),
key = video.key,
site = site,
resolution = resolution,
title = video.name,
type = type
)
}
}
| 19
|
Kotlin
|
2
| 3
|
d64398507d60a20a445db1451bdd8be23d65c9aa
| 1,735
|
CineScout
|
Apache License 2.0
|
app/src/main/java/com/jerey/klog/MainActivity.kt
|
Jerey-Jobs
| 92,164,479
| false
| null |
package com.jerey.klog
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import com.jerey.loglib.Klog
import com.jerey.loglib.log
class MainActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/**
* Klog 使用demo
*/
var str = "nihao"
str.log() //直接输出该对象toString
.toUpperCase()
.log("upper") //输出带提示的处理结果
.toLowerCase() //继续处理
.log("lower")
//修改Klog设置, 开启边框打印
Klog.getSettings()
.setBorderEnable(true)
Klog.a("aaaaaaa") //普通log输出方式1
Klog.a(contents = "bbbbb") //普通log输出方式2
Klog.i("jerey", "aaaaaaa") //带tag输出
var list = arrayListOf<String>("aaa", "bb", "cccc", "ddddd")
list.log("init")
.map { it -> it.toUpperCase() }
.log("after map")
.filter { it -> it.length > 2 }
.log("after filter")
}
}
| 1
|
Kotlin
|
6
| 21
|
2614200f7ccb86d06b2a16546852141571e2cc1f
| 1,260
|
Klog
|
Apache License 2.0
|
app/src/main/java/com/dluvian/voyage/data/provider/RelayProfileProvider.kt
|
dluvian
| 766,355,809
| false
|
{"Kotlin": 757648}
|
package com.dluvian.voyage.data.provider
import android.util.Log
import com.dluvian.voyage.data.nostr.RelayUrl
import rust.nostr.protocol.RelayInformationDocument
import rust.nostr.protocol.nip11GetInformationDocument
import java.util.Collections
private const val TAG = "RelayProfileProvider"
class RelayProfileProvider {
private val cache =
Collections.synchronizedMap(mutableMapOf<RelayUrl, RelayInformationDocument>())
suspend fun getRelayProfile(httpsUrl: String): RelayInformationDocument? {
val cached = cache[httpsUrl]
if (cached != null) return cached
val fromNetwork = kotlin.runCatching {
nip11GetInformationDocument(url = httpsUrl)
}.onFailure {
Log.w(TAG, "Failed to fetch RelayProfile of $httpsUrl", it)
}.getOrNull()
if (fromNetwork != null) cache[httpsUrl] = fromNetwork
return fromNetwork
}
}
| 45
|
Kotlin
|
4
| 31
|
08ca1e3d99c6d5fb8f7286dbe7c81c2c608eda88
| 917
|
voyage
|
MIT License
|
showkase-processor-testing/src/test/resources/ShowkaseProcessorTest/composable_function_with_multiple_showkasecomposable_annotations_stacked_generates_output/input/Composables.kt
|
airbnb
| 257,758,318
| false
|
{"Kotlin": 715619}
|
package com.airbnb.android.showkase_processor_testing
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.runtime.Composable
import androidx.compose.ui.semantics.SemanticsProperties.Text
import androidx.compose.ui.tooling.preview.Preview
import com.airbnb.android.showkase.annotation.ShowkaseComposable
@ShowkaseComposable(
name = "small font",
group = "font scales",
widthDp = 250,
heightDp = 250,
)
@ShowkaseComposable(
name = "large font",
group = "font scales",
widthDp = 200,
heightDp = 200,
)
@Composable
public fun StackedShowkaseComposables() {
}
| 50
|
Kotlin
|
106
| 2,073
|
9c3d6fc313d63b8f555fc65232ac15f798aede9a
| 620
|
Showkase
|
Apache License 2.0
|
src/Day10.kt
|
aneroid
| 572,802,061
| false
|
{"Kotlin": 27313}
|
import Operation.*
private enum class Operation(val cycleCost: Int) {
NOOP(1),
ADDX(2),
;
companion object {
fun fromString(s: String): Operation =
values().first { it.name == s.uppercase() }
}
}
private class CPU(var accX: Int = 1) {
private var cycle = 1
private val cyclesOfInterest = 20..220 step 40
val signalStrengths = mutableListOf<Int>()
// variables added for part 2
val pixels = mutableListOf(mutableListOf<Char>())
val spriteSize = 3
private fun processCycle() {
if (cycle in cyclesOfInterest) {
// println(" *** processCycle: $cycle")
signalStrengths += signalStrength()
}
// drawSprite
val crtPos = (cycle - 1) % 40
val spritePos = accX - 1
pixels.last().add(if (crtPos in spritePos until spritePos + spriteSize) '#' else '.')
if (cycle % 40 == 0) {
pixels.add(mutableListOf())
}
}
private fun signalStrength(): Int = accX * cycle
fun execute(op: Operation, arg: Int) {
repeat(op.cycleCost) {
// println(" cycle $cycle: accX = $accX")
processCycle()
cycle++
}
when (op) {
NOOP -> Unit
ADDX -> accX += arg
}
}
}
class Day10(input: List<String>) {
private val program = input.map {
it.substring(0, 4).toOP() to it.substringAfter(" ", "0").toInt()
}
private fun String.toOP() = Operation.fromString(this)
private fun processProgram(): CPU =
CPU().apply {
program.forEach { (instr, arg) ->
// println("${instr.name} $arg")
execute(instr, arg)
}
}
fun partOne(): Int {
val cpu = processProgram()
println("signal strengths: ${cpu.signalStrengths}")
return cpu.signalStrengths.sum()
}
fun partTwo(): List<String> {
val cpu = processProgram()
println(cpu.pixels.joinToString("\n") {
it.joinToString("")
// .replace(".", " ")
// .replace("#", "█")
.replace(".", "⚫️️")
.replace("#", "⚪")
})
return cpu.pixels.map { it.joinToString("") }
}
}
fun main() {
val testInput = readInput("Day10_test")
val input = readInput("Day10")
println("part One:")
assertThat(Day10(testInput).partOne()).isEqualTo(13140)
println("actual: ${Day10(input).partOne()}\n")
println("part Two:")
// uncomment when ready
val expectedOutputPart2 = """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent().lines()
assertThat(Day10(testInput).partTwo().take(6)).isEqualTo(expectedOutputPart2)
println("actual: ${Day10(input).partTwo()}\n")
}
| 0
|
Kotlin
|
0
| 0
|
cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd
| 3,102
|
advent-of-code-2022-kotlin
|
Apache License 2.0
|
test4k/src/main/kotlin/com/github/christophpickl/kpotpourri/test4k/assertions.kt
|
christophpickl
| 83,411,497
| false
| null |
package com.github.christophpickl.kpotpourri.test4k
import org.testng.Assert
import java.io.PrintWriter
import java.io.StringWriter
/**
* Global function supporting nulls as causes.
*/
fun fail(message: String, cause: Throwable? = null) {
if (cause != null) {
Assert.fail(message, cause)
} else {
Assert.fail(message) // cause must not be null
}
}
/**
* Tests for correct exception type (or supertype).
*/
inline fun <reified E : Throwable> assertThrown(code: () -> Unit) {
assertThrown<E>({ true }, code)
}
/**
* Tests for correct exception type and message.
*/
inline fun <reified E : Throwable> assertThrown(expectedMessage: String, code: () -> Unit) {
assertThrown<E>({ it.message == expectedMessage }, code)
}
/**
* Tests for correct exception type and message subparts.
*/
inline fun <reified E : Throwable> assertThrown(expectedMessageParts: List<String>, code: () -> Unit) {
assertThrown<E>({ it.message!!.__containsAll(expectedMessageParts) }, code)
}
/**
* Duplicate from common4k, in order to avoid cyclic dependency.
*/
fun String.__containsAll(substrings: List<String>, ignoreCase: Boolean = false) =
substrings.all { this.contains(it, ignoreCase) }
/**
* Expect an exception to be thrown which can be individually checked for correctness.
*/
inline fun <reified E : Throwable> assertThrown(matcher: (E) -> Boolean, code: () -> Unit) {
val expectedExceptionType = E::class.java.simpleName
try {
code()
fail("Expected an exception to be thrown of type $expectedExceptionType")
} catch (t: Throwable) {
if (t !is E) {
fail("Unexpected exception type (${t.javaClass.simpleName}) was thrown!\n${t.toStackTrace()}")
} else if (!matcher(t)) {
fail("Unexpected exception was thrown! Expected a $expectedExceptionType but was thrown:\n${t.toStackTrace()}")
}
// thrown exception matched, everything is OK
}
}
/**
* Utility method to transform the stack trace to its string representation.
*/
fun Throwable.toStackTrace(): String {
val writer = StringWriter()
printStackTrace(PrintWriter(writer))
return writer.toString()
}
| 0
|
Kotlin
|
0
| 4
|
eb6ad4d00be86ce88417d32dcb49370a632a9c1e
| 2,200
|
kpotpourri
|
Apache License 2.0
|
services/customer-service/src/main/kotlin/io/github/rafaeljpc/tutorial/ktor/services/model/Customer.kt
|
rafaeljpc
| 211,521,384
| false
| null |
package io.github.rafaeljpc.tutorial.ktor.services.model
data class Customer(
var id: Long = 0,
var name: String,
var email: String
)
| 0
|
Kotlin
|
0
| 1
|
0c820a24236431ee39193e45520b269165130c48
| 158
|
ktor-tutorial
|
Apache License 2.0
|
meistercharts-canvas/src/jsMain/kotlin/com/meistercharts/js/ResizeObserverJS.kt
|
Neckar-IT
| 599,079,962
| false
|
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
|
/**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.js
import it.neckar.open.unit.other.px
import org.w3c.dom.DOMRectReadOnly
import org.w3c.dom.Element
/**
* https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
*
* Warning: IE11 does not support the ResizeObserver!
*/
external class ResizeObserver(callback: (Array<ResizeObserverEntry>, ResizeObserver) -> Unit) {
/**
* Unobserves all observed Element targets of a particular observer.
*/
fun disconnect()
/**
* Initiates the observing of a specified Element.
* @param target A reference to an Element or SVGElement to be observed.
*/
fun observe(target: Element)
/**
* Ends the observing of a specified Element.
* @param target A reference to an Element or SVGElement to be unobserved.
*/
fun unobserve(target: Element)
}
/**
* https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry
*/
external class ResizeObserverEntry {
/**
* An object containing the new border box size of the observed element when the callback is run.
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/borderBoxSize">borderBoxSize</a>
*/
val borderBoxSize: Array<BoxSize>
/**
* An object containing the new content box size of the observed element when the callback is run.
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize">contentBoxSize</a>
*/
val contentBoxSize: Array<BoxSize>
/**
* A DOMRectReadOnly object containing the new size of the observed element when the callback is run.
* Note that this is better supported than the above two properties, but it is left over from an earlier
* implementation of the Resize Observer API, is still included in the spec for web compat reasons, and
* may be deprecated in future versions.
*/
val contentRect: DOMRectReadOnly
/**
* A reference to the Element or SVGElement being observed.
*/
val target: Element
}
/**
* See https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/borderBoxSize
* or https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize
*/
external class BoxSize {
/**
* The length of the observed element's border box in the block dimension.
* For boxes with a horizontal writing-mode, this is the vertical dimension, or height;
* if the writing-mode is vertical, this is the horizontal dimension, or width.
*/
val blockSize: @px Number
/**
* The length of the observed element's border box in the inline dimension.
* For boxes with a horizontal writing-mode, this is the horizontal dimension, or width;
* if the writing-mode is vertical, this is the vertical dimension, or height.
*/
val inlineSize: @px Number
}
| 3
|
Kotlin
|
3
| 5
|
ed849503e845b9d603598e8d379f6525a7a92ee2
| 3,388
|
meistercharts
|
Apache License 2.0
|
src/main/kotlin/com/bawer/tasks/revolut/ewallet/extensions.kt
|
febael
| 185,681,437
| false
|
{"Kotlin": 67008}
|
package com.bawer.tasks.revolut.ewallet
import org.slf4j.LoggerFactory
inline fun <reified T : Any> T.myLogger() =
LoggerFactory.getLogger(this::class.java.name.substringBefore("\$Companion"))
| 0
|
Kotlin
|
0
| 0
|
96cdf95831839a7e32d61f81c3c5030aaf4ff81f
| 202
|
ewallet-2
|
Apache License 2.0
|
app/src/main/java/com/example/kotlin_jetpack/ui/ui/home/HomeViewModel.kt
|
zzm525465248
| 492,705,951
| false
|
{"Kotlin": 236095, "Java": 113}
|
package com.example.kotlin_jetpack.ui.ui.home
import android.widget.TextView
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.kotlin_jetpack.Api.OnSellRepository
import com.example.kotlin_jetpack.R
import com.example.kotlin_jetpack.bean.*
import kotlinx.coroutines.launch
class HomeViewModel : ViewModel() {
val banner_list= MutableLiveData<List<BannerX>>()
val recommendedsonglist=MutableLiveData<List<Results>>()
val homelist= MutableLiveData<List<Block>>()
val songlist=MutableLiveData<List<Data1>>()
val qbfwlist= MutableLiveData<List<Datas>>()
val songdetails_list=MutableLiveData<List<Song_details_Bean.Song>>()
private val onSellRepository by lazy{
OnSellRepository()
}
//首页全部服务
fun Qbfw_home(){
viewModelScope.launch {
val bean=onSellRepository.homeQbfw()
qbfwlist.value=bean.data
}
}
//首页轮播图
fun Banner_home(){
this.banner()
}
//歌单推荐
fun RecommendedSongList(){
this.getRecommendedSongListl()
}
//首页数据
fun Home_List(){
this.homeList()
}
//歌曲Url
fun Song_List(id: Int){
this.songList(id)
}
//获取歌曲数组URL
// fun SongURl_List(id:List<Int>){
// viewModelScope.launch {
// val bean=onSellRepository.songURL_List(id)
// songlist.value=bean.data
// }
// }
//推荐歌单观察
private fun getRecommendedSongListl(){
viewModelScope.launch {
val bean=onSellRepository.recommendedSongList()
recommendedsonglist.value=bean.result
}
}
//轮播图数据观察
private fun banner(){
viewModelScope.launch {
val bean=onSellRepository.banner_list()
banner_list.value=bean.banners
}
}
//首页数据观察
private fun homeList(){
viewModelScope.launch {
val bean=onSellRepository.homeList()
homelist.value=bean.data.blocks
}
}
//歌曲url数据观察
private fun songList(id:Int){
viewModelScope.launch {
val bean=onSellRepository.songUrl(id)
songlist.value=bean.data
}
}
//获取歌曲详情
fun getUrl_list(list: String){
viewModelScope.launch {
val bean=onSellRepository.getlove_Details(list)
songdetails_list.value=bean.songs
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ff8eddd25b68d671e4eb2de2bcfc67a1e81c48df
| 2,490
|
Ordinary_music
|
Apache License 2.0
|
fuel/src/test/kotlin/com/github/kittinunf/fuel/RequestValidationTest.kt
|
robinchew
| 165,104,009
| true
|
{"Kotlin": 595384, "Shell": 647}
|
package com.github.kittinunf.fuel
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.Method
import com.github.kittinunf.fuel.core.interceptors.validatorResponseInterceptor
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.CoreMatchers.nullValue
import org.junit.Assert.assertThat
import org.junit.Test
import org.hamcrest.CoreMatchers.`is` as isEqualTo
class RequestValidationTest : MockHttpTestCase() {
@Test
fun httpValidationWithDefaultCase() {
// Register all valid
for (status in (200..299)) {
mock.chain(
request = mock.request().withMethod(Method.GET.value).withPath("/$status"),
response = mock.response().withStatusCode(status)
)
}
// Register teapot
mock.chain(
request = mock.request().withMethod(Method.GET.value).withPath("/418"),
response = mock.response().withStatusCode(418)
)
// Test defaults
for (status in (200..299)) {
val (request, response, result) = FuelManager().request(Method.GET, mock.path("$status")).response()
val (_, error) = result
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(response.statusCode, isEqualTo(status))
}
// Test invalid
val (request, response, result) = FuelManager().request(Method.GET, mock.path("418")).response()
val (_, error) = result
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, notNullValue())
assertThat(error!!.errorData, notNullValue())
assertThat(response.statusCode, isEqualTo(418))
}
@Test
fun httpValidationWithCustomValidCase() {
val preDefinedStatusCode = 203
val manager = FuelManager()
manager.removeAllResponseInterceptors()
manager.addResponseInterceptor(validatorResponseInterceptor(200..202))
// Response to ANY GET request, with a 203 which should have been okay, but it's not with
// the custom valid case
mock.chain(
request = mock.request().withMethod(Method.GET.value),
response = mock.response().withStatusCode(203)
)
// this validate (200..202) which should fail with 203
val (request, response, result) = manager.request(Method.GET, mock.path("any")).responseString()
val (data, error) = result
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, notNullValue())
assertThat(data, nullValue())
assertThat(response.statusCode, isEqualTo(preDefinedStatusCode))
}
@Test
fun httpValidationWithCustomInvalidCase() {
val preDefinedStatusCode = 418
val manager = FuelManager()
manager.removeAllResponseInterceptors()
manager.addResponseInterceptor(validatorResponseInterceptor(400..419))
mock.chain(
request = mock.request().withMethod(Method.GET.value),
response = mock.response().withStatusCode(preDefinedStatusCode)
)
val (request, response, result) = manager.request(Method.GET, mock.path("status/$preDefinedStatusCode")).response()
val (data, error) = result
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())
assertThat(response.statusCode, isEqualTo(preDefinedStatusCode))
}
}
| 1
|
Kotlin
|
1
| 1
|
e6e3eb3ae8f2cb7681daf5ac392199c9f4d97d1a
| 3,674
|
Fuel
|
MIT License
|
idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinAssignmentStatement.kt
|
arrow-kt
| 109,678,056
| true
| null |
// Copyright 2000-2017 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.idea.debugger.sequence.trace.dsl
import com.intellij.debugger.streams.trace.dsl.Expression
import com.intellij.debugger.streams.trace.dsl.Variable
import com.intellij.debugger.streams.trace.dsl.impl.AssignmentStatement
class KotlinAssignmentStatement(override val variable: Variable, override val expression: Expression) : AssignmentStatement {
override fun toCode(indent: Int): String = "${variable.toCode()} = ${expression.toCode()}".withIndent(indent)
}
| 12
|
Kotlin
|
1
| 43
|
d2a24985b602e5f708e199aa58ece652a4b0ea48
| 632
|
kotlin
|
Apache License 2.0
|
demo/src/main/java/com/vwo/sampleapp/extensions/__SharedPrefrence__.kt
|
wingify
| 46,113,606
| false
| null |
package com.vwo.sample.extensions
import android.app.Activity
import android.content.SharedPreferences
/**
* Created by aman on Mon 16/07/18 17:24.
*/
fun Activity.getVWOPrefs(): SharedPreferences = getSharedPreferences("VWO_shared_prefs", Activity.MODE_PRIVATE)
| 4
| null |
6
| 9
|
1bd1642e331e5b136fe49f2112c513500e344d6e
| 266
|
vwo-android
|
MIT License
|
kaspresso/src/main/java/androidx/test/espresso/web/assertion/WebAssertionExt.kt
|
KasperskyLab
| 208,070,025
| false
| null |
package androidx.test.espresso.web.assertion
import androidx.test.espresso.web.model.Atom
import androidx.test.espresso.web.webdriver.WebDriverAtomScriptsProvider
import org.hamcrest.Matcher
import org.hamcrest.StringDescription
/**
* Uses [WebViewAssertions.ResultCheckingWebAssertion] class, that has package-local access in Espresso, so it has to be
* in the same package.
*
* @return a string description of [WebAssertion].
*/
internal fun WebAssertion<*>.describeTo(builder: StringBuilder, result: Any) {
when (this@describeTo) {
is WebViewAssertions.ResultCheckingWebAssertion -> {
builder.append(" \"${getResultMatcher().getResultDescription()}\"")
}
else -> {
builder.append(" ${with(WebDriverAtomScriptsReceiver) { atom.getActionDescription() }}")
if (result.toString() != "") {
builder.append(" with result \"$result\"")
}
}
}
}
private fun WebAssertion<*>.getResultMatcher(): Matcher<*> {
return javaClass
.getDeclaredField("resultMatcher")
.apply { isAccessible = true }
.get(this) as Matcher<*>
}
private fun Matcher<*>.getResultDescription(): String {
return StringBuilder()
.apply { this@getResultDescription.describeTo(StringDescription(this)) }
.toString()
.replace("is ", "element has text ")
.replace("a string containing ", "element contains text ")
}
private object WebDriverAtomScriptsReceiver : WebDriverAtomScriptsProvider() {
fun Atom<*>.getActionDescription(): String {
return when (script) {
GET_VISIBLE_TEXT_ANDROID -> "using web action=\"get visible text\""
CLEAR_ANDROID -> "using web action=\"clear\""
CLICK_ANDROID -> "using web action=\"click on element\""
SCROLL_INTO_VIEW_ANDROID -> "using web action=\"scroll into view\""
SEND_KEYS_ANDROID -> "using web action=\"end keys\""
ACTIVE_ELEMENT_ANDROID -> "using web action=\"active element\""
FRAME_BY_ID_OR_NAME_ANDROID -> "using web action=\"frame by id or name\""
FRAME_BY_INDEX_ANDROID -> "using web action=\"frame by index android\""
FIND_ELEMENT_ANDROID -> "using web action=\"find element\""
FIND_ELEMENTS_ANDROID -> "using web action=\"find elements\""
else -> ""
}
}
}
| 55
| null |
150
| 1,784
|
9c94128c744d640dcd646b86de711d2a1b9c3aa1
| 2,394
|
Kaspresso
|
Apache License 2.0
|
src/main/kotlin/com/mooregreatsoftware/gradle/util/Utils.kt
|
jdigger
| 44,330,407
| false
| null |
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.mooregreatsoftware.gradle.defaults
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.regex.Pattern
import java.util.stream.Stream
import java.util.stream.StreamSupport
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun <T> stream(items: java.lang.Iterable<T>): Stream<T> {
return StreamSupport.stream<T>(items.spliterator(), false)
}
/**
* Delete a directory, akin to "rm -rf".
*/
@Throws(IOException::class)
fun deleteDir(path: Path) {
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
@Throws(IOException::class)
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
@Throws(IOException::class)
override fun postVisitDirectory(dir: Path, e: IOException?): FileVisitResult {
if (e == null) {
Files.delete(dir)
return FileVisitResult.CONTINUE
}
else {
// directory iteration failed
throw e
}
}
})
}
fun jdkVersion(): JdkVersion {
val javaVer = System.getProperty("java.version")
val matcher = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)_(\\d+)$").matcher(javaVer)
if (matcher.matches()) {
val major = Integer.parseInt(matcher.group(1) as String)
val minor = Integer.parseInt(matcher.group(2) as String)
val patch = Integer.parseInt(matcher.group(3) as String)
val update = Integer.parseInt(matcher.group(4) as String)
return JdkVersion(major, minor, patch, update)
}
else {
throw IllegalArgumentException("Could not parse \"" + javaVer + "\"")
}
}
val isBuggyJavac: Boolean
get() {
val jdkVersion = jdkVersion()
return jdkVersion.minor == 8 && jdkVersion.update < 45
}
/**
* Compares two [Map]s of [Comparable] items. If one is null, that sorts lower. If one's size is
* smaller, that sorts lower. Otherwise the keys are compared. (See [.compareSets].)
* If the keys are the same, the first difference in the values found when searching the sorted keys is used for
* the comparision.
*
* @see Comparable
*/
fun <K : Comparable<K>, V : Comparable<V>> compareMaps(m1: Map<K, V>?,
m2: Map<K, V>?): Int {
if (m1 == null) {
return if (m2 == null) 0 else -1
}
else if (m2 == null) return 1
if (m1.size == m2.size) {
if (m1.isEmpty()) return 0
val m1Keys = m1.keys
val m2Keys = m2.keys
val keysComp = compareSets(m1Keys, m2Keys)
if (keysComp == 0) {
val keyIter = m1Keys.sorted().iterator()
while (keyIter.hasNext()) {
val key = keyIter.next()
val m1Val = m1[key] as V
val m2Val = m2[key] as V
val valComp = m1Val.compareTo(m2Val)
if (valComp != 0) return valComp
}
return 0
}
else
return keysComp
}
else
return if (m1.size > m2.size) 1 else -1
}
/**
* Compares two [Set]s of [Comparable] items. If one is null, that sorts lower. If one's size is
* smaller, that sorts lower. Otherwise the first non-equal value after they are sorted is used for the comparision.
* @see Comparable
*/
fun <U : Comparable<U>> compareSets(s1: Set<U>?, s2: Set<U>?): Int {
if (s1 == null) {
return if (s2 == null) 0 else -1
}
else if (s2 == null) return 1
if (s1.size == s2.size) {
if (s1.isEmpty()) return 0
val s1SortedIter = s1.sorted().iterator()
val s2SortedIter = s2.sorted().iterator()
while (s1SortedIter.hasNext()) { // both iter's hasNext() is guaranteed to be the same since same size
val s1Val = s1SortedIter.next()
val s2Val = s2SortedIter.next()
val compVal = s1Val.compareTo(s2Val)
if (compVal != 0) return compVal
}
return 0
}
else
return if (s1.size > s2.size) 1 else -1
}
data class JdkVersion(val major: Int, val minor: Int, val patch: Int, val update: Int)
| 1
| null |
1
| 1
|
ea36a8b1c4ac46ceba4b1f8969831968bef682bf
| 4,999
|
gradle-defaults
|
Apache License 2.0
|
xml/xml-psi-impl/mdn-doc-gen/src/BcdUtil.kt
|
ingokegel
| 72,937,917
| true
| null |
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.type.TypeFactory
import com.intellij.bcd.json.Bcd
import com.intellij.bcd.json.Identifier
import java.io.File
import java.io.InputStream
fun readBcd(path: String): Bcd =
File(path).inputStream().readBcd()
fun Bcd.resolve(path: String): Identifier =
tryResolve(path) ?: throw RuntimeException("Failed to resolve $path")
fun Bcd.tryResolve(path: String): Identifier? {
val segments = path.split('.', '/')
if (segments.isEmpty()) return null
var result = this.additionalProperties[segments[0]]
?: return null
for (segment in segments.subList(1, segments.size)) {
result = result.additionalProperties[segment]
?: return null
}
return result
}
private val objectMapper = ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setTypeFactory(TypeFactory.defaultInstance().withClassLoader(Bcd::class.java.classLoader))
private fun InputStream.readBcd(): Bcd =
objectMapper.readValue(this, Bcd::class.java)
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 1,135
|
intellij-community
|
Apache License 2.0
|
socketdemo/src/main/java/com/example/socketdemo/MainActivity.kt
|
Tzy2001
| 750,701,200
| false
|
{"Gradle": 29, "Java Properties": 4, "Shell": 2, "Text": 2, "Ignore List": 29, "Batchfile": 2, "Markdown": 1, "Proguard": 23, "Kotlin": 238, "XML": 461, "Java": 187, "INI": 1, "JSON": 1}
|
package com.example.socketdemo
import android.net.wifi.WifiManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.socketdemo.adapter.MsgAdapter
import com.example.socketdemo.client.ClientCallback
import com.example.socketdemo.client.SocketClient
import com.example.socketdemo.databinding.ActivityMainBinding
import com.example.socketdemo.server.ServerCallback
import com.example.socketdemo.server.SocketServer
import com.example.socketdemo.ui.Message
class MainActivity : AppCompatActivity(), ServerCallback, ClientCallback {
private val TAG = MainActivity::class.java.simpleName
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
private val buffer = StringBuffer()
//當前是否為服務端
private var isServer = true
//Socket服務是否打開
private var openSocket = false
//Socket服務是否連接
private var connectSocket = false
//消息列表
private val messages = ArrayList<Message>()
//消息适配器
private lateinit var msgAdapter: MsgAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
initView()
}
private fun initView() {
binding.tvIpAddress.text = "IP地址: ${getIp()}"
//服務端和客戶端切換
binding.rg.setOnCheckedChangeListener { _, checkedId ->
isServer = when (checkedId) {
R.id.rb_server -> true
R.id.rb_client -> false
else -> false
}
binding.layServer.visibility = if (isServer) View.VISIBLE else View.GONE
binding.layClient.visibility = if (isServer) View.GONE else View.VISIBLE
binding.etMsg.hint = if (isServer) "發送給客戶端" else "發送給服務端"
}
//開啟服務/關閉服務 服務端處理
binding.btnStartService.setOnClickListener {
openSocket =
if (openSocket) {
SocketServer.stopServer();false
} else {
SocketServer.startServer(
this
)
}
//顯示日誌
// showInfo(if (openSocket) "開啟服務" else "關閉服務")
//消息提示
showMsg(if (openSocket) "開啟服務" else "關閉服務")
//改變按鈕文字
binding.btnStartService.text = if (openSocket) "關閉服務" else "開啟服務"
}
//連接服務/斷開連接 客戶端處理
binding.btnConnectService.setOnClickListener {
val ip = binding.etIpAddress.text.toString()
if (ip.isEmpty()) {
showMsg("請輸入IP地址")
return@setOnClickListener
}
connectSocket = if (connectSocket) {
SocketClient.closeConnect()
false
} else {
SocketClient.connectServer(ip, this)
true
}
// showInfo(if (connectSocket) "連接服务" else "關閉連接")
//消息提示
showMsg(if (connectSocket) "連接服务" else "關閉連接")
binding.btnConnectService.text = if (connectSocket) "关闭连接" else "連接服務"
}
//發送消息個服務端、客戶端
binding.btnSendMsg.setOnClickListener {
val msg = binding.etMsg.text.toString()
if (msg.isEmpty()) {
showMsg("請輸入要發送的信息")
return@setOnClickListener
}
//檢查是否能發送消息
val isSend = if (openSocket) openSocket else if (connectSocket) connectSocket else false
if (!isSend) {
showMsg("當前未開啟服務或連接服務")
return@setOnClickListener
}
if (isServer) SocketServer.sendToClient(msg) else SocketClient.sendToServer(msg)
binding.etMsg.setText("")
updateList(if (isServer) 1 else 2, msg)
}
//初始化列表
msgAdapter = MsgAdapter(messages)
binding.rvMsg.apply {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = msgAdapter
}
}
private fun showMsg(msg: String) = Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
// private fun showInfo(info: String) {
// buffer.append(info).append("\n")
// runOnUiThread { binding.tvInfo.text = buffer.toString() }
// }
/**
* 功能描述:更新列表数据
* @param [type]
* @param [msg]
* @author Tzy
* @date 2024/01/16 10:45
*/
private fun updateList(type: Int, msg: String) {
// messages.add(Message(type,msg))
messages.add(Message(false,msg))
runOnUiThread {
(if (messages.size==0) 0 else messages.size-1).apply {
msgAdapter.notifyItemChanged(this)
binding.rvMsg.smoothScrollToPosition(this)
}
}
}
private fun getIp() =
intToIP((applicationContext.getSystemService(WIFI_SERVICE) as WifiManager).connectionInfo.ipAddress)
private fun intToIP(ip: Int) =
"${(ip and 0xFF)}.${(ip shr 8 and 0xFF)}.${(ip shr 16 and 0xFF)}.${(ip shr 24 and 0xFF)}"
// override fun receiveServerMsg(msg: String) {
// updateList(1,msg)
// }
//
// override fun receiveClientMsg(success: Boolean, msg: String) {
// updateList(2,msg)
// }
override fun receiveServerMsg(ipAddress: String, msg: String) {
}
override fun receiveClientMsg(ipAddress: String, msg: String) {
}
override fun otherMsg(msg: String) {
Log.d(TAG,msg)
}
}
| 0
|
Java
|
0
| 0
|
b54ec3624624885750df5e90041152f411c236d4
| 5,561
|
Android-Demos
|
Apache License 2.0
|
src/main/kotlin/com/intellij/plugin/powershell/lang/lsp/languagehost/PowerShellNotInstalled.kt
|
ant-druha
| 146,094,753
| false
| null |
package com.intellij.plugin.powershell.lang.lsp.languagehost
class PowerShellNotInstalled(msg: String) : Exception(msg)
| 51
| null |
20
| 72
|
5f73e89df8ca2fb167daf451ad92b507a14352a9
| 121
|
intellij-powershell
|
Apache License 2.0
|
base/src/test/kotlin/proguard/classfile/kotlin/KotlinMetadataVersionFilterTest.kt
|
Guardsquare
| 263,266,232
| false
|
{"Java": 5872772, "Smali": 1388507, "Kotlin": 1237210, "HTML": 5772}
|
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2021 Guardsquare NV
*/
package proguard.classfile.kotlin
import io.kotest.core.spec.style.FreeSpec
import io.mockk.mockk
import io.mockk.verify
import proguard.classfile.Clazz
import proguard.classfile.ProgramClass
import proguard.classfile.attribute.Attribute.RUNTIME_VISIBLE_ANNOTATIONS
import proguard.classfile.attribute.annotation.Annotation
import proguard.classfile.attribute.annotation.ArrayElementValue
import proguard.classfile.attribute.annotation.ConstantElementValue
import proguard.classfile.attribute.annotation.ElementValue
import proguard.classfile.attribute.annotation.visitor.AllAnnotationVisitor
import proguard.classfile.attribute.annotation.visitor.AnnotationTypeFilter
import proguard.classfile.attribute.annotation.visitor.AnnotationVisitor
import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor
import proguard.classfile.attribute.visitor.AllAttributeVisitor
import proguard.classfile.attribute.visitor.AttributeNameFilter
import proguard.classfile.editor.ConstantPoolEditor
import proguard.classfile.kotlin.KotlinConstants.TYPE_KOTLIN_METADATA
import proguard.classfile.kotlin.visitor.KotlinMetadataVersionFilter
import proguard.classfile.util.kotlin.KotlinMetadataInitializer
import proguard.classfile.visitor.ClassVisitor
import testutils.ClassPoolBuilder
import testutils.KotlinSource
class KotlinMetadataVersionFilterTest : FreeSpec({
val (programClassPool, _) = ClassPoolBuilder.fromSource(
KotlinSource(
"Test.kt",
"""
class Person
""".trimIndent()
)
)
val supportedMetadataVisitor = mockk<ClassVisitor>(relaxed = true)
val unsupportedMetadataVisitor = mockk<ClassVisitor>(relaxed = true)
"Given a class with a supported metadata version" - {
val supportedClazz = programClassPool.getClass("Person") as ProgramClass
"Then the KotlinMetadataVersionFilter accepts this class" {
supportedClazz.accept(KotlinMetadataVersionFilter(KotlinMetadataInitializer::isSupportedMetadataVersion, supportedMetadataVisitor, unsupportedMetadataVisitor))
verify(exactly = 1) {
supportedClazz.accept(supportedMetadataVisitor)
}
}
}
"Given a class with an unsupported metadata version" - {
val unsupportedClazz = programClassPool.getClass("Person") as ProgramClass
// This visitor updates the mv field in the kotlin metadata annotation.
unsupportedClazz.accept(
AllAttributeVisitor(
AttributeNameFilter(
RUNTIME_VISIBLE_ANNOTATIONS,
AllAnnotationVisitor(
AnnotationTypeFilter(
TYPE_KOTLIN_METADATA,
object : AnnotationVisitor {
override fun visitAnnotation(clazz: Clazz, annotation: Annotation) {
annotation.elementValuesAccept(
clazz,
object : ElementValueVisitor {
override fun visitAnyElementValue(clazz: Clazz, annotation: Annotation, elementValue: ElementValue) {}
override fun visitArrayElementValue(clazz: Clazz, annotation: Annotation, arrayElementValue: ArrayElementValue) {
arrayElementValue.elementValueAccept(
clazz, annotation, 0,
object : ElementValueVisitor {
override fun visitConstantElementValue(clazz: Clazz, annotation: Annotation, constantElementValue: ConstantElementValue) {
val index = ConstantPoolEditor(clazz as ProgramClass).addIntegerConstant(9001)
constantElementValue.u2constantValueIndex = index
}
}
)
}
}
)
}
}
)
)
)
)
)
"Then the KotlinMetadataVersionFilter rejects the class" {
unsupportedClazz.accept(KotlinMetadataVersionFilter(KotlinMetadataInitializer::isSupportedMetadataVersion, supportedMetadataVisitor, unsupportedMetadataVisitor))
verify(exactly = 1) {
unsupportedMetadataVisitor.visitProgramClass(unsupportedClazz)
}
}
}
})
| 8
|
Java
|
61
| 279
|
158061999ebd35ffa8e79a55cd38c06d0aeb10d7
| 5,044
|
proguard-core
|
Apache License 2.0
|
app/src/main/java/com/wuruoye/know/util/DateUtil.kt
|
ruoyewu
| 183,387,390
| false
|
{"Gradle": 3, "Markdown": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 128, "XML": 74, "Java": 16}
|
package com.wuruoye.know.util
import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.util.*
/**
* Created at 2019/4/5 15:31 by wuruoye
* Description:
*/
object DateUtil {
fun milli2Date(milli: Long): String {
return DateUtil.milli2Date("yyyy-MM-dd HH:mm", milli)
}
@SuppressLint("SimpleDateFormat")
fun milli2Date(format: String, milli: Long): String {
val calendar = Calendar.getInstance()
calendar.timeInMillis = milli
val df = SimpleDateFormat(format)
return df.format(calendar.time)
}
fun num2cn(num: Long): String {
var num = num
var level = 0
val builder = StringBuilder()
while (num > 0) {
val n = (num % 10000).toInt()
val clot = chFromNum(n)
if (clot.isNotEmpty()) {
builder.append(LEVEL_ITEM[level]).append(clot.reversed())
}
num /= 10000
++level
}
if (builder.isNotEmpty() && builder.last() == '零') {
builder.setLength(builder.length-1)
}
return builder.reverse().toString()
}
private fun chFromNum(num: Int): String {
var num = num
var decimal = 0
val build = StringBuilder()
while (num > 0) {
val n = num % 10
val clot = if (n > 0) {
"${NUM_ITEM[n]}${DECIMAL_ITEM[decimal]}"
} else {
if (build.isEmpty() || build.last().toString() == NUM_ITEM[0]) ""
else NUM_ITEM[0]
}
build.append(clot.reversed())
num /= 10
++decimal
}
// change 一十二 to 十二 for 12
if (build.length > 1 && build.last() == '一' && build.elementAt(build.length-2) == '十')
build.setLength(build.length-1)
if (num == 0 && decimal < 4) {
build.append('零')
}
return build.reverse().toString()
}
private val NUM_ITEM = arrayOf("零", "一", "二", "三", "四", "五", "六", "七", "八", "九")
private val DECIMAL_ITEM = arrayOf("", "十", "百", "千")
private val LEVEL_ITEM = arrayOf("", "万", "亿", "兆")
}
| 1
| null |
1
| 1
|
2de5a7fdecc8c135463c99c47cde417de0cbe2ec
| 2,189
|
know2
|
Apache License 2.0
|
app/src/main/java/com/linheimx/zimudog/utils/rxbus/RxBus.kt
|
linheimx
| 70,407,347
| false
| null |
package com.linheimx.zimudog.utils.rxbus
import io.reactivex.Flowable
import io.reactivex.processors.FlowableProcessor
import io.reactivex.processors.PublishProcessor
import io.reactivex.subscribers.SerializedSubscriber
/**
* Created by x1c on 2017/5/6.
*/
object RxBus {
private val _Bus: FlowableProcessor<Any>
init {
_Bus = PublishProcessor.create<Any>().toSerialized()
}
/**
* 发送消息
*
* @param o
*/
fun post(o: Any) {
_Bus.onNext(o)
}
/**
* 确定接收消息的类型
*
* @param aClass
* @param <T>
* @return
</T> */
fun <T> toFlowable(aClass: Class<T>): Flowable<T> {
return _Bus.ofType(aClass)
}
/**
* 判断是否有订阅者
*
* @return
*/
fun hasSubscribers(): Boolean {
return _Bus.hasSubscribers()
}
}
| 1
| null |
2
| 20
|
e3aee61d1d5d03c46caeb0f6655a93ea4192bfa3
| 840
|
ZimuDog
|
Apache License 2.0
|
app/src/main/java/com/linheimx/zimudog/utils/rxbus/RxBus.kt
|
linheimx
| 70,407,347
| false
| null |
package com.linheimx.zimudog.utils.rxbus
import io.reactivex.Flowable
import io.reactivex.processors.FlowableProcessor
import io.reactivex.processors.PublishProcessor
import io.reactivex.subscribers.SerializedSubscriber
/**
* Created by x1c on 2017/5/6.
*/
object RxBus {
private val _Bus: FlowableProcessor<Any>
init {
_Bus = PublishProcessor.create<Any>().toSerialized()
}
/**
* 发送消息
*
* @param o
*/
fun post(o: Any) {
_Bus.onNext(o)
}
/**
* 确定接收消息的类型
*
* @param aClass
* @param <T>
* @return
</T> */
fun <T> toFlowable(aClass: Class<T>): Flowable<T> {
return _Bus.ofType(aClass)
}
/**
* 判断是否有订阅者
*
* @return
*/
fun hasSubscribers(): Boolean {
return _Bus.hasSubscribers()
}
}
| 1
| null |
2
| 20
|
e3aee61d1d5d03c46caeb0f6655a93ea4192bfa3
| 840
|
ZimuDog
|
Apache License 2.0
|
native/commonizer/testData/callableMemberCommonization/extensionReceivers/original/jvm/package_root.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
class Planet(val name: String, val diameter: Double)
val intProperty get() = 42
val Int.intProperty get() = this
val Short.intProperty get() = toInt()
val Long.intProperty get() = toInt()
val String.intProperty get() = length
val Planet.intProperty get() = diameter.toInt()
fun intFunction() = 42
fun Int.intFunction() = this
fun Short.intFunction() = toInt()
fun Long.intFunction() = toInt()
fun String.intFunction() = length
fun Planet.intFunction() = diameter.toInt()
val mismatchedProperty1 get() = 42
val Double.mismatchedProperty2 get() = 42
fun mismatchedFunction1() = 42
fun Double.mismatchedFunction2() = 42
val <T> T.propertyWithTypeParameter1 get() = 42
val <T : Any?> T.propertyWithTypeParameter2 get() = 42
val <T : Any> T.propertyWithTypeParameter3 get() = 42
val <T : CharSequence> T.propertyWithTypeParameter4: Int get() = length
val <T : Appendable> T.propertyWithTypeParameter5: Int get() = length
val <T : String> T.propertyWithTypeParameter6: Int get() = length
val String.propertyWithTypeParameter7: Int get() = length
val <Q> Q.propertyWithTypeParameter8 get() = 42
val <T, Q> T.propertyWithTypeParameter9 get() = 42
fun <T> T.functionWithTypeParameter1() {}
fun <Q> Q.functionWithTypeParameter2() {}
fun <T, Q> T.functionWithTypeParameter3() {}
fun <T, Q> Q.functionWithTypeParameter4() {}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,319
|
kotlin
|
Apache License 2.0
|
CameraUtils/lib/src/main/java/com/example/android/camera/utils/YuvToRgbConverter.kt
|
gordinmitya
| 317,994,095
| true
|
{"Kotlin": 282712, "Java": 60904, "RenderScript": 2800, "Shell": 2218}
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.camera.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.ImageFormat
import android.media.Image
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicYuvToRGB
import android.renderscript.Type
import java.nio.ByteBuffer
/**
* Helper class used to efficiently convert a [Media.Image] object from
* [ImageFormat.YUV_420_888] format to an RGB [Bitmap] object.
*/
class YuvToRgbConverter(context: Context) {
private val rs = RenderScript.create(context)
private val scriptYuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs))
private var reuseBuffer: ByteBuffer? = null
private var bytes: ByteArray = ByteArray(0)
private var inputAllocation: Allocation? = null
private var outputAllocation: Allocation? = null
// for CameraX pass ImageProxy
@Synchronized
fun yuvToRgb(image: Image, output: Bitmap) {
val converted = Yuv.toBuffer(image, reuseBuffer)
reuseBuffer = converted.buffer
if (inputAllocation == null
|| inputAllocation!!.type.x != image.width
|| inputAllocation!!.type.y != image.height
|| inputAllocation!!.type.yuv != converted.type
|| bytes.size != converted.buffer.capacity()
) {
val yuvType: Type.Builder = Type.Builder(rs, Element.U8(rs))
.setX(image.width)
.setY(image.height)
.setYuvFormat(converted.type)
inputAllocation = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT)
bytes = ByteArray(converted.buffer.capacity())
val rgbaType: Type.Builder = Type.Builder(rs, Element.RGBA_8888(rs))
.setX(image.width)
.setY(image.height)
outputAllocation = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT)
}
converted.buffer.get(bytes)
inputAllocation!!.copyFrom(bytes)
// Convert NV21 or YUV_420_888 format to RGB
inputAllocation!!.copyFrom(bytes)
scriptYuvToRgb.setInput(inputAllocation)
scriptYuvToRgb.forEach(outputAllocation)
outputAllocation!!.copyTo(output)
}
}
| 0
|
Kotlin
|
0
| 0
|
cad3b23c791fc7fbb04f1b33aaf8d9e3aa04a7aa
| 2,950
|
camera-samples
|
Apache License 2.0
|
sample/kotlinapp/src/main/java/com/marcinmoskala/kotlinapp/StudentDataActivity.kt
|
wangzailfm
| 111,484,537
| true
|
{"Gradle": 9, "Shell": 2, "YAML": 2, "Markdown": 4, "INI": 4, "Ignore List": 3, "Batchfile": 1, "Text": 2, "XML": 24, "Java": 28, "Proguard": 2, "Kotlin": 82, "Java Properties": 1}
|
package com.marcinmoskala.kotlinapp
import activitystarter.Arg
import activitystarter.MakeActivityStarter
import android.os.Bundle
import com.marcinmoskala.activitystarter.argExtra
import kotlinx.android.synthetic.main.activity_data.*
@MakeActivityStarter
class StudentDataActivity : BaseActivity() {
@get:Arg(optional = true) var name: String by argExtra(defaultName)
@get:Arg(optional = true) var id: Int by argExtra(defaultId)
@get:Arg var grade: Char by argExtra()
@get:Arg var passing: Boolean by argExtra()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_data)
nameView.text = "Name: " + name
idView.text = "Id: " + id
gradeView.text = "Grade: " + grade
isPassingView.text = "Passing status: " + passing
}
companion object {
private val NO_ID = -1
val defaultName = "No name provided"
val defaultId = NO_ID
}
}
| 0
|
Kotlin
|
0
| 1
|
de5390e252285e5d4f1bd65366030c9d3c36e10c
| 1,001
|
ActivityStarter
|
Apache License 2.0
|
rewrite-test/src/main/kotlin/org/openrewrite/java/tree/ContinueTest.kt
|
openrewrite
| 263,442,622
| false
| null |
/*
* Copyright 2020 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.java.tree
import org.junit.jupiter.api.Test
import org.openrewrite.java.JavaParser
import org.openrewrite.java.JavaTreeTest
import org.openrewrite.java.JavaTreeTest.NestingLevel.Block
interface ContinueTest : JavaTreeTest {
@Test
fun continueFromWhileLoop(jp: JavaParser) = assertParsePrintAndProcess(
jp, Block, """
while(true) continue;
"""
)
@Test
fun continueFromLabeledWhileLoop(jp: JavaParser) = assertParsePrintAndProcess(
jp, Block, """
labeled: while(true)
continue labeled;
"""
)
}
| 47
| null |
51
| 431
|
5515571843fc3ce486fbf9a83258779d90517a0a
| 1,244
|
rewrite
|
Apache License 2.0
|
app/src/main/java/com/kyberswap/android/presentation/main/alert/LeaderBoardFragment.kt
|
KYRDTeam
| 181,612,742
| false
| null |
package com.kyberswap.android.presentation.main.alert
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kyberswap.android.AppExecutors
import com.kyberswap.android.R
import com.kyberswap.android.databinding.FragmentLeaderBoardBinding
import com.kyberswap.android.domain.SchedulerProvider
import com.kyberswap.android.domain.model.UserInfo
import com.kyberswap.android.presentation.base.BaseFragment
import com.kyberswap.android.presentation.helper.DialogHelper
import com.kyberswap.android.presentation.helper.Navigator
import com.kyberswap.android.presentation.main.profile.alert.GetLeaderBoardState
import com.kyberswap.android.util.di.ViewModelFactory
import javax.inject.Inject
class LeaderBoardFragment : BaseFragment() {
private lateinit var binding: FragmentLeaderBoardBinding
@Inject
lateinit var navigator: Navigator
@Inject
lateinit var dialogHelper: DialogHelper
@Inject
lateinit var appExecutors: AppExecutors
@Inject
lateinit var viewModelFactory: ViewModelFactory
@Inject
lateinit var schedulerProvider: SchedulerProvider
private val handler by lazy {
Handler()
}
private var userInfo: UserInfo? = null
private var isCampaignResult: Boolean? = null
private val viewModel by lazy {
ViewModelProvider(this, viewModelFactory).get(LeaderBoardViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
userInfo = arguments?.getParcelable(USER_INFO_PARAM)
isCampaignResult = arguments?.getBoolean(LATEST_CAMPAIGN_RESULT, false)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentLeaderBoardBinding.inflate(inflater, container, false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
userInfo?.let {
if (isCampaignResult == true) {
binding.title = getString(R.string.campaign_result)
viewModel.getCampaignResult(it)
} else {
binding.title = getString(R.string.alerts_leader_board)
viewModel.getLeaderBoard(it)
}
}
binding.isCampaignResult = isCampaignResult
binding.rvLeaderBoard.layoutManager = LinearLayoutManager(
activity,
RecyclerView.VERTICAL,
false
)
val adapter = LeaderBoardAlertAdapter(appExecutors)
binding.rvLeaderBoard.adapter = adapter
viewModel.getAlertsCallback.observe(viewLifecycleOwner, Observer {
it?.getContentIfNotHandled()?.let { state ->
showProgress(state == GetLeaderBoardState.Loading)
when (state) {
is GetLeaderBoardState.Success -> {
adapter.submitAlerts(state.alerts)
binding.campaign = state.campaignInfo
binding.isNoData = state.alerts.isEmpty()
binding.lastCampaignTitle = state.lastCampaignTitle
binding.lnCampaignInfo.visibility =
if (state.campaignInfo.id <= 0 && isCampaignResult != true && state.lastCampaignTitle.isEmpty()) View.GONE else View.VISIBLE
binding.executePendingBindings()
}
is GetLeaderBoardState.ShowError -> {
showError(
state.message ?: getString(R.string.something_wrong)
)
}
}
}
})
binding.tvWinner.setOnClickListener {
navigator.navigateToLeaderBoard(
currentFragment,
userInfo,
true
)
}
binding.flToggle.setOnClickListener {
binding.expandableLayout.toggle()
binding.imgToggle.isSelected = !binding.imgToggle.isSelected
}
binding.tvEligibleToken.setOnClickListener {
dialogHelper.showEligibleToken(
appExecutors,
binding.campaign?.eligibleTokens?.split(",") ?: listOf()
)
}
binding.imgBack.setOnClickListener {
activity?.onBackPressed()
}
}
override fun onDestroyView() {
handler.removeCallbacksAndMessages(null)
super.onDestroyView()
}
companion object {
private const val USER_INFO_PARAM = "user_info"
private const val LATEST_CAMPAIGN_RESULT = "latest_campaign_result"
fun newInstance(userInfo: UserInfo?, isCampaignResult: Boolean = false) =
LeaderBoardFragment().apply {
arguments = Bundle().apply {
putParcelable(USER_INFO_PARAM, userInfo)
putBoolean(LATEST_CAMPAIGN_RESULT, isCampaignResult)
}
}
}
}
| 1
| null |
10
| 26
|
abd4ab033d188918849e5224cc8204409776391b
| 5,376
|
android-app
|
MIT License
|
Android/app/src/main/java/io/agora/app/karaoke/kit/KaraokeRoomActivity.kt
|
apex-wang
| 659,114,842
| true
|
{"Markdown": 19, "Text": 3, "Ignore List": 5, "Git Config": 1, "Ruby": 3, "Swift": 23, "OpenStep Property List": 1, "XML": 45, "JSON": 9, "Java Properties": 2, "Gradle": 4, "Shell": 2, "Batchfile": 2, "INI": 2, "Proguard": 2, "Kotlin": 7, "Java": 107, "JavaScript": 1, "Maven POM": 1, "Dockerfile": 1, "YAML": 2, "JSON with Comments": 1}
|
package io.agora.app.karaoke.kit
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import io.agora.app.karaoke.RoomListActivity
import io.agora.app.karaoke.databinding.KaraokeRoomActivityBinding
import io.agora.auikit.model.AUIRoomConfig
import io.agora.auikit.model.AUIRoomContext
import io.agora.auikit.model.AUIRoomInfo
import io.agora.auikit.service.IAUIRoomManager.AUIRoomManagerRespDelegate
import io.agora.auikit.service.http.CommonResp
import io.agora.auikit.service.http.HttpManager
import io.agora.auikit.service.http.application.ApplicationInterface
import io.agora.auikit.service.http.application.TokenGenerateReq
import io.agora.auikit.service.http.application.TokenGenerateResp
import io.agora.auikit.service.rtm.AUIRtmErrorProxyDelegate
import io.agora.auikit.ui.basic.AUIAlertDialog
import io.agora.scene.show.utils.PermissionHelp
import retrofit2.Response
class KaraokeRoomActivity : AppCompatActivity(), AUIRoomManagerRespDelegate, AUIRtmErrorProxyDelegate {
companion object {
private var roomInfo: AUIRoomInfo? = null
private var themeId: Int = View.NO_ID
fun launch(context: Context, roomInfo: AUIRoomInfo) {
Companion.roomInfo = roomInfo
val intent = Intent(context, KaraokeRoomActivity::class.java)
intent.addFlags(FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
}
private val mViewBinding by lazy { KaraokeRoomActivityBinding.inflate(LayoutInflater.from(this)) }
private val mPermissionHelp = PermissionHelp(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (themeId != View.NO_ID) {
setTheme(themeId)
}
setContentView(mViewBinding.root)
val roomInfo = roomInfo ?: return
mViewBinding.karaokeRoomView.setOnShutDownClick {
onUserLeaveRoom()
}
mPermissionHelp.checkMicPerm(
{
generateToken { config ->
KaraokeUiKit.launchRoom(roomInfo, config, mViewBinding.karaokeRoomView, KaraokeUiKit.RoomEventHandler {
})
KaraokeUiKit.subscribeError(roomInfo.roomId, this)
KaraokeUiKit.bindRespDelegate(this)
}
},
{
finish()
},
true
)
}
private fun generateToken(onSuccess: (AUIRoomConfig) -> Unit) {
val config = AUIRoomConfig( roomInfo?.roomId ?: "")
config.themeId = RoomListActivity.ThemeId
var response = 3
val trySuccess = {
response -= 1;
if (response == 0) {
onSuccess.invoke(config)
}
}
val userId = AUIRoomContext.shared().currentUserInfo.userId
HttpManager
.getService(ApplicationInterface::class.java)
.tokenGenerate(TokenGenerateReq(config.channelName, userId))
.enqueue(object : retrofit2.Callback<CommonResp<TokenGenerateResp>> {
override fun onResponse(call: retrofit2.Call<CommonResp<TokenGenerateResp>>, response: Response<CommonResp<TokenGenerateResp>>) {
val rspObj = response.body()?.data
if (rspObj != null) {
config.rtcToken007 = rspObj.rtcToken
config.rtmToken007 = rspObj.rtmToken
AUIRoomContext.shared()?.commonConfig?.appId = rspObj.appId
}
trySuccess.invoke()
}
override fun onFailure(call: retrofit2.Call<CommonResp<TokenGenerateResp>>, t: Throwable) {
trySuccess.invoke()
}
})
HttpManager
.getService(ApplicationInterface::class.java)
.tokenGenerate006(TokenGenerateReq(config.rtcChannelName, userId))
.enqueue(object : retrofit2.Callback<CommonResp<TokenGenerateResp>> {
override fun onResponse(call: retrofit2.Call<CommonResp<TokenGenerateResp>>, response: Response<CommonResp<TokenGenerateResp>>) {
val rspObj = response.body()?.data
if (rspObj != null) {
//rtcRtcToken006
config.rtcRtcToken006 = rspObj.rtcToken
config.rtcRtmToken006 = rspObj.rtmToken
}
trySuccess.invoke()
}
override fun onFailure(call: retrofit2.Call<CommonResp<TokenGenerateResp>>, t: Throwable) {
trySuccess.invoke()
}
})
HttpManager
.getService(ApplicationInterface::class.java)
.tokenGenerate(TokenGenerateReq(config.rtcChorusChannelName, userId))
.enqueue(object : retrofit2.Callback<CommonResp<TokenGenerateResp>> {
override fun onResponse(call: retrofit2.Call<CommonResp<TokenGenerateResp>>, response: Response<CommonResp<TokenGenerateResp>>) {
val rspObj = response.body()?.data
if (rspObj != null) {
// rtcChorusRtcToken007
config.rtcChorusRtcToken007 = rspObj.rtcToken
}
trySuccess.invoke()
}
override fun onFailure(call: retrofit2.Call<CommonResp<TokenGenerateResp>>, t: Throwable) {
trySuccess.invoke()
}
})
}
private var mRoomDestroyAlert = false
override fun onRoomDestroy(roomId: String) {
if (mRoomDestroyAlert) {
return
}
mRoomDestroyAlert = true
AUIAlertDialog(this).apply {
setTitle("Tip")
setMessage("房间已销毁")
setPositiveButton("确认") {
dismiss()
shutDownRoom()
}
show()
}
}
override fun onRoomInfoChange(roomId: String, roomInfo: AUIRoomInfo) {
}
override fun onTokenPrivilegeWillExpire(channelName: String?) {
TODO("Not yet implemented")
}
override fun onBackPressed() {
onUserLeaveRoom()
}
private fun onUserLeaveRoom() {
val owner = (roomInfo?.roomOwner?.userId == AUIRoomContext.shared().currentUserInfo.userId)
AUIAlertDialog(this).apply {
setTitle("Tip")
if (owner) {
setMessage("是否离开并销毁房间?")
} else {
setMessage("是否离开房间?")
}
setPositiveButton("确认") {
dismiss()
shutDownRoom()
}
setNegativeButton("取消") {
dismiss()
}
show()
}
}
private fun shutDownRoom() {
roomInfo?.roomId?.let { roomId ->
KaraokeUiKit.destroyRoom(roomId)
KaraokeUiKit.unsubscribeError(roomId, this@KaraokeRoomActivity)
KaraokeUiKit.unbindRespDelegate(this@KaraokeRoomActivity)
}
finish()
}
}
| 0
| null |
0
| 0
|
acc5f2823364b3645ad21d5d7c29fb2c653e144a
| 7,296
|
AUIKitKaraoke
|
MIT License
|
idea/tests/org/jetbrains/jet/completion/DataFlowValueRenderingTest.kt
|
chashnikov
| 14,658,474
| true
|
{"Java": 14526655, "Kotlin": 6831811, "JavaScript": 897073, "Groovy": 43935, "CSS": 14421, "Shell": 9248}
|
/*
* Copyright 2010-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.completion
import org.jetbrains.jet.plugin.PluginTestCaseBase
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import org.jetbrains.jet.plugin.project.AnalyzerFacadeWithCache
import org.jetbrains.jet.lang.psi.JetFile
import org.jetbrains.jet.lang.resolve.BindingContext
import org.jetbrains.jet.lang.psi.JetExpression
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.jet.plugin.completion.renderDataFlowValue
import org.jetbrains.jet.JetTestUtils
import com.intellij.openapi.util.io.FileUtil
import java.io.File
abstract class AbstractDataFlowValueRenderingTest: LightCodeInsightFixtureTestCase() {
override fun getTestDataPath() : String {
return PluginTestCaseBase.getTestDataPathBase() + "/dataFlowValueRendering/"
}
fun doTest(fileName: String) {
val fixture = myFixture!!
fixture.configureByFile(fileName)
val jetFile = fixture.getFile() as JetFile
val element = jetFile.findElementAt(fixture.getCaretOffset())
val expression = PsiTreeUtil.getParentOfType(element, javaClass<JetExpression>())!!
val info = AnalyzerFacadeWithCache.getContextForElement(expression)[BindingContext.EXPRESSION_DATA_FLOW_INFO, expression]!!
val allValues = (info.getCompleteTypeInfo().keySet() + info.getCompleteNullabilityInfo().keySet()).toSet()
val actual = allValues.map { renderDataFlowValue(it) }.filterNotNull().sort().makeString("\n")
JetTestUtils.assertEqualsToFile(File(FileUtil.getNameWithoutExtension(fileName) + ".txt"), actual)
}
}
| 1
|
Java
|
1
| 1
|
88a261234860ff0014e3c2dd8e64072c685d442d
| 2,197
|
kotlin
|
Apache License 2.0
|
environment/src/main/kotlin/jetbrains/exodus/tree/btree/ILeafNode.kt
|
mohammadfarari1360
| 637,398,375
| true
|
{"Java Properties": 1, "Gradle Kotlin DSL": 16, "Shell": 1, "Markdown": 6, "Batchfile": 1, "Java": 478, "Kotlin": 390, "INI": 1}
|
/*
* Copyright 2010 - 2023 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 jetbrains.exodus.tree.btree
import jetbrains.exodus.ByteIterable
import jetbrains.exodus.log.Loggable
import jetbrains.exodus.tree.Dumpable
import jetbrains.exodus.tree.INode
import jetbrains.exodus.tree.LongIterator
import java.io.PrintStream
interface ILeafNode : INode {
val address: Long
fun compareKeyTo(iterable: ByteIterable): Int
fun compareValueTo(iterable: ByteIterable): Int
fun valueExists(value: ByteIterable): Boolean
fun addressIterator(): LongIterator
val isDup: Boolean
val isMutable: Boolean
val tree: BTreeBase
val dupCount: Long
val isDupLeaf: Boolean
companion object {
val EMPTY: ILeafNode = object : ILeafNode {
override fun hasValue(): Boolean {
return false
}
override val key: ByteIterable
get() = ByteIterable.EMPTY
override val value: ByteIterable
get() = ByteIterable.EMPTY
override val address: Long
get() = Loggable.NULL_ADDRESS
override fun compareKeyTo(iterable: ByteIterable): Int {
throw UnsupportedOperationException()
}
override fun compareValueTo(iterable: ByteIterable): Int {
throw UnsupportedOperationException()
}
override fun valueExists(value: ByteIterable): Boolean {
throw UnsupportedOperationException()
}
override fun addressIterator(): LongIterator {
throw UnsupportedOperationException()
}
override val isDup: Boolean
get() = false
override val isMutable: Boolean
get() = false
override val tree: BTreeBase
get() {
throw UnsupportedOperationException()
}
override val dupCount: Long
get() = 0
override val isDupLeaf: Boolean
get() = false
override fun dump(out: PrintStream, level: Int, renderer: Dumpable.ToString?) {
out.println("Empty leaf node")
}
}
}
}
| 0
| null |
0
| 1
|
07f82043044f2a967c0f3c6c00bcc82b6e9126ef
| 2,794
|
xodus
|
Apache License 2.0
|
domain/src/main/kotlin/info/moevm/se/domain/interactors/FetchWeatherInteractor.kt
|
moevm
| 170,087,136
| false
|
{"Gradle": 5, "Text": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Kotlin": 47, "Proguard": 2, "JSON": 1, "XML": 55, "Java": 2}
|
package info.moevm.se.domain.interactors
class FetchWeatherInteractor {
}
| 1
| null |
1
| 1
|
1d2d3706163f0974c323a8a7c9d8af30ddf25e6f
| 74
|
adfmp19-weather-advisor
|
MIT License
|
src/main/kotlin/com/mapk/core/ValueParameter.kt
|
ProjectMapK
| 244,005,921
| false
|
{"Gradle Kotlin DSL": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Kotlin": 28, "Java": 1, "YAML": 2, "XML": 8}
|
package com.mapk.core
import kotlin.reflect.KClass
interface ValueParameter<T : Any> {
val annotations: List<Annotation>
val isNullable: Boolean
val isOptional: Boolean
val name: String
val requiredClazz: KClass<T>
}
| 0
|
Kotlin
|
1
| 1
|
d1c5b366f5d00926ec418104c453f0569cc50f4f
| 239
|
Shared
|
Apache License 2.0
|
backpack-common/src/main/java/net/skyscanner/backpack/util/ExperimentalBackpackApi.kt
|
Skyscanner
| 117,813,847
| false
| null |
/**
* Backpack for Android - Skyscanner's Design System
*
* Copyright 2018 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.skyscanner.backpack.util
/**
* The API marked by this annotation is not stable and may be changed at
* any time without considering this as a breaking change.
*
* The code might not be covered with tests or documented.
*
* It's intended to be used by Koala squad members for API/code experimentation
* or to mark the features which are currently in progress.
*/
@Suppress("DEPRECATION")
@RequiresOptIn(level = RequiresOptIn.Level.ERROR)
@Retention(AnnotationRetention.BINARY)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.ANNOTATION_CLASS,
AnnotationTarget.PROPERTY,
AnnotationTarget.FIELD,
AnnotationTarget.LOCAL_VARIABLE,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.TYPEALIAS,
)
@MustBeDocumented
annotation class ExperimentalBackpackApi
| 8
| null |
31
| 94
|
9b5448b446c7bc46560e430595829e5f4f090e6b
| 1,573
|
backpack-android
|
Apache License 2.0
|
src/main/java/de/byjoker/jfql/statement/ConditionBuilder.kt
|
joker-games
| 311,407,723
| false
|
{"Kotlin": 37587, "Java": 19429, "Python": 12073, "JavaScript": 5114}
|
package de.byjoker.jfql.statement
import de.byjoker.jfql.exception.ConnectorException
class ConditionBuilder(private val field: String) {
private var state: State? = null
private var method: Method? = null
private var needed: Any? = null
fun `is`(): ConditionBuilder {
this.state = State.IS
return this
}
fun not(): ConditionBuilder {
this.state = State.NOT
return this
}
fun equals(needed: Any): ConditionBuilder {
this.method = Method.EQUALS
this.needed = needed
return this
}
fun equalsIgnoreCase(needed: Any): ConditionBuilder {
this.method = Method.EQUALS_IGNORE_CASE
this.needed = needed
return this
}
fun contains(needed: Any): ConditionBuilder {
this.method = Method.CONTAINS
this.needed = needed
return this
}
fun containsIgnoreCase(needed: Any): ConditionBuilder {
this.method = Method.CONTAINS_IGNORE_CASE
this.needed = needed
return this
}
fun needed(needed: Any): ConditionBuilder {
this.needed = needed
return this
}
fun build(): Condition {
if (state == null || method == null || needed == null) {
throw ConnectorException("Required filed isn't present!")
}
val builder = StringBuilder(field).append(" ")
when (method) {
Method.EQUALS -> if (state == State.NOT) builder.append("!== ") else builder.append("=== ")
else -> {
if (state == State.NOT) {
builder.append("!=")
} else {
builder.append("==")
}
builder.append(" ").append(method!!.method)
}
}
builder.append("'").append(needed).append("'")
return Condition { builder.toString() }
}
enum class State {
IS, NOT
}
enum class Method(val method: String) {
EQUALS("equals:"), EQUALS_IGNORE_CASE("equals_ignore_case:"), CONTAINS("contains:"), CONTAINS_IGNORE_CASE("contains_ignore_case:")
}
}
| 0
|
Kotlin
|
0
| 0
|
273b22cdd7a5a1628712fbebd575de1645319973
| 2,137
|
JFQLConnector
|
MIT License
|
784-insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.kt
|
AM-Kitty
| 783,747,812
| false
|
{"Kotlin": 24972}
|
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
// Keywords: Recursion, BST
fun insertIntoBST(root: TreeNode?, `val`: Int): TreeNode? {
val insertNode = TreeNode(`val`)
if (root == null) return insertNode
insert(root, insertNode)
return root
}
private fun insert(root: TreeNode, insertNode: TreeNode){
if (insertNode.`val` < root.`val`) {
root.left?.let {
insert(it, insertNode)
} ?: run {
root.left = insertNode
}
} else {
root.right?.let {
insert(it, insertNode)
} ?: run {
root.right = insertNode
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7d22d41c74396e7d36bd2319afffed92a48c7c9c
| 903
|
Leetcode-Kotlin
|
MIT License
|
MentalBlocks2/app/src/main/java/com/ivanloy/mentalblocks/SnapOnScrollListener.kt
|
ivanloy
| 169,242,127
| false
| null |
package com.ivanloy.mentalblocks
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SnapHelper
class SnapOnScrollListener(
private val snapHelper: SnapHelper,
var behavior: Behavior = Behavior.NOTIFY_ON_SCROLL,
var onSnapPositionChangeListener: OnSnapPositionChangeListener? = null
) : RecyclerView.OnScrollListener() {
enum class Behavior {
NOTIFY_ON_SCROLL,
NOTIFY_ON_SCROLL_STATE_IDLE
}
private var snapPosition = RecyclerView.NO_POSITION
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (behavior == Behavior.NOTIFY_ON_SCROLL) {
maybeNotifySnapPositionChange(recyclerView)
}
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (behavior == Behavior.NOTIFY_ON_SCROLL_STATE_IDLE
&& newState == RecyclerView.SCROLL_STATE_IDLE) {
maybeNotifySnapPositionChange(recyclerView)
}
}
private fun maybeNotifySnapPositionChange(recyclerView: RecyclerView) {
val snapPosition = snapHelper.getSnapPosition(recyclerView)
val snapPositionChanged = this.snapPosition != snapPosition
if (snapPositionChanged) {
onSnapPositionChangeListener?.onSnapPositionChange(snapPosition)
this.snapPosition = snapPosition
}
}
fun SnapHelper.getSnapPosition(recyclerView: RecyclerView): Int {
val layoutManager = recyclerView.layoutManager ?: return RecyclerView.NO_POSITION
val snapView = findSnapView(layoutManager) ?: return RecyclerView.NO_POSITION
return layoutManager.getPosition(snapView)
}
}
| 0
|
Kotlin
|
0
| 0
|
666082162fb0eecc2a3455ba05d7afef29295f5f
| 1,695
|
Mental-Blocks
|
MIT License
|
app/src/main/java/com/ifmvo/androidad/ui/FlowAdActivity.kt
|
ifmvo
| 182,952,555
| false
|
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 19, "Kotlin": 46, "Java": 1}
|
package com.ifmvo.androidad.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.ifmvo.androidad.R
/*
* (●゚ω゚●) 原生 列表中展示
*
* Created by Matthew_Chen on 2019-07-05.
*/
class FlowAdActivity : AppCompatActivity() {
companion object {
fun action(context: Context) {
context.startActivity(Intent(context, FlowAdActivity::class.java))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_common)
val bt = supportFragmentManager.beginTransaction()
bt.replace(R.id.fgContainer, FlowAdFragment())
bt.commit()
}
}
| 0
|
Kotlin
|
4
| 7
|
e44524f0a139715bf3d96ff55b1813ce6aa929f8
| 771
|
TogetherAdSea
|
Apache License 2.0
|
model_http/src/main/java/com/wynne/http/MyService.kt
|
tony-xxw
| 122,974,025
| false
| null |
package com.wynne.http
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.util.Log
class MyService(var handle: Handler) : Service() {
private var handler: Handler? = null
init {
this.handle = handle
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
val stopDelayed: Long = intent.getLongExtra("Delayed", 2000)
handler?.postDelayed(Runnable {
Log.d("XXW", "11111111111")
val LaunchIntent: Intent = packageManager.getLaunchIntentForPackage(application.packageName)
LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(LaunchIntent)
this@MyService.stopSelf()
}, stopDelayed)
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
}
| 1
| null |
1
| 7
|
4c8595c84086a11f1abba8538c2de8c86f17212d
| 948
|
KnowledgeTree
|
Apache License 2.0
|
app/src/main/java/dev/saurabhmishra/mvvm/ui/base/BaseViewModel.kt
|
sm3saurabh
| 309,044,627
| false
| null |
package dev.saurabhmishra.mvvm.ui.base
/**
* Created by <NAME> on 01/11/20
*/
class BaseViewModel {
}
| 0
|
Kotlin
|
0
| 0
|
f9ea0858a8e1c50eced836d630c7b13e03065c85
| 104
|
Android-MVVM-Tmdb
|
Apache License 2.0
|
Detect/ObjectDetect/app/src/main/java/com/objectdetect/MainActivity.kt
|
YyuTtian
| 428,930,710
| false
|
{"Text": 313, "Markdown": 561, "Gradle": 38, "Java Properties": 20, "Shell": 41, "Ignore List": 61, "Batchfile": 38, "Proguard": 15, "XML": 168, "Kotlin": 24, "INI": 9, "Java": 81, "HTML": 24, "CSS": 22, "Less": 21, "JavaScript": 5741, "JSON": 720, "JSON with Comments": 15, "YAML": 92, "PowerShell": 28, "CoffeeScript": 11, "Git Attributes": 1, "Roff Manpage": 2, "EJS": 29, "Makefile": 10, "TypeScript": 5, "EditorConfig": 2, "Nix": 1, "Browserslist": 1, "C": 6, "C++": 12, "Groovy": 8, "Dart": 211}
|
package com.objectdetect
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.camera.CameraView
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.objects.ObjectDetection
import com.google.mlkit.vision.objects.defaults.ObjectDetectorOptions
import com.objectdetect.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTransparentStatusBar()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.CAMERA), 1)
}
binding.camera.addCallback(object : CameraView.Callback() {
override fun onBitmapChange(cameraView: CameraView?, bitmap: Bitmap?) {
super.onBitmapChange(cameraView, bitmap)
check(bitmap)
}
})
}
override fun onResume() {
super.onResume()
binding.camera.start()
}
override fun onPause() {
super.onPause()
binding.camera.stop()
}
private var preCheckTs = 0L
private fun check(bitmap: Bitmap?) {
if (bitmap == null || System.currentTimeMillis() - preCheckTs < 200) {
return
}
preCheckTs = System.currentTimeMillis()
val options = ObjectDetectorOptions.Builder()
.setDetectorMode(ObjectDetectorOptions.SINGLE_IMAGE_MODE) // 处理单张图片
.build()
val objectDetection = ObjectDetection.getClient(options)
val image = InputImage.fromBitmap(bitmap, 0)
objectDetection.process(image).addOnSuccessListener {
for (i in it) {
binding.tipView.setRect(i.boundingBox)
}
}.addOnFailureListener {
println("check err " + it.message)
}
}
private fun setTransparentStatusBar() {
try {
val window = this.window
val decorView = window.decorView
val option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
decorView.systemUiVisibility = option
window.statusBarColor = Color.TRANSPARENT
} catch (e: Exception) {
}
}
}
| 0
|
Java
|
0
| 0
|
773110007aee222a25f671c497c8f48e60c14a3a
| 2,636
|
Sample
|
Apache License 2.0
|
screencaptor/src/main/java/com/wealthfront/screencaptor/views/modifier/ViewVisibilityModifier.kt
|
wealthfront
| 267,915,434
| false
| null |
package com.wealthfront.screencaptor.views.modifier
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import com.wealthfront.screencaptor.views.extensions.getAllChildren
internal object ViewVisibilityModifier {
internal fun hideViews(
view: View,
viewIdsToExclude: Set<Int>
): Map<Int, Int> {
val visibilityState = mutableMapOf<Int, Int>()
view.getAllChildren().forEach { child ->
if (viewIdsToExclude.any { child.id == it }) {
visibilityState[child.id] = child.visibility
if (child.visibility == VISIBLE) {
child.visibility = INVISIBLE
}
}
}
return visibilityState
}
internal fun showViews(
view: View,
viewIdsToExclude: Set<Int>,
initialStateOfViews: Map<Int, Int>
) {
view.getAllChildren().forEach { child ->
if (viewIdsToExclude.any { child.id == it }) {
child.visibility = initialStateOfViews.getValue(child.id)
}
}
}
}
| 5
| null |
3
| 15
|
92fd4051f869d026f54b7529490bea73b93f4cb5
| 994
|
screencaptor
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.