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/test/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/csip/CSIPDpsApiMockServer.kt | ministryofjustice | 445,140,246 | false | {"Kotlin": 1739042, "Mustache": 1803, "Dockerfile": 1118} | package uk.gov.justice.digital.hmpps.prisonertonomisupdate.csip
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.get
import org.junit.jupiter.api.extension.AfterAllCallback
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.springframework.test.context.junit.jupiter.SpringExtension
class CSIPDpsApiExtension : BeforeAllCallback, AfterAllCallback, BeforeEachCallback {
companion object {
@JvmField
val csipDpsApi = CSIPDpsApiMockServer()
lateinit var objectMapper: ObjectMapper
}
override fun beforeAll(context: ExtensionContext) {
objectMapper = (SpringExtension.getApplicationContext(context).getBean("jacksonObjectMapper") as ObjectMapper)
csipDpsApi.start()
}
override fun beforeEach(context: ExtensionContext) {
csipDpsApi.resetRequests()
}
override fun afterAll(context: ExtensionContext) {
csipDpsApi.stop()
}
}
class CSIPDpsApiMockServer : WireMockServer(WIREMOCK_PORT) {
companion object {
private const val WIREMOCK_PORT = 8098
}
fun stubHealthPing(status: Int) {
stubFor(
get("/health/ping").willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withBody(if (status == 200) "pong" else "some error")
.withStatus(status),
),
)
}
fun ResponseDefinitionBuilder.withBody(body: Any): ResponseDefinitionBuilder {
this.withBody(CSIPDpsApiExtension.objectMapper.writeValueAsString(body))
return this
}
}
| 1 | Kotlin | 0 | 2 | b9797f0b01ad8603c984d28c4d4ebb043ec0c870 | 1,839 | hmpps-prisoner-to-nomis-update | MIT License |
core/client/src/main/kotlin/org/http4k/connect/util.kt | http4k | 295,641,058 | false | {"Kotlin": 1624385, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675} | package org.http4k.connect
import kotlin.reflect.KClass
inline fun <reified T : Any> kClass(): KClass<T> = T::class
// TODO suggesting moving into http4k-core: KotlinExtensions.kt
fun <T: Any> StringBuilder.appendAll(items: Collection<T>, fn: (T) -> String): StringBuilder {
for (item in items) {
append(fn(item))
}
return this
}
| 7 | Kotlin | 17 | 37 | 3522f4a2bf5e476b849ec367700544d89e006f71 | 353 | http4k-connect | Apache License 2.0 |
base/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/dependency/DexingTransform.kt | qiangxu1996 | 301,210,525 | false | {"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121} | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.dependency
import com.android.build.gradle.internal.errors.MessageReceiverImpl
import com.android.build.gradle.internal.publishing.AndroidArtifacts
import com.android.build.gradle.internal.scope.VariantScope
import com.android.build.gradle.internal.tasks.recordArtifactTransformSpan
import com.android.build.gradle.options.SyncOptions
import com.android.builder.dexing.ClassFileInputs
import com.android.builder.dexing.DexArchiveBuilder
import com.android.builder.dexing.r8.ClassFileProviderFactory
import com.android.sdklib.AndroidVersion
import com.android.tools.build.gradle.internal.profile.GradleTransformExecutionType
import com.google.common.io.Closer
import com.google.common.io.Files
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.artifacts.transform.InputArtifact
import org.gradle.api.artifacts.transform.InputArtifactDependencies
import org.gradle.api.artifacts.transform.TransformAction
import org.gradle.api.artifacts.transform.TransformOutputs
import org.gradle.api.attributes.Attribute
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileSystemLocation
import org.gradle.api.internal.artifacts.ArtifactAttributes.ARTIFACT_FORMAT
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.CompileClasspath
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
import org.slf4j.LoggerFactory
import java.io.File
import java.nio.file.Path
abstract class BaseDexingTransform : TransformAction<BaseDexingTransform.Parameters> {
interface Parameters: GenericTransformParameters {
@get:Input
val minSdkVersion: Property<Int>
@get:Input
val debuggable: Property<Boolean>
@get:Input
val enableDesugaring: Property<Boolean>
@get:Classpath
val bootClasspath: ConfigurableFileCollection
@get:Internal
val errorFormat: Property<SyncOptions.ErrorFormatMode>
@get:Optional
@get:Input
val libConfiguration: Property<String>
}
@get:Classpath
@get:InputArtifact
abstract val primaryInput: Provider<FileSystemLocation>
protected abstract fun computeClasspathFiles(): List<Path>
override fun transform(outputs: TransformOutputs) {
recordArtifactTransformSpan(
parameters.projectName.get(),
GradleTransformExecutionType.DEX_ARTIFACT_TRANSFORM
) {
val inputFile = primaryInput.get().asFile
val name = Files.getNameWithoutExtension(inputFile.name)
val outputDir = outputs.dir(name)
Closer.create().use { closer ->
val d8DexBuilder = DexArchiveBuilder.createD8DexBuilder(
parameters.minSdkVersion.get(),
parameters.debuggable.get(),
ClassFileProviderFactory(parameters.bootClasspath.files.map(File::toPath))
.also { closer.register(it) },
ClassFileProviderFactory(computeClasspathFiles()).also { closer.register(it) },
parameters.enableDesugaring.get(),
parameters.libConfiguration.orNull,
MessageReceiverImpl(
parameters.errorFormat.get(),
LoggerFactory.getLogger(DexingNoClasspathTransform::class.java)
)
)
ClassFileInputs.fromPath(inputFile.toPath()).use { classFileInput ->
classFileInput.entries { true }.use { classesInput ->
d8DexBuilder.convert(
classesInput,
outputDir.toPath(),
false
)
}
}
}
}
}
}
abstract class DexingNoClasspathTransform : BaseDexingTransform() {
override fun computeClasspathFiles() = listOf<Path>()
}
abstract class DexingWithClasspathTransform : BaseDexingTransform() {
/**
* Using compile classpath normalization is safe here due to the design of desugar:
* Method bodies are only moved to the companion class within the same artifact,
* not between artifacts.
*/
@get:CompileClasspath
@get:InputArtifactDependencies
abstract val classpath: FileCollection
override fun computeClasspathFiles() = classpath.files.map(File::toPath)
}
fun getDexingArtifactConfigurations(scopes: Collection<VariantScope>): Set<DexingArtifactConfiguration> {
return scopes.map { getDexingArtifactConfiguration(it) }.toSet()
}
fun getDexingArtifactConfiguration(scope: VariantScope): DexingArtifactConfiguration {
val minSdk = scope.variantConfiguration.minSdkVersionWithTargetDeviceApi.featureLevel
val debuggable = scope.variantConfiguration.buildType.isDebuggable
val enableDesugaring = scope.java8LangSupportType == VariantScope.Java8LangSupport.D8
val enableApiDesugaring = scope.globalScope.extension.compileOptions.javaApiDesugaringEnabled
return DexingArtifactConfiguration(minSdk, debuggable, enableDesugaring, enableApiDesugaring)
}
data class DexingArtifactConfiguration(
private val minSdk: Int,
private val isDebuggable: Boolean,
private val enableDesugaring: Boolean,
private val enableApiDesugaring: Boolean?
) {
private val needsClasspath = enableDesugaring && minSdk < AndroidVersion.VersionCodes.N
fun registerTransform(
projectName: String,
dependencyHandler: DependencyHandler,
bootClasspath: FileCollection,
libConfiguration: String,
errorFormat: SyncOptions.ErrorFormatMode
) {
dependencyHandler.registerTransform(getTransformClass()) { spec ->
spec.parameters { parameters ->
parameters.projectName.set(projectName)
parameters.minSdkVersion.set(minSdk)
parameters.debuggable.set(isDebuggable)
parameters.enableDesugaring.set(enableDesugaring)
if (needsClasspath) {
parameters.bootClasspath.from(bootClasspath)
}
parameters.errorFormat.set(errorFormat)
if (enableApiDesugaring != null && enableApiDesugaring) {
parameters.libConfiguration.set(libConfiguration)
}
}
spec.from.attribute(ARTIFACT_FORMAT, AndroidArtifacts.ArtifactType.CLASSES.type)
spec.to.attribute(ARTIFACT_FORMAT, AndroidArtifacts.ArtifactType.DEX.type)
getAttributes().forEach { (attribute, value) ->
spec.from.attribute(attribute, value)
spec.to.attribute(attribute, value)
}
}
}
private fun getTransformClass(): Class<out BaseDexingTransform> {
return if (needsClasspath) {
DexingWithClasspathTransform::class.java
} else {
DexingNoClasspathTransform::class.java
}
}
fun getAttributes(): Map<Attribute<String>, String> {
return mapOf(
ATTR_MIN_SDK to minSdk.toString(),
ATTR_IS_DEBUGGABLE to isDebuggable.toString(),
ATTR_ENABLE_DESUGARING to enableDesugaring.toString()
)
}
}
val ATTR_MIN_SDK: Attribute<String> = Attribute.of("dexing-min-sdk", String::class.java)
val ATTR_IS_DEBUGGABLE: Attribute<String> =
Attribute.of("dexing-is-debuggable", String::class.java)
val ATTR_ENABLE_DESUGARING: Attribute<String> =
Attribute.of("dexing-enable-desugaring", String::class.java)
| 1 | Java | 1 | 1 | 3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4 | 8,377 | vmtrace | Apache License 2.0 |
packages/canvas-svg/src-native/android/canvassvg/src/main/java/org/nativescript/canvas/svg/NSCSVG.kt | NativeScript | 293,639,798 | false | {"JavaScript": 4865930, "C++": 4818365, "TypeScript": 1787701, "Rust": 1584865, "C": 1154938, "Kotlin": 176053, "Swift": 117579, "Objective-C": 111338, "Shell": 25459, "WGSL": 24349, "Java": 21275, "PLSQL": 12630, "Vue": 9703, "CMake": 7266, "Ruby": 4921, "SCSS": 3329, "Objective-C++": 2913, "HTML": 2558, "CSS": 1564, "Makefile": 1525, "Python": 1140} | package org.nativescript.canvas.svg
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.nio.ByteBuffer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
import kotlin.math.min
class NSCSVG : View {
var bitmap: Bitmap? = null
internal set
internal val lock = Any()
private var pendingInvalidate: Boolean = false
private val executor = Executors.newSingleThreadExecutor()
internal var src: String = ""
internal var srcPath: String = ""
private var mMatrix = Matrix()
var sync: Boolean = false
constructor(context: Context) : super(context, null) {
init(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context)
}
private fun init(context: Context) {
if (isInEditMode) {
return
}
setBackgroundColor(Color.TRANSPARENT)
}
private var currentTask: java.util.concurrent.Future<*>? = null
private fun resize(w: Int, h: Int) {
doDraw()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
if ((w != 0 && h != 0) && w != layoutParams.width && h != layoutParams.height) {
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
resize(w, h)
}
}
override fun onDraw(canvas: Canvas) {
bitmap?.let {
canvas.drawBitmap(it, mMatrix, null)
}
}
private fun doDraw() {
bitmap?.let {
currentTask?.cancel(true)
if (sync) {
if (srcPath.isNotEmpty()) {
nativeDrawSVGFromPath(it, resources.displayMetrics.density, srcPath)
pendingInvalidate = false
invalidate()
} else {
nativeDrawSVG(it, resources.displayMetrics.density, src)
pendingInvalidate = false
invalidate()
}
return
}
synchronized(lock) {
currentTask = executor.submit {
if (srcPath.isNotEmpty()) {
nativeDrawSVGFromPath(it, resources.displayMetrics.density, srcPath)
handler?.post {
pendingInvalidate = false
invalidate()
}
} else {
nativeDrawSVG(it, resources.displayMetrics.density, src)
handler?.post {
pendingInvalidate = false
invalidate()
}
}
currentTask = null
}
}
}
}
fun setSrc(src: String) {
this.src = src
doDraw()
}
fun setSrcPath(path: String) {
this.srcPath = path
doDraw()
}
interface Callback {
fun onSuccess(view: NSCSVG?)
}
companion object {
init {
try {
System.loadLibrary("canvassvg")
} catch (_: Exception) {
}
}
@JvmStatic
private external fun nativeDrawSVG(bitmap: Bitmap, scale: Float, svg: String)
@JvmStatic
private external fun nativeDrawSVGFromPath(bitmap: Bitmap, scale: Float, svg: String)
@JvmStatic
private external fun nativeDrawSVGFromBytes(bitmap: Bitmap, scale: Float, bytes: ByteBuffer)
@JvmStatic
fun fromPathSync(context: Context, path: String): NSCSVG? {
val view = NSCSVG(context)
val file = File(path)
if (file.length() == 0L) {
return null
}
val text = file.readText()
val dim = parseSVGDimensions(context, text)
view.layoutParams = ViewGroup.LayoutParams(dim.width, dim.height)
val bitmap = Bitmap.createBitmap(dim.width, dim.height, Bitmap.Config.ARGB_8888)
nativeDrawSVGFromPath(bitmap, context.resources.displayMetrics.density, path)
return view
}
@JvmStatic
fun fromPath(context: Context, path: String, callback: Callback) {
val executor = Executors.newSingleThreadExecutor()
executor.execute {
val view = NSCSVG(context)
val file = File(path)
if (file.length() == 0L) {
callback.onSuccess(null)
return@execute
}
val text = file.readText()
val dim = parseSVGDimensions(context, text)
view.layoutParams = ViewGroup.LayoutParams(dim.width, dim.height)
val bitmap = Bitmap.createBitmap(dim.width, dim.height, Bitmap.Config.ARGB_8888)
nativeDrawSVGFromPath(bitmap, context.resources.displayMetrics.density, path)
callback.onSuccess(view)
}
}
@JvmStatic
fun fromStringSync(context: Context, width: Int, height: Int, string: String): NSCSVG {
val view = NSCSVG(context)
view.layoutParams = ViewGroup.LayoutParams(width, height)
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
nativeDrawSVG(bitmap, context.resources.displayMetrics.density, string)
view.bitmap = bitmap
return view
}
@JvmStatic
fun fromString(context: Context, width: Int, height: Int, string: String, callback: Callback) {
val executor = Executors.newSingleThreadExecutor()
executor.execute {
val view = NSCSVG(context)
view.layoutParams = ViewGroup.LayoutParams(width, height)
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
nativeDrawSVG(bitmap, context.resources.displayMetrics.density, string)
view.bitmap = bitmap
callback.onSuccess(view)
}
}
@JvmStatic
fun fromRemote(context: Context, path: String, callback: Callback) {
val executor = Executors.newSingleThreadExecutor()
executor.execute {
try {
val url = URL(path)
val connection = url.openConnection() as HttpURLConnection
val br = BufferedReader(InputStreamReader(connection.inputStream))
val svg = br.readText()
val view = NSCSVG(context)
val dim = parseSVGDimensions(context, svg)
view.layoutParams = ViewGroup.LayoutParams(dim.width, dim.height)
val bitmap = Bitmap.createBitmap(dim.width, dim.height, Bitmap.Config.ARGB_8888)
nativeDrawSVG(bitmap, context.resources.displayMetrics.density, svg)
view.bitmap = bitmap
callback.onSuccess(view)
} catch (e: Exception) {
e.printStackTrace()
callback.onSuccess(null)
}
}
}
@JvmStatic
fun fromRemoteSync(
context: Context,
path: String
): NSCSVG? {
var view: NSCSVG? = null
val thread = Thread {
view = NSCSVG(context)
val url = URL(path)
val connection = url.openConnection() as HttpURLConnection
val br = BufferedReader(InputStreamReader(connection.inputStream))
val svg = br.readText()
val dim = parseSVGDimensions(context, svg)
view?.layoutParams = ViewGroup.LayoutParams(dim.width, dim.height)
val bitmap = Bitmap.createBitmap(dim.width, dim.height, Bitmap.Config.ARGB_8888)
nativeDrawSVG(bitmap, context.resources.displayMetrics.density, svg)
view?.bitmap = bitmap
}
thread.start()
thread.join()
return view
}
internal class Dimensions {
var width = 0
var height = 0
}
internal fun parseSVGDimensions(context: Context, svgString: String): Dimensions {
val pattern = Pattern.compile("<svg\\s*([^>]*)>", Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(svgString)
val dimensions = Dimensions()
if (matcher.find()) {
val svgAttributes = matcher.group(1)
val attributesPattern = Pattern.compile("(?:width|height|viewBox)\\s*=\\s*\"([^\"]+)\"")
val attributesMatcher = attributesPattern.matcher(svgAttributes)
var width = 0.0
var height = 0.0
var widthDefined = false
var heightDefined = false
val viewBox = DoubleArray(4)
while (attributesMatcher.find()) {
val attributePair = attributesMatcher.group(0)?.trim()
attributePair?.split("=")?.let { parts ->
if (parts.size == 2) {
val attributeName = parts[0].trim()
var attributeValue = parts[1].trim().replace("\"", "")
val stringLiteralPattern = Pattern.compile("\\\\\"(\\d*\\.?\\d+)\\\\\"")
val stringLiteralMatcher = stringLiteralPattern.matcher(attributeValue)
if (stringLiteralMatcher.matches()) {
stringLiteralMatcher.group(1)?.let {
attributeValue = it
}
}
if (attributeName == "width") {
width = attributeValue.toDouble() * context.resources.displayMetrics.density
widthDefined = true
} else if (attributeName == "height") {
height = attributeValue.toDouble() * context.resources.displayMetrics.density
heightDefined = true
} else if (attributeName == "viewBox") {
val viewBoxValues = parts[1].trim { it <= ' ' }
.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (i in 0 until min(4.0, viewBoxValues.size.toDouble()).toInt()) {
var value = viewBoxValues[i].trim().replace("\"", "");
val slm = stringLiteralPattern.matcher(value)
if (slm.matches()) {
slm.group(1)?.let {
value = it
}
}
viewBox[i] = value.toDouble()
}
}
}
}
}
if (width == 0.0 && viewBox.size == 4) {
val viewBoxWidth = viewBox[2]
val viewBoxHeight = viewBox[3]
val aspectRatio = viewBoxWidth / viewBoxHeight
width = context.resources.displayMetrics.widthPixels * aspectRatio
}
if (height == 0.0 && viewBox.size == 4) {
val viewBoxWidth = viewBox[2]
val viewBoxHeight = viewBox[3]
val aspectRatio = viewBoxWidth / viewBoxHeight
height = context.resources.displayMetrics.heightPixels / aspectRatio
}
if ((width == 0.0 || width.isNaN()) && !widthDefined) {
width = context.resources.displayMetrics.widthPixels.toDouble()
}
if ((height == 0.0 || height.isNaN()) && !heightDefined) {
height = context.resources.displayMetrics.heightPixels.toDouble()
}
dimensions.width = width.toInt()
dimensions.height = height.toInt()
}
return dimensions
}
}
}
| 13 | JavaScript | 18 | 88 | c26750fbd89fdb37ecdaf02ee650bd59b468ae57 | 9,833 | canvas | Apache License 2.0 |
src/main/kotlin/io/github/tundraclimate/tree/OnBreakLog.kt | TundraClimate | 523,355,117 | false | null | package io.github.tundraclimate.tree
import io.github.tundraclimate.coldlib.server.ListenEvent
import io.github.tundraclimate.coldlib.util.runTaskLater
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.inventory.ItemStack
object OnBreakLog {
fun register() {
ListenEvent.addBreakBlockTask { e ->
if (!e.block.type.isLog()) return@addBreakBlockTask
val world = e.block.world
if (LumberJack.conf.isDefaultEnable() || e.player.onSneak(ShiftAction.ENABLED)) {
if (e.player.onSneak(ShiftAction.DISABLED))
return@addBreakBlockTask
val searcher = LogSearcher(world)
val collectLoc = e.block.location
val logs = mutableListOf<Block>()
val block = e.block
val sap = getSapling(block.type)
var count = LumberJack.conf.getBreakLimit()
fun addLogs(loc: Location) {
val upper = searcher.checkUpper(loc).toMutableList()
val lower = searcher.checkLower(loc)
if (LumberJack.conf.isBreakLeaf()) upper.addAll(searcher.checkLeaf(loc))
logs.add(world.getBlockAt(loc))
count -= 1
if (count == 0) return
if (upper.isEmpty())
if (!LumberJack.conf.isBreakUpper()) {
if (lower.isEmpty()) return
} else return
upper.forEach {
if (!logs.contains(it))
addLogs(it.location)
}
if (!LumberJack.conf.isBreakUpper())
lower.forEach {
if (!logs.contains(it))
addLogs(it.location)
}
}
addLogs(collectLoc)
if (!LumberJack.conf.isCollectItems())
logs.forEach { it.breakNaturally(e.player.inventory.itemInMainHand) }
else {
val tmp = logs.map { it.type }
val b = world.getBlockAt(collectLoc)
logs.forEach { it.type = Material.AIR }
tmp.forEach {
b.type = it
b.breakNaturally(e.player.inventory.itemInMainHand)
}
}
if ((LumberJack.conf.isAutoSupply() || e.player.onSneak(ShiftAction.AUTO_SUPPLY)) && Location(
world,
collectLoc.blockX.toDouble(),
(collectLoc.blockY - 1).toDouble(),
collectLoc.blockZ.toDouble()
).block.type.isDirt()
) {
if (e.player.inventory.contains(getSapling(block.type))) {
runTaskLater(1L) {
world.getBlockAt(collectLoc).type = sap
e.player.inventory.let {
val i = it.first(sap)
val newElem = ItemStack(it.elementAt(i))
newElem.amount -= 1
it.setItem(i, newElem)
}
}
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 8503bed78d0ed14e24a7dad3b830a71cc3c76be5 | 3,484 | LumberJack | MIT License |
app/src/main/java/com/rami/koroutinesdemo/ui/di/UIModule.kt | rami-de | 214,674,311 | false | null | package com.rami.koroutinesdemo.ui.di
import android.content.Context
import android.net.Uri
import com.squareup.picasso.Picasso
import com.squareup.picasso.Request
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class UIModule {
val BASE_TMDB_IMAGES_URL = "https://image.tmdb.org/t/p/w500"
@Provides
@Singleton
fun providePicasso(context: Context): Picasso {
return Picasso.Builder(context)
.requestTransformer {
val request = Request.Builder(Uri.parse(BASE_TMDB_IMAGES_URL + it.uri.toString())).build()
request
}
.build()
}
} | 0 | Kotlin | 0 | 0 | 2b748717e49ead520bc5c4f2b247b4e7fc826f83 | 660 | KoroutinesDemo | MIT License |
adprofiles-tk-logics/src/main/kotlin/ru/logics/chains/stubs/ProfileUpdateStub.kt | otuskotlin | 377,707,851 | false | null | package logics.chains.stubs
import ProfileStub
import cor.ICorChainDsl
import cor.handlers.chain
import cor.handlers.worker
import context.CorStatus
import context.MpContext
import exceptions.MpStubCaseNotFound
import models.MpStubCase
internal fun ICorChainDsl<MpContext>.adUpdateStub(title: String) = chain {
this.title = title
on { status == CorStatus.RUNNING && stubCase != MpStubCase.NONE }
worker {
this.title = "Успешный стабкейс для UPDATE"
on { stubCase == MpStubCase.SUCCESS }
handle {
responseProfile = requestProfile.copy(role = ProfileStub.getModel().role)
status = CorStatus.FINISHING
}
}
worker {
this.title = "Обработка отсутствия подходящего стабкейса"
on { status == CorStatus.RUNNING }
handle {
status = CorStatus.FAILING
addError(
e = MpStubCaseNotFound(stubCase.name),
)
}
}
}
| 1 | Kotlin | 0 | 0 | b55653c2119e43f7b91b2bc878dcf4ce082615a0 | 967 | ok-202105-adprofiles-tk | MIT License |
master-package/bonus-lessons-2020/integration-tests-rest-api/src/main/kotlin/com/testwithspring/master/user/PersonFinder.kt | brabii | 428,071,292 | true | {"Markdown": 102, "Text": 2, "Ignore List": 1, "INI": 124, "Maven POM": 95, "Gradle": 82, "Java": 1553, "Java Server Pages": 28, "XML": 231, "Java Properties": 58, "SQL": 24, "HTML": 64, "CSS": 4, "JavaScript": 38, "JSON": 6, "JSON with Comments": 2, "Less": 2, "Ant Build System": 2, "Kotlin": 140, "Groovy": 276, "AsciiDoc": 1} | package com.testwithspring.master.user
import com.testwithspring.master.common.NotFoundException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.jdbc.core.RowMapper
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import java.sql.ResultSet
import java.sql.SQLException
import java.util.*
/**
* Provides a function which queries person information from
* the database.
*/
@Component
open class PersonFinder(@Autowired private val jdbcTemplate: NamedParameterJdbcTemplate) {
companion object {
private val LOGGER: Logger = LoggerFactory.getLogger(PersonFinder::class.java)
private const val QUERY_FIND_PERSON_INFORMATION = "SELECT u.id as id, " +
"u.name AS name " +
"FROM user_accounts u " +
"WHERE u.id = :id"
private class PersonInformationRowMapper : RowMapper<PersonDTO> {
@Throws(SQLException::class)
override fun mapRow(rs: ResultSet, rowNum: Int): PersonDTO {
return PersonDTO(
name = rs.getString("name"),
userId = rs.getLong("id")
)
}
}
}
/**
* Finds the person information information of the specified user.
* @param userId The user id of the user who information will be returned.
* @return The "found" person information.
* @throws NotFoundException If no person is found with the given user id.
*/
@Transactional(readOnly = true)
open fun findPersonInformationByUserId(userId: Long): PersonDTO {
LOGGER.info("Finding person information by using the user id: {}", userId)
try {
val found: PersonDTO = jdbcTemplate.queryForObject(
QUERY_FIND_PERSON_INFORMATION,
mapOf(Pair("id", userId)),
PersonInformationRowMapper()
)
LOGGER.info("Found person information: {}", found)
return found
} catch (ex: EmptyResultDataAccessException) {
LOGGER.error("No person information found with user id: {}", userId)
throw NotFoundException("No person information found with user id: $userId")
}
}
} | 0 | null | 0 | 1 | 34ff510322734bb1c2ac13b732591a2bc88644d0 | 2,516 | test-with-spring | Apache License 2.0 |
kuery-client-compiler/src/main/kotlin/dev/hsbrysk/kuery/compiler/ir/misc/CallableIds.kt | be-hase | 806,354,598 | false | {"Kotlin": 164350} | package dev.hsbrysk.kuery.compiler.ir.misc
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
internal object CallableIds {
val LIST_OF = CallableId(FqName("kotlin.collections"), Name.identifier("listOf"))
}
| 2 | Kotlin | 0 | 7 | e1480c7c50267eb36a42f49d4855a82c5aa4a1e7 | 285 | kuery-client | MIT License |
src/main/kotlin/ecommerce/customer/restvo/CrOrderDetailInfoResultVo.kt | teneous | 126,196,808 | false | {"Kotlin": 39545, "HTML": 5893, "JavaScript": 484, "Java": 437} | package ecommerce.customer.restvo
/**
* 订单明细
* Created by syoka on 2018/7/6.
*/
data class CrOrderDetailInfoResultVo(
/*订单信息*/
var order_info:CrOrderDetailBaseInfoVo?=null,
/*顾客信息*/
var customer_info:CrOrderDetailCustomerInfoVo?=null,
/*商品信息*/
var product_info:List<CrOrderDetailProductInfoVo>?=null
) | 0 | Kotlin | 1 | 1 | afe1bc82f608b127fa77a5c42a9df50030849659 | 330 | ecommerce-kotlin | Apache License 2.0 |
commons/src/test/kotlin/com/itangcent/common/string/GracefulToStringKtTest.kt | Earth-1610 | 178,314,657 | false | {"Kotlin": 1216447, "Java": 35079, "Shell": 3153} | package com.itangcent.common.string
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
/**
* Test case of [GracefulToString]
*/
internal class GracefulToStringKtTest {
@Test
fun gracefulString() {
assertNull(null.gracefulString())
assertEquals("", "".gracefulString())
assertEquals("xxx", "xxx".gracefulString())
assertEquals("123", 123.gracefulString())
assertEquals("123.456", 123.456.gracefulString())
assertEquals("abc,123.456", arrayOf("abc", 123.456).gracefulString())
assertEquals("123.456,abc", listOf(123.456, "abc").gracefulString())
assertEquals("123.456,abc,abc,123.456", listOf(123.456, "abc", arrayOf("abc", 123.456)).gracefulString())
}
} | 0 | Kotlin | 5 | 8 | af802e7ea26b233610c9d35af89365c93f48158b | 821 | intellij-kotlin | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/EmojiPeople.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/EmojiPeople")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val EmojiPeople: SvgIconComponent
| 10 | null | 5 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 204 | kotlin-wrappers | Apache License 2.0 |
pubnub-chat-impl/src/commonMain/kotlin/com/pubnub/chat/internal/message/MessageImpl.kt | pubnub | 798,715,242 | false | {"Kotlin": 744105, "Ruby": 9635, "Swift": 1599, "HTML": 454, "JavaScript": 214} | package com.pubnub.chat.internal.message
import com.pubnub.api.JsonElement
import com.pubnub.api.models.consumer.history.PNFetchMessageItem
import com.pubnub.api.models.consumer.history.PNFetchMessageItem.Action
import com.pubnub.api.models.consumer.pubsub.PNMessageResult
import com.pubnub.chat.Message
import com.pubnub.chat.internal.ChatInternal
import com.pubnub.chat.internal.defaultGetMessageResponseBody
import com.pubnub.chat.types.EventContent
data class MessageImpl(
override val chat: ChatInternal,
override val timetoken: Long,
override val content: EventContent.TextMessageContent,
override val channelId: String,
override val userId: String,
override val actions: Map<String, Map<String, List<Action>>>? = null,
val metaInternal: JsonElement? = null
) : BaseMessage<Message>(
chat = chat,
timetoken = timetoken,
content = content,
channelId = channelId,
userId = userId,
actions = actions,
metaInternal = metaInternal
) {
override fun copyWithActions(actions: Actions?): Message = copy(actions = actions)
companion object {
internal fun fromDTO(chat: ChatInternal, pnMessageResult: PNMessageResult): Message {
val content =
chat.config.customPayloads?.getMessageResponseBody?.invoke(pnMessageResult.message, pnMessageResult.channel, ::defaultGetMessageResponseBody)
?: defaultGetMessageResponseBody(pnMessageResult.message)
?: EventContent.UnknownMessageFormat(pnMessageResult.message)
return MessageImpl(
chat,
pnMessageResult.timetoken!!,
content,
pnMessageResult.channel,
pnMessageResult.publisher!!,
metaInternal = pnMessageResult.userMetadata
)
}
internal fun fromDTO(chat: ChatInternal, messageItem: PNFetchMessageItem, channelId: String): Message {
val content =
chat.config.customPayloads?.getMessageResponseBody?.invoke(messageItem.message, channelId, ::defaultGetMessageResponseBody)
?: defaultGetMessageResponseBody(messageItem.message)
?: EventContent.UnknownMessageFormat(messageItem.message)
return MessageImpl(
chat,
messageItem.timetoken!!,
content,
channelId,
messageItem.uuid!!,
messageItem.actions,
messageItem.meta
)
}
}
}
| 1 | Kotlin | 0 | 2 | cd0571fac31ef9efe67c4bb8f2f19990d6c36a95 | 2,586 | kmp-chat | MIT License |
data/src/main/java/com/andremion/movie/data/remote/MovieRemoteDataSource.kt | andremion | 129,904,460 | false | null | /*
* Copyright (c) 2018. <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.andremion.movie.data.remote
import com.andremion.movie.data.remote.api.MovieService
import com.andremion.movie.data.remote.api.response.ListResponse
import com.andremion.movie.data.remote.model.ConfigRemote
import com.andremion.movie.data.remote.model.MovieRemote
import io.reactivex.Single
class MovieRemoteDataSource(private val movieService: MovieService) {
fun getConfiguration(): Single<ConfigRemote> {
return movieService.getConfiguration()
}
fun findNowPlayingMovies(): Single<ListResponse<MovieRemote>> {
return movieService.findNowPlayingMovies()
}
fun findMoviesByText(text: String): Single<ListResponse<MovieRemote>> {
return movieService.findMoviesByText(text)
}
fun getMovieById(id: Long): Single<MovieRemote> {
return movieService.getMovieById(id)
}
} | 0 | Kotlin | 0 | 1 | 2c0486f9c31f0d6eb23098d46f4200b6415a0579 | 1,443 | Movie | Apache License 2.0 |
source/app/src/main/java/com/quanlv/musicplayer/ui/adapters/FolderAdapter.kt | lvquan99 | 285,835,908 | false | null | package com.quanlv.musicplayer.ui.adapters
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.quanlv.musicplayer.R
import com.quanlv.musicplayer.databinding.FolderItemBinding
import com.quanlv.musicplayer.extensions.deepEquals
import com.quanlv.musicplayer.extensions.inflateWithBinding
import com.quanlv.musicplayer.interfaces.ItemClickListener
import com.quanlv.musicplayer.models.Folder
class FolderAdapter(private val context: Context?) :
RecyclerView.Adapter<FolderAdapter.ViewHolder>() {
var folderList: MutableList<Folder> = mutableListOf()
var itemClickListener: ItemClickListener<Folder>? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val viewBinding = parent.inflateWithBinding<FolderItemBinding>(R.layout.folder_item)
return ViewHolder(viewBinding)
}
override fun getItemCount(): Int {
return folderList.size
}
fun updateDataSet(newList: List<Folder>) {
folderList = newList.toMutableList()
notifyDataSetChanged()
}
private fun getItem(position: Int) = folderList[position]
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
inner class ViewHolder(private val binding: FolderItemBinding) :
RecyclerView.ViewHolder(binding.root), View.OnClickListener {
fun bind(folder: Folder) {
binding.apply {
this.folder = folder
itemMenu.setOnClickListener(this@ViewHolder)
container.setOnClickListener(this@ViewHolder)
executePendingBindings()
}
}
override fun onClick(view: View) {
if (itemClickListener != null)
when (view.id) {
R.id.item_menu -> itemClickListener!!.onPopupMenuClick(
view,
adapterPosition,
getItem(adapterPosition),
folderList
)
R.id.container -> itemClickListener!!.onItemClick(
view,
adapterPosition,
getItem(adapterPosition)
)
}
}
}
} | 0 | Kotlin | 1 | 2 | fd58dc83f5f03e8d407bb100dc1a170da65d7742 | 2,375 | music-application | The Unlicense |
app/src/main/java/ru/kovsh/tasku/ui/mainMenu/view/MainMenuView.kt | KovshefulCoder | 670,538,720 | false | null | package ru.kovsh.tasku.ui.mainMenu.view
import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.debounce
import ru.kovsh.tasku.R
import ru.kovsh.tasku.ui.auth.entities.sharedStates.UserAuthenticationState
import ru.kovsh.tasku.ui.main.view.MainScreen
import ru.kovsh.tasku.ui.mainMenu.entities.AreaUI
import ru.kovsh.tasku.ui.mainMenu.entities.MenuCategory
import ru.kovsh.tasku.ui.mainMenu.entities.menuCategories
import ru.kovsh.tasku.ui.mainMenu.viewModel.MainMenuViewModel
import ru.kovsh.tasku.ui.shared.SharedViewModel
import ru.kovsh.tasku.ui.shared.entities.statesClasses.LoadingState
import ru.kovsh.tasku.ui.theme.Background
import ru.kovsh.tasku.ui.theme.Base0
import ru.kovsh.tasku.ui.theme.Base200
import ru.kovsh.tasku.ui.theme.Base500
import ru.kovsh.tasku.ui.theme.Base800
import ru.kovsh.tasku.ui.theme.DarkBlueBackground800
import ru.kovsh.tasku.ui.theme.DarkBlueBackground900
import ru.kovsh.tasku.ui.theme.PlaceholderText
import ru.kovsh.tasku.ui.theme.typography
@SuppressLint("StateFlowValueCalledInComposition")
@Composable
internal fun MainMenuScreen(
onUnauthorized: () -> Unit,
onRepeatLoadingTasks: () -> Unit,
onResetRemoteState: () -> Unit,
onAreaClick: (Long, String) -> Unit,
onSettingsClick: () -> Unit,
onMenuButtonClicked: (Int) -> Unit,
viewModel: MainMenuViewModel,
sharedViewModel: SharedViewModel,
) {
val sharedState by sharedViewModel.state.collectAsStateWithLifecycle()
val screenState by viewModel.screenState.collectAsState()
val fabStates by viewModel.fabState.collectAsStateWithLifecycle()
val areas = viewModel.areas
if (sharedState.authorizationStatus == UserAuthenticationState.Unauthorized) {
onUnauthorized()
}
when (screenState.isAuthorized) {
UserAuthenticationState.None -> {
MainScreen()
}
UserAuthenticationState.Unauthorized -> {
onUnauthorized()
}
UserAuthenticationState.Authorized, UserAuthenticationState.NoServer -> {
Log.i("MainMenuScreen", "Tasks loading status: ${sharedState.remoteState}")
MainMenuScreen(
onFabClick = viewModel::onFabClick,
onUpdateVisibleAreas = viewModel::onUpdateVisibleAreas,
onFabChange = viewModel::onFabChange,
onFabStart = viewModel::onFabStart,
onFabEnd = viewModel::onFabEnd,
onAddNewArea = viewModel::onAddNewArea,
onCalculateLazySizes = viewModel::onCalculateLazySizesForFAB,
onAreaClick = onAreaClick,
onSettingsClick = onSettingsClick,
onRepeatLoadingTasks = onRepeatLoadingTasks,
onResetRemoteState = onResetRemoteState,
onMenuButtonClicked = onMenuButtonClicked,
menuCategories = menuCategories,
areas = areas,
textFieldUnderFabIndex = fabStates.textFieldUnderFabIndex,
textFieldUnderFabHeight = fabStates.textFieldUnderFabHeight,
newElementIndex = screenState.newElementIndex,
loadTasksStatus = sharedState.remoteState,
)
}
}
}
@OptIn(FlowPreview::class)
@Composable
private fun MainMenuScreen(
onFabClick: () -> Unit,
onUpdateVisibleAreas: (MutableMap<Int, Pair<Float, Float>>) -> Unit,
onFabChange: (Float, Float) -> Unit,
onFabStart: () -> Unit,
onFabEnd: () -> Unit,
onCalculateLazySizes: (Int, Int, Dp) -> Unit,
onAddNewArea: (String) -> Unit,
onAreaClick: (Long, String) -> Unit,
onSettingsClick: () -> Unit,
onRepeatLoadingTasks: () -> Unit,
onResetRemoteState: () -> Unit,
onMenuButtonClicked: (Int) -> Unit = {},
menuCategories: List<MenuCategory>,
areas: List<AreaUI>,
modifier: Modifier = Modifier,
textFieldUnderFabIndex: Int = -2,
textFieldUnderFabHeight: Dp = 0.dp,
newElementIndex: Int = -2,
loadTasksStatus: LoadingState = LoadingState.Idle,
) {
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
val focusRequester = remember { FocusRequester() }
val lazyColumnYCoordinate = remember { mutableStateOf(0f) }
val listState = rememberLazyListState()
val visibleAreasCoordinates = remember { mutableMapOf<Int, Pair<Float, Float>>() }
Column(
modifier = modifier.fillMaxSize(),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Column(modifier = Modifier.weight(15f)) {
SearchButton(textID = R.string.main_menu_search_placeholder)
Spacer(modifier = Modifier.height(20.dp)) //TODO() FIX
MenuCategories(
onCalculateLazySizes = onCalculateLazySizes,
onMenuButtonClicked = onMenuButtonClicked,
menuCategories = menuCategories
)
Divider(color = Base800)
LazyColumn(
modifier = Modifier.onGloballyPositioned { coordinates ->
lazyColumnYCoordinate.value = coordinates.positionInRoot().y
},
state = listState
) {
if (areas.isEmpty() && (textFieldUnderFabIndex == -1 || newElementIndex == -1)) {
item {
TextFieldPlaceholderUnderFab(
onAddNewArea,
textFieldUnderFabHeight,
focusRequester
)
}
}
itemsIndexed(areas) { index, area ->
RenderLazyColumn(
onCalculateLazySizes = onCalculateLazySizes,
onAddNewArea = onAddNewArea,
onAreaClick = onAreaClick,
onReturnCoordinates = { i, x, y ->
if (y >= lazyColumnYCoordinate.value) {
visibleAreasCoordinates[i] = Pair(x, y)
} else if (visibleAreasCoordinates.containsKey(i)) {
visibleAreasCoordinates.remove(i)
}
},
index = index,
area = area,
areasSize = areas.size,
textFieldUnderFabIndex = textFieldUnderFabIndex,
textFieldUnderFabHeight = textFieldUnderFabHeight,
newElementIndex = newElementIndex,
focusRequester = focusRequester
)
}
}
// transfer coordinates of visible areas to the viewModel
LaunchedEffect(listState) {
snapshotFlow { listState.layoutInfo.visibleItemsInfo }
.debounce(300) // delay the collection of data to not overburden the system
.collect { visibleItemPositions ->
val indexes = visibleItemPositions.map { it.index }
visibleAreasCoordinates.keys.removeAll { it !in indexes }
onUpdateVisibleAreas(visibleAreasCoordinates)
}
}
val areaPx = with(LocalDensity.current) { textFieldUnderFabHeight.toPx() }
LaunchedEffect(
textFieldUnderFabIndex == (visibleAreasCoordinates.keys.maxOrNull() ?: -3)
) {
// -3 - 100% not equal to textFieldUnderFabIndex
if (textFieldUnderFabIndex != -2) {
listState.scrollBy(areaPx)
delay(500)
}
}
}
Column(modifier = Modifier.weight(1f, false))
{
SettingsButton(
onSettingsClick = onSettingsClick,
textID = R.string.main_menu_settings
)
}
}
FAB(
modifier = Modifier.align(Alignment.BottomEnd),
onFabClick = onFabClick,
onFabChange = onFabChange,
onFabStart = onFabStart,
onFabEnd = onFabEnd,
focusRequester = focusRequester
)
if (loadTasksStatus != LoadingState.Idle) {
LoadingStatus(
onRepeatLoading = onRepeatLoadingTasks,
onResetRemoteState = onResetRemoteState,
modifier = Modifier.align(Alignment.TopEnd),
remoteState = loadTasksStatus
)
}
}
}
@Composable
fun SearchButton(textID: Int, modifier: Modifier = Modifier) {
val text = stringResource(id = textID)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Spacer(modifier = Modifier.weight(1f))
Button(onClick = { /*TODO*/ },
modifier = Modifier.weight(9f),
colors = ButtonDefaults.buttonColors(
backgroundColor = DarkBlueBackground900, contentColor = PlaceholderText
),
shape = RoundedCornerShape(10.dp),
content = {
Image(
painter = painterResource(id = R.drawable.ic_main_menu_search),
contentDescription = text,
modifier = Modifier.padding(end = 8.dp)
)
Text(
text = text,
style = typography.caption,
)
})
Spacer(modifier = Modifier.weight(1f))
}
}
@Composable
fun MenuCategories(
onCalculateLazySizes: (Int, Int, Dp) -> Unit,
onMenuButtonClicked: (Int) -> Unit = {},
modifier: Modifier = Modifier,
menuCategories: List<MenuCategory>,
) {
Column(
verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start
) {
for (i in menuCategories.indices) when (i) {
1, 4, menuCategories.lastIndex -> {
MainMenuCategory(
onCalculateLazySizes = onCalculateLazySizes,
category = menuCategories[i],
onMenuButtonClicked = { onMenuButtonClicked(menuCategories[i].id) }
)
Spacer(modifier = Modifier.height(12.dp))
}
else -> MainMenuCategory(
onCalculateLazySizes = onCalculateLazySizes,
category = menuCategories[i],
onMenuButtonClicked = { onMenuButtonClicked(menuCategories[i].id) }
)
}
}
}
@Composable
fun MainMenuCategory(
onCalculateLazySizes: (Int, Int, Dp) -> Unit,
onMenuButtonClicked: () -> Unit = {},
modifier: Modifier = Modifier,
category: MenuCategory,
) {
val density = LocalDensity.current.density
TextButton(
onClick = onMenuButtonClicked,
modifier = Modifier
.fillMaxWidth()
.onSizeChanged {
onCalculateLazySizes(it.width, it.height, (it.height / density).dp)
},
content = {
val name = stringResource(id = category.nameID)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start,
) {
Image(
painter = painterResource(id = category.iconID),
contentDescription = name,
modifier = Modifier
.weight(1f, false)
.fillMaxWidth()
)
Text(
text = name, style = typography.subtitle2, modifier = Modifier.weight(8f)
)
//TODO() This row does not center vertically
Row(
modifier = Modifier
.weight(1f, false)
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
if (category.tasksCounter > 0) {
Text(
modifier = Modifier,
text = category.tasksCounter.toString(),
style = typography.body1.copy(
fontWeight = FontWeight.Bold, color = Base500
)
)
}
}
}
})
}
@Composable
fun SettingsButton(
onSettingsClick: () -> Unit,
textID: Int, modifier: Modifier = Modifier
) {
val text = stringResource(id = textID)
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Button(
onClick = onSettingsClick,
colors = ButtonDefaults.buttonColors(backgroundColor = Background),
shape = RoundedCornerShape(10.dp),
content = {
Image(
painter = painterResource(id = R.drawable.ic_main_menu_settings),
contentDescription = text,
modifier = Modifier.padding(end = 8.dp)
)
Text(
text = text,
style = typography.button.copy(
color = Base500
),
)
})
}
}
@Composable
fun AreaButton(
onAreaClick: (Long, String) -> Unit,
modifier: Modifier = Modifier,
area: AreaUI,
) {
TextButton(
onClick = { onAreaClick(area.id, area.name) },
colors = ButtonDefaults.textButtonColors(backgroundColor = area.color),
modifier = modifier.fillMaxWidth()
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
AreaImage(
modifier = Modifier
.weight(1f, false)
.fillMaxWidth(),
areaName = area.name,
areaIconID = area.iconID
)
Text(
text = area.name, style = typography.subtitle2, modifier = Modifier.weight(9f)
)
}
}
}
@Composable
fun AreaImage(
modifier: Modifier = Modifier,
areaName: String,
areaIconID: Int = R.drawable.ic_main_menu_area
) {
Image(
painter = painterResource(id = areaIconID),
contentDescription = areaName,
modifier = modifier
)
}
@Composable
fun RenderLazyColumn(
onCalculateLazySizes: (Int, Int, Dp) -> Unit,
onAddNewArea: (String) -> Unit,
onReturnCoordinates: (Int, Float, Float) -> Unit,
onAreaClick: (Long, String) -> Unit,
index: Int,
area: AreaUI,
areasSize: Int,
textFieldUnderFabIndex: Int,
textFieldUnderFabHeight: Dp,
newElementIndex: Int,
focusRequester: FocusRequester,
) {
if (index == 0 && (textFieldUnderFabIndex == -1 || newElementIndex == -1)) {
TextFieldPlaceholderUnderFab(onAddNewArea, textFieldUnderFabHeight, focusRequester)
}
val density = LocalDensity.current.density
AreaButton(
onAreaClick = onAreaClick,
modifier = Modifier
.onSizeChanged {
onCalculateLazySizes(it.width, it.height, (it.height / density).dp)
}
.onGloballyPositioned { coordinates ->
onReturnCoordinates(
index,
coordinates.positionInRoot().x,
coordinates.positionInRoot().y
)
},
area = area,
)
if (index != -1) {
if ((index == textFieldUnderFabIndex || index == newElementIndex) ||
(index == areasSize - 1 && (textFieldUnderFabIndex == areasSize - 1 || newElementIndex == areasSize - 1))
) {
TextFieldPlaceholderUnderFab(onAddNewArea, textFieldUnderFabHeight, focusRequester)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoadingStatus(
onRepeatLoading: () -> Unit,
onResetRemoteState: () -> Unit,
modifier: Modifier = Modifier,
remoteState: LoadingState
) {
when (remoteState) {
LoadingState.Loading -> {
CircularProgressIndicator(
color = Base500,
modifier = modifier.size(20.dp),
strokeWidth = 2.dp
)
}
LoadingState.Error -> {
ModalBottomSheet(
onDismissRequest = onResetRemoteState,
containerColor = DarkBlueBackground900,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(DarkBlueBackground900)
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Error during loading tasks",
style = typography.body1.copy(
color = Base0
)
)
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Button(
onClick = onResetRemoteState,
colors = ButtonDefaults.buttonColors(
backgroundColor = DarkBlueBackground800
),
) {
Text(
text = "Continue offline",
style = typography.button.copy(
color = Base200
)
)
}
Button(
onClick = onResetRemoteState,
colors = ButtonDefaults.buttonColors(
backgroundColor = DarkBlueBackground800
),
) {
Text(
text = "Repeat",
style = typography.button.copy(
color = Base200
)
)
}
}
}
}
// Box(
// modifier = Modifier.clip(RoundedCornerShape(10.dp))
// ) {
// Row(
// modifier = modifier.background(DarkBlueBackground900),
// verticalAlignment = Alignment.CenterVertically,
// horizontalArrangement = Arrangement.SpaceAround
// ) {
// Spacer(modifier = Modifier.width(4.dp))
// Image(
// painter = painterResource(id = R.drawable.ic_failed_loading),
// contentDescription = "Error",
// modifier = modifier.size(24.dp)
// )
// Spacer(modifier = Modifier.width(4.dp))
// Text(
// text = "Error during loading tasks",
// style = typography.body1.copy(
// color = Base0
// )
// )
// Spacer(modifier = Modifier.width(4.dp))
// Button(onClick = onRepeatLoading) {
// Text(
// text = "Repeat",
// style = typography.caption.copy(
// color = Base0
// ),
// )
// }
// Spacer(modifier = Modifier.width(4.dp))
// }
// }
}
LoadingState.Success -> {
Image(
painter = painterResource(id = R.drawable.ic_success_loading),
contentDescription = "Error",
modifier = modifier
)
}
else -> {}
}
} | 0 | Kotlin | 0 | 0 | 5b4a23217599e03b8c69bcde10295803cca728d5 | 23,267 | Tasku | Apache License 2.0 |
android/app/src/main/java/com/example/bachelorproef/util/onTextChangedListener.kt | BrackeNavaron | 251,107,076 | false | null | package com.example.bachelorproef.util
interface IOnTextChangedListener {
fun onTextChanged(text: CharSequence?)
} | 0 | Kotlin | 0 | 0 | 30b9e1803903f1144386a2fb0c6e8be229822cf5 | 119 | bachproef_sourcecode | MIT License |
app/src/main/kotlin/batect/ui/fancy/CleanupProgressDisplayLine.kt | batect | 102,647,061 | false | null | /*
Copyright 2017-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 batect.ui.fancy
import batect.config.Container
import batect.execution.model.events.ContainerCreatedEvent
import batect.execution.model.events.ContainerRemovedEvent
import batect.execution.model.events.TaskEvent
import batect.execution.model.events.TaskNetworkCreatedEvent
import batect.execution.model.events.TaskNetworkDeletedEvent
import batect.ui.text.Text
import batect.ui.text.TextRun
import batect.utils.pluralize
class CleanupProgressDisplayLine {
private var networkHasBeenCreated = false
private var networkHasBeenDeleted = false
private val containersCreated = mutableSetOf<Container>()
private val containersRemoved = mutableSetOf<Container>()
fun onEventPosted(event: TaskEvent) {
when (event) {
is ContainerCreatedEvent -> containersCreated.add(event.container)
is ContainerRemovedEvent -> containersRemoved.add(event.container)
is TaskNetworkCreatedEvent -> networkHasBeenCreated = true
is TaskNetworkDeletedEvent -> networkHasBeenDeleted = true
}
}
fun print(): TextRun {
val text = when {
containersStillToCleanUp.isNotEmpty() -> printContainerCleanupStatus()
stillNeedToCleanUpNetwork -> printNetworkCleanupStatus()
else -> TextRun("Clean up: done")
}
return Text.white(text)
}
private val containersStillToCleanUp: Set<Container>
get() = containersCreated - containersRemoved
private val stillNeedToCleanUpNetwork: Boolean
get() = networkHasBeenCreated && !networkHasBeenDeleted
private fun printContainerCleanupStatus(): TextRun {
val containers = containersStillToCleanUp.map { it.name }.sorted().map { Text.bold(it) }
return Text("Cleaning up: ${pluralize(containers.size, "container")} (") + humanReadableList(containers) + Text(") left to remove...")
}
private fun printNetworkCleanupStatus(): TextRun {
return TextRun("Cleaning up: removing task network...")
}
}
| 24 | null | 47 | 687 | 67c942241c7d52b057c5268278d6252301c48087 | 2,616 | batect | Apache License 2.0 |
app/src/main/java/st235/com/github/seamcarving/presentation/editor/options/EditorControlPanelView.kt | st235 | 450,792,791 | false | {"Kotlin": 161871} | package st235.com.github.seamcarving.presentation.editor.options
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import st235.com.github.seamcarving.R
import st235.com.github.seamcarving.presentation.components.ToggleGroupLayout
import st235.com.github.seamcarving.utils.dp
class EditorControlPanelView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : LinearLayout(context, attrs), ToggleGroupLayout.Toggleable {
private val iconView: AppCompatImageView
private val textView: AppCompatTextView
override var isToggleable: Boolean = false
set(newValue) {
field = newValue
invalidate()
}
init {
orientation = VERTICAL
gravity = Gravity.CENTER
setPadding(12.dp, 4.dp, 12.dp, 4.dp)
LayoutInflater.from(context).inflate(R.layout.content_editor_control_panel_view, this)
iconView = findViewById(R.id.icon_view)
textView = findViewById(R.id.text_view)
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.EditorControlPanelView)
isToggleable = typedArray.getBoolean(R.styleable.EditorControlPanelView_toggleable, false)
val iconRef = typedArray.getResourceId(R.styleable.EditorControlPanelView_ecpv_icon, -1)
if (iconRef != -1) {
iconView.setImageResource(iconRef)
}
val iconBackgroundRef = typedArray.getResourceId(R.styleable.EditorControlPanelView_ecpv_iconBackground, -1)
if (iconBackgroundRef != -1) {
iconView.setBackgroundResource(iconBackgroundRef)
}
val iconTintColorState = typedArray.getColorStateList(R.styleable.EditorControlPanelView_ecpv_iconTint)
iconView.imageTintList = iconTintColorState
textView.text = typedArray.getString(R.styleable.EditorControlPanelView_ecpv_text)
typedArray.recycle()
}
fun setText(text: String?) {
textView.text = text
}
fun setIcon(image: Drawable, scaleType: ImageView.ScaleType? = null) {
iconView.setImageDrawable(image)
scaleType?.let {
iconView.scaleType = it
}
}
fun setIconBackground(image: Drawable) {
iconView.background = image
}
override fun setSelected(selected: Boolean) {
super.setSelected(selected)
textView.isSelected = selected
iconView.isSelected = selected
}
} | 0 | Kotlin | 2 | 6 | 133399ffc67ec0e738b582e66d11bd2fbf8e41ae | 2,692 | ContentAwarePhotoEditor | MIT License |
dEngageSDK/app/src/main/java/com/dengage/sdk/manager/geofence/GeofencePermissionActivity.kt | whitehorse-technology | 221,203,061 | false | {"Kotlin": 187912, "Java": 146854} | package com.dengage.sdk.manager.geofence
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.dengage.sdk.data.cache.Prefs
import com.dengage.sdk.domain.geofence.model.DengageLocationPermission
class GeofencePermissionActivity : Activity() {
companion object {
private const val LOCATION_PERMISSION_REQUEST_CODE = 19000001
private const val BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE = 19000002
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val accessFineLocationPermission = ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
val accessCoarseLocationPermission = ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
if (!(accessFineLocationPermission || accessCoarseLocationPermission)) {
ActivityCompat.requestPermissions(
this, arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
),
LOCATION_PERMISSION_REQUEST_CODE
)
} else {
val locationPermission: DengageLocationPermission = GeofencePermissionsHelper.getLocationPermissionStatus(this)
if (locationPermission != DengageLocationPermission.ALWAYS) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
ActivityCompat.requestPermissions(
this, arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE
)
}
} else {
finish()
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String?>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED ||
grantResults.size > 1 && grantResults[1] == PackageManager.PERMISSION_GRANTED
) {
val locationPermission: DengageLocationPermission =
GeofencePermissionsHelper.getLocationPermissionStatus(this)
if (locationPermission != DengageLocationPermission.ALWAYS) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
ActivityCompat.requestPermissions(
this, arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE
)
}
}
} else {
finish()
}
} else if (requestCode == BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
finish()
if(Prefs.geofenceEnabled) {
//Dengage.startGeofence() //TODO:gerek var mı?
}
} else {
finish()
}
}
}
} | 3 | Kotlin | 0 | 1 | e0f5c23baa1d6e3eccb7051c2ad3ca32ca4df70c | 3,644 | dengage.android.sdk | MIT License |
src/main/kotlin/gitlabformkt/GitLabFormDsl.kt | s-spindler | 631,059,788 | false | null | package gitlabformkt
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
class GitLabFormDsl {
private var gitlab: GitLabDsl? = null
private var skipGroups: SkipDsl? = null
private var skipProjects: SkipDsl? = null
private var projectsAndGroups: ProjectsAndGroupsDsl? = null
fun gitlab(block: GitLabDsl.() -> Unit) {
this.gitlab = this.gitlab ?: GitLabDsl().apply(block)
}
fun projectsAndGroups(block: ProjectsAndGroupsDsl.() -> Unit) {
this.projectsAndGroups = this.projectsAndGroups ?: ProjectsAndGroupsDsl().apply(block)
}
fun skipGroups(block: SkipDsl.() -> Unit) {
this.skipGroups = this.skipGroups ?: SkipDsl().apply(block)
}
fun skipProjects(block: SkipDsl.() -> Unit) {
this.skipProjects = this.skipProjects ?: SkipDsl().apply(block)
}
fun println() = println(Json.encodeToString(this))
}
fun gitlabForm(block: GitLabFormDsl.() -> Unit) = GitLabFormDsl().apply(block)
| 0 | Kotlin | 0 | 0 | abd67bdce2cdc4b1f47b8791f8eb46d795cbfdb4 | 1,057 | gitlabform-kt | Apache License 2.0 |
module_course/src/main/java/com/knight/kotlin/module_course/CourseApplication.kt | KnightAndroid | 438,567,015 | false | {"Kotlin": 1697915, "Java": 209228, "HTML": 46741} | package com.knight.kotlin.module_course
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import com.google.auto.service.AutoService
import com.knight.kotlin.library_base.app.ApplicationLifecycle
/**
* Author:Knight
* Time:2022/6/2 15:50
* Description:CourseApplication
*/
@AutoService(ApplicationLifecycle::class)
class CourseApplication : ApplicationLifecycle {
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var mCourseApplication: CourseApplication
}
override fun onAttachBaseContext(context: Context) {
mCourseApplication = this
}
override fun onCreate(application: Application) {
}
override fun onTerminate(application: Application) {
}
override fun initSafeTask(): MutableList<() -> String> {
val list = mutableListOf<() -> String>()
return list
}
override fun initDangerousTask() {
}
} | 0 | Kotlin | 1 | 6 | 3e4bc2df92b90f6502a76779ed3465c5f0968fe3 | 960 | wanandroidByKotlin | Apache License 2.0 |
bitcoincore/src/main/kotlin/io/horizontalsystems/bitcoincore/transactions/TransactionInvalidator.kt | horizontalsystems | 147,199,533 | false | null | package io.horizontalsystems.bitcoincore.transactions
import io.horizontalsystems.bitcoincore.blocks.IBlockchainDataListener
import io.horizontalsystems.bitcoincore.core.IStorage
import io.horizontalsystems.bitcoincore.core.ITransactionInfoConverter
import io.horizontalsystems.bitcoincore.models.InvalidTransaction
import io.horizontalsystems.bitcoincore.models.Transaction
import io.horizontalsystems.bitcoincore.storage.FullTransactionInfo
class TransactionInvalidator(
private val storage: IStorage,
private val transactionInfoConverter: ITransactionInfoConverter,
private val listener: IBlockchainDataListener
) {
fun invalidate(transaction: Transaction) {
val invalidTransactionsFullInfo = getDescendantTransactionsFullInfo(transaction.hash)
if (invalidTransactionsFullInfo.isEmpty()) return
invalidTransactionsFullInfo.forEach { fullTxInfo ->
fullTxInfo.header.status = Transaction.Status.INVALID
}
val invalidTransactions = invalidTransactionsFullInfo.map { fullTxInfo ->
val txInfo = transactionInfoConverter.transactionInfo(fullTxInfo)
val serializedTxInfo = txInfo.serialize()
InvalidTransaction(fullTxInfo.header, serializedTxInfo, fullTxInfo.rawTransaction)
}
storage.moveTransactionToInvalidTransactions(invalidTransactions)
listener.onTransactionsUpdate(listOf(), invalidTransactions, null)
}
private fun getDescendantTransactionsFullInfo(txHash: ByteArray): List<FullTransactionInfo> {
val fullTransactionInfo = storage.getFullTransactionInfo(txHash) ?: return listOf()
val list = mutableListOf(fullTransactionInfo)
val inputs = storage.getTransactionInputsByPrevOutputTxHash(fullTransactionInfo.header.hash)
inputs.forEach { input ->
val descendantTxs = getDescendantTransactionsFullInfo(input.transactionHash)
list.addAll(descendantTxs)
}
return list
}
}
| 20 | Kotlin | 55 | 96 | 110018d54d82bb4e3c2a1d6b0ddd1bb9eeff9167 | 2,009 | bitcoin-kit-android | MIT License |
app/src/main/java/com/alexiscrack3/spinny/settings/SettingsActivity.kt | alexiscrack3 | 267,722,677 | false | null | package com.alexiscrack3.spinny.settings
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.alexiscrack3.spinny.R
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
this.supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
companion object {
fun getIntent(context: Context): Intent {
return Intent(context, SettingsActivity::class.java)
}
}
}
| 0 | Kotlin | 1 | 0 | c1e2b7e55fed56a227a6c90432e898489ae47cbf | 729 | spinny-android | MIT License |
app/src/main/java/com/alexiscrack3/spinny/settings/SettingsActivity.kt | alexiscrack3 | 267,722,677 | false | null | package com.alexiscrack3.spinny.settings
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.alexiscrack3.spinny.R
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
this.supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
companion object {
fun getIntent(context: Context): Intent {
return Intent(context, SettingsActivity::class.java)
}
}
}
| 0 | Kotlin | 1 | 0 | c1e2b7e55fed56a227a6c90432e898489ae47cbf | 729 | spinny-android | MIT License |
src/main/kotlin/server/interpreter/Transform.kt | realmofuz | 676,313,076 | false | null | package server.interpreter
import blockMap
import java.nio.ByteBuffer
fun Interpreter.transform() {
var buf: MutableList<Byte> = mutableListOf()
var counter = 0
var latestBlock = -10
while(true) {
if(bytes.remaining() == 0) {
break
}
val it = bytes.get()
if(it.toInt() == -127) {
counter++
} else {
for(x in 1..counter) {
buf.add(-127)
}
counter = 0
buf.add(it)
}
if(counter == 20) {
if(latestBlock != -10) {
for(x in 1..20) {
buf.removeAt(0)
}
blockMap[latestBlock] = ByteBuffer.wrap(buf.toByteArray())
}
buf = mutableListOf()
latestBlock = bytes.getInt()
}
}
} | 0 | Kotlin | 0 | 0 | 5914dce891f08aadf7b4f3bc3e9e4a1955020f46 | 852 | xyraith | Apache License 2.0 |
kommons-test/src/jvmTest/kotlin/com/bkahlert/kommons/test/junit/UniqueIdResolverTest.kt | bkahlert | 323,048,013 | false | {"Kotlin": 1649529, "JavaScript": 540} | package com.bkahlert.kommons.test.junit
import com.bkahlert.kommons.test.testAll
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.platform.engine.UniqueId
class UniqueIdResolverTest {
@Test fun test_name(uniqueId: UniqueId) = testAll {
uniqueId.toString() shouldBe listOf(
"[engine:junit-jupiter]",
"[class:com.bkahlert.kommons.test.junit.UniqueIdResolverTest]",
"[method:test_name(org.junit.platform.engine.UniqueId)]",
).joinToString("/")
}
@Nested
inner class NestedTest {
@Test fun test_name(uniqueId: UniqueId) = testAll {
uniqueId.toString() shouldBe listOf(
"[engine:junit-jupiter]",
"[class:com.bkahlert.kommons.test.junit.UniqueIdResolverTest]",
"[nested-class:NestedTest]",
"[method:test_name(org.junit.platform.engine.UniqueId)]",
).joinToString("/")
}
}
}
| 5 | Kotlin | 0 | 18 | 747cb51cf6e6b729d574396a4938eabafbdac1fe | 1,022 | kommons | MIT License |
fourthline/src/test/java/de/solarisbank/sdk/fourthline/domain/location/LocationUseCaseTest.kt | Solarisbank | 336,233,277 | false | {"Kotlin": 468901, "Java": 6478, "Shell": 1215} | package de.solarisbank.sdk.fourthline.domain.location
import de.solarisbank.sdk.fourthline.data.dto.Location
import de.solarisbank.sdk.fourthline.data.dto.LocationResult
import de.solarisbank.sdk.fourthline.data.location.LocationDataSourceImpl
import de.solarisbank.sdk.fourthline.data.location.LocationRepositoryImpl
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.mockk.every
import io.mockk.mockk
import io.reactivex.Single
class LocationUseCaseTest : StringSpec({
val location = Location(1111.0, 1111.0)
fun initLocationUseCase(
locationDto: LocationResult
): LocationUseCase {
val locationDataSourceImplMockk = mockk<LocationDataSourceImpl> {
every { getLocation() } returns Single.just(locationDto)
}
return LocationUseCase(LocationRepositoryImpl(locationDataSourceImplMockk))
}
"verifyLocationSuccess" {
val expectedLocationDto = LocationResult.Success(location)
val locationUseCase: LocationUseCase = initLocationUseCase(expectedLocationDto)
val actualLocationDto: LocationResult = locationUseCase.getLocation().blockingGet()
actualLocationDto shouldBe expectedLocationDto
}
"verifyLocationNetworkNotEnabledError" {
val expectedLocationDto = LocationResult.NetworkNotEnabledError
val locationUseCase: LocationUseCase = initLocationUseCase(expectedLocationDto)
val actualLocationDto: LocationResult = locationUseCase.getLocation().blockingGet()
actualLocationDto shouldBe expectedLocationDto
}
"verifyLocationClientNotEnabledError" {
val expectedLocationDto = LocationResult.LocationClientNotEnabledError
val locationUseCase: LocationUseCase = initLocationUseCase(expectedLocationDto)
val actualLocationDto: LocationResult = locationUseCase.getLocation().blockingGet()
actualLocationDto shouldBe expectedLocationDto
}
"verifyLocationFetchingError" {
val expectedLocationDto = LocationResult.LocationFetchingError
val locationUseCase: LocationUseCase = initLocationUseCase(expectedLocationDto)
val actualLocationDto: LocationResult = locationUseCase.getLocation().blockingGet()
actualLocationDto shouldBe expectedLocationDto
}
}) | 0 | Kotlin | 0 | 6 | 555ae8cb524ad592115245f13d73bd4cfdd46c9c | 2,308 | identhub-android | MIT License |
src/main/kotlin/org/move/cli/runconfig/producers/TestCommandConfigurationProducer.kt | pontem-network | 279,299,159 | false | null | package org.move.cli.runconfig.producers
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import org.move.cli.AptosCommandLine
import org.move.cli.MoveProject
import org.move.lang.MoveFile
import org.move.lang.core.psi.MvFunction
import org.move.lang.core.psi.MvModule
import org.move.lang.core.psi.containingModule
import org.move.lang.core.psi.ext.findMoveProject
import org.move.lang.core.psi.ext.hasTestFunctions
import org.move.lang.core.psi.ext.isTest
import org.move.lang.modules
import org.move.lang.moveProject
import org.toml.lang.psi.TomlFile
class TestCommandConfigurationProducer : AptosCommandConfigurationProducer() {
override fun configFromLocation(location: PsiElement) = fromLocation(location)
companion object {
fun fromLocation(location: PsiElement, climbUp: Boolean = true): AptosCommandLineFromContext? {
return when {
location is MoveFile -> {
val module = location.modules().firstOrNull { it.hasTestFunctions() } ?: return null
findTestModule(module, climbUp)
}
location is TomlFile && location.name == "Move.toml" -> {
val moveProject = location.findMoveProject() ?: return null
findTestProject(location, moveProject)
}
location is PsiDirectory -> {
val moveProject = location.findMoveProject() ?: return null
if (
location.virtualFile == moveProject.currentPackage.contentRoot
|| location.virtualFile == moveProject.currentPackage.testsFolder
) {
findTestProject(location, moveProject)
} else {
null
}
}
else -> findTestFunction(location, climbUp) ?: findTestModule(location, climbUp)
}
}
private fun findTestFunction(psi: PsiElement, climbUp: Boolean): AptosCommandLineFromContext? {
val fn = findElement<MvFunction>(psi, climbUp) ?: return null
if (!fn.isTest) return null
val modName = fn.containingModule?.name ?: return null
val functionName = fn.name ?: return null
val confName = "Test $modName::$functionName"
val command = "move test --filter $modName::$functionName"
val rootPath = fn.moveProject?.contentRootPath ?: return null
return AptosCommandLineFromContext(fn, confName, AptosCommandLine(command, rootPath))
}
private fun findTestModule(psi: PsiElement, climbUp: Boolean): AptosCommandLineFromContext? {
val mod = findElement<MvModule>(psi, climbUp) ?: return null
if (!mod.hasTestFunctions()) return null
val modName = mod.name ?: return null
val confName = "Test $modName"
val command = "move test --filter $modName"
val rootPath = mod.moveProject?.contentRootPath ?: return null
return AptosCommandLineFromContext(mod, confName, AptosCommandLine(command, rootPath))
}
private fun findTestProject(
location: PsiFileSystemItem,
moveProject: MoveProject
): AptosCommandLineFromContext? {
val packageName = moveProject.currentPackage.packageName
val rootPath = moveProject.contentRootPath ?: return null
val confName = "Test $packageName"
val command = "move test"
return AptosCommandLineFromContext(location, confName, AptosCommandLine(command, rootPath))
}
}
}
| 9 | null | 14 | 50 | af0e2bde6ee134efc96115b38ad6362c9207e29e | 3,741 | intellij-move | MIT License |
app/src/main/java/com/adityagupta/gdsc_nie/data/remote/EventDetailData/EventDetailsData.kt | yat2k | 415,939,124 | true | {"Kotlin": 30019} | package com.adityagupta.gdsc_nie.data.remote.EventDetailData
import com.google.gson.annotations.SerializedName
data class EventDetailsData (
val id: String? = "",
val description: String? = "",
val speaker1link: String? = "",
val speaker1title: String? = "",
val speaker2link: String? = "",
val speaker2title: String? = "",
val speaker3link: String? = "",
val speaker3title: String? = "",
val eventlink: String? = ""
) | 0 | Kotlin | 0 | 0 | a0f35eafbbcce7e945d25d5afb7d775dec0495cd | 456 | GDSC-NIE-Android | MIT License |
services/csm.cloud.project.notifications/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/project/participant/repository/ParticipantRepository.kt | boschglobal | 805,348,245 | false | {"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344} | /*
* *************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2019
*
* *************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.project.participant.repository
import com.bosch.pt.csm.cloud.projectmanagement.common.repository.ShardedSaveOperation
import com.bosch.pt.csm.cloud.projectmanagement.project.participant.model.Participant
import com.bosch.pt.csm.cloud.projectmanagement.project.participant.model.ParticipantRoleEnum
import org.springframework.cache.annotation.Cacheable
import org.springframework.data.mongodb.repository.MongoRepository
import java.util.UUID
interface ParticipantRepository :
MongoRepository<Participant, UUID>,
ShardedSaveOperation<Participant, UUID>,
ParticipantRepositoryExtension {
fun findAllByProjectIdentifierAndRole(projectIdentifier: UUID, role: ParticipantRoleEnum): List<Participant>
fun findOneByProjectIdentifierAndUserIdentifierAndActiveTrue(
projectIdentifier: UUID,
userIdentifier: UUID
): Participant?
fun findFirstByProjectIdentifierAndUserIdentifier(
projectIdentifier: UUID,
userIdentifier: UUID
): Participant
@Cacheable(cacheNames = ["participant-user"])
fun findOneCachedByProjectIdentifierAndUserIdentifierAndActiveTrue(
projectIdentifier: UUID,
userIdentifier: UUID
): Participant?
fun findOneByIdentifierAndProjectIdentifier(identifier: UUID, projectIdentifier: UUID): Participant
@Cacheable(cacheNames = ["participant"])
fun findOneCachedByIdentifierAndProjectIdentifier(
identifier: UUID,
projectIdentifier: UUID
): Participant
fun findAllByProjectIdentifierAndCompanyIdentifierAndRole(
projectIdentifier: UUID,
companyIdentifier: UUID,
role: ParticipantRoleEnum
): List<Participant>
}
| 0 | Kotlin | 3 | 9 | 9f3e7c4b53821bdfc876531727e21961d2a4513d | 1,945 | bosch-pt-refinemysite-backend | Apache License 2.0 |
SquirrelStateMachineDemo/app/src/test/java/com/yueban/squirrelstatemachinedemo/CallStateMachineWrapperKt.kt | yueban | 27,426,345 | false | null | package com.yueban.squirrelstatemachinedemo
import org.squirrelframework.foundation.fsm.StateMachineBuilderFactory
import org.squirrelframework.foundation.fsm.StateMachineConfiguration
import org.squirrelframework.foundation.fsm.impl.AbstractStateMachine
/**
* @author yueban <EMAIL>
* @date 2020-01-06
*/
class CallStateMachineWrapperKt {
companion object {
val INSTANCE: CallStateMachine by lazy {
val builder = StateMachineBuilderFactory.create(
CallStateMachine::class.java, FSMState::class.java, FSMEvent::class.java, CallContext::class.java
)
// sUnInit --> sIniting: login
// sIniting --> sIdle: login: success
// sIniting --> sUnInit: login: fail
builder.externalTransition().from(FSMState.UnInit).to(FSMState.Initing).on(FSMEvent.doLogin).callMethod(FSMMethods.doLogin.name)
builder.externalTransition().from(FSMState.Initing).to(FSMState.Idle).on(FSMEvent.onLoginSuccess)
.callMethod(FSMMethods.onLogin.name)
builder.externalTransition().from(FSMState.Initing).to(FSMState.UnInit).on(FSMEvent.onLoginFailed)
// sIdle --> sPrepareCall: make call: success
// sPrepareCall --> sOutgoing: new Call: direction out
// sIdle --> sIncoming: new Call: direction in
// sIncoming --> sAnswering: answer: success
// sIncoming --> sIdle: answer: fail
builder.externalTransition().from(FSMState.Idle).to(FSMState.MakingCall).on(FSMEvent.makeCall)
.callMethod(FSMMethods.makeCall.name)
builder.externalTransition().from(FSMState.MakingCall).to(FSMState.Outgoing).on(FSMEvent.onOutgoing)
.callMethod(FSMMethods.onOutgoing.name)
builder.externalTransition().from(FSMState.Idle).to(FSMState.Incoming).on(FSMEvent.onIncoming)
.callMethod(FSMMethods.onIncoming.name)
builder.externalTransition().from(FSMState.Incoming).to(FSMState.Answering).on(FSMEvent.onAnswerSuccess)
builder.externalTransition().from(FSMState.Incoming).to(FSMState.Idle).on(FSMEvent.onAnswerFailed)
// sOutgoing --> sConnected: status update: connecting
// sAnswering --> sConnected: status update: connecting
// sConnected --> sEncrypted: encrypted
builder.externalTransitions().fromAmong(FSMState.Outgoing, FSMState.Answering).to(FSMState.Connected)
.on(FSMEvent.onConnected).callMethod(FSMMethods.onConnected.name)
builder.externalTransition().from(FSMState.Connected).to(FSMState.Encrypted).on(FSMEvent.onEncrypted)
// sOutgoing --> sTerming: term
// sIncoming --> sTerming: term
// sAnswering --> sTerming: term
// sConnected --> sTerming: term
// sEncrypted --> sTerming: term
builder.externalTransitions()
.fromAmong(FSMState.Outgoing, FSMState.Incoming, FSMState.Answering, FSMState.Connected, FSMState.Encrypted)
.to(FSMState.Terming).on(FSMEvent.term).callMethod(FSMMethods.doTerm.name)
// sPrepareCall --> sIdle: onTermed
// sOutgoing --> sIdle: onTermed
// sIncoming --> sIdle: onTermed
// sAnswering --> sIdle: onTermed
// sConnected --> sIdle: onTermed
// sEncrypted --> sIdle: onTermed
// sTerming --> sIdle: onTermed
builder.externalTransitions().fromAmong(
FSMState.MakingCall,
FSMState.Outgoing,
FSMState.Incoming,
FSMState.Answering,
FSMState.Connected,
FSMState.Encrypted,
FSMState.Terming
).to(FSMState.Idle).on(FSMEvent.onTermed).callMethod(FSMMethods.onTermed.name)
// sIniting --> sUnInit: logout
// sIdle --> sUnInit: logout
// sPrepareCall --> sUnInit: logout
// sOutgoing --> sUnInit: logout
// sIncoming --> sUnInit: logout
// sAnswering --> sUnInit: logout
// sConnected --> sUnInit: logout
// sEncrypted --> sUnInit: logout
builder.externalTransitions().fromAmong(
FSMState.Initing,
FSMState.Idle,
FSMState.MakingCall,
FSMState.Outgoing,
FSMState.Incoming,
FSMState.Answering,
FSMState.Connected,
FSMState.Encrypted,
FSMState.Terming
).to(FSMState.UnInit).on(FSMEvent.onLogout).callMethod(FSMMethods.onLogout.name)
builder.newStateMachine(FSMState.UnInit, StateMachineConfiguration.create().enableDebugMode(true))
}
}
class CallStateMachine : AbstractStateMachine<CallStateMachine, FSMState, FSMEvent, CallContext>() {
fun doLogin(from: FSMState, to: FSMState, event: FSMEvent, context: CallContext) {
println("doLogin called")
}
fun onLogin(from: FSMState, to: FSMState, event: FSMEvent, context: CallContext) {
println("onLogin called")
}
}
@Suppress("EnumEntryName")
private enum class FSMMethods {
doLogin, onLogin, makeCall, onOutgoing, onIncoming, onConnected, doTerm, onTermed, onLogout
}
sealed class CallContext {
class MakeCallContext(val callNumber: String) : CallContext()
}
enum class FSMEvent {
/**
* 登录
*/
doLogin,
/**
* 登录成功
*/
onLoginSuccess,
/**
* 登录失败
*/
onLoginFailed,
/**
* 拨号
*/
makeCall,
/**
* 去电
*/
onOutgoing,
/**
* 来电
*/
onIncoming,
/**
* 接听成功
*/
onAnswerSuccess,
/**
* 接听失败
*/
onAnswerFailed,
/**
* 已接通
*/
onConnected,
/**
* 已建立加密通话 (秘钥交换成功)
*/
onEncrypted,
/**
* 挂断
*/
term,
/**
* 已挂断
*/
onTermed,
/**
* 已登出
*/
onLogout,
}
enum class FSMState {
/**
* 未初始化
*/
UnInit,
/**
* 初始化中
*/
Initing,
/**
* 通话空闲状态
*/
Idle,
/**
* 正在进行拨号
*/
MakingCall,
/**
* 呼叫中
*/
Outgoing,
/**
* 来电中
*/
Incoming,
/**
* 正在进行接听
*/
Answering,
/**
* 已接通
*/
Connected,
/**
* 已建立加密通话 (秘钥交换成功)
*/
Encrypted,
/**
* 挂断中
*/
Terming,
}
} | 0 | Java | 4 | 16 | 9ff75adc009aadedba4d05850af8a7748afbb6e2 | 6,883 | AndroidExercise | Apache License 2.0 |
DrawableWorkShop/app/src/main/java/osp/leobert/android/drawableworkshop/drawable/AnimLetterDrawable.kt | leobert-lan | 334,001,618 | false | null | package osp.leobert.android.drawableworkshop.drawable
import android.content.res.Resources
import android.content.res.TypedArray
import android.graphics.*
import android.graphics.drawable.Animatable2
import android.graphics.drawable.Drawable
import android.os.SystemClock
import android.util.AttributeSet
import android.util.Log
import android.util.SparseArray
import org.xmlpull.v1.XmlPullParser
import osp.leobert.android.drawableworkshop.R
import kotlin.math.min
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* <p><b>Package:</b> osp.leobert.android.drawableworkshop.drawable </p>
* <p><b>Project:</b> DrawableWorkShop </p>
* <p><b>Classname:</b> AnimLetterDrawable </p>
* Created by leobert on 2021/1/29.
*/
class AnimLetterDrawable : Drawable(), Animatable2, Runnable {
private class Size(val type: Int) : ReadWriteProperty<AnimLetterDrawable, Float?> {
private var prop: Float? = null
override fun getValue(thisRef: AnimLetterDrawable, property: KProperty<*>): Float? {
return prop ?: thisRef.run {
val rect = Rect()
this.paint.getTextBounds(this.letters, 0, this.letters.length, rect)
val s = when (type) {
0 -> rect.width()
else -> rect.height()
}.toFloat()
prop = s
prop
}
}
override fun setValue(thisRef: AnimLetterDrawable, property: KProperty<*>, value: Float?) {
prop = value
}
}
private fun obtainAttributes(
res: Resources,
theme: Resources.Theme?, set: AttributeSet, attrs: IntArray
): TypedArray {
return theme?.obtainStyledAttributes(set, attrs, 0, 0) ?: res.obtainAttributes(set, attrs)
}
val tag = "AnimLetterDrawable"
var letters: String = "A"
set(value) {
field = value
width = null
height = null
invalidateSelf()
}
var color: Int = Color.CYAN
set(value) {
field = value
paint.color = value
invalidateSelf()
}
var textSize: Float = 60f
set(value) {
field = value
width = null
height = null
paint.textSize = value
invalidateSelf()
}
private var frameIndex = 0
private val totalFrames = 30 * 3 //3 second, 30frames per second
private val originalLetterLocations = SparseArray<PointF>()
private val finalLetterLocations = SparseArray<PointF>()
private var width by Size(0)
private var height by Size(1)
private val paint = Paint().apply {
textSize = 60f
color = Color.CYAN
}
override fun getIntrinsicHeight(): Int {
return height?.toInt() ?: -1
}
override fun getIntrinsicWidth(): Int {
return width?.toInt() ?: -1
}
override fun draw(canvas: Canvas) {
Log.d(tag, "on draw,$letters , $height,$frameIndex")
val progress = if (totalFrames > 1) {
frameIndex.toFloat() / (totalFrames - 1).toFloat()
} else {
1f
}
paint.alpha = min(255, (255 * progress).toInt() + 100)
for (i in letters.indices) {
val endPoint: PointF = finalLetterLocations.get(i)
val startPoint: PointF = originalLetterLocations.get(i)
val x: Float = startPoint.x + (endPoint.x - startPoint.x) * progress
val y: Float = startPoint.y + (endPoint.y - startPoint.y) * progress
canvas.drawText(letters[i].toString(), x, y, paint)
}
}
override fun setAlpha(alpha: Int) {
//ignore
}
override fun setColorFilter(colorFilter: ColorFilter?) {
//ignore
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
override fun inflate(
r: Resources,
parser: XmlPullParser,
attrs: AttributeSet,
theme: Resources.Theme?
) {
super.inflate(r, parser, attrs, theme)
val a: TypedArray = obtainAttributes(r, theme, attrs, R.styleable.anim_letter_drawable)
letters = a.getString(R.styleable.anim_letter_drawable_android_text) ?: "A"
textSize = a.getDimension(R.styleable.anim_letter_drawable_android_textSize, 60f)
color = a.getColor(R.styleable.anim_letter_drawable_android_color, Color.CYAN)
a.recycle()
paint.color = color
paint.textSize = textSize
}
override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
Log.d(tag, "onBoundsChange, $bounds")
height = bounds.height().toFloat()
width = bounds.width().toFloat()
calcLetterStartEndLocations()
invalidateSelf()
}
private fun calcLetterStartEndLocations() {
originalLetterLocations.clear()
finalLetterLocations.clear()
val height = this.height ?: throw IllegalStateException("height cannot be null")
val width = this.width ?: throw IllegalStateException("width cannot be null")
val centerY: Float = height / 2f + paint.textSize / 2
val totalLength = paint.measureText(letters)
val startX = (width - totalLength) / 2
var currentStartX = startX
for (i in letters.indices) {
val str: String = letters[i].toString()
val currentLength: Float = paint.measureText(str)
originalLetterLocations.put(
i, PointF(
Math.random().toFloat() * width, Math.random()
.toFloat() * height
)
)
finalLetterLocations.put(i, PointF(currentStartX, centerY))
// TODO: 2021/2/1 consider padding for letters inner
currentStartX += currentLength
}
}
private val animationCallbacks: MutableSet<Animatable2.AnimationCallback> = linkedSetOf()
private var mAnimating: Boolean = false
private fun setFrame(frame: Int, unschedule: Boolean, animate: Boolean) {
if (frame >= totalFrames) {
return
}
mAnimating = animate
frameIndex = frame
if (unschedule || animate) {
unscheduleSelf(this)
}
if (animate) {
// Unscheduling may have clobbered these values; restore them
frameIndex = frame
scheduleSelf(this, SystemClock.uptimeMillis() + durationPerFrame)
}
invalidateSelf()
}
private fun nextFrame(unschedule: Boolean) {
var nextFrame: Int = frameIndex + 1
val isLastFrame = nextFrame + 1 == totalFrames
if (nextFrame + 1 > totalFrames) {
nextFrame = totalFrames - 1
}
setFrame(nextFrame, unschedule, !isLastFrame)
}
private val durationPerFrame = 3000 / totalFrames
override fun start() {
Log.d(tag, "start called")
mAnimating = true
if (!isRunning) {
// Start from 0th frame.
setFrame(
frame = 0, unschedule = false, animate = false
)
} else {
setFrame(
frame = 0, unschedule = false, animate = true
)
}
}
override fun stop() {
mAnimating = false
if (isRunning) {
frameIndex = 0
//un-schedule it at first
unscheduleSelf(this)
setFrame(0, unschedule = true, animate = false)
}
}
override fun isRunning(): Boolean {
return mAnimating
}
override fun registerAnimationCallback(callback: Animatable2.AnimationCallback) {
animationCallbacks.add(callback)
}
override fun unregisterAnimationCallback(callback: Animatable2.AnimationCallback): Boolean {
return animationCallbacks.remove(callback)
}
override fun clearAnimationCallbacks() {
animationCallbacks.clear()
}
override fun run() {
Log.d(tag, "callback by schedule")
if (isRunning) {
nextFrame(false)
} else {
//safe call
setFrame(0, unschedule = true, animate = false)
}
}
} | 0 | Kotlin | 0 | 3 | a968a3092a6cf071ed841f079416776e0479ae76 | 8,261 | DrawableWorkShop | MIT License |
ComicX/src/main/java/com/qiuchenly/comicparse/UI/adapter/ComicHomeAdapter.kt | MyGhost233 | 203,593,656 | false | {"Kotlin": 333289, "Java": 254227} | package com.qiuchenly.comicparse.UI.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat.startActivity
import android.support.v4.view.ViewPager
import android.view.View
import com.google.gson.Gson
import com.qiuchenly.comicparse.Bean.*
import com.qiuchenly.comicparse.Bean.RecommendItemType.TYPE.Companion.TYPE_BIKA
import com.qiuchenly.comicparse.Bean.RecommendItemType.TYPE.Companion.TYPE_DMZJ_HOT
import com.qiuchenly.comicparse.Bean.RecommendItemType.TYPE.Companion.TYPE_DMZJ_LASTUPDATE
import com.qiuchenly.comicparse.Bean.RecommendItemType.TYPE.Companion.TYPE_DMZJ_NORMAL
import com.qiuchenly.comicparse.Bean.RecommendItemType.TYPE.Companion.TYPE_DMZJ_SPEC_2
import com.qiuchenly.comicparse.Bean.RecommendItemType.TYPE.Companion.TYPE_DONGMANZHIJIA_CATEGORY
import com.qiuchenly.comicparse.Bean.RecommendItemType.TYPE.Companion.TYPE_TITLE
import com.qiuchenly.comicparse.Bean.RecommendItemType.TYPE.Companion.TYPE_TOP
import com.qiuchenly.comicparse.Core.ActivityKey.KEY_CATEGORY_JUMP
import com.qiuchenly.comicparse.Core.Comic
import com.qiuchenly.comicparse.R
import com.qiuchenly.comicparse.UI.BaseImp.BaseRecyclerAdapter
import com.qiuchenly.comicparse.UI.activity.SearchResult
import com.qiuchenly.comicparse.UI.view.ComicHomeContract
import com.qiuchenly.comicparse.Utils.CustomUtils
import kotlinx.android.synthetic.main.item_foosize_newupdate.view.*
import kotlinx.android.synthetic.main.item_rankview.view.*
import kotlinx.android.synthetic.main.item_recommend_normal.view.*
import kotlinx.android.synthetic.main.vpitem_top_ad.view.*
import java.lang.ref.WeakReference
class ComicHomeAdapter(var mBaseView: ComicHomeContract.View, private var mContext: WeakReference<Context?>) : BaseRecyclerAdapter<RecommendItemType>(), ComicHomeContract.DMZJ_Adapter {
override fun addDMZJCategory(mComicCategory: ArrayList<ComicHome_Category>) {
addData(RecommendItemType().apply {
this.title = "动漫之家全部分类"
type = TYPE_TITLE
})
mComicCategory.forEach {
addData(RecommendItemType().apply {
type = TYPE_DONGMANZHIJIA_CATEGORY
this.mItemData = Gson().toJson(it)
})
}
}
private var isInitForLoadMore = false
//加载热门漫画数据
fun addDMZJHot(mComicCategory: ArrayList<DataItem>) {
if (!isInitForLoadMore) {
addData(RecommendItemType().apply {
this.title = "热门推荐漫画"
type = TYPE_TITLE
})
isInitForLoadMore = true
}
mComicCategory.forEach {
addData(RecommendItemType().apply {
type = TYPE_DMZJ_HOT
this.mItemData = Gson().toJson(it)
})
}
}
/**
* 在mInitUI(param1,param2,param3)方法后被调用.先初始化Item数据再显示该Item
*/
override fun onViewShowOrHide(position: Int, item: View, isShow: Boolean) {
if (getItemViewType(position) == TYPE_TOP) {
if (isShow) {
mCarouselAdapter.startScroll()
} else {
mCarouselAdapter.aWaitScroll()
}
}
}
override fun canLoadMore(): Boolean {
return true
}
override fun getViewType(position: Int): Int {
return if (position < getRealSize()) position
else super.getViewType(position)
}
override fun getItemLayout(viewType: Int): Int {
return when (viewType) {
TYPE_TOP -> R.layout.item_recommend_topview
RecommendItemType.TYPE.TYPE_RANK -> R.layout.item_rankview
TYPE_DMZJ_NORMAL,
TYPE_DMZJ_LASTUPDATE,
TYPE_DONGMANZHIJIA_CATEGORY,
TYPE_DMZJ_HOT,//加载热门漫画
TYPE_BIKA -> R.layout.item_foosize_newupdate
TYPE_DMZJ_SPEC_2 -> R.layout.item_foosize_newupdate_2
TYPE_TITLE -> R.layout.item_recommend_normal
else -> R.layout.item_recommend_normal
}
}
override fun getItemViewType(position: Int): Int {
return if (position < getRealSize())
getItemData(position).type
else
super.getItemViewType(position)
}
override fun onViewShow(item: View, data: RecommendItemType, position: Int, ViewType: Int) {
mInitUI(item, data, position)
}
fun getSizeByItem(position: Int): Int {
return when (getItemViewType(position)) {
TYPE_BIKA,
TYPE_DMZJ_NORMAL,
TYPE_DMZJ_HOT,
TYPE_DONGMANZHIJIA_CATEGORY,
TYPE_DMZJ_LASTUPDATE -> 2
TYPE_DMZJ_SPEC_2 -> 3
else -> 6
}
}
private var mCarouselAdapter = object : CarouselAdapter() {
override fun onViewInitialization(mView: View, itemData: String?, position: Int) {
with(mView) {
tv_bookName.text = mTopTitles[position]
CustomUtils.loadImageCircle(mView.context, mTopImages[position], vp_item_topad_cv, 15)
this.setOnClickListener {
val itemData = mComicList?.get(0)?.data?.get(position)!!
val mFilterIntent = when (itemData["type"]) {
"7" -> {//动漫之家公告
Intent("android.intent.action.GET_DMZJ_URL").apply {
putExtras(Bundle().apply {
//漫画基本信息 做跳转
putString(KEY_CATEGORY_JUMP, itemData["url"])
})
}
}
"1" -> {//漫画
//将数据与普通漫画数据格式化一致,修复加载数据问题.
val mComicStringRealInfo = com.google.gson.Gson().toJson(itemData)
Intent("android.intent.action.ComicDetails").apply {
putExtras(Bundle().apply {
//漫画基本信息 做跳转
putString(KEY_CATEGORY_JUMP, com.google.gson.Gson().toJson(ComicInfoBean().apply {
this.mComicType = ComicSource.DongManZhiJia
this.mComicString = mComicStringRealInfo
}))
})
}
}
else -> null
}
if (mFilterIntent != null) {
mContext.get()?.startActivity(mFilterIntent)
}
}
}
}
}
@SuppressLint("SetTextI18n")
private fun mInitUI(view: View, data: RecommendItemType?, position: Int) {
when (data?.type) {
/**
* Banner栏数据
*/
TYPE_TOP -> {
mCarouselAdapter.setData(mTopTitles)
val mViewPager = view.findViewById<ViewPager>(R.id.vp_banner)
mViewPager.adapter = mCarouselAdapter
mCarouselAdapter.setVP(mViewPager)
}
/**
* 暂时没用到
*/
RecommendItemType.TYPE.TYPE_RANK -> {
//RANK 点击
with(view) {
tv_times.text = (java.util.Calendar.getInstance()
.get(java.util.Calendar.DAY_OF_MONTH)
).toString()
CustomUtils.loadImage(view.context, "随机图片1", iv_privatefm_img_back, 55, 500)
CustomUtils.loadImage(view.context, "随机图片1", iv_day_img_back, 55, 500)
CustomUtils.loadImage(view.context, "随机图片1", iv_mix_img_back, 55, 500)
CustomUtils.loadImage(view.context, "随机图片1", iv_charts_img_back, 55, 500)
iv_day_img_click.setOnClickListener {
/* startActivity(view.context,
Intent(view.context, EveryDayRecommend::class.java),
null)*/
}
}
}
/**
* 类别标题
*/
TYPE_TITLE -> {
//RANK 点击
with(view) {
tv_listName.text = data.title
setOnClickListener(null)
}
}
/**
* 动漫之家/分类处理数据专属
* ID对照表
* 6 = 火热专题广告
* 5 = 新漫周刊数据 与6一致
* 8 = 大师级作者
* 1 = 漫画
*/
TYPE_DMZJ_NORMAL,
TYPE_DMZJ_LASTUPDATE,
TYPE_DMZJ_HOT,
TYPE_DMZJ_SPEC_2 -> {
var mImage = ""
var mComicBookName = ""
var mComicStatusOrAuthor = ""
var mItemComicType: String //漫画
var mComicStringRealInfo: String
with(view) {
when (data.type) {
TYPE_DMZJ_LASTUPDATE -> {
val item = Gson().fromJson(data.mItemData, Map::class.java) as Map<String, String>
mImage = item["cover"] ?: ""
mItemComicType = "1"
mComicBookName = item["title"] ?: ""
mComicStatusOrAuthor = item["authors"] ?: ""
//将数据与普通漫画数据格式化一致,修复加载数据问题.
mComicStringRealInfo = Gson().toJson(DataItem().apply {
this.cover = item["cover"] ?: ""
this.obj_id = item["id"] ?: ""
this.sub_title = item["authors"] ?: ""
this.title = item["title"] ?: ""
this.status = item["status"] ?: ""
})
}
else -> {
val mItemData = Gson().fromJson(data.mItemData, DataItem::class.java)
mItemComicType = mItemData.type
mComicStringRealInfo = data.mItemData
mImage = mItemData.cover
mComicBookName = mItemData.title
mComicStatusOrAuthor =
if (mItemData.sub_title == "") mItemData.status
else mItemData.sub_title
foo_bookName_upNews.visibility =
when (mItemData.type) {
//隐藏下半部分的栏
"8", "6", "5" -> View.INVISIBLE
else -> View.VISIBLE
}
}
}
CustomUtils.loadImage(view.context, mImage, foo_bookImg, 0, 500)
foo_bookName.text = mComicBookName
foo_bookName_upNews.text = mComicStatusOrAuthor
setOnClickListener {
//TODO 此处需要作进一步优化
val mIntent = when (mItemComicType) {
"1" -> {
Intent("android.intent.action.ComicDetails").apply {
putExtra(KEY_CATEGORY_JUMP, Gson().toJson(ComicInfoBean().apply {
this.mComicType = ComicSource.DongManZhiJia
this.mComicString = mComicStringRealInfo
}))
}
}
"8", "6" -> {
null
}
"5" -> {
//周刊数据列表未处理
null
}
else -> null
}
if (mIntent != null) {
context.startActivity(mIntent)
}
}
}
}
TYPE_DONGMANZHIJIA_CATEGORY -> {
with(view) {
val mCate = Gson().fromJson(data.mItemData, ComicHome_Category::class.java)
var mImageSrc = ""
var mCategoryName = ""
val mType = ComicSource.DongManZhiJia
mCategoryName = mCate.title
mImageSrc = mCate.cover
CustomUtils.loadImage(view.context, mImageSrc, foo_bookImg, 0, 500)
foo_bookName.text = mCategoryName
//for this type,unuseless
foo_bookName_upNews.visibility = View.GONE
setOnClickListener {
context.startActivity(Intent(context, SearchResult::class.java).apply {
putExtra(KEY_CATEGORY_JUMP, Gson().toJson(ComicCategoryBean().apply {
this.mCategoryName = mCategoryName
this.mComicType = mType
this.mData = data.mItemData
}
))
}, null)
}
}
}
}
}
//===================== 动漫之家数据处理 =====================
private var mComicList: ArrayList<ComicComm>? = null
private var mTopImages = arrayListOf<String>()
private var mTopTitles = arrayListOf<String>()
override fun addDMZJData(mComicList: ArrayList<ComicComm>) {
setData(ArrayList())
isInitForLoadMore = false
mTopImages = arrayListOf()
mTopTitles = arrayListOf()
this.mComicList = mComicList
for (item in mComicList) {
if (item.category_id != "46")
addData(RecommendItemType().apply {
this.title = item.title
type = TYPE_TITLE
})
when (item.category_id) {
"46" -> {
//顶端首页数据
addData(RecommendItemType().apply {
this.title = item.title
type = TYPE_TOP
})
if (item.data != null) {
for (item2 in item.data!!) {
mTopImages.add(item2["cover"] ?: "")
mTopTitles.add(item2["title"] ?: "")
}
}
}
// 56 最新上架也包含在内
else -> {
if (item.data != null) {
for (item2 in item.data!!) {
addData(RecommendItemType().apply {
this.title = item2["title"]
type = when (item.category_id) {
"48", "53", "55" -> TYPE_DMZJ_SPEC_2
"56" -> TYPE_DMZJ_LASTUPDATE
else -> TYPE_DMZJ_NORMAL
}
this.mItemData = Gson().toJson(item2)
})
}
}
}
}
}
}
} | 0 | Kotlin | 4 | 1 | a78a6913132db468b6646adaf08cf241773d9e4c | 15,541 | iComic | MIT License |
flipted/app/src/main/java/edu/calpoly/flipted/ui/myProgress/missions/MissionsRecyclerViewAdapter.kt | CPSECapstone | 337,579,565 | false | null | package edu.calpoly.flipted.ui.myProgress.missions
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.recyclerview.widget.RecyclerView
import edu.calpoly.flipted.R
import edu.calpoly.flipted.businesslogic.missions.MissionProgress
import edu.calpoly.flipted.ui.myProgress.missionDetails.MissionTaskFragment
class MissionsViewHolder(private val fragment: Fragment, view: View): RecyclerView.ViewHolder(view), View.OnClickListener {
private val progressBar: ProgressBar = view.findViewById(R.id.mission_progress)
private val missionTitle: TextView = view.findViewById(R.id.mission_item_text)
private lateinit var missionId: String
fun bind(missionProgress: MissionProgress) {
itemView.setOnClickListener(this)
missionId = missionProgress.mission.uid
missionTitle.text = missionProgress.mission.name
val completedTaskCount = missionProgress.progress.count { it.submission != null }
progressBar.max = missionProgress.progress.size
progressBar.progress = completedTaskCount
}
override fun onClick(v: View?) {
fragment.parentFragment?.parentFragmentManager?.commit {
replace(R.id.main_view, MissionTaskFragment.newInstance(missionId))
setReorderingAllowed(true)
addToBackStack(null)
}
}
}
class MissionsRecyclerViewAdapter(private val fragment: Fragment): RecyclerView.Adapter<MissionsViewHolder>(){
var missions:List<MissionProgress> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MissionsViewHolder {
val itemView = LayoutInflater.from(fragment.requireActivity()).inflate(R.layout.mission_progress_item, parent, false)
return MissionsViewHolder(fragment, itemView)
}
override fun getItemCount(): Int = missions.size
override fun onBindViewHolder(holder: MissionsViewHolder, position: Int) {
holder.bind(missions[position])
}
}
| 0 | Kotlin | 0 | 1 | 4e5449655bb0f75908e676279cad28e6297c5cb9 | 2,139 | ambigouslyandroid | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/CpuOff.kt | walter-juan | 868,046,028 | false | null | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.CpuOff: ImageVector
get() {
if (_cpuOff != null) {
return _cpuOff!!
}
_cpuOff = Builder(name = "CpuOff", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 5.0f)
horizontalLineToRelative(9.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
verticalLineToRelative(9.0f)
moveToRelative(-0.292f, 3.706f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -0.708f, 0.294f)
horizontalLineToRelative(-12.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f)
verticalLineToRelative(-12.0f)
curveToRelative(0.0f, -0.272f, 0.108f, -0.518f, 0.284f, -0.698f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(13.0f, 9.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
moveToRelative(0.0f, 4.0f)
horizontalLineToRelative(-6.0f)
verticalLineToRelative(-6.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 10.0f)
horizontalLineToRelative(2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 14.0f)
horizontalLineToRelative(2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(10.0f, 3.0f)
verticalLineToRelative(2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.0f, 3.0f)
verticalLineToRelative(2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(21.0f, 10.0f)
horizontalLineToRelative(-2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(21.0f, 14.0f)
horizontalLineToRelative(-2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.0f, 21.0f)
verticalLineToRelative(-2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(10.0f, 21.0f)
verticalLineToRelative(-2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 3.0f)
lineToRelative(18.0f, 18.0f)
}
}
.build()
return _cpuOff!!
}
private var _cpuOff: ImageVector? = null
| 0 | null | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 5,812 | compose-icon-collections | MIT License |
android/app/src/main/java/br/com/zup/beagle/android/networking/grpc/sample/ui/MainActivity.kt | ZupIT | 372,971,323 | false | {"TypeScript": 115425, "Kotlin": 59641, "Swift": 46758, "JavaScript": 24456, "Ruby": 2950, "Shell": 568} | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.zup.beagle.android.networking.grpc.sample.ui
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import br.com.zup.beagle.android.networking.RequestData
import br.com.zup.beagle.android.networking.grpc.sample.config.SAMPLE_ENDPOINT
import br.com.zup.beagle.android.networking.grpc.sample.databinding.MainActivityBinding
import br.com.zup.beagle.android.utils.loadView
import br.com.zup.beagle.android.view.ServerDrivenState
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = MainActivityBinding.inflate(layoutInflater)
binding.root.loadView(this, RequestData(SAMPLE_ENDPOINT)) {
if (it is ServerDrivenState.Finished) {
binding.progressBar.visibility = View.GONE
}
}
setContentView(binding.root)
}
} | 0 | TypeScript | 0 | 1 | 33458199beb1e2c58ee6221d71ec13f3675b465a | 1,573 | beagle-grpc | Apache License 2.0 |
buildSrc/src/main/kotlin/appPackage/Plugin.kt | nimblehq | 670,978,859 | false | null | object Plugin {
const val ANDROID_APPLICATION = "com.android.application"
const val ANDROID_LIBRARY = "com.android.library"
const val ANDROID = "android"
const val MULTIPLATFORM = "multiplatform"
const val COCOAPODS = "native.cocoapods"
const val BUILD_KONFIG = "com.codingfeline.buildkonfig"
}
| 70 | Kotlin | 0 | 0 | 84adb4d6327038fba8220b8fa18810da34b1c27a | 319 | ic-kmm-kayla-bruce | MIT License |
notifications/notifications/src/main/kotlin/org/opensearch/notifications/model/SendMessageRequest.kt | zhongnansu | 360,034,061 | true | {"Kotlin": 605348, "TypeScript": 480764, "JavaScript": 21807, "Java": 3344, "Python": 1574} | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.opensearch.notifications.model
import org.opensearch.action.ActionRequest
import org.opensearch.action.ActionRequestValidationException
import org.opensearch.common.io.stream.StreamInput
import org.opensearch.common.io.stream.StreamOutput
import org.opensearch.common.xcontent.ToXContent
import org.opensearch.common.xcontent.ToXContentObject
import org.opensearch.common.xcontent.XContentBuilder
import org.opensearch.common.xcontent.XContentFactory
import org.opensearch.common.xcontent.XContentParser
import org.opensearch.common.xcontent.XContentParserUtils
import org.opensearch.commons.notifications.model.Attachment
import org.opensearch.commons.notifications.model.ChannelMessage
import org.opensearch.commons.utils.createJsonParser
import org.opensearch.commons.utils.fieldIfNotNull
import org.opensearch.commons.utils.logger
import org.opensearch.commons.utils.stringList
import org.opensearch.notifications.NotificationPlugin.Companion.LOG_PREFIX
import java.io.IOException
/**
* Data class for storing the send message request.
*/
internal class SendMessageRequest : ActionRequest, ToXContentObject {
val refTag: String
val recipients: List<String>
val title: String
val channelMessage: ChannelMessage
companion object {
private val log by logger(SendMessageRequest::class.java)
private const val REF_TAG_FIELD = "ref_tag"
private const val RECIPIENTS_FIELD = "recipient_list"
private const val TITLE_FIELD = "title"
private const val TEXT_DESCRIPTION_FIELD = "text_description"
private const val HTML_DESCRIPTION_FIELD = "html_description"
private const val ATTACHMENT_FIELD = "attachment"
}
constructor(
refTag: String,
recipients: List<String>,
title: String,
channelMessage: ChannelMessage
) : super() {
this.refTag = refTag
this.recipients = recipients
this.title = title
this.channelMessage = channelMessage
}
@Throws(IOException::class)
constructor(input: StreamInput) : this(input.createJsonParser())
/**
* Parse the data from parser and create object
* @param parser data referenced at parser
*/
constructor(parser: XContentParser) : super() {
var refTag: String? = null
var title: String? = null
var textDescription: String? = null
var htmlDescription: String? = null
var attachment: Attachment? = null
var recipients: List<String> = listOf()
XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser)
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
val fieldName = parser.currentName()
parser.nextToken()
when (fieldName) {
REF_TAG_FIELD -> refTag = parser.text()
RECIPIENTS_FIELD -> recipients = parser.stringList()
TITLE_FIELD -> title = parser.text()
TEXT_DESCRIPTION_FIELD -> textDescription = parser.text()
HTML_DESCRIPTION_FIELD -> htmlDescription = parser.text()
ATTACHMENT_FIELD -> attachment = Attachment.parse(parser)
else -> {
parser.skipChildren()
log.info("$LOG_PREFIX:Skipping Unknown field $fieldName")
}
}
}
refTag = refTag ?: "noRef"
if (recipients.isEmpty()) {
throw IllegalArgumentException("Empty recipient list")
}
title ?: throw IllegalArgumentException("$TITLE_FIELD field not present")
textDescription ?: throw IllegalArgumentException("$TEXT_DESCRIPTION_FIELD not present")
this.refTag = refTag
this.recipients = recipients
this.title = title
this.channelMessage = ChannelMessage(textDescription, htmlDescription, attachment)
}
/**
* {@inheritDoc}
*/
@Throws(IOException::class)
override fun writeTo(output: StreamOutput) {
toXContent(XContentFactory.jsonBuilder(output), ToXContent.EMPTY_PARAMS)
}
/**
* create XContentBuilder from this object using [XContentFactory.jsonBuilder()]
* @return created XContentBuilder object
*/
fun toXContent(): XContentBuilder? {
return toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS)
}
/**
* {@inheritDoc}
*/
override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder {
return builder!!.startObject()
.field(REF_TAG_FIELD, refTag)
.field(RECIPIENTS_FIELD, recipients)
.field(TITLE_FIELD, title)
.field(TEXT_DESCRIPTION_FIELD, channelMessage.textDescription)
.fieldIfNotNull(HTML_DESCRIPTION_FIELD, channelMessage.htmlDescription)
.fieldIfNotNull(ATTACHMENT_FIELD, channelMessage.attachment)
.endObject()
}
/**
* {@inheritDoc}
*/
override fun validate(): ActionRequestValidationException? {
return null
}
}
| 0 | Kotlin | 0 | 0 | 9dd5aa3c52b06d8790804ac429a952bf1af204e7 | 5,997 | notifications | Apache License 2.0 |
core/theming/src/main/java/com/otsembo/pinit/theming/presentation/Messages.kt | otsembo | 505,852,199 | false | {"Kotlin": 82193} | package com.otsembo.pinit.theming.presentation
import android.view.View
import com.google.android.material.snackbar.Snackbar
// snack bars
fun View.snackIt(message: String) {
Snackbar.make(this, message, Snackbar.LENGTH_LONG).show()
}
| 0 | Kotlin | 0 | 0 | 136c8f85006bd31eb37285947ee41e26df9a6973 | 241 | Pin-It | Apache License 1.1 |
m-gles20-pipeline/src/main/java/org/frikadelki/deepv/pipeline/program/UniformHandle.kt | frikadelki | 122,027,202 | false | null | /*
* Deep Venture K3D
* Copyright 2018 -*- frikadelki-corps -*-
* Created by frikadelki on 2018/2/5
*/
package org.frikadelki.deepv.pipeline.program
import android.opengl.GLES20
import org.frikadelki.deepv.pipeline.glErred
import org.frikadelki.deepv.pipeline.math.Matrix4
import org.frikadelki.deepv.pipeline.math.Vector4
import org.frikadelki.deepv.pipeline.math.Vector4Array
class UniformHandle internal constructor(private val handle: Int, private val checkDisposed: () -> Unit) {
fun setBoolean(boolean: Boolean) {
checkDisposed()
GLES20.glUniform1i(handle, if (boolean) 1 else 0)
}
fun setFloat(float: Float) {
checkDisposed()
GLES20.glUniform1f(handle, float)
}
fun setVector(vector: Vector4) {
setVector(vector.rawData, UniformVecSize.FOUR, 1, vector.rawOffset)
}
fun setVectorArray(array: Vector4Array) {
setVector(array.rawData, UniformVecSize.FOUR, array.vectorsCount, array.rawOffset)
}
private fun setVector(data: FloatArray, size: UniformVecSize, count: Int = 1, offset: Int = 0) {
checkDisposed()
size.bind(handle, data, count, offset)
if (glErred()) {
throw ProgramException("Failed to set uniform vector data.")
}
}
fun setMatrix(matrix: Matrix4) {
setMatrix(matrix.rawData, UniformMatSize.FOUR, 1, matrix.rawOffset)
}
private fun setMatrix(data: FloatArray, size: UniformMatSize, count: Int = 1, offset: Int = 0, transpose: Boolean = false) {
checkDisposed()
size.bind(handle, data, count, offset, transpose)
if (glErred()) {
throw ProgramException("Failed to set uniform matrix data.")
}
}
}
internal enum class UniformVecSize(val size: Int) {
ONE(1) {
override fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int) {
GLES20.glUniform1fv(handle, count, data, offset)
}
},
TWO(2) {
override fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int) {
GLES20.glUniform2fv(handle, count, data, offset)
}
},
THREE(3) {
override fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int) {
GLES20.glUniform3fv(handle, count, data, offset)
}
},
FOUR(4) {
override fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int) {
GLES20.glUniform4fv(handle, count, data, offset)
}
},
;
protected abstract fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int)
fun bind(handle: Int, data: FloatArray, count: Int, offset: Int) {
checkData(data, count, offset)
bindInternal(handle, data, count, offset)
}
private fun checkData(data: FloatArray, count: Int, offset: Int) {
if (count <= 0) {
throw IllegalArgumentException()
}
if (offset < 0) {
throw IllegalArgumentException()
}
if (offset + count * size > data.size) {
throw IllegalArgumentException()
}
}
}
internal enum class UniformMatSize(wh: Int) {
TWO(2) {
override fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int, transpose: Boolean) {
GLES20.glUniformMatrix2fv(handle, count, transpose, data, offset)
}
},
THREE(3) {
override fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int, transpose: Boolean) {
GLES20.glUniformMatrix3fv(handle, count, transpose, data, offset)
}
},
FOUR(4) {
override fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int, transpose: Boolean) {
GLES20.glUniformMatrix4fv(handle, count, transpose, data, offset)
}
},
;
private val size: Int = wh * wh
fun bind(handle: Int, data: FloatArray, count: Int, offset: Int, transpose: Boolean) {
if (count <= 0) {
throw IllegalArgumentException()
}
if (offset < 0) {
throw IllegalArgumentException()
}
if (offset + count * size > data.size) {
throw IllegalArgumentException()
}
bindInternal(handle, data, count, offset, transpose)
}
protected abstract fun bindInternal(handle: Int, data: FloatArray, count: Int, offset: Int, transpose: Boolean)
} | 0 | Kotlin | 0 | 0 | fd8350e61b360fe60ddd06438e3405c683f4813a | 4,424 | deep-venture-k3d | MIT License |
EcosystemSimulation/src/shmp/visualizer/text/TileMapper.kt | ShMPMat | 212,499,539 | false | null | package shmp.visualizer.text
import shmp.simulation.space.tile.Tile
data class TileMapper(val mapper: (Tile) -> String, val order: Int, val name: String = "Unnamed")
| 0 | Kotlin | 0 | 0 | 9fc6faafa1dbd9737dac71dc8a77960accdae81f | 169 | CulturesSim | MIT License |
app/src/main/java/com/kartikasw/kelilinkseller/core/domain/repository/SellerRepository.kt | kartikasw | 578,519,767 | false | null | package com.kartikasw.kelilinkseller.core.domain.repository
import com.kartikasw.kelilinkseller.core.domain.Resource
import com.kartikasw.kelilinkseller.core.domain.model.Seller
import com.google.firebase.auth.FirebaseUser
import kotlinx.coroutines.flow.Flow
interface SellerRepository {
fun getUser(): FirebaseUser
fun setFcmToken(token: String)
fun getFcmToken(): String
fun updatePassword(oldPassword: String, newPassword: String): Flow<Resource<Seller>>
} | 0 | Kotlin | 0 | 0 | 33bd841f8dba7c3f1b3ce9a18a7f588b2a5b955f | 479 | kelilink-seller | MIT License |
src/main/kotlin/app/pankaj/api/auth/domain/model/Role.kt | pankaj046 | 785,842,370 | false | {"Kotlin": 39728} | package app.pankaj.api.auth.domain.model
enum class Role {
USER, ADMIN, Public
}
| 0 | Kotlin | 0 | 0 | cd8d004002454f6d1b00ed02c15bb3866b261224 | 86 | ktor-starter | The Unlicense |
korender-framework/korender/src/commonMain/kotlin/declaration/Materials.kt | zakgof | 752,263,385 | false | {"Kotlin": 370131, "GLSL": 23847} | package com.zakgof.korender.declaration
import com.zakgof.korender.impl.engine.ShaderDeclaration
import com.zakgof.korender.impl.material.StockUniforms
object Materials {
fun standard(vararg options: StandardMaterialOption, plugins: Map<String, String> = mapOf(), block: StockUniforms.() -> Unit) =
MaterialDeclaration(
ShaderDeclaration("standard.vert", "standard.frag", options, plugins),
StockUniforms().apply(block)
)
fun custom(vertexFile: String, fragFile: String, vararg defs: String, plugins: Map<String, String> = mapOf(), uniforms: UniformSupplier = UniformSupplier { null }) =
MaterialDeclaration(
ShaderDeclaration(vertexFile, fragFile, setOf(*defs), plugins),
uniforms
)
fun billboardStandard(fragFile: String = "standard.frag", vararg options: StandardMaterialOption, plugins: Map<String, String> = mapOf(), block: StockUniforms.() -> Unit) =
BillboardMaterialDeclaration(
ShaderDeclaration("billboard.vert", fragFile, options, plugins),
StockUniforms().apply(block)
)
fun billboardCustom(fragFile: String, vararg defs: String, plugins: Map<String, String> = mapOf(), uniforms: UniformSupplier = UniformSupplier { null }) =
BillboardMaterialDeclaration(
ShaderDeclaration("billboard.vert", fragFile, setOf(*defs), plugins),
uniforms
)
}
class MaterialDeclaration internal constructor(internal val shader: ShaderDeclaration, internal val uniforms: UniformSupplier)
class BillboardMaterialDeclaration internal constructor(internal val shader: ShaderDeclaration, internal val uniforms: UniformSupplier)
class FilterDeclaration internal constructor(internal val shader: ShaderDeclaration, internal val uniforms: UniformSupplier)
| 0 | Kotlin | 0 | 0 | 94f8991075ac3dd96e36f0487fce50eef3a7873f | 1,823 | korender | Apache License 2.0 |
kotlin/src/main/kotlin/zoo/BlueTiger.kt | MateuszHaberla | 417,452,357 | false | {"Kotlin": 2418} | package zoo
data class BlueTiger(
override val name: String,
) : Animal {
override val specie: Specie = Specie.BLUE_TIGER
override var isHungry: Boolean = false
}
| 5 | Kotlin | 0 | 0 | c2127c933b59d913696ab8f4724ac4af6f729e20 | 176 | JVM-secrets | Apache License 2.0 |
app/src/main/java/com/thiosin/novus/domain/model/Subreddit.kt | khongi | 309,088,201 | false | null | package com.thiosin.novus.domain.model
import com.thiosin.novus.data.network.model.subreddit.SubredditListingChildData
import com.thiosin.novus.data.network.model.subreddit.SubredditListingResponse
data class Subreddit(
val queryName: String,
val displayName: String,
val type: SubredditType = SubredditType.Community,
val iconUrl: String? = null,
val iconResource: Int? = null
)
enum class SubredditType {
Frontpage,
All,
Popular,
Community
}
fun SubredditListingResponse.toSubredditList(): List<Subreddit> {
return data.children.map { it.data.toSubreddit() }
}
fun SubredditListingChildData.toSubreddit(): Subreddit {
return Subreddit(
queryName = displayName,
displayName = "/$displayNamePrefixed",
iconUrl = iconImg
)
}
| 0 | Kotlin | 0 | 0 | 3092281a87d6f8f8d46c32f710ff1740934a8398 | 801 | novus | Apache License 2.0 |
data-rating/src/main/java/com/melonhead/data_rating/services/RatingService.kt | julieminer | 542,405,576 | false | {"Kotlin": 224747} | package com.melonhead.data_rating.services
import com.melonhead.data_rating.models.RatingChangeRequest
import com.melonhead.data_rating.models.RatingResults
import com.melonhead.data_rating.routes.HttpRoutes
import com.melonhead.data_rating.routes.HttpRoutes.ID_PLACEHOLDER
import com.melonhead.lib_app_data.AppData
import com.melonhead.lib_logging.Clog
import com.melonhead.lib_networking.extensions.catching
import com.melonhead.lib_networking.extensions.catchingSuccess
import io.ktor.client.HttpClient
import io.ktor.client.request.*
import io.ktor.http.ContentType
import io.ktor.http.contentType
interface RatingService {
suspend fun getRatings(mangaIds: List<String>): Map<String, Int>
suspend fun setRating(mangaId: String, ratingNumber: Int)
}
internal class RatingServiceImpl(
private val client: HttpClient,
private val appData: AppData,
): RatingService {
override suspend fun getRatings(mangaIds: List<String>): Map<String, Int> {
val session = appData.getSession() ?: return emptyMap()
Clog.i("getRatings: manga list: $mangaIds")
val result = client.catching<Map<String, RatingResults>>("getRatings") {
client.get(HttpRoutes.RATING_URL) {
headers {
contentType(ContentType.Application.Json)
bearerAuth(session)
}
url {
mangaIds.forEach {
encodedParameters.append("manga[]", it)
}
}
}
}
return result?.map {
it.key to it.value.rating
}?.toMap() ?: emptyMap()
}
override suspend fun setRating(mangaId: String, ratingNumber: Int) {
val session = appData.getSession() ?: return
Clog.i("setRating: manga $mangaId rating $ratingNumber")
client.catchingSuccess("setRating") {
client.post(HttpRoutes.RATING_CHANGE_URL.replace(ID_PLACEHOLDER, mangaId)) {
headers {
contentType(ContentType.Application.Json)
bearerAuth(session)
}
setBody(RatingChangeRequest(ratingNumber))
}
}
}
}
| 6 | Kotlin | 0 | 0 | a6ddd8fd1bb6eed716bd196f0b7c57872b21a816 | 2,217 | mangadexdroid | Do What The F*ck You Want To Public License |
app/src/main/java/eu/kanade/tachiyomi/data/similar/SimilarUpdateJob.kt | FlaminSarge | 216,350,514 | true | {"Kotlin": 1309386} | package eu.kanade.tachiyomi.data.similar
import com.evernote.android.job.Job
import com.evernote.android.job.JobManager
import com.evernote.android.job.JobRequest
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import java.util.concurrent.TimeUnit
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class SimilarUpdateJob : Job() {
override fun onRunJob(params: Params): Result {
SimilarUpdateService.start(context)
return Result.SUCCESS
}
companion object {
const val TAG = "RelatedUpdate"
fun setupTask() {
// Get if we should have any download restrictions
val preferences = Injekt.get<PreferencesHelper>()
val restrictions = preferences.similarUpdateRestriction()!!
val acRestriction = "ac" in restrictions
val wifiRestriction = if ("wifi" in restrictions)
JobRequest.NetworkType.UNMETERED
else
JobRequest.NetworkType.CONNECTED
// Build the download job
JobRequest.Builder(TAG)
.setPeriodic(TimeUnit.HOURS.toMillis(24), TimeUnit.MINUTES.toMillis(60))
.setRequiredNetworkType(wifiRestriction)
.setRequiresCharging(acRestriction)
.setRequirementsEnforced(true)
.setUpdateCurrent(true)
.build()
.schedule()
}
fun runTaskNow() {
JobRequest.Builder(TAG)
.startNow()
.build()
.schedule()
}
fun cancelTask() {
JobManager.instance().cancelAllForTag(TAG)
}
}
}
| 0 | Kotlin | 0 | 0 | 571eab14b6b184998494d0b9beb9980c1342183c | 1,694 | Neko | Apache License 2.0 |
app/src/main/java/com/arcadan/dodgetheenemies/adapters/InventoryAdapter.kt | ArcaDone | 351,158,574 | false | null | package com.arcadan.dodgetheenemies.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.arcadan.dodgetheenemies.databinding.ItemConsumableBinding
import com.arcadan.dodgetheenemies.models.Consumable
class InventoryAdapter(private val onClickListener: OnClickListener) :
ListAdapter<Consumable, InventoryAdapter.ItemViewHolder>(DiffCallback()) {
override fun onBindViewHolder(holderItem: ItemViewHolder, position: Int) {
val item = getItem(position)
holderItem.itemView.setOnClickListener { onClickListener.onClick(item) }
holderItem.bind(item)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
return ItemViewHolder(ItemConsumableBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
class ItemViewHolder(private val binding: ItemConsumableBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: Consumable) {
binding.item = item
binding.executePendingBindings()
}
}
class OnClickListener(val clickListener: (item: Consumable) -> Unit) {
fun onClick(item: Consumable) = clickListener(item)
}
class DiffCallback : DiffUtil.ItemCallback<Consumable>() {
override fun areItemsTheSame(oldItem: Consumable, newItem: Consumable): Boolean {
return oldItem.consumables.title == newItem.consumables.title
}
override fun areContentsTheSame(oldItem: Consumable, newItem: Consumable): Boolean {
return oldItem == newItem
}
}
}
| 0 | Kotlin | 0 | 2 | 24133757b19f2b2fea64542347b339f8621284f6 | 1,748 | DodgeTheEnemies | MIT License |
app/src/main/java/com/bookcrossing/mobile/interactor/LocationInteractor.kt | fobo66 | 96,350,722 | false | null | /*
* Copyright 2020 Andrey Mukamolov
*
* 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.bookcrossing.mobile.interactor
import com.bookcrossing.mobile.data.LocationRepository
import com.bookcrossing.mobile.models.Coordinates
import io.reactivex.Single
import timber.log.Timber
import javax.inject.Inject
class LocationInteractor @Inject constructor(
private val locationRepository: LocationRepository
) {
/**
* Determine the city of the location of the book
*/
fun resolveCity(coordinates: Coordinates?): Single<String> {
return locationRepository.resolveCity(
coordinates?.lat ?: 0.0,
coordinates?.lng ?: 0.0
)
.doOnError(Timber::e)
}
} | 10 | Kotlin | 1 | 3 | 3428041869733e10d48250a935cf84ec7ab2c36d | 1,234 | BookcrossingMobile | Apache License 2.0 |
src/commonMain/kotlin/choliver/nespot/cartridge/PrgMemory.kt | oliver-charlesworth | 251,006,755 | false | null | package choliver.nespot.cartridge
import choliver.nespot.BASE_PRG_ROM
import choliver.nespot.PRG_RAM_SIZE
import choliver.nespot.PRG_ROM_SIZE
import choliver.nespot.common.Address
import choliver.nespot.common.Data
import choliver.nespot.common.data
import choliver.nespot.memory.Memory
// TODO - unify with RAM
class PrgMemory(
private val raw: ByteArray,
bankSize: Int = raw.size,
private val onSet: (addr: Address, data: Data) -> Unit = { _, _ -> }
) : Memory {
val bankMap = BankMap(bankSize = bankSize, addressSpaceSize = PRG_ROM_SIZE)
val ram = ByteArray(PRG_RAM_SIZE)
override fun get(addr: Address) = when {
(addr >= BASE_PRG_ROM) -> raw[bankMap.map(addr - BASE_PRG_ROM)]
else -> ram[addr % PRG_RAM_SIZE]
}.data()
override fun set(addr: Address, data: Data) {
when {
(addr >= BASE_PRG_ROM) -> onSet(addr, data)
else -> ram[addr % PRG_RAM_SIZE] = data.toByte()
}
}
}
| 14 | Kotlin | 0 | 1 | 01e108952aa982c4abb4c5274457554feb1517ea | 924 | nespot | MIT License |
day04/src/com/itcast/day03/09.继承.kt | weibo1987 | 133,453,597 | true | {"Kotlin": 100093, "Java": 19216, "Shell": 16001, "Batchfile": 6691} | package com.itcast.day03
/**
* ClassName:`09.继承`
* Description:
*/
fun main(args: Array<String>) {
val son = Son()
println(son.name)
println(son.age)
son.horbe()
}
//kotlin的类都是final的 不能被继承
open class Father{
open var name = "张三"
open var age = 20
//动态行为
open fun horbe(){
println("父亲喜欢抽烟")
}
}
//子承父业
class Son:Father(){
override var name: String = "张四"
override var age: Int = 10
override fun horbe() {
// super.horbe()
println("孩子喜欢看书")
}
} | 1 | Kotlin | 1 | 1 | 6f5b99a51f2acb0c38d8d63191ff9eb1c89a0244 | 523 | BlockChain-1 | MIT License |
packages/graalvm/src/test/kotlin/elide/runtime/gvm/internals/intrinsics/js/struct/map/JsSortedMapTest.kt | elide-dev | 506,113,888 | false | null | package elide.runtime.gvm.internals.intrinsics.js.struct.map
import elide.runtime.intrinsics.js.MapLike
import elide.testing.annotations.Test
import elide.testing.annotations.TestCase
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
/** Tests for the [JsSortedMap] implementation. */
@TestCase internal class JsSortedMapTest : AbstractJsMapTest<JsSortedMap<String, Any?>>() {
/** @inheritDoc */
override fun empty(): JsSortedMap<String, Any?> = JsSortedMap.empty()
/** @inheritDoc */
override fun spawnGeneric(pairs: Collection<Pair<String, Any?>>): JsSortedMap<String, Any?> =
JsSortedMap.fromPairs(pairs)
/** @inheritDoc */
override fun spawnFromMap(map: Map<String, Any?>): JsSortedMap<String, Any?> =
JsSortedMap.copyOf(map)
/** @inheritDoc */
override fun spawnFromEntries(entries: Collection<Map.Entry<String, Any?>>): JsSortedMap<String, Any?> =
JsSortedMap.fromEntries(entries)
/** @inheritDoc */
override fun spawnFromJsEntries(entries: Collection<MapLike.Entry<String, Any?>>): JsSortedMap<String, Any?> =
JsSortedMap.from(entries)
/** @inheritDoc */
override fun spawnUnbounded(pairs: Iterable<Pair<String, Any?>>): JsSortedMap<String, Any?> =
JsSortedMap.unboundedPairs(pairs)
/** @inheritDoc */
override fun spawnUnboundedEntries(entries: Iterable<Map.Entry<String, Any?>>): JsSortedMap<String, Any?> =
JsSortedMap.unboundedEntries(entries)
/** @inheritDoc */
override fun spawnUnboundedJsEntries(entries: Iterable<MapLike.Entry<String, Any?>>): JsSortedMap<String, Any?> =
JsSortedMap.unbounded(entries)
/** @inheritDoc */
override fun implName(): String = "JsSortedMap"
@Test fun testBasicConstructor() {
val map = JsSortedMap<String, Any?>()
assertNotNull(map, "should be able to construct an empty map via the constructor")
}
@Test fun testToString() {
val map = JsSortedMap<String, Any?>()
assertEquals("Map(mutable, sorted, size=0)", map.toString())
}
@Test fun testComparator() {
val map = JsSortedMap<String, Any?>()
assertNull(map.comparator())
}
@Test fun testSpawn() {
val regular = mutableMapOf("hi" to "hello")
val map = JsSortedMap.of(regular)
assertNotNull(map)
assertEquals("hello", map["hi"])
}
}
| 36 | Kotlin | 4 | 33 | 91800dbbf291e65a91d451ed50c9673d82efd174 | 2,307 | elide | MIT License |
data/RF03702/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF03702"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
1 to 5
104 to 108
}
value = "#84c859"
}
color {
location {
7 to 14
95 to 102
}
value = "#1707e6"
}
color {
location {
17 to 22
87 to 92
}
value = "#bf857a"
}
color {
location {
24 to 34
75 to 85
}
value = "#f6804f"
}
color {
location {
36 to 44
65 to 73
}
value = "#81ab7c"
}
color {
location {
6 to 6
103 to 103
}
value = "#4e4012"
}
color {
location {
15 to 16
93 to 94
}
value = "#140273"
}
color {
location {
23 to 23
86 to 86
}
value = "#cb2dfd"
}
color {
location {
35 to 35
74 to 74
}
value = "#a66e6a"
}
color {
location {
45 to 64
}
value = "#c31250"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 1,704 | Rfam-for-RNArtist | MIT License |
src/giphy/GiphyListItem.kt | ralfstuckert | 131,523,276 | false | {"Kotlin": 16121, "HTML": 1767, "CSS": 827} | package giphy
import kotlinx.html.js.onClickFunction
import kotlinx.html.title
import react.*
import react.dom.div
import react.dom.img
import react.dom.li
interface GiphyListItemProps : RProps {
var giphy: Giphy
var onSelect: (Giphy) -> Unit
}
class GiphyListItem(props: GiphyListItemProps) : RComponent<GiphyListItemProps, RState>(props) {
override fun RBuilder.render() {
val giphy = props.giphy
li("list-group-item") {
attrs.onClickFunction = { props.onSelect(giphy) }
div("giphy-item media") {
div("media-left") {
img("media-object") {
attrs {
src = giphy.previewUrl
alt = giphy.fileName
title = giphy.fileName
}
}
}
}
}
}
}
fun RBuilder.giphyListItem(giphy: Giphy, onSelect: (Giphy) -> Unit) = child(GiphyListItem::class) {
attrs.giphy = giphy
attrs.key = giphy.id
attrs.onSelect = onSelect
}
| 0 | Kotlin | 5 | 18 | 3e17e4cbe06cdccf4b90e7be90523819373d49a5 | 1,101 | kotlin-react-sample | MIT License |
src/main/kotlin/no/nav/sykmeldinger/sykmelding/kafka/SykmeldingConsumer.kt | navikt | 530,979,591 | false | null | package no.nav.sykmeldinger.sykmelding.kafka
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.ktor.client.plugins.ClientRequestException
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import no.nav.syfo.model.ReceivedSykmelding
import no.nav.sykmeldinger.application.ApplicationState
import no.nav.sykmeldinger.arbeidsforhold.ArbeidsforholdService
import no.nav.sykmeldinger.pdl.error.PersonNotFoundInPdl
import no.nav.sykmeldinger.pdl.model.PdlPerson
import no.nav.sykmeldinger.pdl.service.PdlPersonService
import no.nav.sykmeldinger.sykmelding.SykmeldingMapper
import no.nav.sykmeldinger.sykmelding.SykmeldingService
import no.nav.sykmeldinger.sykmelding.model.Sykmeldt
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.slf4j.LoggerFactory
import java.time.Duration
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneOffset
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
private val objectMapper: ObjectMapper = jacksonObjectMapper().apply {
registerModule(JavaTimeModule())
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
}
class SykmeldingConsumer(
private val kafkaConsumer: KafkaConsumer<String, String>,
private val applicationState: ApplicationState,
private val pdlPersonService: PdlPersonService,
private val arbeidsforholdService: ArbeidsforholdService,
private val sykmeldingService: SykmeldingService,
private val cluster: String
) {
companion object {
private val log = LoggerFactory.getLogger(SykmeldingConsumer::class.java)
private const val OK_TOPIC = "teamsykmelding.ok-sykmelding"
private const val AVVIST_TOPIC = "teamsykmelding.avvist-sykmelding"
private const val MANUELL_TOPIC = "teamsykmelding.manuell-behandling-sykmelding"
}
private val sykmeldingTopics =
listOf(OK_TOPIC, AVVIST_TOPIC, MANUELL_TOPIC)
private var totalDuration = kotlin.time.Duration.ZERO
private val sykmeldingDuration = kotlin.time.Duration.ZERO
private var totalRecords = 0
private var okRecords = 0
private var avvistRecords = 0
private var manuellRecords = 0
private var lastDate = OffsetDateTime.MIN
@OptIn(DelicateCoroutinesApi::class)
fun startConsumer() {
GlobalScope.launch(Dispatchers.IO) {
GlobalScope.launch(Dispatchers.IO) {
while (applicationState.ready) {
no.nav.sykmeldinger.log.info(
"total: $totalRecords, ok: $okRecords, manuell: $manuellRecords, avvist: $avvistRecords, last $lastDate avg tot: ${
getDurationPerRecord(
totalDuration,
totalRecords
)
} ms"
)
delay(10000)
}
}
while (applicationState.ready) {
try {
kafkaConsumer.subscribe(sykmeldingTopics)
consume()
} catch (ex: Exception) {
log.error("error running sykmelding-consumer", ex)
} finally {
kafkaConsumer.unsubscribe()
log.info("Unsubscribed from topic $sykmeldingTopics and waiting for 10 seconds before trying again")
delay(10_000)
}
}
}
}
@OptIn(ExperimentalTime::class)
private suspend fun consume() = withContext(Dispatchers.IO) {
while (applicationState.ready) {
val consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(1))
if (!consumerRecords.isEmpty) {
totalDuration += measureTime {
totalRecords += consumerRecords.count()
lastDate = OffsetDateTime.ofInstant(
Instant.ofEpochMilli(consumerRecords.last().timestamp()),
ZoneOffset.UTC
)
val sykmeldinger = consumerRecords.map { cr ->
val sykmelding: ReceivedSykmelding? = cr.value()?.let { objectMapper.readValue(it, ReceivedSykmelding::class.java) }
when (cr.topic()) {
OK_TOPIC -> okRecords++
MANUELL_TOPIC -> manuellRecords++
AVVIST_TOPIC -> avvistRecords++
}
cr.key() to sykmelding
}
sykmeldinger.forEach {
handleSykmelding(it.first, it.second)
}
}
}
}
}
private suspend fun handleSykmelding(sykmeldingId: String, receivedSykmelding: ReceivedSykmelding?) {
if (receivedSykmelding != null) {
val sykmelding = SykmeldingMapper.mapToSykmelding(receivedSykmelding)
try {
val sykmeldt = pdlPersonService.getPerson(receivedSykmelding.personNrPasient, sykmeldingId).toSykmeldt()
val arbeidsforhold = arbeidsforholdService.getArbeidsforhold(sykmeldt.fnr)
arbeidsforhold.forEach { arbeidsforholdService.insertOrUpdate(it) }
sykmeldingService.saveOrUpdate(sykmeldingId, sykmelding, sykmeldt)
} catch (e: PersonNotFoundInPdl) {
if (cluster != "dev-gcp") {
log.error("Person not found in PDL, for sykmelding $sykmeldingId", e)
throw e
} else {
log.warn("Person not found in PDL, for sykmelding $sykmeldingId, skipping in dev")
}
} catch (e: ClientRequestException) {
if (cluster != "dev-gcp") {
log.error("Error doing request $sykmeldingId", e)
throw e
} else {
log.warn("Error doing request $sykmeldingId, skipping in dev", e)
}
}
} else {
sykmeldingService.deleteSykmelding(sykmeldingId)
log.info("Deleted sykmelding etc with sykmeldingId: $sykmeldingId")
}
}
private fun getDurationPerRecord(duration: kotlin.time.Duration, records: Int): Long {
return when (duration.inWholeMilliseconds == 0L || records == 0) {
false -> duration.div(records).inWholeMilliseconds
else -> 0L
}
}
}
fun PdlPerson.toSykmeldt(): Sykmeldt {
return Sykmeldt(fnr = fnr, fornavn = navn.fornavn, mellomnavn = navn.mellomnavn, etternavn = navn.etternavn)
}
| 0 | Kotlin | 1 | 0 | 9c0a6da53b99b2cd3eef384bea7ba4853ec8d044 | 7,193 | sykmeldinger-backend-kafka | MIT License |
android-weather-mvp-clean/data/src/main/kotlin/io/sametkurumahmut/weather/data/repository/CityWeatherDataRepository.kt | sametkurumahmut | 116,595,636 | false | null | package io.sametkurumahmut.weather.data.repository
import io.reactivex.Observable
import io.reactivex.Single
import io.sametkurumahmut.weather.common.mapper.Mapper
import io.sametkurumahmut.weather.common.schedulers.rx.RxSchedulerProvider
import io.sametkurumahmut.weather.data.model.CityWeatherEntity
import io.sametkurumahmut.weather.data.repository.cache.CityWeatherCache
import io.sametkurumahmut.weather.data.source.CityWeatherDataSource
import io.sametkurumahmut.weather.domain.WeatherInfoNotAvailableException
import io.sametkurumahmut.weather.domain.data.repository.CityWeatherRepository
import io.sametkurumahmut.weather.domain.device.location.Location
import io.sametkurumahmut.weather.domain.device.net.NetInfo
import io.sametkurumahmut.weather.domain.interactor.CompletableUseCase
import io.sametkurumahmut.weather.domain.interactor.ObservableUseCase
import io.sametkurumahmut.weather.domain.model.CityWeather
import javax.inject.Inject
class CityWeatherDataRepository @Inject constructor(
private val cityWeatherCache: CityWeatherCache,
private val cityWeatherCacheDataSource: CityWeatherDataSource,
private val cityWeatherRemoteDataSource: CityWeatherDataSource,
private val getLocationUseCase: ObservableUseCase<Location, Nothing>,
private val onNetConnectedUseCase: CompletableUseCase<Nothing>,
private val netInfo: NetInfo,
private val mapper: Mapper<CityWeatherEntity, CityWeather>,
private val rxSchedulers: RxSchedulerProvider) : CityWeatherRepository {
//region CityWeatherRepository Methods
override fun clearCurrentLocationWeather() = this.cityWeatherCache.clearCurrentLocationWeather()
override fun getCurrentLocationWeather(): Observable<CityWeather> {
val observableCityWeatherEntity = if (this.netInfo.isConnected()) {
this.getRemoteCityWeather()
} else {
Observable.concat(
this.cityWeatherCache.isCached()
.flatMap {
if (it && !this.cityWeatherCache.isExpired()) {
this.cityWeatherCacheDataSource.getCurrentLocationWeather()
} else {
Single.error(
WeatherInfoNotAvailableException(
if (!it)
"Cache doesn't exist"
else
"Cache is expired"))
}
}
.toObservable(),
this.onNetConnectedUseCase.execute().toObservable(),
this.getRemoteCityWeather())
}
return observableCityWeatherEntity
.map {
this.mapper.from(it)
}
}
override fun saveCityWeather(cityWeather: CityWeather)
= this.cityWeatherCache.saveCityWeather(this.mapper.to(cityWeather))
//endregion
//region Methods
private fun getRemoteCityWeather() = this.getLocationUseCase.execute()
.observeOn(this.rxSchedulers.io)
.flatMap {
this.cityWeatherRemoteDataSource.getCityWeatherByLocation(it.latitude, it.longitude)
.flatMap {
this.cityWeatherCacheDataSource.saveCityWeather(it).toSingle { it }
}
.toObservable()
}
//endregion
}
| 1 | null | 1 | 1 | 329b53e856851d0fd505aa87d4e2aa3d1545ce41 | 3,657 | weather-mvp-clean | Apache License 2.0 |
shared/src/commonMain/kotlin/data/repository/portfolio/PortfolioRepositoryImpl.kt | adelsaramii | 727,620,001 | false | {"Kotlin": 1014333, "Swift": 2299, "Shell": 228} | package com.attendace.leopard.data.repository.portfolio
import arrow.core.Either
import com.attendace.leopard.data.local.setting.AuthSettings
import com.attendance.leopard.data.model.LeopardTabBarTypes
import com.attendance.leopard.data.model.ModifyPortfolioResponse
import com.attendace.leopard.data.model.Portfolio
import com.attendance.leopard.data.model.Subordinate
import com.attendance.leopard.data.source.remote.model.dto.ModifyPortfolioInput
import com.attendance.leopard.data.source.remote.model.dto.PortfolioRequestTypesDto
import com.attendance.leopard.data.source.remote.model.dto.toDomainModel
import com.attendance.leopard.data.source.remote.model.dto.toPortfolio
import com.attendance.leopard.data.source.remote.model.dto.toPortfolioRequestTypes
import com.attendance.leopard.data.source.remote.model.dto.toSubordinate
import com.attendace.leopard.data.source.remote.service.portfolio.PortfolioService
import com.attendace.leopard.util.error.Failure
import kotlinx.coroutines.flow.Flow
class PortfolioRepositoryImpl(
private val portfolioService: PortfolioService,
private val authSettings: AuthSettings,
) : PortfolioRepository {
override suspend fun getPortfolio(
pageNumber: Int?,
pageSize: Int?,
requestCode: String?,
startDate: String?,
endDate: String?,
applicantId: String?,
searchValue: String?
): Either<Failure.NetworkFailure, List<Portfolio>> {
return portfolioService.getPortfolio(
pageNumber = pageNumber,
pageSize = pageSize,
requestCode = requestCode,
startDate = startDate,
endDate = endDate,
applicantId = applicantId,
searchValue = searchValue
).map {
it.map { it.toPortfolio() }
}
}
override suspend fun getPortfolioRequestTypes(): Either<Failure.NetworkFailure, List<LeopardTabBarTypes>> {
return portfolioService.getPortfolioRequestTypes().map { modelDto ->
val requestType = PortfolioRequestTypesDto("0", "All", modelDto.total)
modelDto.portfolioRequestTypes.add(0, requestType)
modelDto.portfolioRequestTypes.map { it.toPortfolioRequestTypes() }
}
}
override suspend fun modifyPortfolio(
portfolioItems: List<ModifyPortfolioInput>
): Either<Failure.NetworkFailure, List<ModifyPortfolioResponse>> {
return portfolioService.modifyPortfolio(portfolioItems)
.map { it.map { it.toDomainModel() } }
}
override suspend fun getPortfolioApplicantApi(): Either<Failure.NetworkFailure, List<Subordinate>> {
return portfolioService.getPortfolioApplicantApi().map {
it.map { it.toSubordinate() }
}
}
override suspend fun getAccessToken(): Flow<String> {
return authSettings.getAccessToken()
}
override suspend fun getBaseUrl(): Flow<String> {
return authSettings.getBaseUrl()
}
}
| 0 | Kotlin | 0 | 0 | ed51d4c99caafefc5fc70cedbe0dd0fa62cce271 | 2,978 | Leopard-Multiplatform | Apache License 2.0 |
kmqtt-common/src/commonMain/kotlin/socket/streams/ByteArrayOutputStream.kt | davidepianca98 | 235,132,697 | false | {"Kotlin": 524141, "Dockerfile": 3673} | package socket.streams
public class ByteArrayOutputStream : OutputStream {
private var count = 0
private var array: UByteArray = UByteArray(1024)
private fun ensureCapacity(length: Int) {
if (count + length > array.size)
array = array.copyOf(array.size + length * 2)
}
override fun write(b: UByte) {
ensureCapacity(1)
array[count] = b
count += 1
}
public fun write(b: UByteArray, off: Int, len: Int) {
ensureCapacity(len)
array = b.copyInto(array, count, off, len)
count += len
}
override fun write(b: UByteArray) {
ensureCapacity(b.size)
write(b, 0, b.size)
}
public fun size(): Int {
return count
}
public fun toByteArray(): UByteArray {
return array.copyOfRange(0, count)
}
override fun toString(): String {
return array.toByteArray().decodeToString() // UTF-8
}
}
| 2 | Kotlin | 19 | 92 | eff347bc03c4093a974731d0974e5592bde5bb49 | 949 | KMQTT | MIT License |
app/src/main/java/me/ykrank/s1next/data/api/ApiException.kt | ykrank | 52,680,091 | false | {"Kotlin": 850930, "Java": 727444, "HTML": 20430} | package me.ykrank.s1next.data.api
/**
* Created by ykrank on 2016/6/17.
*/
open class ApiException : Exception {
constructor(msg: String?) : super(msg) {}
constructor(cause: Throwable) : super(cause) {}
constructor(message: String?, cause: Throwable) : super(message, cause) {}
class AuthenticityTokenException : ApiException {
constructor(msg: String?) : super(msg) {}
constructor(cause: Throwable) : super(cause) {}
constructor(message: String?, cause: Throwable) : super(message, cause) {}
}
class ApiServerException : ApiException {
constructor(msg: String?) : super(msg) {}
constructor(cause: Throwable) : super(cause) {}
constructor(message: String?, cause: Throwable) : super(message, cause) {}
}
class AppServerException(msg: String?, val code: Int) : ApiException(msg)
}
| 1 | Kotlin | 37 | 317 | 0c0b0fdb992db9b046265ee6e9b50ac676a1c104 | 875 | S1-Next | Apache License 2.0 |
app/src/main/java/com/fueled/recyclerviewbindings/model/MainModel.kt | chetdeva | 103,640,066 | false | null | package com.fueled.recyclerviewbindings.model
import android.databinding.BaseObservable
import android.databinding.Bindable
import com.fueled.recyclerviewbindings.BR
/**
* Copyright (c) 2017 Fueled. All rights reserved.
*
* @author chetansachdeva on 24/09/17
*/
class MainModel : BaseObservable() {
@get:Bindable
var resetLoadingState: Boolean = false
set(resetLoadingState) {
field = resetLoadingState
notifyPropertyChanged(BR.resetLoadingState)
}
@get:Bindable
var visibleThreshold: Int = 0
set(visibleThreshold) {
field = visibleThreshold
notifyPropertyChanged(BR.visibleThreshold)
}
}
| 2 | Kotlin | 7 | 30 | c42050f7f38738d23cae14d44b3745c26127e099 | 695 | recyclerview-bindings | MIT License |
beam-bundle/src/main/kotlin/dev/d1s/beam/bundle/configuration/DaemonConnectorProperties.kt | d1snin | 632,895,652 | false | null | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.d1s.beam.bundle.configuration
import io.ktor.http.*
import io.ktor.server.config.*
private const val DAEMON_DOCKER_HOST = "beam-daemon"
internal val ApplicationConfig.daemonHttpAddress
get() = property("daemon.connector.http").getString()
.ensureCorrectUrl()
internal val ApplicationConfig.daemonWsAddress
get() = property("daemon.connector.ws").getString()
.ensureCorrectUrl()
private fun String.ensureCorrectUrl(): String {
val url = URLBuilder(this)
if (url.host == DAEMON_DOCKER_HOST) {
url.set {
host = "localhost"
}
return url.buildString()
}
return this
} | 7 | null | 0 | 5 | 34490a23f3fccc5527ced519d35939498d27d788 | 1,249 | beam | Apache License 2.0 |
fake/src/commonMain/kotlin/in/surajsau/jisho/fake/FakeJmdictRepository.kt | surajsau | 489,927,815 | false | null | package `in`.surajsau.jisho.fake
import `in`.surajsau.jisho.model.jmdict.Entry
import `in`.surajsau.jisho.model.jmdict.Gloss
import `in`.surajsau.jisho.model.jmdict.Info
import `in`.surajsau.jisho.model.jmdict.JReading
import `in`.surajsau.jisho.model.jmdict.JmdictQueryResult
import `in`.surajsau.jisho.model.jmdict.Kanji
import `in`.surajsau.jisho.model.jmdict.Sense
class FakeJmdictRepository {
suspend fun searchForKanji(query: String): List<JmdictQueryResult> {
return Entries.filter { entry ->
entry.kanjis.any { kanji -> kanji.value.contains(convertQueryToRegex(text = query)) }
}
.map { entry ->
JmdictQueryResult(
id = entry.id,
kanjiString = entry.kanjis.joinToString(";") { it.value },
readingString = entry.readings.joinToString(";") { it.value },
glossString = entry.senses.joinToString(";") { sense ->
sense.glosses.joinToString("|") { gloss -> "${gloss.value}-${gloss.type ?: ""}" }
},
readingRestrictionString = entry.readings.joinToString(";") { it.restriction.joinToString("|") }
)
}
}
suspend fun searchForReading(query: String): List<JmdictQueryResult> {
return Entries.filter { entry ->
entry.readings.any { reading -> reading.value.contains(convertQueryToRegex(text = query)) }
}
.map { entry ->
JmdictQueryResult(
id = entry.id,
kanjiString = entry.kanjis.joinToString(";") { it.value },
readingString = entry.readings.joinToString(";") { it.value },
glossString = entry.senses.joinToString(";") { sense ->
sense.glosses.joinToString("|") { gloss -> "${gloss.value}-${gloss.type ?: ""}" }
},
readingRestrictionString = entry.readings.joinToString(";") { it.restriction.joinToString("|") }
)
}
}
/*
Use case prepends and appends '%' for sqlite LIKE query.
For our fake repository, using a Regex instead should serve well.
%query: any string ending with 'query'. In regex it would be query$
query%: any string beginning with 'query'. In regex it would be ^query
*/
private fun convertQueryToRegex(text: String): Regex {
return Regex(pattern = when (text.indexOf("%")) {
0 -> text.replace("%", "") + "$"
else -> "^" + text.replace("%", "")
})
}
suspend fun getEntry(id: Long): Entry {
return Entries.firstOrNull { it.id == id } ?: throw Exception()
}
suspend fun totalCount(): Long {
return Entries.size.toLong()
}
companion object {
private val Entries = listOf(
Entry(
id = 2356220,
kanjis = listOf(
Kanji(value = "行方向奇偶検査", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "ぎょうほうこうきぐうけんさ",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "longitudinal parity check", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356230,
kanjis = listOf(
Kanji(value = "行列演算", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "ぎょうれつえんざん",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "matrix operation", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356240,
kanjis = listOf(
Kanji(value = "行列記法", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "ぎょうれつきほう",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "matrix notation", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356250,
kanjis = listOf(
Kanji(value = "行列代数", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "ぎょうれつだいすう",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "linear algebra", type = null), Gloss(value = "matrix algebra", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356260,
kanjis = listOf(
Kanji(value = "行列表現", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "ぎょうれつひょうげん",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "matrix representation", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356270,
kanjis = listOf(
Kanji(value = "行列要素", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "ぎょうれつようそ",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "matrix element", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356280,
kanjis = listOf(
Kanji(value = "行枠", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "ぎょうわく",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "line box", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356290,
kanjis = listOf(
Kanji(value = "降順キー", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "こうじゅんキー",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "descending key", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356310,
kanjis = listOf(
Kanji(value = "項目選択", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "こうもくせんたく",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "item selection", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356320,
kanjis = listOf(
Kanji(value = "項目名", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "こうもくめい",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "item name", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356350,
kanjis = listOf(
Kanji(value = "高位レベル", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "こういレベル",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "higher level", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356360,
kanjis = listOf(
Kanji(value = "高域通過フィルタ", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "こういきつうかフィルタ",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "high pass filter", type = null), Gloss(value = "HPF", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356370,
kanjis = listOf(
Kanji(value = "高画質", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "こうがしつ",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "high image quality", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356380,
kanjis = listOf(
Kanji(value = "高解像度", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "こうかいぞうど",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "high resolution", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
Entry(
id = 2356390,
kanjis = listOf(
Kanji(value = "高級言語", info = emptyList(), priority = emptyList())
),
readings = listOf(
JReading(
value = "こうきゅうげんご",
info = emptyList(),
priority = emptyList(),
isNotTrueReading = false,
restriction = emptyList()
)
),
senses = listOf(
Sense(
glosses = listOf(Gloss(value = "high-level language", type = null)),
particleOfSpeeches = listOf(Info("n")),
fields = listOf(Info("comp")),
dialects = emptyList(),
antonyms = emptyList(),
example = emptyList()
)
)
),
)
}
suspend fun getEntriesForJlpt(level: Long): List<JmdictQueryResult> {
return emptyList()
}
suspend fun getForKanjiOrReading(query: String): JmdictQueryResult? {
return null
}
} | 0 | Kotlin | 0 | 1 | f926cd4111d7d19f1f4853cff13200b4d00f5760 | 18,124 | Multiplatform-Jisho | Apache License 2.0 |
database/src/main/java/com/n0stalgiaultra/database/utils/FragmentIdHandler.kt | N0stalgiaUltra | 695,229,889 | false | {"Kotlin": 60296} | package com.n0stalgiaultra.database.utils
import android.content.Context
class FragmentIdHandler(private val context: Context) {
private val sharedPreferences =
context.getSharedPreferences("BuscaCEP", Context.MODE_PRIVATE)
fun saveID(fragementID: Int){
sharedPreferences.edit().putInt("FragID", fragementID).apply()
}
fun getID(): Int{
return sharedPreferences.getInt("FragID", 0)
}
} | 0 | Kotlin | 0 | 0 | 2bd16aa2faf0ac6a99c764be382fd2693cf91eca | 433 | AcheseuCEP | Apache License 2.0 |
src/main/kotlin/codes/foobar/wedapp/user/User.kt | apgv | 119,103,169 | false | null | package codes.foobar.wedapp.user
import codes.foobar.wedapp.role.Role
import java.time.ZonedDateTime
data class User(
val id: Int,
val name: String,
val email: String,
val roles: List<Role>,
val updatedDateTime: ZonedDateTime
) | 1 | null | 1 | 1 | f5006f446f758c0a79f6bd7db97b46390580c1eb | 269 | wedapp | MIT License |
app/src/main/java/com/shid/mosquefinder/app/ui/main/states/AzkharViewState.kt | theshid | 275,887,919 | false | null | package com.shid.mosquefinder.app.ui.main.states
import com.shid.mosquefinder.app.ui.models.DeeplPresentation
internal data class AzkharViewState(
val isComplete: Boolean,
val error: Error?,
val translation:DeeplPresentation?
)
| 0 | Kotlin | 0 | 1 | ef20551bc24f9956b4c487fb49585d736211e05b | 242 | Mosque-Finder | The Unlicense |
injective-core/src/jvmMain/kotlin/injective/permissions/v1beta1/query.converter.kt | jdekim43 | 759,720,689 | false | {"Kotlin": 8940168, "Java": 3242559} | // Transform from injective/permissions/v1beta1/query.proto
@file:GeneratorVersion(version = "0.3.1")
package injective.permissions.v1beta1
import kr.jadekim.protobuf.`annotation`.GeneratorVersion
import kr.jadekim.protobuf.converter.ProtobufConverter
public actual object QueryParamsRequestConverter : ProtobufConverter<QueryParamsRequest> by
QueryParamsRequestJvmConverter
public actual object QueryParamsResponseConverter : ProtobufConverter<QueryParamsResponse> by
QueryParamsResponseJvmConverter
public actual object QueryAllNamespacesRequestConverter :
ProtobufConverter<QueryAllNamespacesRequest> by QueryAllNamespacesRequestJvmConverter
public actual object QueryAllNamespacesResponseConverter :
ProtobufConverter<QueryAllNamespacesResponse> by QueryAllNamespacesResponseJvmConverter
public actual object QueryNamespaceByDenomRequestConverter :
ProtobufConverter<QueryNamespaceByDenomRequest> by QueryNamespaceByDenomRequestJvmConverter
public actual object QueryNamespaceByDenomResponseConverter :
ProtobufConverter<QueryNamespaceByDenomResponse> by QueryNamespaceByDenomResponseJvmConverter
public actual object QueryAddressesByRoleRequestConverter :
ProtobufConverter<QueryAddressesByRoleRequest> by QueryAddressesByRoleRequestJvmConverter
public actual object QueryAddressesByRoleResponseConverter :
ProtobufConverter<QueryAddressesByRoleResponse> by QueryAddressesByRoleResponseJvmConverter
public actual object QueryAddressRolesRequestConverter : ProtobufConverter<QueryAddressRolesRequest>
by QueryAddressRolesRequestJvmConverter
public actual object QueryAddressRolesResponseConverter :
ProtobufConverter<QueryAddressRolesResponse> by QueryAddressRolesResponseJvmConverter
public actual object QueryVouchersForAddressRequestConverter :
ProtobufConverter<QueryVouchersForAddressRequest> by QueryVouchersForAddressRequestJvmConverter
public actual object QueryVouchersForAddressResponseConverter :
ProtobufConverter<QueryVouchersForAddressResponse> by
QueryVouchersForAddressResponseJvmConverter
| 0 | Kotlin | 0 | 0 | eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc | 2,076 | chameleon.proto | Apache License 2.0 |
src/main/kotlin/io/foxcapades/lib/cli/builder/flag/CliFlag.fn.kt | Foxcapades | 850,780,005 | false | {"Kotlin": 253956} | package io.foxcapades.lib.cli.builder.flag
inline val CliFlag.hasShortForm
get() = shortForm != '\u0000'
inline val CliFlag.hasLongForm
get() = longForm != ""
| 8 | Kotlin | 0 | 0 | 457d895219666963b70ac10df70092a7b778ebea | 165 | lib-kt-cli-builder | MIT License |
droid-app/CoffeeDose/app/src/main/java/com/office14/coffeedose/extensions/LiveData.kt | sofinms | 249,805,970 | true | {"Kotlin": 102441, "C#": 99646, "TypeScript": 65904, "HTML": 11001, "JavaScript": 1831, "Dockerfile": 1083, "CSS": 299} | package com.office14.coffeedose.extensions
import androidx.lifecycle.MutableLiveData
fun <T> mutableLiveData(default: T? = null): MutableLiveData<T> {
val data = MutableLiveData<T>()
if (default != null)
data.value = default
return data
} | 0 | null | 0 | 0 | 109a16dbce748a363eeb290ebba46c4b9dbbf357 | 262 | Drinks | MIT License |
kofu/src/test/kotlin/org/springframework/fu/kofu/samples/scheduling.kt | skivol | 208,869,043 | false | {"Gradle Kotlin DSL": 44, "AsciiDoc": 7, "Shell": 27, "INI": 60, "Ignore List": 2, "Batchfile": 22, "Text": 4, "Java": 154, "HTML": 14, "Mustache": 26, "Kotlin": 214, "YAML": 2, "CSS": 2, "SQL": 12, "JSON": 19, "Markdown": 1, "Maven POM": 1, "Less": 4, "SVG": 2, "Java Properties": 1, "XML": 1} | package org.springframework.fu.kofu.samples
import org.springframework.fu.kofu.reactiveWebApplication
import org.springframework.fu.kofu.scheduling.scheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler
import java.util.concurrent.Executors
class Task {
@Scheduled(fixedRate = 5_000)
fun run() {
println("Task execution")
}
}
fun schedulingDsl() {
reactiveWebApplication {
beans {
bean<Task>()
}
scheduling {
taskScheduler = ConcurrentTaskScheduler(Executors.newSingleThreadScheduledExecutor())
}
}
}
| 1 | null | 1 | 1 | 47030ba83b32c1c8901f1d9c64edd643a0b2d1c1 | 612 | spring-fu | Apache License 2.0 |
app/src/debug/java/com/reputationoverflow/HiltTestActivity.kt | knowingbros | 389,701,494 | false | null | package com.reputationoverflow
import androidx.appcompat.app.AppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class HiltTestActivity : AppCompatActivity()
| 0 | Kotlin | 0 | 2 | 9f09777074455fc389918187628eb19b59a7e8e2 | 190 | stackoverflow-stackexchange-login-android | MIT License |
app/src/main/java/com/perol/asdpl/pixivez/ui/settings/HistoryAdapter.kt | ultranity | 258,955,010 | false | {"Gradle Kotlin DSL": 4, "Java Properties": 2, "Shell": 1, "Text": 32, "Ignore List": 3, "Batchfile": 1, "Markdown": 9, "TOML": 1, "YAML": 2, "Proguard": 2, "JSON": 4, "Kotlin": 224, "XML": 164, "CSS": 3, "Java": 20, "JavaScript": 5, "HTML": 1, "robots.txt": 1} | /*
* MIT License
*
* Copyright (c) 2019 Perol_Notsfsssf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE
*/
package com.perol.asdpl.pixivez.ui.settings
import android.graphics.drawable.ColorDrawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.chad.brvah.BaseQuickAdapter
import com.chad.brvah.viewholder.BaseViewHolder
import com.perol.asdpl.pixivez.R
import com.perol.asdpl.pixivez.data.entity.HistoryEntity
import com.perol.asdpl.pixivez.objects.ThemeUtil
// TODO: reuse
class HistoryAdapter :
BaseQuickAdapter<HistoryEntity, BaseViewHolder>(R.layout.view_history_item) {
override fun convert(holder: BaseViewHolder, item: HistoryEntity) {
val imageView = holder.getView<ImageView>(R.id.item_img)
Glide.with(imageView.context).load(item.thumb)
.placeholder(ColorDrawable(ThemeUtil.halftrans)).into(imageView)
holder.setText(R.id.title, item.title)
holder.setTextColor(
R.id.title,
if (item.isUser) ThemeUtil.getColorHighlight(context)
else ThemeUtil.getTextColorPrimary(context)
)
}
}
| 6 | Kotlin | 33 | 692 | d5caf81746e4f16a1af64d45490a358fd19aec1a | 2,150 | Pix-EzViewer | MIT License |
langsmith-java-core/src/test/kotlin/com/langsmith/api/services/blocking/FeedbackConfigServiceTest.kt | langchain-ai | 774,515,765 | false | {"Kotlin": 2288977, "Shell": 1314, "Dockerfile": 305} | // File generated from our OpenAPI spec by Stainless.
package com.langsmith.api.services.blocking
import com.langsmith.api.TestServerExtension
import com.langsmith.api.client.okhttp.LangSmithOkHttpClient
import com.langsmith.api.models.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(TestServerExtension::class)
class FeedbackConfigServiceTest {
@Test
fun callCreate() {
val client =
LangSmithOkHttpClient.builder()
.baseUrl(TestServerExtension.BASE_URL)
.apiKey("My API Key")
.build()
val feedbackConfigService = client.feedbackConfigs()
val feedbackConfigSchema =
feedbackConfigService.create(
FeedbackConfigCreateParams.builder()
.feedbackConfig(
FeedbackConfigCreateParams.FeedbackConfig.builder()
.type(FeedbackConfigCreateParams.FeedbackConfig.Type.CONTINUOUS)
.categories(
listOf(
FeedbackConfigCreateParams.FeedbackConfig.Category.builder()
.value(42.23)
.label("x")
.build()
)
)
.max(42.23)
.min(42.23)
.build()
)
.feedbackKey("string")
.build()
)
println(feedbackConfigSchema)
feedbackConfigSchema.validate()
}
@Test
fun callList() {
val client =
LangSmithOkHttpClient.builder()
.baseUrl(TestServerExtension.BASE_URL)
.apiKey("My API Key")
.build()
val feedbackConfigService = client.feedbackConfigs()
val feedbackConfigListResponse =
feedbackConfigService.list(FeedbackConfigListParams.builder().build())
println(feedbackConfigListResponse)
for (feedbackConfigSchema: FeedbackConfigSchema in feedbackConfigListResponse) {
feedbackConfigSchema.validate()
}
}
}
| 1 | Kotlin | 0 | 2 | 922058acd6e168f6e1db8d9e67a24850ab7e93a0 | 2,314 | langsmith-java | Apache License 2.0 |
app/src/main/java/com/imtae/localdatapreservationapp/User.kt | Im-Tae | 293,298,313 | false | null | package com.imtae.localdatapreservationapp
data class User(
val name: String,
val age: Int
) | 2 | null | 0 | 3 | 8d57c920de8bae7c52f7bf4e8013f67c9691fc7c | 101 | LocalDataPreservation | Apache License 2.0 |
app/src/main/java/com/yogeshpaliyal/keypass/importer/KeePassAccountImporter.kt | yogeshpaliyal | 334,702,754 | false | null | package com.yogeshpaliyal.keypass.importer
import android.net.Uri
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import com.opencsv.CSVReader
import com.yogeshpaliyal.common.data.AccountModel
import com.yogeshpaliyal.keypass.R
import com.yogeshpaliyal.keypass.ui.redux.actions.Action
import com.yogeshpaliyal.keypass.ui.redux.actions.ToastAction
class KeePassAccountImporter : AccountsImporter {
override fun getImporterTitle(): Int = R.string.keepass_backup
override fun getImporterDesc(): Int = R.string.keepass_backup_desc
override fun allowedMimeType(): String {
return "text/comma-separated-values"
}
@Composable
override fun readFile(file: Uri, resolve: (List<AccountModel>) -> Unit, onCompleteOrCancel: (action: Action?) -> Unit) {
val context = LocalContext.current
LaunchedEffect(key1 = file, block = {
val inputStream = context.contentResolver.openInputStream(file)
val reader = CSVReader(inputStream?.reader())
val myEntries: List<Array<String>> = reader.readAll()
val headers = myEntries[0]
val result = myEntries.drop(1).map { data ->
headers.zip(data).toMap()
}
val listOfAccounts = ArrayList<AccountModel>()
result.forEach {
listOfAccounts.add(
AccountModel(
title = it["Title"],
notes = it["Notes"],
password = it["Password"],
username = it["Username"],
site = it["URL"],
tags = it["Group"],
secret = if (it["TOTP"].isNullOrBlank()) null else it["TOTP"]
)
)
}
resolve(listOfAccounts)
onCompleteOrCancel(ToastAction(R.string.backup_restored))
})
LoadingDialog()
}
}
| 37 | null | 72 | 555 | 0fc4efcf95700bd263a5c2b44192e99f4ddea354 | 2,035 | KeyPass | MIT License |
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/presentation/staking/unbond/select/SelectUnbondViewModel.kt | novasamatech | 415,834,480 | false | null | package io.novafoundation.nova.feature_staking_impl.presentation.staking.unbond.select
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import io.novafoundation.nova.common.base.BaseViewModel
import io.novafoundation.nova.common.mixin.api.Validatable
import io.novafoundation.nova.common.resources.ResourceManager
import io.novafoundation.nova.common.validation.ValidationExecutor
import io.novafoundation.nova.common.validation.progressConsumer
import io.novafoundation.nova.feature_staking_api.domain.model.relaychain.StakingState
import io.novafoundation.nova.feature_staking_impl.R
import io.novafoundation.nova.feature_staking_impl.domain.StakingInteractor
import io.novafoundation.nova.feature_staking_impl.domain.staking.unbond.UnbondInteractor
import io.novafoundation.nova.feature_staking_impl.domain.validations.unbond.UnbondValidationPayload
import io.novafoundation.nova.feature_staking_impl.domain.validations.unbond.UnbondValidationSystem
import io.novafoundation.nova.feature_staking_impl.presentation.StakingRouter
import io.novafoundation.nova.feature_staking_impl.presentation.staking.unbond.confirm.ConfirmUnbondPayload
import io.novafoundation.nova.feature_staking_impl.presentation.staking.unbond.hints.UnbondHintsMixinFactory
import io.novafoundation.nova.feature_staking_impl.presentation.staking.unbond.unbondPayloadAutoFix
import io.novafoundation.nova.feature_staking_impl.presentation.staking.unbond.unbondValidationFailure
import io.novafoundation.nova.feature_wallet_api.domain.model.Asset
import io.novafoundation.nova.feature_wallet_api.domain.model.planksFromAmount
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.amountChooser.AmountChooserMixin
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.FeeLoaderMixin
import io.novafoundation.nova.feature_wallet_api.presentation.model.transferableAmountModelOf
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import java.math.BigDecimal
import kotlin.time.ExperimentalTime
class SelectUnbondViewModel(
private val router: StakingRouter,
private val interactor: StakingInteractor,
private val unbondInteractor: UnbondInteractor,
private val resourceManager: ResourceManager,
private val validationExecutor: ValidationExecutor,
private val validationSystem: UnbondValidationSystem,
private val feeLoaderMixin: FeeLoaderMixin.Presentation,
unbondHintsMixinFactory: UnbondHintsMixinFactory,
amountChooserMixinFactory: AmountChooserMixin.Factory
) : BaseViewModel(),
Validatable by validationExecutor,
FeeLoaderMixin by feeLoaderMixin {
private val _showNextProgress = MutableLiveData(false)
val showNextProgress: LiveData<Boolean> = _showNextProgress
private val accountStakingFlow = interactor.selectedAccountStakingStateFlow()
.filterIsInstance<StakingState.Stash>()
.shareInBackground()
private val assetFlow = accountStakingFlow
.flatMapLatest { interactor.assetFlow(it.controllerAddress) }
.shareInBackground()
val transferableFlow = assetFlow.mapLatest(::transferableAmountModelOf)
.shareInBackground()
val hintsMixin = unbondHintsMixinFactory.create(coroutineScope = this)
val amountMixin = amountChooserMixinFactory.create(
scope = this,
assetFlow = assetFlow,
balanceField = Asset::bonded,
balanceLabel = R.string.staking_main_stake_balance_staked
)
init {
listenFee()
}
fun nextClicked() {
maybeGoToNext()
}
fun backClicked() {
router.back()
}
@OptIn(ExperimentalTime::class)
private fun listenFee() {
amountMixin.backPressuredAmount
.onEach { loadFee(it) }
.launchIn(viewModelScope)
}
private fun loadFee(amount: BigDecimal) {
feeLoaderMixin.loadFee(
coroutineScope = viewModelScope,
feeConstructor = { token ->
val amountInPlanks = token.planksFromAmount(amount)
val asset = assetFlow.first()
unbondInteractor.estimateFee(accountStakingFlow.first(), asset.bondedInPlanks, amountInPlanks)
},
onRetryCancelled = ::backClicked
)
}
private fun requireFee(block: (BigDecimal) -> Unit) = feeLoaderMixin.requireFee(
block,
onError = { title, message -> showError(title, message) }
)
private fun maybeGoToNext() = requireFee { fee ->
launch {
val asset = assetFlow.first()
val payload = UnbondValidationPayload(
stash = accountStakingFlow.first(),
asset = asset,
fee = fee,
amount = amountMixin.amount.first(),
)
validationExecutor.requireValid(
validationSystem = validationSystem,
payload = payload,
validationFailureTransformer = { unbondValidationFailure(it, resourceManager) },
autoFixPayload = ::unbondPayloadAutoFix,
progressConsumer = _showNextProgress.progressConsumer()
) { correctPayload ->
_showNextProgress.value = false
openConfirm(correctPayload)
}
}
}
private fun openConfirm(validationPayload: UnbondValidationPayload) {
val confirmUnbondPayload = ConfirmUnbondPayload(
amount = validationPayload.amount,
fee = validationPayload.fee
)
router.openConfirmUnbond(confirmUnbondPayload)
}
}
| 9 | null | 8 | 9 | 67cd6fd77aae24728a27b81eb7f26ac586463aaa | 5,858 | nova-wallet-android | Apache License 2.0 |
prosessering-core/src/test/kotlin/no/nav/familie/prosessering/internal/TaskLoggRepositoryTest.kt | navikt | 301,413,863 | false | {"Kotlin": 134768} | package no.nav.familie.prosessering.internal
import no.nav.familie.prosessering.IntegrationRunnerTest
import no.nav.familie.prosessering.TaskFeil
import no.nav.familie.prosessering.domene.Task
import no.nav.familie.prosessering.domene.TaskLoggRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
internal class TaskLoggRepositoryTest : IntegrationRunnerTest() {
@Autowired
private lateinit var taskService: TaskService
@Autowired
private lateinit var taskLoggRepository: TaskLoggRepository
@Test
internal fun `skal hente metadata til task`() {
var task = taskService.save(Task("minType", "payload"))
task = taskService.kommenter(task, "kommentar på task", "", false)
task = taskService.feilet(task, TaskFeil(task, RuntimeException("Feil")), 3, 3, false)
task = taskService.ferdigstill(task)
val taskLoggMetadata = taskLoggRepository.finnTaskLoggMetadata(listOf(task.id)).single()
assertThat(taskLoggMetadata.taskId).isEqualTo(task.id)
assertThat(taskLoggMetadata.antallLogger).isEqualTo(4)
assertThat(taskLoggMetadata.sisteKommentar).isEqualTo("kommentar på task")
}
}
| 5 | Kotlin | 0 | 2 | 7fab7b47592d59829b515ac11a7d61978ee4a946 | 1,271 | familie-prosessering-backend | MIT License |
viewmodels/src/main/java/com/redvelvet/viewmodel/movie_details_seeall/AllReviewArgs.kt | RedVelvet-Team | 670,763,637 | false | null | package com.redvelvet.viewmodel.movie_details_seeall
import androidx.lifecycle.SavedStateHandle
class AllReviewArgs(savedStateHandle: SavedStateHandle) {
val id: String = savedStateHandle[ID] ?: "0"
companion object{
const val ID = "id"
}
} | 1 | Kotlin | 1 | 4 | b9b17caa25439823ae354d3262921fb5f88c73d7 | 263 | IMovie | Apache License 2.0 |
application/src/main/java/com/android/application/MainActivity.kt | Abdulrahman-AlGhamdi | 344,500,974 | false | null | package com.android.application
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.android.forceupdate.manager.ForceUpdateManager
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val forceUpdateManager = ForceUpdateManager(activity = this)
forceUpdateManager.updateApplication(
apkLink = "https://storage.evozi.com/apk/dl/16/09/04/com.spotify.music_82316170.apk",
header = null,
optional = false,
animation = null
)
}
} | 0 | Kotlin | 2 | 2 | 7274b5014000eb4c46060dd08df7039970d7702b | 679 | ForceUpdate | Apache License 2.0 |
libraries/tools/abi-comparator/src/main/kotlin/org/jetbrains/kotlin/abicmp/checkers/GenericMetadataChecker.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.abicmp.checkers
import kotlinx.metadata.KmConstructor
import kotlinx.metadata.KmFunction
import kotlinx.metadata.KmProperty
import kotlinx.metadata.KmTypeAlias
import org.jetbrains.kotlin.abicmp.reports.MetadataPropertyReport
import org.jetbrains.kotlin.abicmp.reports.NamedDiffEntry
interface GenericMetadataChecker<T> : Checker {
fun check(metadata1: T, metadata2: T, report: MetadataPropertyReport)
}
abstract class GenericMetadataPropertyChecker<T>(name: String) :
PropertyChecker<String, T>("class.metadata.$name"),
GenericMetadataChecker<T> {
override fun check(metadata1: T, metadata2: T, report: MetadataPropertyReport) {
val value1 = getProperty(metadata1)
val value2 = getProperty(metadata2)
if (!areEqual(value1, value2)) {
report.addPropertyDiff(NamedDiffEntry(name, value1, value2))
}
}
}
fun constructorMetadataPropertyChecker(name: String, propertyGetter: (KmConstructor) -> String) =
object : GenericMetadataPropertyChecker<KmConstructor>("constructor.$name") {
override fun getProperty(node: KmConstructor) = propertyGetter(node)
}
fun functionMetadataPropertyChecker(name: String, propertyGetter: (KmFunction) -> String) =
object : GenericMetadataPropertyChecker<KmFunction>("function.$name") {
override fun getProperty(node: KmFunction) = propertyGetter(node)
}
fun typeAliasMetadataPropertyChecker(name: String, propertyGetter: (KmTypeAlias) -> String) =
object : GenericMetadataPropertyChecker<KmTypeAlias>("typeAlias.$name") {
override fun getProperty(node: KmTypeAlias) = propertyGetter(node)
}
fun propertyMetadataPropertyChecker(name: String, propertyGetter: (KmProperty) -> String) =
object : GenericMetadataPropertyChecker<KmProperty>("property.$name") {
override fun getProperty(node: KmProperty) = propertyGetter(node)
} | 166 | null | 5771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,124 | kotlin | Apache License 2.0 |
src/main/kotlin/endertitan/echolib/block/INetworkBlock.kt | ender-titan1 | 708,160,119 | false | {"Kotlin": 32797} | package endertitan.echolib.block
import endertitan.echolib.resourcenetworks.ResourceNetwork
interface INetworkBlock {
fun connectToNetworks(): Array<ResourceNetwork<*>>
} | 0 | Kotlin | 0 | 1 | 14adabc99e3ce44b1089afc1a1f939d48fb083f6 | 176 | echo-lib | MIT License |
app/src/main/java/com/israis007/contactslist/ContactsAdapter.kt | israis007 | 256,557,019 | false | null | package com.israis007.contactslist
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ContactsAdapter(
private val context: Context,
private val contacts: List<Contact>,
private val layoutId: Int
): RecyclerView.Adapter<ContactsAdapter.ContactItem>() {
inner class ContactItem(private val contactView: View): RecyclerView.ViewHolder(contactView) {
fun bindItems(contact: Contact, position: Int){
val tvIndex = contactView.findViewById<TextView>(R.id.tv_index)
val ivAvatar = contactView.findViewById<ImageView>(R.id.iv_avatar)
val tvName = contactView.findViewById<TextView>(R.id.tv_name)
if (position == 0 || contacts[position - 1].index != contact.index)
tvIndex.apply {
visibility = View.VISIBLE
text = contact.index
}
else
tvIndex.visibility = View.GONE
tvName.text = contact.name
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactItem =
ContactItem(LayoutInflater.from(context).inflate(layoutId, parent, false))
override fun getItemCount(): Int = contacts.size
override fun onBindViewHolder(holder: ContactItem, position: Int) = holder.bindItems(contacts[position], position)
} | 0 | Kotlin | 0 | 0 | ce363c0d40280b1d5bcc9a2ef58393ad765bb475 | 1,525 | ContactsList | Apache License 2.0 |
app/src/main/java/org/simple/clinic/util/CsvToPdfConverter.kt | simpledotorg | 132,515,649 | false | null | package org.simple.clinic.util
import com.itextpdf.kernel.geom.PageSize
import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter
import com.itextpdf.layout.Document
import com.itextpdf.layout.element.Cell
import com.itextpdf.layout.element.Paragraph
import com.itextpdf.layout.element.Table
import com.itextpdf.layout.properties.UnitValue
import com.opencsv.CSVReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.OutputStream
import javax.inject.Inject
class CsvToPdfConverter @Inject constructor() {
fun convert(inputStream: InputStream, outputStream: OutputStream) {
val entries = readCsvFile(inputStream)
createPdfDocument(outputStream, entries)
}
private fun createPdfDocument(outputStream: OutputStream, entries: List<Array<String>>) {
val pdfDoc = PdfDocument(PdfWriter(outputStream))
val document = Document(pdfDoc, PageSize.A4.rotate())
val documentName = entries[0].joinToString()
val numberOfColumns = entries[1].size
val table = Table(UnitValue.createPercentArray(numberOfColumns), true)
.setFontSize(8f)
document.add(Paragraph(documentName))
document.add(table)
// First element is the document name, therefore it should not be part of the table
for (i in 1 until entries.size) {
// Flushing content to doc every 100 rows to keep the memory footprint low to avoid OOM
flushContentToTable(currentIndex = i, table = table)
entries[i].forEach { cellContent ->
val cell = Cell()
.setKeepTogether(true)
.add(Paragraph(cellContent))
.setMargin(0f)
table.addCell(cell)
}
}
table.complete()
document.close()
}
private fun flushContentToTable(currentIndex: Int, table: Table) {
if (currentIndex % 100 == 0) {
table.flush()
}
}
private fun readCsvFile(inputStream: InputStream): List<Array<String>> {
val reader = CSVReader(InputStreamReader(inputStream))
return reader.readAll()
}
}
| 13 | null | 73 | 236 | ff699800fbe1bea2ed0492df484777e583c53714 | 2,035 | simple-android | MIT License |
src/main/kotlin/io/framed/framework/view/SelectView.kt | Eden-06 | 138,000,306 | false | {"Kotlin": 675525, "SCSS": 21894, "HTML": 768} | package io.framed.framework.view
import de.westermann.kobserve.Property
import de.westermann.kobserve.event.EventHandler
import org.w3c.dom.HTMLSelectElement
import org.w3c.dom.events.Event
import org.w3c.dom.events.EventListener
import kotlin.dom.clear
/**
* @author lars
*/
class SelectView<T : Any>(
initValues: List<T>,
initSelected: T,
val transform: (T) -> String
) : View<HTMLSelectElement>("select") {
constructor(initValues: List<T>, property: Property<T>, transform: (T) -> String) : this(initValues, property.get(), transform) {
bind(property)
}
fun bind(property: Property<T>) {
onChange {
property.set(it);
}
property.onChange {
selected = property.get()
}
}
var values: List<T> = emptyList()
set(value) {
field = value
html.clear()
value.forEach {
html.appendChild(OptionView().also { option ->
option.text = transform(it)
option.value = it.toString()
}.html)
}
}
var index: Int
get() = html.selectedIndex
set(value) {
html.selectedIndex = value
}
var selected: T
get() = values[index]
set(value) {
index = values.indexOf(value)
}
val onChange = EventHandler<T>()
init {
this.values = initValues
this.selected = initSelected
html.addEventListener("change", object : EventListener {
override fun handleEvent(event: Event) {
onChange.emit(selected)
}
})
}
}
fun <T : Any> ViewCollection<in SelectView<*>, *>.selectView(
initValues: List<T>,
initSelected: T,
transform: (T) -> String
) = SelectView(initValues, initSelected, transform).also(this::append)
fun <T : Any> ViewCollection<in SelectView<*>, *>.selectView(
initValues: List<T>,
property: Property<T>,
transform: (T) -> String
) = SelectView(initValues, property, transform).also(this::append)
| 5 | Kotlin | 1 | 2 | 27f4a4c44d90f20f748ab779c3c184cb012a59fe | 2,138 | FRaMED-io | MIT License |
nstack-kotlin-core/src/main/java/dk/nodes/nstack/kotlin/models/Error.kt | nstack-io | 196,024,461 | false | null | package dk.nodes.nstack.kotlin.models
sealed class Error {
object UnknownError : Error()
object NetworkError : Error()
data class ApiError(val errorCode: Int) : Error()
} | 9 | null | 9 | 13 | 60732494b2cd20b58cf9ab0880aa10ae3f94e5b6 | 183 | android-sdk | MIT License |
app/src/main/java/com/noah/express_send/ui/adapter/IndexFragmentAdapter.kt | HpBoss | 362,725,551 | false | {"Gradle": 10, "Java Properties": 2, "Shell": 1, "Ignore List": 10, "Batchfile": 1, "Markdown": 1, "INI": 6, "Proguard": 8, "Kotlin": 124, "XML": 190, "Java": 11} | package com.noah.express_send.ui.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.noah.express_send.R
import com.noah.express_send.ui.adapter.io.IOrderInfo
import com.noah.internet.response.ResponseOrder
import java.util.ArrayList
/**
* @Auther: 何飘
* @Date: 2/28/21 14:36
* @Description:
*/
class IndexFragmentAdapter(
private val mContext: Context,
private val iOrderInfo: IOrderInfo
) : RecyclerView.Adapter<IndexFragmentAdapter.ViewHolder>(){
private val orderInfoList = ArrayList<ResponseOrder>()
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvBrand: TextView = view.findViewById(R.id.tv_brand)
val tvClassify: TextView = view.findViewById(R.id.tv_classify)
val tvWeight: TextView = view.findViewById(R.id.tv_weight)
val tvDetailAddress: TextView = view.findViewById(R.id.tv_address)
val tvDormitory: TextView = view.findViewById(R.id.tv_dormitorys)
val imgAvatar: ImageView = view.findViewById(R.id.cardView_avatar)
val imgMoreOption: ImageView = view.findViewById(R.id.btn_moreOption)
val tvPayIntegralNum: TextView = view.findViewById(R.id.tv_payIntegralNum)
val tvNickname: TextView = view.findViewById(R.id.tv_userName)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(
R.layout.item_order_info_indexs,
parent,
false
)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val orderInfo = orderInfoList[position]
holder.tvBrand.text = orderInfo.expressName
holder.tvClassify.text = orderInfo.typeName
holder.tvWeight.text = orderInfo.weight
holder.tvDetailAddress.text = orderInfo.addressName
holder.tvDormitory.text = orderInfo.dormitory
holder.tvNickname.text = orderInfo.nickName
holder.tvPayIntegralNum.text = mContext.getString(R.string.payIntegralNum, orderInfo.payIntegralNum)
Glide.with(mContext).load(orderInfo.avatarUrl)
.apply(RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE))
.preload(50,50)
Glide.with(mContext)
.load(orderInfo.avatarUrl).placeholder(R.drawable.ic_place_holder)
.apply(RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE))
.into(holder.imgAvatar)
holder.imgMoreOption.setOnClickListener {
iOrderInfo.setOnClickItemMore(position, orderInfo.id)
}
}
override fun getItemCount(): Int {
return orderInfoList.size
}
fun setAdapter(orderList: ArrayList<ResponseOrder>) {
orderInfoList.clear()
orderInfoList.addAll(orderList)
notifyDataSetChanged()
}
fun clearAdapterList() {
orderInfoList.clear()
notifyDataSetChanged()
}
fun removeAt(position: Int) {
orderInfoList.removeAt(position)
notifyItemRemoved(position)
}
fun getOrderPhoneNum(position: Int): String{
return orderInfoList[position].phoneNum
}
} | 0 | Kotlin | 0 | 4 | 7c24efba30f5e7864762623af9e794e5245759a7 | 3,518 | ExpressSend | Apache License 2.0 |
kotest-assertions/kotest-assertions-shared/src/jvmTest/kotlin/com/sksamuel/kotest/data/SuspendTest.kt | kotest | 47,071,082 | false | null | package com.sksamuel.kotest.data
import io.kotest.core.spec.style.FunSpec
import io.kotest.data.forAll
import io.kotest.data.row
import kotlinx.coroutines.delay
class SuspendTest : FunSpec({
test("forAll1 should support suspend functions") {
forAll(
row(1)
) {
delay(10)
}
}
test("forAll2 should support suspend functions") {
forAll(
row(1, 2)
) { _, _ ->
delay(10)
}
}
test("forAll3 should support suspend functions") {
forAll(
row(1, 2, 3)
) { _, _, _ ->
delay(10)
}
}
test("forAll4 should support suspend functions") {
forAll(
row(1, 2, 3, 4)
) { _, _, _, _ ->
delay(10)
}
}
test("forAll5 should support suspend functions") {
forAll(
row(1, 2, 3, 4, 5)
) { _, _, _, _, _ ->
delay(10)
}
}
test("forAll6 should support suspend functions") {
forAll(
row(1, 2, 3, 4, 5, 6)
) { _, _, _, _, _, _ ->
delay(10)
}
}
test("forAll7 should support suspend functions") {
forAll(
row(1, 2, 3, 4, 5, 6, 7)
) { _, _, _, _, _, _, _ ->
delay(10)
}
}
})
| 160 | null | 648 | 4,435 | 2ce83d0f79e189c90e2d7bb3d16bd4f75dec9c2f | 1,242 | kotest | Apache License 2.0 |
onixlabs-corda-bnms-workflow/src/main/kotlin/io/onixlabs/corda/bnms/workflow/relationship/IssueRelationshipFlowHandler.kt | onix-labs | 281,494,633 | false | null | /*
* Copyright 2020-2021 ONIXLabs
*
* 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 io.onixlabs.corda.bnms.workflow.relationship
import co.paralleluniverse.fibers.Suspendable
import io.onixlabs.corda.bnms.contract.relationship.Relationship
import io.onixlabs.corda.bnms.workflow.checkMembershipsAndAttestations
import io.onixlabs.corda.core.workflow.currentStep
import io.onixlabs.corda.identityframework.workflow.FINALIZING
import io.onixlabs.corda.identityframework.workflow.SIGNING
import net.corda.core.flows.*
import net.corda.core.node.StatesToRecord
import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.ProgressTracker
import net.corda.core.utilities.ProgressTracker.Step
import net.corda.core.utilities.unwrap
class AmendRelationshipFlowHandler(
private val session: FlowSession,
override val progressTracker: ProgressTracker = tracker()
) : FlowLogic<SignedTransaction>() {
companion object {
@JvmStatic
fun tracker() = ProgressTracker(RECEIVING, SIGNING, FINALIZING)
private object RECEIVING : Step("Receiving check membership instruction.")
}
@Suspendable
override fun call(): SignedTransaction {
currentStep(RECEIVING)
val checkMembership = session.receive<Boolean>().unwrap { it }
currentStep(SIGNING)
val transaction = subFlow(object : SignTransactionFlow(session) {
override fun checkTransaction(stx: SignedTransaction) {
if (checkMembership) {
val relationship = stx.tx.outputsOfType<Relationship>().singleOrNull()
?: throw FlowException("Failed to obtain a relationship from the transaction.")
checkMembershipsAndAttestations(relationship)
}
}
})
currentStep(FINALIZING)
return subFlow(ReceiveFinalityFlow(session, transaction.id, StatesToRecord.ONLY_RELEVANT))
}
@InitiatedBy(AmendRelationshipFlow.Initiator::class)
private class Handler(private val session: FlowSession) : FlowLogic<SignedTransaction>() {
private companion object {
object OBSERVING : Step("Observing relationship amendment.") {
override fun childProgressTracker() = tracker()
}
}
override val progressTracker = ProgressTracker(OBSERVING)
@Suspendable
override fun call(): SignedTransaction {
currentStep(OBSERVING)
return subFlow(AmendRelationshipFlowHandler(session, OBSERVING.childProgressTracker()))
}
}
}
| 1 | Kotlin | 0 | 0 | 1f9e1fd0db0a83a782aefca78afa9940f26f0a64 | 3,113 | onixlabs-corda-bnms | Apache License 2.0 |
demo/src/main/java/foundation/algorand/demo/settings/AccountDialogFragment.kt | algorandfoundation | 790,646,087 | false | {"Kotlin": 48620, "Java": 574} | package foundation.algorand.demo.settings
import android.app.Dialog
import android.os.Bundle
import android.view.*
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.algorand.algosdk.account.Account
import foundation.algorand.demo.WalletViewModel
import foundation.algorand.demo.databinding.FragmentAccountDialogBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/** A simple [DialogFragment] subclass. */
class AccountDialogFragment(
private val account: Account,
private val rekey: Account,
private val selected: Account
) : DialogFragment() {
companion object {
const val TAG = "AccountDialogFragment"
}
private val wallet: WalletViewModel by activityViewModels()
private lateinit var binding: FragmentAccountDialogBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentAccountDialogBinding.inflate(inflater, container, false)
binding.account = account
binding.rekey = rekey
binding.selected = selected
binding.balance = "loading"
wallet.selected.observe(viewLifecycleOwner) { binding.selected = it }
return binding.root
}
override fun onResume() {
lifecycleScope.launch {
binding.balance =
wallet.algod.AccountInformation(account.address)
.execute()
.body()
.amount
.toString()
if (binding.balance == "0") {
delay(5000)
binding.balance =
wallet.algod.AccountInformation(account.address)
.execute()
.body()
.amount
.toString()
}
}
super.onResume()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
return dialog
}
}
| 1 | Kotlin | 2 | 4 | 0faaf59900e517433dff8c9c1d7bb8e7d83a3ebd | 2,316 | liquid-auth-android | Apache License 2.0 |
KotlinToSwift/src/main/kotlin/fr/jhelp/kotlinToSwift/lineParser/ClosureLambdaLineParser.kt | jhelpgg | 600,408,546 | false | null | package fr.jhelp.kotlinToSwift.lineParser
import java.util.regex.Pattern
private val PATTERN_CLOSURE_LAMBDA = Pattern.compile("(\\{[^-]+)->")
private val PATTERN_WEAK_SELF = Pattern.compile("@WeakSelf\\(\"(.*)\"\\)\\s*val\\s+sSelf\\s*=\\s*self")
private val PATTERN_WEAK_SELF_PARAMETER = Pattern.compile("\\{([^-{]+)->\\s+@WeakSelf\\(\"(.*)\"\\)\\s*val\\s+sSelf\\s*=\\s*self")
private const val GROUP_CLOSURE_LAMBDA_DECLARATION = 1
private const val GROUP_CLOSURE_LAMBDA_RETURN_VALUE = 2
private const val GROUP_CLOSURE_LAMBDA_ONLY_RETURN_VALUE = 1
private const val WEAK_SELF = " [weak self] "
private const val GUARD_ELSE_HEADER = "\nguard let sSelf = self else { return "
class ClosureLambdaLineParser : LineParser
{
override fun parse(trimLine: String): String
{
val replacement = StringBuilder(trimLine)
var lineToParse : String
var someReplacementHappen = false
var loopReplacement : Boolean
do
{
loopReplacement = false
lineToParse= replacement.toString()
replacement.clear()
var matcher = PATTERN_WEAK_SELF_PARAMETER.matcher(lineToParse)
if (matcher.find())
{
replacement.append(lineToParse.substring(0, matcher.start()))
replacement.append("{")
replacement.append(WEAK_SELF)
replacement.append(matcher.group(GROUP_CLOSURE_LAMBDA_DECLARATION))
replacement.append(" in ")
replacement.append(GUARD_ELSE_HEADER)
replacement.append(matcher.group(GROUP_CLOSURE_LAMBDA_RETURN_VALUE)
.replace("\\\"", "\"")
.replace("\\\\", "\\")
.replace("\\n", "\n")
.replace("\\t", "\t"))
replacement.append(" }\n")
replacement.append(lineToParse.substring(matcher.end()).trim())
someReplacementHappen = true
loopReplacement = true
continue
}
matcher = PATTERN_WEAK_SELF.matcher(lineToParse)
if(matcher.find())
{
replacement.append(lineToParse.substring(0, matcher.start()))
replacement.append(WEAK_SELF)
replacement.append(" in ")
replacement.append(GUARD_ELSE_HEADER)
replacement.append(matcher.group(GROUP_CLOSURE_LAMBDA_ONLY_RETURN_VALUE)
.replace("\\\"", "\"")
.replace("\\\\", "\\")
.replace("\\n", "\n")
.replace("\\t", "\t"))
replacement.append(" }\n")
replacement.append(lineToParse.substring(matcher.end()).trim())
someReplacementHappen = true
loopReplacement = true
continue
}
matcher = PATTERN_CLOSURE_LAMBDA.matcher(lineToParse)
if (matcher.find())
{
if (trimLine.endsWith("->"))
{
return FORCE_LINE_CONTINUE
}
replacement.append(lineToParse.substring(0, matcher.start()))
replacement.append(matcher.group(GROUP_CLOSURE_LAMBDA_DECLARATION).trim())
replacement.append(" in ")
replacement.append(lineToParse.substring(matcher.end()))
someReplacementHappen = true
loopReplacement = true
continue
}
} while (loopReplacement)
if(someReplacementHappen) {
return lineToParse
}
return ""
}
} | 0 | Kotlin | 0 | 0 | 6ab79ff8f826b8c6fbf059b4ca68b9ec1da965e8 | 3,841 | Kotlwift | Apache License 2.0 |
src/nl/hannahsten/texifyidea/reference/CommandDefinitionReference.kt | sizmailov | 158,587,819 | false | null | package nl.hannahsten.texifyidea.reference
import com.intellij.psi.*
import com.intellij.util.containers.toArray
import nl.hannahsten.texifyidea.index.LatexDefinitionIndex
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.util.Magic
import nl.hannahsten.texifyidea.util.forcedFirstRequiredParameterAsCommand
import nl.hannahsten.texifyidea.util.projectSearchScope
/**
* @author Abby Berkers
*/
class CommandDefinitionReference(element: LatexCommands) : PsiReferenceBase<LatexCommands>(element), PsiPolyVariantReference {
init {
rangeInElement = ElementManipulators.getValueTextRange(element)
}
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
val project = element.project
return LatexDefinitionIndex.getCommandsByNames(Magic.Command.commandDefinitions, project, project.projectSearchScope)
.filter { it.forcedFirstRequiredParameterAsCommand()?.name == element.commandToken.text }
.map { PsiElementResolveResult(it.commandToken) }
.toArray(emptyArray())
}
override fun resolve(): PsiElement? {
val resolveResults = multiResolve(false)
return if (resolveResults.size == 1) resolveResults[0].element else null
}
} | 1 | null | 1 | 1 | ded3956f4ada07110f3acca07c684b97ae4d6910 | 1,287 | TeXiFy-IDEA | MIT License |
app/src/main/java/com/xwq/companyvxwhelper/permission/PermissionFactory.kt | aidenpierce2 | 421,354,234 | false | null | package com.xwq.companyvxwhelper.permission
import com.xwq.companyvxwhelper.base.Enum.PermissionArray
import com.xwq.companyvxwhelper.permission.Base.BasePermission
class PermissionFactory {
companion object {
var instance : PermissionFactory = PermissionFactory()
}
fun getTargetPermissionGroup(permissionName : PermissionArray) : BasePermission {
when (permissionName) {
PermissionArray.SDCARD -> {
return StoragePermission()
}
PermissionArray.MESSAGE -> {
return SmsPermission()
}
PermissionArray.LOCATION -> {
return LocationPermission()
}else -> {
return DefaultPermission()
}
}
}
fun getPermissionName (requestCode : Int) : PermissionArray {
when (requestCode) {
StoragePermission.requestCode -> {
return PermissionArray.SDCARD
}
SmsPermission.requestCode -> {
return PermissionArray.MESSAGE
}
LocationPermission.requestCode -> {
return PermissionArray.LOCATION
}else -> {
return PermissionArray.DEFAULT
}
}
}
} | 0 | Kotlin | 0 | 0 | f3dea6373b9a48e9fbbd69dba8a27da10d6569b3 | 1,283 | companyvxwhelper | MIT License |
app/src/main/java/com/jesen/cod/gitappkotlin/utils/dateFormatterUtil.kt | Jesen0823 | 343,987,158 | false | {"Java Properties": 3, "Gradle": 7, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 2, "Proguard": 4, "Kotlin": 125, "INI": 5, "XML": 69, "Java": 8, "JSON": 3} | package com.jesen.cod.gitappkotlin.utils
import java.text.SimpleDateFormat
import java.util.*
import java.util.TimeZone.*
val dateFormatter by lazy {
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.CHINA)
.apply {
timeZone = getTimeZone("GMT")
}
}
val outputDateFormatter by lazy {
SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
}
fun Date.format(pattern: String): String = SimpleDateFormat(pattern, Locale.CHINA).format(this)
fun timeToDate(time: String) = dateFormatter.parse(time)
fun Date.view(): String {
val now = System.currentTimeMillis()
val seconds = (now - this.time) / 1000
val minutes = seconds / 60
return if (minutes >= 60) {
val hours = minutes / 60
if (hours in 24..47) {
"Yesterday"
} else if (hours >= 48) {
outputDateFormatter.format(this)
} else {
"$hours hours ago"
}
} else if (minutes < 1) {
"$seconds seconds ago"
} else {
"$minutes minutes ago"
}
} | 2 | Kotlin | 0 | 0 | 69f9b7ec07bc70545feff5788b02a29373fe66cf | 1,044 | GitAppKotlin | Apache License 2.0 |
army-knife-gms/src/main/java/com/eaglesakura/armyknife/android/gms/LiveDocumentSnapshotImpl.kt | eaglesakura | 140,512,537 | false | {"Kotlin": 442196, "Ruby": 2418, "Dockerfile": 2227, "Java": 678} | package com.eaglesakura.armyknife.android.gms
import androidx.lifecycle.LiveData
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.EventListener
import com.google.firebase.firestore.ListenerRegistration
internal class LiveDocumentSnapshotImpl(
private val ref: DocumentReference
) : LiveData<DocumentSnapshot>() {
init {
ref.get().addOnCompleteListener {
value = it.result
}
}
private var register: ListenerRegistration? = null
override fun onActive() {
super.onActive()
register = ref.addSnapshotListener(listener)
}
override fun onInactive() {
register?.remove()
register = null
super.onInactive()
}
private val listener = EventListener<DocumentSnapshot> { snapshot, _ ->
if (snapshot != null) {
value = snapshot
}
}
}
/**
* Convert live data.
* e.g.)
* val doc = ...
* doc.toLiveData().observe { snapshot ->
* if(snapshot != null) {
* // do something
* }
* }
*/
fun DocumentReference.toLiveData(): LiveData<DocumentSnapshot> = LiveDocumentSnapshotImpl(this) | 3 | Kotlin | 0 | 0 | 6be9a21c69e9f01654e4586615124363d82908a9 | 1,216 | army-knife | MIT License |
src/jsMain/kotlin/books.kt | sleclercq | 324,861,119 | false | {"CSS": 3924063, "Kotlin": 3909, "HTML": 212} | import dev.fritz2.binding.RootStore
import dev.fritz2.dom.html.RenderContext
import dev.fritz2.dom.html.Table
fun RenderContext.books(books: List<Book>): Table {
val booksStore = object : RootStore<List<Book>>(books) {
var count = 0
val addItem = handle { list ->
count++
list + Book(
"yet another book title no. $count",
"Some Author",
"978-3-16-148410-${count}")
}
val deleteItem = handle<Book> { list, current ->
list.minus(current)
}
}
return table("books") {
thead {
tr {
th { +"Title" }
th { +"Author" }
th { +"Actions" }
}
}
booksStore.data.renderEach { b -> book(b, booksStore.deleteItem) }
button("button") {
+"add an item"
clicks handledBy booksStore.addItem
}
}
}
| 0 | CSS | 0 | 0 | d5ca01be3d41c35f8cfaef3e17b1e69469aef4c4 | 960 | labibli | MIT License |
src/test/kotlin/com/londogard/nlp/TokenizerTests.kt | londogard | 324,636,955 | false | null | package com.londogard.nlp
import ai.djl.huggingface.tokenizers.HuggingFaceTokenizer
import com.londogard.nlp.tokenizer.*
import com.londogard.nlp.utils.LanguageSupport
import org.amshove.kluent.shouldBeEqualTo
import kotlin.test.Test
class TokenizerTests {
@Test
fun testCharTokenizer() {
val tokenizer = CharTokenizer()
tokenizer.split("abc") shouldBeEqualTo listOf("a", "b", "c")
tokenizer.split("a bc") shouldBeEqualTo listOf("a", " ", "b", "c")
}
@Test
fun testSimpleTokenizer() {
val tokenizer = SimpleTokenizer()
tokenizer.split("abc") shouldBeEqualTo listOf("abc")
tokenizer.split("a bc") shouldBeEqualTo listOf("a", "bc")
tokenizer.split("and, some") shouldBeEqualTo listOf("and", ",", "some")
}
@Test
fun testSentencePieceTokenizer() {
val tokenizer = SentencePieceTokenizer.fromLanguageSupportAndSizeOrNull(LanguageSupport.sv, VocabSize.v1000)
tokenizer?.split("hej där borta?") shouldBeEqualTo listOf("▁h", "e", "j", "▁där", "▁b", "or", "ta", "?")
}
@Test
fun testHuggingFaceTokenizer() {
val tokenizer = HuggingFaceTokenizerWrapper(HuggingFaceTokenizer.newInstance("bert-base-uncased"))
tokenizer.split("Hello over there!") shouldBeEqualTo listOf("[CLS]", "hello", "over", "there", "!", "[SEP]")
}
} | 15 | Kotlin | 3 | 55 | 6e5692575b6b0be69f4fe06b9118d6d0eb8befe3 | 1,356 | londogard-nlp-toolkit | Apache License 2.0 |
app/src/main/java/com/MovieDb/app/core/utils/FilterUtils.kt | jeremy02 | 505,357,747 | false | {"Java": 221019, "Kotlin": 149653} | package com.MovieDb.app.core.utils
import androidx.sqlite.db.SimpleSQLiteQuery
object FilterUtils {
@JvmStatic
fun getFilteredFavoriteQuery(filter: FilterFavorite): SimpleSQLiteQuery {
val simpleQuery = StringBuilder().append("SELECT * FROM favoriteEntities")
if (!filter.isShowAllMediaType) {
simpleQuery.append(" WHERE type = ")
if (filter.isShowMovieOnly) simpleQuery.append("'" + Constants.MEDIA_TYPE_MOVIE + "'") else if (filter.isShowTVOnly) simpleQuery.append(
"'" + Constants.MEDIA_TYPE_TV + "'"
)
}
simpleQuery.append(" ORDER BY ")
if (filter.isSortedByTitle) simpleQuery.append("title ASC") else if (filter.isSortedByRating) simpleQuery.append(
"scoreAverage DESC"
) else if (filter.isSortedByReleaseDate) simpleQuery.append("startDate DESC")
return SimpleSQLiteQuery(simpleQuery.toString())
}
} | 1 | null | 1 | 1 | c09b98754b76b94fe69167a4a6569e4b204425e1 | 939 | MovieDb | MIT License |
qchatkit/src/main/java/com/netease/yunxin/kit/qchatkit/repo/model/QChatMessageUpdateEventInfo.kt | shine2008 | 739,441,093 | true | {"Java Properties": 2, "Gradle Kotlin DSL": 5, "Shell": 1, "Markdown": 1, "Batchfile": 1, "INI": 2, "Proguard": 3, "Kotlin": 52, "Java": 206} | /*
* Copyright (c) 2022 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be
* found in the LICENSE file.
*/
package com.netease.yunxin.kit.qchatkit.repo.model
class QChatMessageRevokeEventInfo(
val msgUpdateInfo: QChatMsgUpdateInfoItem?,
val message: QChatMessageInfo?
) {
override fun toString(): String {
return "QChatMessageRevokeEventInfo(msgUpdateInfo=$msgUpdateInfo, message=$message)"
}
}
| 0 | Java | 0 | 0 | 9058d04b2d04d8d2ffad9fdda4d0d377ab90e50b | 476 | qchat-uikit-android | MIT License |
src/main/java/dev/sora/relay/game/GameSession.kt | OIMeowIO | 592,181,303 | true | {"Batchfile": 1, "Shell": 1, "Markdown": 2, "INI": 2, "Kotlin": 100, "Java": 71} | package dev.sora.relay.game
import com.google.gson.JsonParser
import com.nukkitx.protocol.bedrock.BedrockPacket
import com.nukkitx.protocol.bedrock.data.*
import com.nukkitx.protocol.bedrock.packet.*
import dev.sora.relay.RakNetRelaySession
import dev.sora.relay.RakNetRelaySessionListener
import dev.sora.relay.cheat.BasicThing.Companion.chat
import dev.sora.relay.cheat.command.CommandManager
import dev.sora.relay.cheat.module.ModuleManager
import dev.sora.relay.cheat.module.impl.combat.ModuleAntiBot.chat
import dev.sora.relay.cheat.module.impl.misc.ModuleChatBypass
import dev.sora.relay.game.entity.EntityPlayerSP
import dev.sora.relay.game.event.EventManager
import dev.sora.relay.game.event.EventPacketInbound
import dev.sora.relay.game.event.EventPacketOutbound
import dev.sora.relay.game.event.EventTick
import dev.sora.relay.game.utils.TimerUtil
import dev.sora.relay.game.utils.movement.MovementUtils
import dev.sora.relay.game.world.WorldClient
import dev.sora.relay.utils.base64Decode
import java.util.*
class GameSession : RakNetRelaySessionListener.PacketListener {
val thePlayer = EntityPlayerSP()
val theWorld = WorldClient(this)
lateinit var moduleManager: ModuleManager
val eventManager = EventManager()
var cnMode = true
lateinit var netSession: RakNetRelaySession
private val hookedTimer: TimerUtil = TimerUtil()
var hooked = false
var xuid = ""
var identity = UUID.randomUUID().toString()
var displayName = "Player"
val netSessionInitialized: Boolean
get() = this::netSession.isInitialized
override fun onPacketInbound(packet: BedrockPacket): Boolean {
val event = EventPacketInbound(this, packet)
eventManager.emit(event)
if (event.isCanceled()) {
return false
}
if (packet is StartGamePacket) {
if(cnMode) {
event.cancel()
packet.playerMovementSettings = SyncedPlayerMovementSettings().apply {
movementMode = AuthoritativeMovementMode.SERVER
rewindHistorySize = 0
isServerAuthoritativeBlockBreaking = true
}
packet.authoritativeMovementMode = AuthoritativeMovementMode.SERVER
println("Hooked$packet")
hookedTimer.reset()
netSession.inboundPacket(packet)
return false
}
thePlayer.entityId = packet.runtimeEntityId
theWorld.entityMap.clear()
} else if (packet is RespawnPacket) {
thePlayer.entityId = packet.runtimeEntityId
}
if (hookedTimer.delay(15000f) && !hooked) {
if (MovementUtils.isMoving(this)) netSession.inboundPacket(TextPacket().apply {
type = TextPacket.Type.RAW
isNeedsTranslation = false
message = "[§9§lProtoHax§r] Hooked StartGamePacket, Welcome!"
xuid = ""
sourceName = ""
})
hooked = true
}
thePlayer.onPacket(packet)
theWorld.onPacket(packet)
return true
}
override fun onPacketOutbound(packet: BedrockPacket): Boolean {
val event = EventPacketOutbound(this, packet)
eventManager.emit(event)
if (event.isCanceled()) {
return false
}
if (packet is LoginPacket) {
val body = JsonParser.parseString(packet.chainData.toString()).asJsonObject.getAsJsonArray("chain")
for (chain in body) {
val chainBody =
JsonParser.parseString(base64Decode(chain.asString.split(".")[1]).toString(Charsets.UTF_8)).asJsonObject
if (chainBody.has("extraData")) {
val xData = chainBody.getAsJsonObject("extraData")
xuid = xData.get("XUID").asString
identity = xData.get("identity").asString
displayName = xData.get("displayName").asString
}
}
} else if (packet is PlayerAuthInputPacket) {
if(cnMode) {
if (!moduleManager.getModuleByName("FreeCam")!!.state) {
netSession.outboundPacket(MovePlayerPacket().apply {
runtimeEntityId = thePlayer.entityId
position = packet.position
rotation = packet.rotation
mode = MovePlayerPacket.Mode.NORMAL
isOnGround = (thePlayer.motionY == 0.0)
ridingRuntimeEntityId = 0
entityType = 0
tick = packet.tick
})
}
}
/*if(packet.playerActions.isNotEmpty())chat(this,"Actions: "+packet.playerActions)
for (playerAction in packet.playerActions) {
netSession.outboundPacket(PlayerActionPacket().apply {
runtimeEntityId=thePlayer.entityId
action=playerAction.action
blockPosition=playerAction.blockPosition
})
}*/
}
if(packet !is MovePlayerPacket && cnMode) thePlayer.handleClientPacket(packet, this)
return true
}
fun onTick() {
eventManager.emit(EventTick(this))
}
fun sendPacket(packet: BedrockPacket) {
val event = EventPacketOutbound(this, packet)
eventManager.emit(event)
if (event.isCanceled()) {
return
}
/*val chatBypass = moduleManager.getModuleByName("ChatBypass") as ModuleChatBypass
if(event.packet is TextPacket && chatBypass.state){
event.packet.message=chatBypass.getStr(event.packet.message)
}*/
netSession.outboundPacket(packet)
}
fun sendPacketToClient(packet: BedrockPacket) {
val event = EventPacketInbound(this, packet)
eventManager.emit(event)
if (event.isCanceled()) {
return
}
netSession.outboundPacket(packet)
}
}
| 0 | Java | 0 | 1 | 1b302e622be69ea7f7a1e5ee4bae82f34c8c63b9 | 6,131 | ProtoHax | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.