path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01-Estructurada/src/main/kotlin/Funciones.kt | joseluisgs | 509,140,631 | false | {"Kotlin": 193489, "Java": 3788} | fun main() {
val valor = miFuncion2()
println(valor)
// Parametros con valores por defecto
println(parametros("Pepe"))
println(parametros("Pepe", 23))
println(parametros("Pepe", 23, true))
// Parametros nombrados
println(parametros(edad = 25, repetidor = false, nombre = "Pedro"))
// Numero variable de parámetros
println(calificacion("Pepe", 7.0))
println(calificacion("Pepe", 7.0, 8.5))
println(calificacion("Pepe", 7.0, 8.5, 9.0))
var notas = DoubleArray(10)
println(calificacion("Pepe", *notas))
val (a, b) = notas
}
fun miFuncion(): Int {
return 1
}
fun miFuncion2() = "Esto es una expression Body"
// Parametros
/*fun parametros(nombre: String, edad:Int): String {
return "$nombre $edad"
}
// Parametros
fun parametros(nombre: String, edad:Int, repetidor: Boolean): String {
return "$nombre $edad $repetidor";
}*/
// Parametros con valores por defecto
fun parametros(nombre: String, edad: Int = 18, repetidor: Boolean = false): String {
return "$nombre $edad $repetidor"
}
// Numero indeterminado de parametros
fun calificacion(nombre: String, vararg notas: Double): String {
// for(i in notas)
return "$nombre $notas"
}
| 0 | Kotlin | 3 | 20 | 47a6bbb5cbd088eb0b01184338ece4aa8cbffdec | 1,220 | Kotlin-Bootcamp-DAMnificados-2022 | MIT License |
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/http/ServerWebSocket.kt | yeikel | 471,845,103 | true | {"Kotlin": 1432807, "Java": 28771} | /*
* Copyright 2019 Red Hat, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.kotlin.core.http
import io.vertx.core.Future
import io.vertx.core.buffer.Buffer
import io.vertx.core.http.ServerWebSocket
import io.vertx.core.http.WebSocketFrame
import io.vertx.core.streams.WriteStream
import io.vertx.kotlin.coroutines.awaitResult
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.write]
*
* @param data
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use write returning a future and chain with await()", replaceWith = ReplaceWith("write(data).await()"))
suspend fun ServerWebSocket.writeAwait(data: Buffer): Unit {
return awaitResult {
this.write(data, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.end]
*
* @param data
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use end returning a future and chain with await()", replaceWith = ReplaceWith("end(data).await()"))
suspend fun ServerWebSocket.endAwait(data: Buffer): Unit {
return awaitResult {
this.end(data, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.pipeTo]
*
* @param dst the destination write stream
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use pipeTo returning a future and chain with await()", replaceWith = ReplaceWith("pipeTo(dst).await()"))
suspend fun ServerWebSocket.pipeToAwait(dst: WriteStream<Buffer>): Unit {
return awaitResult {
this.pipeTo(dst, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.writePing]
*
* @param data the data to write, may be at most 125 bytes
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use writePing returning a future and chain with await()", replaceWith = ReplaceWith("writePing(data).await()"))
suspend fun ServerWebSocket.writePingAwait(data: Buffer): Unit {
return awaitResult {
this.writePing(data, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.writePong]
*
* @param data the data to write, may be at most 125 bytes
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use writePong returning a future and chain with await()", replaceWith = ReplaceWith("writePong(data).await()"))
suspend fun ServerWebSocket.writePongAwait(data: Buffer): Unit {
return awaitResult {
this.writePong(data, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.end]
*
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use end returning a future and chain with await()", replaceWith = ReplaceWith("end().await()"))
suspend fun ServerWebSocket.endAwait(): Unit {
return awaitResult {
this.end(io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.close]
*
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use close returning a future and chain with await()", replaceWith = ReplaceWith("close().await()"))
suspend fun ServerWebSocket.closeAwait(): Unit {
return awaitResult {
this.close(io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.close]
*
* @param statusCode
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use close returning a future and chain with await()", replaceWith = ReplaceWith("close(statusCode).await()"))
suspend fun ServerWebSocket.closeAwait(statusCode: Short): Unit {
return awaitResult {
this.close(statusCode, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.close]
*
* @param statusCode
* @param reason
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use close returning a future and chain with await()", replaceWith = ReplaceWith("close(statusCode, reason).await()"))
suspend fun ServerWebSocket.closeAwait(statusCode: Short, reason: String?): Unit {
return awaitResult {
this.close(statusCode, reason, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
@Deprecated(message = "Instead use writeFrame returning a future and chain with await()", replaceWith = ReplaceWith("writeFrame(frame).await()"))
suspend fun ServerWebSocket.writeFrameAwait(frame: WebSocketFrame): Unit {
return awaitResult {
this.writeFrame(frame, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
@Deprecated(message = "Instead use writeFinalTextFrame returning a future and chain with await()", replaceWith = ReplaceWith("writeFinalTextFrame(text).await()"))
suspend fun ServerWebSocket.writeFinalTextFrameAwait(text: String): Unit {
return awaitResult {
this.writeFinalTextFrame(text, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
@Deprecated(message = "Instead use writeFinalBinaryFrame returning a future and chain with await()", replaceWith = ReplaceWith("writeFinalBinaryFrame(data).await()"))
suspend fun ServerWebSocket.writeFinalBinaryFrameAwait(data: Buffer): Unit {
return awaitResult {
this.writeFinalBinaryFrame(data, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
@Deprecated(message = "Instead use writeBinaryMessage returning a future and chain with await()", replaceWith = ReplaceWith("writeBinaryMessage(data).await()"))
suspend fun ServerWebSocket.writeBinaryMessageAwait(data: Buffer): Unit {
return awaitResult {
this.writeBinaryMessage(data, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
@Deprecated(message = "Instead use writeTextMessage returning a future and chain with await()", replaceWith = ReplaceWith("writeTextMessage(text).await()"))
suspend fun ServerWebSocket.writeTextMessageAwait(text: String): Unit {
return awaitResult {
this.writeTextMessage(text, io.vertx.core.Handler { ar -> it.handle(ar.mapEmpty()) })
}
}
/**
* Suspending version of method [io.vertx.core.http.ServerWebSocket.setHandshake]
*
* @param future the future to complete with
* @return [Int]
*
* NOTE: This function has been automatically generated from [io.vertx.core.http.ServerWebSocket] using Vert.x codegen.
*/
@Deprecated(message = "Instead use setHandshake returning a future and chain with await()", replaceWith = ReplaceWith("setHandshake(future).await()"))
suspend fun ServerWebSocket.setHandshakeAwait(future: Future<Int>): Int {
return awaitResult {
this.setHandshake(future, it)
}
}
| 0 | Kotlin | 0 | 0 | f1510445d972145978a21e4ca44c37877428b07e | 8,064 | vertx-lang-kotlin | Apache License 2.0 |
camerax_lib/src/main/java/com/kiylx/camerax_lib/main/manager/model/CaptureResultListener.kt | Knightwood | 517,621,489 | false | {"Kotlin": 216577, "Java": 15340} | package com.kiylx.camerax_lib.main.manager.model;
import com.kiylx.camerax_lib.main.store.SaveFileData
/**
* 拍照,视频后的回调,fragment实现它,把结果传给外界
*/
interface CaptureResultListener {
//Called when the video record is finished and saved
fun onVideoRecorded(saveFileData: SaveFileData?)
//called when the photo is taken and saved
fun onPhotoTaken(saveFileData: SaveFileData?)
}
| 0 | Kotlin | 3 | 19 | e5fcc31979ba3b6c6370f8ba9341e7630c0f447f | 434 | CameraX-mlkit-FaceDetection | Apache License 2.0 |
src/main/kotlin/me/steven/indrev/networks/NetworkState.kt | dmkenza | 570,693,908 | true | {"Kotlin": 991867, "Java": 56861} | package me.steven.indrev.networks
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap
import it.unimi.dsi.fastutil.longs.LongOpenHashSet
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet
import net.minecraft.nbt.NbtCompound
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.math.BlockPos
import net.minecraft.world.PersistentState
open class NetworkState<T : Network>(val type: Network.Type<T>, val world: ServerWorld) : PersistentState() {
val networksByPos = Long2ObjectOpenHashMap<T>()
val networks = ObjectOpenHashSet<Network>()
private val queuedUpdates = LongOpenHashSet()
val updatedPositions = LongOpenHashSet()
fun queueUpdate(pos: Long, force: Boolean = false) {
if (!networksByPos.contains(pos) || force) queuedUpdates.add(pos)
}
operator fun set(pos: BlockPos, network: Network) {
networksByPos[pos.asLong()] = network as T
}
open fun remove(network: Network) {
network.pipes.forEach { pos ->
networksByPos.remove(pos.asLong())
onRemoved(pos)
}
network.containers.forEach { (pos, _) ->
networksByPos.remove(pos.asLong())
onRemoved(pos)
}
networks.remove(network)
}
open fun add(network: Network) {
this.networks.add(network)
}
open fun tick(world: ServerWorld) {
// this is to avoid a weird CME I cannot reproduce
// something is queueing an update while going through the other ones (nothing is ever removed from it until the .clear())
// so I copy and clear the original before iterating so if anything is added while iterating, it will be processed in the next tick.
// TODO find this CME and fix it :)
val copy = LongOpenHashSet(queuedUpdates)
queuedUpdates.clear()
copy.forEach { pos ->
if (!updatedPositions.contains(pos)) {
val network = type.factory.deepScan(type, world, BlockPos.fromLong(pos))
if (network.pipes.isNotEmpty())
add(network)
else
remove(network)
}
}
updatedPositions.clear()
world.profiler.push("indrev_${type.key}NetworkTick")
networks.forEach { network -> network.tick(world) }
world.profiler.pop()
}
open fun onRemoved(pos: BlockPos) {
}
open fun onSet(blockPos: BlockPos, network: T) {
}
override fun writeNbt(tag: NbtCompound): NbtCompound {
return tag
}
companion object {
const val ENERGY_KEY = "indrev_networks"
const val FLUID_KEY = "indrev_fluid_networks"
const val ITEM_KEY = "indrev_item_networks"
}
} | 1 | Kotlin | 0 | 0 | d55cffe07daf5f4beec6375d8a53a9f96430b8bd | 2,737 | Industrial-Revolution | Apache License 2.0 |
finance/src/main/java/com/scitrader/finance/core/event/StudyChangedEvent.kt | ABTSoftware | 468,421,926 | false | {"Kotlin": 296559, "Java": 3061} | package com.scitrader.finance.core.event
import com.scitrader.finance.study.IStudy
data class StudyChangedEvent(val study: IStudy) : IStudyEvent
| 3 | Kotlin | 0 | 2 | 00245ef7ee93ee79b1b5a1e8a6a77bce0f02777b | 147 | Finance.Android | Apache License 2.0 |
app/src/main/java/com/bryan/personalproject/ui/adapter/QuizAdapter.kt | TBNR-1257 | 729,129,439 | false | {"Kotlin": 76279} | package com.bryan.personalproject.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bryan.personalproject.data.model.Quiz
import com.bryan.personalproject.databinding.ItemLayoutQuizBinding
class QuizAdapter(
private var quizzes :List<Quiz>,
private val fileName: String
): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(child: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val binding = ItemLayoutQuizBinding.inflate(
LayoutInflater.from(child.context),
child,
false
)
return QuizViewHolder(binding)
}
override fun getItemCount() = quizzes.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val quiz = quizzes[position]
if (holder is QuizViewHolder) {
holder.bind(quiz)
}
}
fun setQuiz(quizs: List<Quiz>) {
this.quizzes = quizs
notifyDataSetChanged()
}
inner class QuizViewHolder(
private val binding: ItemLayoutQuizBinding
): RecyclerView.ViewHolder(binding.root) {
fun bind(quiz: Quiz) {
binding.run {
tvQuizId.text = "Quiz Id: ${quiz.QuizId}"
tvTitle.text = "Title: ${quiz.title}"
tvCreatedBy.text = "Created By: ${quiz.creatorName}"
}
}
}
} | 0 | Kotlin | 0 | 0 | 49ac5aefea86c4569843df4c050a22ce0471c2ca | 1,468 | SEM4_QuizApp | MIT License |
Android/app/src/main/java/com/gsm/alimsam/ui/MovingCheckActivity.kt | Im-Tae | 266,930,672 | false | {"Kotlin": 21998} | package com.gsm.alimsam.ui
import android.content.pm.ActivityInfo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.view.isVisible
import com.gsm.alimsam.R
import com.gsm.alimsam.manager.Moving
import com.gsm.alimsam.manager.MovingAdapter
import com.gsm.alimsam.manager.Retrofit
import com.gsm.alimsam.utils.DataSingleton
import com.gsm.alimsam.utils.DateUtil
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_moving_check.*
import kotlinx.android.synthetic.main.title_bar.*
class MovingCheckActivity : AppCompatActivity() {
private val retrofit by lazy { Retrofit.create() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
overridePendingTransition(R.anim.fade_out, R.anim.no_animation)
setContentView(R.layout.activity_moving_check)
init()
getData()
backButton.setOnClickListener { finish(); overridePendingTransition(R.anim.fade_out, R.anim.fade_in) }
moving_swipeRefreshLayout.setOnRefreshListener {
moving_swipeRefreshLayout.postDelayed({ moving_swipeRefreshLayout.setRefreshing(false) }, 500)
getData()
}
}
private fun getData() {
retrofit.getMovingData(DateUtil.getToday(),DataSingleton.getStudentGradeForRetrofit() + DataSingleton.getStucentClassForRetrofit())
.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
.subscribe({
setRecyclerView(it)
}, {})
}
private fun setRecyclerView(it: ArrayList<Moving>?) {
moving_listview.adapter?.notifyDataSetChanged()
val movingAdapter = MovingAdapter(this, it!!)
moving_listview.adapter = movingAdapter
}
private fun init() {
titleName.text = "이동현황"
moving_gradeName.text = DataSingleton.getInstance()?.studentGrade
moving_className.text = DataSingleton.getInstance()?.studentClass
selectClassAndGradeButton.isVisible = false
}
override fun onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.fade_out, R.anim.fade_in) }
}
| 0 | Kotlin | 1 | 0 | b2a89cf88526629d978b41a8e3d0776b7ea87d95 | 2,335 | Alimsam-Android | MIT License |
usvm-jvm-instrumentation/src/main/kotlin/org/usvm/instrumentation/util/Printer.kt | UnitTestBot | 586,907,774 | false | {"Kotlin": 2547205, "Java": 471958} | package org.usvm.instrumentation.util
import org.jacodb.api.cfg.JcInst
import java.io.PrintStream
object TracePrinter {
fun printTraceToConsole(trace: List<JcInst>, printStream: PrintStream = System.out) =
printStream.println(buildString {
val maxLengthInstruction = trace.maxOf { it.toString().length }
val maxLengthMethod = trace.maxOf { it.location.method.name.length + it.location.method.description.length }
val maxLengthClass = trace.maxOf { it.location.method.enclosingClass.name.length }
for (element in trace) {
val inst = element.toString().padStart(maxLengthInstruction)
val method = "${element.location.method.name}${element.location.method.description}".padStart(maxLengthMethod)
val cl = element.location.method.enclosingClass.name.padStart(maxLengthClass)
appendLine("$inst | $method | $cl")
}
})
} | 39 | Kotlin | 0 | 7 | 94c5a49a0812737024dee5be9d642f22baf991a2 | 960 | usvm | Apache License 2.0 |
codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/customization/s3/S3SigningConfig.kt | ungtb10d | 543,793,859 | true | {"Kotlin": 304183, "Swift": 156241, "Shell": 19439, "Dockerfile": 654} | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package software.amazon.smithy.aws.swift.codegen.customization.s3
import software.amazon.smithy.aws.swift.codegen.middleware.AWSSigningMiddleware
import software.amazon.smithy.aws.traits.auth.UnsignedPayloadTrait
import software.amazon.smithy.model.Model
import software.amazon.smithy.model.shapes.OperationShape
import software.amazon.smithy.model.shapes.ServiceShape
import software.amazon.smithy.swift.codegen.SwiftSettings
import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator
import software.amazon.smithy.swift.codegen.integration.SwiftIntegration
import software.amazon.smithy.swift.codegen.middleware.MiddlewareStep
import software.amazon.smithy.swift.codegen.middleware.OperationMiddleware
import software.amazon.smithy.swift.codegen.model.expectShape
import software.amazon.smithy.swift.codegen.model.hasTrait
class S3SigningConfig : SwiftIntegration {
override val order: Byte
get() = 127
override fun enabledForService(model: Model, settings: SwiftSettings): Boolean {
return model.expectShape<ServiceShape>(settings.service).isS3
}
override fun customizeMiddleware(
ctx: ProtocolGenerator.GenerationContext,
operationShape: OperationShape,
operationMiddleware: OperationMiddleware
) {
operationMiddleware.removeMiddleware(operationShape, MiddlewareStep.FINALIZESTEP, "AWSSigningMiddleware")
operationMiddleware.appendMiddleware(operationShape, AWSSigningMiddleware(::middlewareParamsString, ctx.model, ctx.symbolProvider))
}
private fun middlewareParamsString(op: OperationShape): String {
val hasUnsignedPayload = op.hasTrait<UnsignedPayloadTrait>()
return "useDoubleURIEncode: false, shouldNormalizeURIPath: false, signedBodyHeader: .contentSha256, unsignedBody: $hasUnsignedPayload"
}
}
| 0 | Kotlin | 0 | 0 | c41830c2ec30d7d2d641aa3fd6d80016cbe9e83f | 1,949 | aws-sdk-swift-1 | Apache License 2.0 |
app/src/main/java/com/kartikey/foodrunner/database/RestaurantEntity.kt | KartikeySharma | 284,233,364 | false | {"Kotlin": 120470} | package com.kartikey.foodrunner.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "restaurants")
data class RestaurantEntity
(
@ColumnInfo(name = "restaurant_id") @PrimaryKey var restaurantId: String,
@ColumnInfo(name = "restaurant_name") var restaurantName: String
) | 0 | Kotlin | 11 | 1 | b940567098772f765d53bb0b17560218777fb286 | 352 | FoodRunner | MIT License |
build.gradle.kts | pcimcioch | 247,550,225 | false | null | repositories {
mavenCentral()
}
plugins {
kotlin("jvm") version "1.5.31"
kotlin("plugin.serialization") version "1.5.31"
`maven-publish`
signing
id("org.jetbrains.dokka") version "1.5.31"
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation("com.charleskorn.kaml:kaml:0.37.0")
api("org.jetbrains.kotlinx:kotlinx-datetime:0.3.1")
testImplementation("org.junit.jupiter:junit-jupiter:5.9.3")
testImplementation("org.assertj:assertj-core:3.24.2")
}
tasks {
compileKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
test {
useJUnitPlatform()
}
}
val dokkaJar by tasks.creating(Jar::class) {
group = JavaBasePlugin.DOCUMENTATION_GROUP
description = "Assembles Kotlin docs with Dokka"
archiveClassifier.set("javadoc")
from(tasks.dokkaJavadoc)
}
java {
withSourcesJar()
toolchain {
languageVersion.set(JavaLanguageVersion.of(8))
}
}
publishing {
publications {
create<MavenPublication>("maven") {
from(components["java"])
artifact(dokkaJar)
pom {
name.set("GitlabCi Kotlin DSL")
description.set("Library providing Kotlin DSL to configure GitlabCI file")
url.set("https://github.com/pcimcioch/gitlab-ci-kotlin-dsl")
licenses {
license {
name.set("The Apache License, Version 2.0")
url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
}
}
scm {
connection.set("scm:git:git://github.com/pcimcioch/gitlab-ci-kotlin-dsl.git")
developerConnection.set("scm:git:<EMAIL>:pcimcioch/gitlab-ci-kotlin-dsl.git")
url.set("https://github.com/pcimcioch/gitlab-ci-kotlin-dsl")
}
developers {
developer {
id.set("pcimcioch")
name.set("<NAME>")
email.set("<EMAIL>")
}
}
}
}
}
repositories {
val url = if (project.version.toString().contains("SNAPSHOT")) "https://oss.sonatype.org/content/repositories/snapshots" else "https://oss.sonatype.org/service/local/staging/deploy/maven2"
maven(url) {
credentials {
username = project.findProperty("ossrhUsername")?.toString() ?: ""
password = project.findProperty("ossrhPassword")?.toString() ?: ""
}
}
}
}
signing {
useInMemoryPgpKeys(project.findProperty("signingKey").toString(), project.findProperty("signingPassword").toString())
sign(publishing.publications["maven"])
} | 0 | Kotlin | 5 | 20 | bf30d3edb0566613a27a787b7f6490f9507412d8 | 2,962 | gitlab-ci-kotlin-dsl | Apache License 2.0 |
crud-framework-web/src/main/java/dev/krud/crudframework/web/rest/CrudControllerProperties.kt | krud-dev | 572,863,861 | false | {"Kotlin": 185051, "Java": 181482, "Shell": 1850} | package dev.krud.crudframework.web.rest
import dev.krud.crudframework.crud.configuration.properties.CrudFrameworkProperties
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties(CrudControllerProperties.CONFIGURATION_PREFIX)
class CrudControllerProperties {
/**
* The base URL for the CRUD Controller
*/
var url = "/crud"
companion object {
const val CONFIGURATION_PREFIX = "${CrudFrameworkProperties.CONFIGURATION_PREFIX}.rest"
}
} | 1 | Kotlin | 0 | 0 | a3c01955a8b181c6b5cd11833f68ca1eded960b7 | 514 | crudframework | MIT License |
data/repository/src/commonMain/kotlin/io/github/droidkaigi/confsched2019/data/repository/AnnouncementRepository.kt | DroidKaigi | 143,598,291 | false | null | package io.github.droidkaigi.confsched2019.data.repository
import io.github.droidkaigi.confsched2019.model.Announcement
interface AnnouncementRepository {
suspend fun announcements(): List<Announcement>
suspend fun refresh()
}
| 43 | Kotlin | 276 | 823 | 839b6dca4780aac1746c819f7ca8af6100afcda8 | 237 | conference-app-2019 | Apache License 2.0 |
tasks/src/main/java/app/tivi/tasks/SyncAllFollowedShows.kt | cxjwmy | 495,546,825 | true | {"Kotlin": 832294, "Shell": 2974} | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.tasks
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import app.tivi.data.entities.RefreshType
import app.tivi.domain.interactors.UpdateFollowedShows
import app.tivi.util.Logger
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
@HiltWorker
class SyncAllFollowedShows @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val updateFollowedShows: UpdateFollowedShows,
private val logger: Logger
) : CoroutineWorker(context, params) {
companion object {
const val TAG = "sync-all-followed-shows"
const val NIGHTLY_SYNC_TAG = "night-sync-all-followed-shows"
}
override suspend fun doWork(): Result {
logger.d("$tags worker running")
updateFollowedShows.executeSync(UpdateFollowedShows.Params(true, RefreshType.FULL))
return Result.success()
}
}
| 0 | Kotlin | 0 | 0 | 70124c20a482cd83ddfe735802f77064c2ba8f20 | 1,592 | tivi | Apache License 2.0 |
simplified-ui-profiles/src/main/java/org/nypl/simplified/ui/profiles/ProfileModificationEvent.kt | robbyice | 421,959,363 | true | {"Kotlin": 2935946, "Java": 390072, "HTML": 75158, "Shell": 3449, "Ruby": 356} | package org.nypl.simplified.ui.profiles
sealed class ProfileModificationEvent {
object Succeeded : ProfileModificationEvent()
object Cancelled : ProfileModificationEvent()
}
| 0 | Kotlin | 0 | 1 | 5f8f35fa8701a92939f3d08d14cd86bf0c23193d | 181 | Simplified-Android-Core | Apache License 2.0 |
Kotlin-Samples/src/main/kotlin/chapter7/Recipe8.kt | PacktPublishing | 126,314,798 | false | null | package chapter7
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.runBlocking
import kotlin.concurrent.thread
import kotlin.coroutines.experimental.Continuation
import kotlin.coroutines.experimental.suspendCoroutine
import kotlin.system.measureTimeMillis
/**
* Chapter: Making Asynchronous programming great again
* Recipe: Wrapping third-party callback-style APIs with coroutines
*/
fun main(vararg args: String) = runBlocking {
val time = measureTimeMillis {
val asyncResults = async {
getResults()
}
println("getResults() is running in bacground. Main thread is not blocked.")
asyncResults.await().map { println(it.displayName) }
println("getResults() completed")
}
println("Total time elapsed: $time ms")
}
suspend fun getResults(): List<Result> =
suspendCoroutine { continuation: Continuation<List<Result>> ->
getResultsAsync { continuation.resume(it) }
}
fun getResultsAsync(callback: (List<Result>) -> Unit) =
thread {
val results = mutableListOf<Result>()
// Simulate some extensive bacground task
Thread.sleep(1000)
results.add(Result("a"))
results.add(Result("b"))
results.add(Result("c"))
callback(results)
}
data class Result(val displayName: String) | 0 | Kotlin | 24 | 26 | a9118396250ded6f4466c20fd0dc62ea6a598ed1 | 1,356 | Kotlin-Standard-Library-Cookbook | MIT License |
src/main/kotlin/org/kreact/core/ActionDispatcher.kt | kreact | 665,785,134 | false | {"Kotlin": 16100} | package org.kreact.core
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableSharedFlow
/**
* An abstract class that manages action dispatching.
*
* @param A The type of action dispatched
* @param S The type of state
* @param E The type of side effect that can occur during the state mutation
*/
abstract class ActionDispatcher<A : Action, S : State, E : SideEffect>(
private val actionFlow: MutableSharedFlow<A>,
private val actionReceiveChannel: Channel<DispatchForResultChannelItem<A, S, E>>,
) {
/**
* Dispatches an action to the flow for processing by the reducer.
*
* @param action The action to dispatch.
*/
suspend fun dispatch(action: A) {
actionFlow.emit(action)
}
/**
* Dispatches an action to the channel for processing and waits for the result from the reducer.
*
* @param action The action to dispatch with suspension.
*/
suspend fun dispatchAndAwait(action: A) {
actionReceiveChannel.send(DispatchForResultChannelItem(action))
actionReceiveChannel.receive()
}
} | 0 | Kotlin | 0 | 3 | 238e4787220f7b203cf5a7c449f26b3ce9539650 | 1,110 | kreact | Apache License 2.0 |
app/src/main/java/com/nosoproject/nosowallet/nosocore/mpCripto.kt | Noso-Project | 440,352,953 | false | {"Kotlin": 236273} | package com.nosoproject.nosowallet.nosocore
import androidx.compose.runtime.MutableState
import com.nosoproject.nosowallet.*
import com.nosoproject.nosowallet.model.*
import com.nosoproject.nosowallet.ui.footer.SyncState
import com.nosoproject.nosowallet.util.Log
import io.realm.kotlin.Realm
import org.bouncycastle.crypto.digests.RIPEMD160Digest
import org.bouncycastle.util.encoders.Base64
import org.bouncycastle.util.encoders.Hex
import java.math.BigInteger
import java.security.MessageDigest
import java.util.*
import kotlin.experimental.xor
class mpCripto {
companion object {
fun CreateNewAddress(): WalletObject {
var MyData = WalletObject()
var Address:String
var KeysPair: KeyPair
KeysPair = SignerUtils.GenerateECKeyPair(KeyType.SECP256K1)
Address = GetAddressFromPublicKey(KeysPair.PublicKey!!)
MyData.Hash = Address
MyData.Custom = ""
MyData.PublicKey = KeysPair.PublicKey
MyData.PrivateKey = KeysPair.PrivateKey
MyData.Balance = 0
MyData.Pending = 0
MyData.Score = 0
MyData.LastOP = 0
return MyData
}
fun CreateNewAddress(public:String, private:String): WalletObject {
var MyData = WalletObject()
var Address:String
var KeysPair: KeyPair
KeysPair = KeyPair()
KeysPair.PublicKey = public
KeysPair.PrivateKey = private
Address = GetAddressFromPublicKey(KeysPair.PublicKey!!)
MyData.Hash = Address
MyData.Custom = ""
MyData.PublicKey = KeysPair.PublicKey
MyData.PrivateKey = KeysPair.PrivateKey
MyData.Balance = 0
MyData.Pending = 0
MyData.Score = 0
MyData.LastOP = 0
return MyData
}
fun XorEncode(key:String, source: String):String{
var result = ""
for(i in source.indices){
val c:Byte = if(key.isNotEmpty()){
key[0+(i % key.length)].code.toByte().xor(source[i].code.toByte())
}else{
source[i].code.toByte()
}
val twoDigitsFix = if(Integer.toHexString(c.toInt()).length == 1){ "0${Integer.toHexString(c.toInt())}"}else{ Integer.toHexString(c.toInt()) }
result += twoDigitsFix.lowercase()
}
return result
}
fun XorDecode(key:String, source: String):String{
var result = ""
for(i in 0 until source.length/2){
var c:Byte = source.substring(i*2,i*2+2).toInt(16).toByte()
if(key.isNotEmpty()){
c = key[0+(i % key.length)].code.toByte().xor(c)
}
result += c.toInt().toChar()
}
return result
}
fun GetAddressFromPublicKey(PubKey:String):String {
var PubSHAHashed:String
var Hash1:String
var Hash2:String
var clave:String
var sumatoria:Int
PubSHAHashed = HashSha256String(PubKey)
Hash1 = HashMD160String(PubSHAHashed)
Hash1 = BMHexto58(Hash1, BigInteger("58"))
sumatoria = BMB58resumen(Hash1)
clave = BMDecto58(sumatoria.toString())
Hash2 = Hash1+clave
return CoinChar +Hash2
}
suspend fun SendTo(
origin:String,
destination:String,
amount:Long,
reference:String,
lastBlock:Long,
sendFromAll:Boolean,
addressList:MutableList<WalletObject>,
lastNodeSelected: NodeInfo?,
syncStatus:MutableState<SyncState>,
realmDB: Realm
):String {
var CurrTime:Long
var Fee:Long
var Remaining:Long
var CoinsAvailable:Long
var ArrayTrfrs = ArrayList<OrderData>()
var Counter = 0
var OrderHashString:String
var TrxLine = 0
var ResultOrderID:String
var OrderString:String
CurrTime = System.currentTimeMillis()/1000
Fee = GetFee(amount)
Remaining = amount+Fee
CoinsAvailable = mpFunctions.GetAddressBalanceFromSummary(
origin,
realmDB
) - mpFunctions.getAddressPendingPays(origin, addressList, realmDB)
if(Remaining <= CoinsAvailable || sendFromAll){
OrderHashString = CurrTime.toString()
//Order list with origin in front
@Suppress("UNCHECKED_CAST")
for(wallet in addressList){
if(wallet.Hash == origin){
addressList.remove(wallet)
addressList.add(0, wallet)
break
}
}
var Amount = amount // Amount == needed Amount
while(Amount > 0){
if((addressList[Counter].Balance- mpFunctions.getAddressPendingPays(
addressList[Counter].Hash!!,
addressList,
realmDB
))>0){
TrxLine += 1
ArrayTrfrs.add(
mpFunctions.SendFundsFromAddress(
addressList[Counter].Hash!!,
destination,
Amount,
Fee,
reference,
CurrTime,
TrxLine,
lastBlock,
addressList[Counter]
)
)
Fee -= ArrayTrfrs.last().AmountFee
Amount -= ArrayTrfrs.last().AmountTrf
OrderHashString += ArrayTrfrs.last().TrfrID
addressList[Counter].Outgoing = ArrayTrfrs.last().AmountTrf
}
Counter++
}
for(tr in ArrayTrfrs){
tr.OrderID = mpFunctions.getOrderHash(TrxLine.toString() + OrderHashString)
Log.e("mpCripto", "new OrderID -> ${tr.OrderID}")
tr.OrderLines = TrxLine
}
ResultOrderID = mpFunctions.getOrderHash(TrxLine.toString() + OrderHashString)
Log.e("mpCripto", "ResultOrderID: $ResultOrderID")
OrderString = mpFunctions.getPTCEcn("ORDER") +"ORDER "+TrxLine.toString()+" $"
for(tr in ArrayTrfrs){
OrderString += mpFunctions.getStringFromOrder(tr) +" $"
}
OrderString = OrderString.substring(0, OrderString.length-2)
return mpNetwork.sendOrder(OrderString, lastNodeSelected, syncStatus)
}else{
Log.e(
"mpCripto",
"Origin with not enough funds, available: $CoinsAvailable, required: $Remaining"
)
return MISSING_FUNDS
}
}
fun getTransferHash(order:String):String {
var result = HashSha256String(order)
result = BMHexto58(result, BigInteger("58"))
var b58sum = BMB58resumen(result)
var clave = BMDecto58(b58sum.toString())
return "tR$result$clave"
}
fun GetFee(amount:Long):Long {
val result = amount/ Comisiontrfr
if(result < MinimunFee){
return MinimunFee
}
return result
}
fun getStringSigned(stringtoSign:String, privateKey: String):String {
var MessageAsBytes:ByteArray
var Signature: ByteArray
MessageAsBytes = mpParser.SpecialBase64Decode(stringtoSign)
Signature = SignerUtils.SignMessage(
MessageAsBytes,
Base64.decode(privateKey),
KeyType.SECP256K1
)
return String(org.bouncycastle.util.encoders.Base64.encode(Signature))
}
fun VerifySignedString(
stringtoverify:String,
signedhash:String,
publickey:String
):Boolean {
var MessageAsBytes = org.bouncycastle.util.encoders.Base64.decode(stringtoverify)
var Signature = org.bouncycastle.util.encoders.Base64.decode(signedhash)
return SignerUtils.VerifySignature(
Signature,
MessageAsBytes,
Base64.decode(publickey),
KeyType.SECP256K1
)
}
//Returns the SHA256 of a String in CAPITAL
fun HashSha256String(StringToHash:String):String {
var Source = StringToHash.toByteArray()
val MessageDigestInstance = MessageDigest.getInstance("SHA-256")
val Digest = MessageDigestInstance.digest(Source)
val result = Digest.fold("", { str, it -> str + "%02x".format(it) })
return result.uppercase() //Display the digest in capital letter ?? ECO: not sure why
}
//Returns the SHA1 of a String in CAPITAL
fun HashSha1String(StringToHash:String):String {
var Source = StringToHash.toByteArray()
val MessageDigestInstance = MessageDigest.getInstance("SHA-1")
val Digest = MessageDigestInstance.digest(Source)
val result = Digest.fold("", { str, it -> str + "%02x".format(it) })
return result
}
fun HashMD160String(StringToHash:String):String {
val bytesFromString = StringToHash.toByteArray()
val mdInstance = RIPEMD160Digest()
mdInstance.update(bytesFromString,0,bytesFromString.size)
var result = ByteArray(mdInstance.digestSize)
mdInstance.doFinal(result, 0)
//Log.e("mpCripto","MD160 result raw: "+String(result))
//Log.e("mpCripto","MD160 result hex: "+String(Hex.encode(result)))
return String(Hex.encode(result))
}
fun getMD5of(string:String):String {
val encoded = encodeMD5String(string)
return toHex(encoded)
}
private fun encodeMD5String(source: String):ByteArray {
val digest = MessageDigest.getInstance("MD5")
return digest.digest(source.toByteArray())
}
private fun toHex(encoded:ByteArray):String {
val hexCoded = StringBuilder()
for (element in encoded) {
val hex = Integer.toHexString(0xff and element.toInt())
if (hex.length == 1) {
hexCoded.append('0')
}
hexCoded.append(hex)
}
return hexCoded.toString()
}
/* Legacy Kotlin based
fun BMHexto58(numerohex:String, alphabetnumber:BigInteger):String {
var decimalValue:BigInteger
var RDiv_Residuo:BigInteger
var Resultado = ""
var AlphabetUsed:String
if(alphabetnumber == BigInteger("36")){
AlphabetUsed = B36Alphabet
}else{
AlphabetUsed = B58Alphabet
}
decimalValue = BMHexToDec(numerohex)
Log.e("mcripto","Ht58 - decimal: $decimalValue")
while (decimalValue.toString().length >= 2){
decimalValue = decimalValue/alphabetnumber
RDiv_Residuo = decimalValue % alphabetnumber
Log.e("mcripto","Ht58 - decimal: $decimalValue residuo: $RDiv_Residuo simbolo: "+AlphabetUsed[RDiv_Residuo.toInt()])
Resultado = AlphabetUsed[RDiv_Residuo.toInt()]+Resultado
}
if(decimalValue > alphabetnumber){
decimalValue = decimalValue/alphabetnumber
RDiv_Residuo = decimalValue % alphabetnumber
Log.e("mcripto","Ht58 - decimal: $decimalValue residuo: $RDiv_Residuo simbolo: "+AlphabetUsed[RDiv_Residuo.toInt()])
Resultado = AlphabetUsed[RDiv_Residuo.toInt()] + Resultado
}
if(decimalValue > BigInteger("0")){
Log.e("mcripto","Ht58 - decimal: $decimalValue simbolo: "+AlphabetUsed[decimalValue.toInt()])
Resultado = AlphabetUsed[decimalValue.toInt()]+Resultado
}
return Resultado
}
*/
fun ClearLeadingCeros(numero:String):String{
// Using BigInteger parser to remove leading zeroes
return BigInteger(numero).toString()
}
fun BMDividir(numeroA:String, Divisor:Int): DivResult {
var cociente = ""
var ThisStep = ""
for(i in 0..(numeroA.length-1)){
ThisStep = ThisStep + numeroA[i]
if(Integer.parseInt(ThisStep) >= Divisor){
cociente = cociente+(Integer.parseInt(ThisStep)/Divisor).toString()
ThisStep = (Integer.parseInt(ThisStep) % Divisor).toString()
}else{
cociente = cociente +"0"
}
}
val r = DivResult()
r.Cociente = ClearLeadingCeros(cociente)
r.Residuo = ClearLeadingCeros(ThisStep)
return r
}
// Method replicated form Nosowallet
fun BMHexto58(numerohex:String, alphabetnumber:BigInteger):String {
var decimalValue:String
var ResultadoDiv: DivResult
var restante:String
var Resultado = ""
var AlphabetUsed:String
if(alphabetnumber == BigInteger("36")){
AlphabetUsed = B36Alphabet
}else{
AlphabetUsed = B58Alphabet
}
decimalValue = BMHexToDec(numerohex).toString()
while (decimalValue.length >= 2){
ResultadoDiv = BMDividir(decimalValue, alphabetnumber.toInt())
decimalValue = ResultadoDiv.Cociente!!
restante = ResultadoDiv.Residuo!!
Resultado = AlphabetUsed[Integer.parseInt(restante)] + Resultado
}
if(Integer.parseInt(decimalValue) >= alphabetnumber.toInt()){
ResultadoDiv = BMDividir(decimalValue, alphabetnumber.toInt())
decimalValue = ResultadoDiv.Cociente!!
restante = ResultadoDiv.Residuo!!
Resultado = AlphabetUsed[Integer.parseInt(restante)] + Resultado
}
if(Integer.parseInt(decimalValue) > 0){
Resultado = AlphabetUsed[Integer.parseInt(decimalValue)]+Resultado
}
return Resultado
}
/* Legacy - Kotlin Base
fun BMDecto58(numero:String):String {
var decimalValue:BigInteger
var RDiv_Residuo:BigInteger
var Resultado = ""
decimalValue = BigInteger(numero)
while (decimalValue.toString().length >= 2){
decimalValue = decimalValue/ BigInteger("58")
RDiv_Residuo = decimalValue % BigInteger("58")
Resultado = B58Alphabet[RDiv_Residuo.toInt()]+Resultado
}
if(decimalValue > BigInteger("58")){
decimalValue = decimalValue/BigInteger("58")
RDiv_Residuo = decimalValue % BigInteger("58")
Resultado = B58Alphabet[RDiv_Residuo.toInt()] + Resultado
}
if(decimalValue > BigInteger("0")){
Resultado = B58Alphabet[decimalValue.toInt()]+Resultado
}
return Resultado
}*/
// Pascal based - Not matching for some reason with Kotlin based
fun BMDecto58(numero:String):String {
var decimalValue:String
var ResultadoDiv: DivResult
var restante:String
var Resultado = ""
decimalValue = BigInteger(numero).toString()
while (decimalValue.length >= 2){
ResultadoDiv = BMDividir(decimalValue, 58)
decimalValue = ResultadoDiv.Cociente!!
restante = ResultadoDiv.Residuo!!
Resultado = B58Alphabet[Integer.parseInt(restante)] + Resultado
}
if(Integer.parseInt(decimalValue) >= 58){
ResultadoDiv = BMDividir(decimalValue, 58)
decimalValue = ResultadoDiv.Cociente!!
restante = ResultadoDiv.Residuo!!
Resultado = B58Alphabet[Integer.parseInt(restante)] + Resultado
}
if(Integer.parseInt(decimalValue) > 0){
Resultado = B58Alphabet[Integer.parseInt(decimalValue)]+Resultado
}
return Resultado
}
fun BMB58resumen(numero58:String):Int {
var total = 0
for(i in 0..(numero58.length-1)){
total = total + B58Alphabet.indexOf(numero58[i])
}
return total
}
fun BMHexToDec(numerohex:String):BigInteger {
return BigInteger(numerohex, 16)
}
}
} | 6 | Kotlin | 1 | 13 | fc3c4b2299903703b138729a650c84b31dc0e1ca | 17,441 | NosoWallet-Android | The Unlicense |
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirCommonConstructorDelegationIssuesChecker.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.analysis.checkers.declaration
import org.jetbrains.kotlin.KtFakeSourceElementKind
import org.jetbrains.kotlin.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.diagnostics.reportOn
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.declarations.FirConstructor
import org.jetbrains.kotlin.fir.declarations.FirErrorPrimaryConstructor
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.fir.declarations.utils.isExpect
import org.jetbrains.kotlin.fir.diagnostics.FirDiagnosticHolder
import org.jetbrains.kotlin.fir.references.*
import org.jetbrains.kotlin.fir.symbols.SymbolInternals
import org.jetbrains.kotlin.fir.symbols.lazyResolveToPhase
import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull
object FirCommonConstructorDelegationIssuesChecker : FirRegularClassChecker() {
override fun check(declaration: FirRegularClass, context: CheckerContext, reporter: DiagnosticReporter) {
val containingClass = context.containingDeclarations.lastIsInstanceOrNull<FirRegularClass>()
if (declaration.isEffectivelyExternal(containingClass, context)) return
val cyclicConstructors = mutableSetOf<FirConstructor>()
var hasPrimaryConstructor = false
val isEffectivelyExpect = declaration.isEffectivelyExpect(context.containingDeclarations.lastOrNull() as? FirRegularClass, context)
// secondary; non-cyclic;
// candidates for further analysis
val otherConstructors = mutableSetOf<FirConstructor>()
for (it in declaration.declarations) {
if (it is FirConstructor) {
if (!it.isPrimary || it is FirErrorPrimaryConstructor) {
otherConstructors += it
it.findCycle(cyclicConstructors)?.let { visited ->
cyclicConstructors += visited
}
} else {
hasPrimaryConstructor = true
}
}
}
otherConstructors -= cyclicConstructors
if (hasPrimaryConstructor) {
for (it in otherConstructors) {
if (!isEffectivelyExpect && it.delegatedConstructor?.isThis != true) {
if (it.delegatedConstructor?.source != null) {
reporter.reportOn(it.delegatedConstructor?.source, FirErrors.PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED, context)
} else {
reporter.reportOn(it.source, FirErrors.PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED, context)
}
}
}
} else {
for (it in otherConstructors) {
// couldn't find proper super() constructor implicitly
if (it.delegatedConstructor?.calleeReference is FirDiagnosticHolder &&
it.delegatedConstructor?.source?.kind is KtFakeSourceElementKind &&
!it.isExpect
) {
reporter.reportOn(it.source, FirErrors.EXPLICIT_DELEGATION_CALL_REQUIRED, context)
}
}
}
cyclicConstructors.forEach {
reporter.reportOn(it.delegatedConstructor?.source, FirErrors.CYCLIC_CONSTRUCTOR_DELEGATION_CALL, context)
}
}
private fun FirConstructor.findCycle(knownCyclicConstructors: Set<FirConstructor> = emptySet()): Set<FirConstructor>? {
val visitedConstructors = mutableSetOf(this)
var it = this
var delegated = this.getDelegated()
while (!(it.isPrimary && it !is FirErrorPrimaryConstructor) && delegated != null) {
if (delegated in visitedConstructors || delegated in knownCyclicConstructors) {
return visitedConstructors
}
it = delegated
delegated = delegated.getDelegated()
visitedConstructors.add(it)
}
return null
}
@OptIn(SymbolInternals::class)
private fun FirConstructor.getDelegated(): FirConstructor? {
this.symbol.lazyResolveToPhase(FirResolvePhase.BODY_RESOLVE)
return delegatedConstructor?.calleeReference?.toResolvedConstructorSymbol(discardErrorReference = true)?.fir
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 4,642 | kotlin | Apache License 2.0 |
app/src/main/java/com/kickstarter/services/LakeService.kt | SaadMakhalSaad2 | 316,064,748 | true | {"Java": 1766207, "Kotlin": 1512946, "Ruby": 27326, "Shell": 4103, "Makefile": 2887} | package com.kickstarter.services
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Headers
import retrofit2.http.PUT
import retrofit2.http.Query
import rx.Observable
interface LakeService {
@Headers("Content-Type: application/json")
@PUT("record")
fun track(@Body body: RequestBody, @Query("client_id") clientId: String) : Observable<Response<ResponseBody>>
}
| 2 | null | 0 | 2 | 4e002f3a4a1c53218570ef1721511e3373109d4d | 455 | android-oss | Apache License 2.0 |
app/src/main/java/com/anytypeio/anytype/ui/widgets/types/LinkWidget.kt | anyproto | 647,371,233 | false | {"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276} | package com.anytypeio.anytype.ui.widgets.types
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.anytypeio.anytype.R
import com.anytypeio.anytype.core_ui.foundation.noRippleClickable
import com.anytypeio.anytype.core_ui.views.HeadlineSubheading
import com.anytypeio.anytype.presentation.widgets.DropDownMenuAction
import com.anytypeio.anytype.presentation.widgets.Widget
import com.anytypeio.anytype.presentation.widgets.WidgetView
import com.anytypeio.anytype.presentation.widgets.getWidgetObjectName
import com.anytypeio.anytype.ui.widgets.menu.WidgetMenu
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun LinkWidgetCard(
item: WidgetView.Link,
onWidgetSourceClicked: (Widget.Source) -> Unit,
onDropDownMenuAction: (DropDownMenuAction) -> Unit,
isInEditMode: Boolean
) {
val isCardMenuExpanded = remember {
mutableStateOf(false)
}
val isHeaderMenuExpanded = remember {
mutableStateOf(false)
}
val haptic = LocalHapticFeedback.current
Box(
modifier = Modifier
.fillMaxWidth()
.padding(start = 20.dp, end = 20.dp, top = 6.dp, bottom = 6.dp)
.alpha(if (isCardMenuExpanded.value || isHeaderMenuExpanded.value) 0.8f else 1f)
.background(
shape = RoundedCornerShape(16.dp),
color = colorResource(id = R.color.dashboard_card_background)
)
.then(
if (isInEditMode)
Modifier.noRippleClickable {
isCardMenuExpanded.value = !isCardMenuExpanded.value
}
else
Modifier.combinedClickable(
onClick = { onWidgetSourceClicked(item.source) },
onLongClick = {
isCardMenuExpanded.value = !isCardMenuExpanded.value
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
},
indication = null,
interactionSource = remember { MutableInteractionSource() }
)
)
) {
Box(
Modifier
.padding(vertical = 6.dp)
.fillMaxWidth()
.height(40.dp)
) {
Text(
text = when (val source = item.source) {
is Widget.Source.Default -> {
source.obj.getWidgetObjectName() ?: stringResource(id = R.string.untitled)
}
is Widget.Source.Bundled -> { stringResource(id = source.res()) }
},
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.align(Alignment.CenterStart)
.padding(
start = 16.dp,
end = if (isInEditMode) 76.dp else 32.dp
),
style = HeadlineSubheading,
color = colorResource(id = R.color.text_primary),
)
AnimatedVisibility(
visible = isInEditMode,
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = 48.dp),
enter = fadeIn(),
exit = fadeOut()
) {
Box {
Image(
painterResource(R.drawable.ic_widget_three_dots),
contentDescription = "Widget menu icon",
modifier = Modifier
.noRippleClickable {
isHeaderMenuExpanded.value = !isHeaderMenuExpanded.value
}
)
WidgetMenu(
isExpanded = isHeaderMenuExpanded,
onDropDownMenuAction = onDropDownMenuAction,
canEditWidgets = !isInEditMode
)
}
}
}
WidgetMenu(
isExpanded = isCardMenuExpanded,
onDropDownMenuAction = onDropDownMenuAction,
canEditWidgets = !isInEditMode
)
}
} | 33 | Kotlin | 26 | 301 | 8b3b7dacae68c015fb8b1b7c9cc76e53f0706430 | 5,514 | anytype-kotlin | RSA Message-Digest License |
analysis/analysis-api/testData/components/importOptimizer/analyseImports/referencesWithErrors/usedConstructor_missingCall.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FILE: main.kt
package test
import dependency.Bar
fun usage() {
val result = Bar()
}
// FILE: dependency.kt
package dependency
class Bar(i: Int) | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 154 | kotlin | Apache License 2.0 |
sphinx/application/network/concepts/queries/concept-network-query-action-track/src/main/java/chat/sphinx/concept_network_query_action_track/NetworkQueryActionTrack.kt | stakwork | 340,103,148 | false | {"Kotlin": 4002503, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453} | package chat.sphinx.concept_network_query_action_track
import chat.sphinx.concept_network_query_action_track.model.SyncActionsDto
import chat.sphinx.kotlin_response.LoadResponse
import chat.sphinx.kotlin_response.ResponseError
import chat.sphinx.wrapper_relay.AuthorizationToken
import chat.sphinx.wrapper_relay.RelayUrl
import chat.sphinx.wrapper_relay.RequestSignature
import chat.sphinx.wrapper_relay.TransportToken
import kotlinx.coroutines.flow.Flow
abstract class NetworkQueryActionTrack {
////////////
/// POST ///
////////////
abstract fun sendActionsTracked(
syncActionsDto: SyncActionsDto,
relayData: Triple<Pair<AuthorizationToken, TransportToken?>, RequestSignature?, RelayUrl>? = null
): Flow<LoadResponse<Any?, ResponseError>>
} | 96 | Kotlin | 8 | 18 | 4fd9556a4a34f14126681535558fe1e39747b323 | 781 | sphinx-kotlin | MIT License |
mediapicker/src/main/java/com/greentoad/turtlebody/mediapicker/core/FileManager.kt | Turtlebody | 177,713,614 | false | {"Kotlin": 109679, "Java": 3797} | package com.greentoad.turtlebody.mediapicker.core
import android.content.Context
import android.database.Cursor
import android.net.Uri
import androidx.core.content.FileProvider.getUriForFile
import com.greentoad.turtlebody.mediapicker.MediaPicker
import com.greentoad.turtlebody.mediapicker.ui.component.folder.audio.AudioFolder
import com.greentoad.turtlebody.mediapicker.ui.component.folder.image_video.ImageVideoFolder
import com.greentoad.turtlebody.mediapicker.ui.component.media.audio.AudioModel
import com.greentoad.turtlebody.mediapicker.ui.component.media.image.ImageModel
import com.greentoad.turtlebody.mediapicker.ui.component.media.video.VideoModel
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import java.io.File
import java.util.*
object FileManager : AnkoLogger {
/**
* For ImageModel
*/
fun fetchImageFolders(context: Context): ArrayList<ImageVideoFolder> {
val folders = ArrayList<ImageVideoFolder>()
val folderFileCountMap = HashMap<String, Int>()
val projection = MediaConstants.Projection.IMAGE_FOLDER
//Create the cursor pointing to the SDCard
val cursor = CursorHelper.getImageVideoFolderCursor(context, MediaPicker.MediaTypes.IMAGE)
cursor?.let {
val columnIndexFolderId = it.getColumnIndexOrThrow(projection[0])
val columnIndexFolderName = it.getColumnIndexOrThrow(projection[1])
val columnIndexFilePath = it.getColumnIndexOrThrow(projection[2])
while (it.moveToNext()) {
val folderId = it.getString(columnIndexFolderId)
if (folderFileCountMap.containsKey(folderId)) {
folderFileCountMap[folderId] = folderFileCountMap[folderId]!! + 1
} else {
val folder = ImageVideoFolder(folderId, it.getString(columnIndexFolderName), it.getString(columnIndexFilePath), 0)
folders.add(folder)
folderFileCountMap[folderId] = 1
}
}
for (fdr in folders) {
fdr.contentCount = folderFileCountMap[fdr.id]!!
}
cursor.close()
}
return folders
}
fun getImageFilesInFolder(context: Context, folderId: String): ArrayList<ImageModel> {
val fileItems = ArrayList<ImageModel>()
val projection = MediaConstants.Projection.IMAGE_FILE
//Create the cursor pointing to the SDCard
val cursor: Cursor? = CursorHelper.getImageVideoFileCursor(context, folderId, MediaPicker.MediaTypes.IMAGE)
cursor?.let {
val columnIndexFileId = it.getColumnIndexOrThrow(projection[0])
val columnIndexFileName = it.getColumnIndexOrThrow(projection[1])
val columnIndexFileSize = it.getColumnIndexOrThrow(projection[2])
val columnIndexFilePath = it.getColumnIndexOrThrow(projection[3])
val columnIndexFileThumbPath = it.getColumnIndexOrThrow(projection[5])
while (it.moveToNext()) {
val fileItem = ImageModel(it.getString(columnIndexFileId),
it.getString(columnIndexFileName),
it.getInt(columnIndexFileSize),
it.getString(columnIndexFilePath),
it.getString(columnIndexFileThumbPath), false)
fileItems.add(fileItem)
}
cursor.close()
}
return fileItems
}
/**
* For VideoModel
*/
fun fetchVideoFolders(context: Context): ArrayList<ImageVideoFolder> {
val folders = ArrayList<ImageVideoFolder>()
val folderFileCountMap = HashMap<String, Int>()
val projection = MediaConstants.Projection.VIDEO_FOLDER
//Create the cursor pointing to the SDCard
val cursor = CursorHelper.getImageVideoFolderCursor(context, MediaPicker.MediaTypes.VIDEO)
cursor?.let {
val columnIndexFolderId = it.getColumnIndexOrThrow(projection[0])
val columnIndexFolderName = it.getColumnIndexOrThrow(projection[1])
val columnIndexFilePath = it.getColumnIndexOrThrow(projection[2])
while (it.moveToNext()) {
val folderId = it.getString(columnIndexFolderId)
if (folderFileCountMap.containsKey(folderId)) {
folderFileCountMap[folderId] = folderFileCountMap[folderId]!! + 1
} else {
val folder = ImageVideoFolder(folderId, it.getString(columnIndexFolderName), it.getString(columnIndexFilePath), 0)
folders.add(folder)
folderFileCountMap[folderId] = 1
}
}
for (fdr in folders) {
fdr.contentCount = folderFileCountMap[fdr.id]!!
}
cursor.close()
}
return folders
}
fun getVideoFilesInFolder(context: Context, folderId: String): ArrayList<VideoModel> {
val fileItems = ArrayList<VideoModel>()
val projection = MediaConstants.Projection.VIDEO_FILE
//Create the cursor pointing to the SDCard
val cursor: Cursor? = CursorHelper.getImageVideoFileCursor(context, folderId, MediaPicker.MediaTypes.VIDEO)
cursor?.let {
val columnIndexFileId = it.getColumnIndexOrThrow(projection[0])
val columnIndexFileName = it.getColumnIndexOrThrow(projection[1])
val columnIndexFileSize = it.getColumnIndexOrThrow(projection[2])
val columnIndexFilePath = it.getColumnIndexOrThrow(projection[3])
val columnIndexFileThumbPath = it.getColumnIndexOrThrow(projection[5])
val columnIndexFileDuration = it.getColumnIndexOrThrow(projection[6])
while (it.moveToNext()) {
val fileItem = VideoModel(it.getString(columnIndexFileId),
it.getString(columnIndexFileName),
it.getInt(columnIndexFileSize),
it.getString(columnIndexFilePath),
it.getString(columnIndexFileThumbPath),
it.getString(columnIndexFileDuration), false)
fileItems.add(fileItem)
}
cursor.close()
}
return fileItems
}
/**
* For audio
*/
fun fetchAudioFolderList(context: Context): ArrayList<AudioFolder> {
val folders = ArrayList<AudioFolder>()
val folderFileCountMap = HashMap<String, Int>()
val projection = MediaConstants.Projection.AUDIO_FOLDER
// Create the cursor pointing to the SDCard
val cursor = CursorHelper.getAudioFolderCursor(context)
cursor?.let {
val columnIndexFolderId = it.getColumnIndexOrThrow(projection[0])
val columnIndexCount = it.getColumnIndexOrThrow("dataCount")
val columnIndexFolderParent = it.getColumnIndexOrThrow(projection[1])
val columnIndexFilePath = it.getColumnIndexOrThrow(projection[2])
val columnIndexDisplayName = it.getColumnIndexOrThrow(projection[3])
while (it.moveToNext()) {
val folderId = it.getString(columnIndexFolderId)
val audioCounts = it.getInt(columnIndexCount)
if (folderFileCountMap.containsKey(folderId)) {
folderFileCountMap[folderId] = folderFileCountMap[folderId]!! + audioCounts
} else {
val folder = AudioFolder(folderId, File(it.getString(columnIndexFilePath)).parentFile.name,
File(it.getString(columnIndexFilePath)).parentFile.path, 0)
folders.add(folder)
folderFileCountMap[folderId] = audioCounts
}
}
for (fdr in folders) {
fdr.contentCount = folderFileCountMap[fdr.id]!!
}
cursor.close()
}
return folders
}
fun getAudioFilesInFolder(context: Context, folderPath: String): ArrayList<AudioModel> {
val fileItems = ArrayList<AudioModel>()
val projection = MediaConstants.Projection.AUDIO_FILE
// Create the cursor pointing to the SDCard
val cursor: Cursor? = CursorHelper.getAudioFilesInFolderCursor(context, folderPath)
cursor?.let {
info { "audio query size: "+ cursor.count }
val columnIndexAudioId = it.getColumnIndexOrThrow(projection[0])
val columnIndexAudioTitle = it.getColumnIndexOrThrow(projection[1])
val columnIndexAudioName = it.getColumnIndexOrThrow(projection[2])
val columnIndexAudioSize = it.getColumnIndexOrThrow(projection[3])
val columnIndexAudioPath = it.getColumnIndexOrThrow(projection[4])
val columnIndexAudioMimeType = it.getColumnIndexOrThrow(projection[5])
while (it.moveToNext()) {
var name = it.getString(columnIndexAudioName)
if(name==null){
name = it.getString(columnIndexAudioTitle)
}
if(name==null){
name = ""
}
val fileItem = AudioModel(it.getString(columnIndexAudioId),
name,
it.getInt(columnIndexAudioSize),
it.getString(columnIndexAudioPath),
//it.getString(columnIndexAudioArtist),
it.getString(columnIndexAudioMimeType),
false)
fileItems.add(fileItem)
}
cursor.close()
}
info { "audioFiles: $fileItems" }
return fileItems
}
@Deprecated("worg implemented")
fun fetchAudioFolders(context: Context): ArrayList<AudioFolder> {
val folders = ArrayList<AudioFolder>()
val folderFileCountMap = HashMap<String, Int>()
val projection = MediaConstants.Projection.ALBUM_FOLDER
// Create the cursor pointing to the SDCard
val cursor = CursorHelper.getAudioFolderCursor(context)
cursor?.let {
val columnIndexFolderId = it.getColumnIndexOrThrow(projection[0])
val columnIndexFolderName = it.getColumnIndexOrThrow(projection[1])
val columnIndexFilePath = it.getColumnIndexOrThrow(projection[2])
while (it.moveToNext()) {
val folderId = it.getString(columnIndexFolderId)
if (folderFileCountMap.containsKey(folderId)) {
folderFileCountMap[folderId] = folderFileCountMap[folderId]!! + 1
} else {
val folder = AudioFolder(folderId, it.getString(columnIndexFolderName),
it.getString(columnIndexFilePath), 0)
folders.add(folder)
folderFileCountMap[folderId] = 1
}
}
for (fdr in folders) {
fdr.contentCount = folderFileCountMap[fdr.id]!!
}
cursor.close()
}
return folders
}
fun getContentUri(context: Context, newFile: File): Uri {
val SHARED_PROVIDER_AUTHORITY = context.packageName+ ".greentoad.turtlebody.mediaprovider"
info { "id: $SHARED_PROVIDER_AUTHORITY" }
return getUriForFile(context, SHARED_PROVIDER_AUTHORITY, newFile)
}
}
| 3 | Kotlin | 15 | 59 | 7ae0520caacc6e7f29cab9a1aebd2e20be832b13 | 11,428 | android-media-picker | MIT License |
compiler/testData/codegen/box/coroutines/suspendFunctionTypeCall/manyParametersNoCapture.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
suspend fun suspendHere(v: String): String = suspendCoroutineUninterceptedOrReturn { x ->
x.resume(v)
COROUTINE_SUSPENDED
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
class Controller {
var result = ""
override fun toString() = "Controller"
}
val controller = Controller()
suspend fun foo(c: suspend Controller.(Long, Int, String) -> String) = controller.c(56L, 55, "abc")
fun box(): String {
var final = ""
builder {
final = foo { l, i, s ->
result = suspendHere("$this#$l#$i#$s")
"OK"
}
}
if (controller.result != "Controller#56#55#abc") return "fail: ${controller.result}"
return final
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 830 | kotlin | Apache License 2.0 |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/util/DataBindingAdapters.kt | si-covid-19 | 286,833,811 | false | null | package de.rki.coronawarnapp.util
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.widget.ImageView
import android.widget.Switch
import androidx.core.widget.ImageViewCompat
import androidx.databinding.BindingAdapter
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.airbnb.lottie.LottieProperty
import com.airbnb.lottie.model.KeyPath
import de.rki.coronawarnapp.util.ContextExtensions.getDrawableCompat
const val IGNORE_CHANGE_TAG = "ignore"
const val DRAWABLE_TYPE = "drawable"
@BindingAdapter("checked")
fun setChecked(switch: Switch, status: Boolean?) {
if (status != null) {
switch.tag = IGNORE_CHANGE_TAG
switch.isChecked = status
switch.tag = null
}
}
@BindingAdapter("animation")
fun setAnimation(view: LottieAnimationView, animation: Int?) {
if (animation != null) {
val context = view.context
val type = context.resources.getResourceTypeName(animation)
if (type == DRAWABLE_TYPE) {
view.setImageDrawable(context.getDrawableCompat(animation))
} else {
view.setAnimation(animation)
view.repeatCount = LottieDrawable.INFINITE
view.repeatMode = LottieDrawable.RESTART
view.playAnimation()
}
}
}
@BindingAdapter("animation_tint")
fun setAnimationColor(view: LottieAnimationView, color: Int?) {
if (color != null) {
view.setColorFilter(color)
view.addValueCallback(
KeyPath("**"),
LottieProperty.COLOR_FILTER
) { PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP) }
}
}
@BindingAdapter("app:tint")
fun setTint(view: ImageView, color: Int) {
ImageViewCompat.setImageTintList(view, ColorStateList.valueOf(color))
}
| 6 | Kotlin | 8 | 15 | 5a3b4be63b5b030da49216a0132a3979cad89af1 | 1,862 | ostanizdrav-android | Apache License 2.0 |
abc/188/b.kt | smallkirby | 321,115,776 | false | {"C++": 809606, "Python": 6068, "Kotlin": 2425, "Swift": 1489, "Shell": 292, "C": 69} | import java.lang.Math.abs
fun main(args: Array<String>) {
val N = readLine()!!.toDouble()
val A = readLine()!!.split(" ").map(String::toInt)
val B = readLine()!!.split(" ").map(String::toInt)
var total = 0
for(i in A.indices){
total += A[i]*B[i]
}
if(total == 0)
println("Yes")
else
println("No")
} | 0 | C++ | 1 | 0 | 83cc56bf078c99a14a05b1254ea37da1cdf20de7 | 355 | procon | The Unlicense |
app/src/main/java/cn/wthee/pcrtool/ui/tool/clan/ClanBattleDetailViewModel.kt | wthee | 277,015,110 | false | {"Kotlin": 1543862} | package cn.wthee.pcrtool.ui.tool.clan
import androidx.compose.runtime.Immutable
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.wthee.pcrtool.data.db.repository.ClanBattleRepository
import cn.wthee.pcrtool.data.db.repository.EnemyRepository
import cn.wthee.pcrtool.data.db.view.ClanBattleInfo
import cn.wthee.pcrtool.data.db.view.ClanBattleTargetCountData
import cn.wthee.pcrtool.data.db.view.EnemyParameterPro
import cn.wthee.pcrtool.data.model.ClanBattleProperty
import cn.wthee.pcrtool.navigation.NavRoute
import cn.wthee.pcrtool.utils.JsonUtil
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* 页面状态:公会战详情
*/
@Immutable
data class ClanBattleDetailUiState(
//公会战列表
val clanBattleList: List<ClanBattleInfo> = emptyList(),
//当前选中boss下标
val bossIndex: Int = 0,
//当前阶段
val phaseIndex: Int = 0,
val minPhase: Int = 0,
val maxPhase: Int = 0,
//boss信息
val bossDataList: List<EnemyParameterPro> = emptyList(),
//所有部位信息
val partEnemyMap: Map<Int, List<EnemyParameterPro>> = hashMapOf(),
val openDialog: Boolean = false
)
/**
* 公会战详情 ViewModel
*/
@HiltViewModel
class ClanBattleDetailViewModel @Inject constructor(
private val clanBattleRepository: ClanBattleRepository,
private val enemyRepository: EnemyRepository,
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val clanBattleProperty: ClanBattleProperty? =
JsonUtil.fromJson(savedStateHandle[NavRoute.CLAN_BATTLE_PROPERTY])
private val clanBattleId: Int? = clanBattleProperty?.clanBattleId
private val minPhase: Int? = clanBattleProperty?.minPhase
private val maxPhase: Int? = clanBattleProperty?.maxPhase
private val index: Int? = clanBattleProperty?.index
private val _uiState = MutableStateFlow(ClanBattleDetailUiState())
val uiState: StateFlow<ClanBattleDetailUiState> = _uiState.asStateFlow()
init {
if (minPhase != null && maxPhase != null && clanBattleId != null && index != null) {
_uiState.update {
it.copy(
phaseIndex = maxPhase - minPhase,
minPhase = minPhase,
maxPhase = maxPhase,
bossIndex = index
)
}
getClanBattleInfo(clanBattleId, maxPhase)
}
}
private fun reloadData(phaseIndex: Int) {
if (clanBattleId != null && minPhase != null) {
getClanBattleInfo(clanBattleId, phaseIndex + minPhase)
}
}
/**
* 弹窗状态更新
*/
fun changeDialog(openDialog: Boolean) {
viewModelScope.launch {
_uiState.update {
it.copy(
openDialog = openDialog
)
}
}
}
/**
* 获取全部公会战记录
*/
private fun getClanBattleInfo(clanBattleId: Int, phase: Int) {
viewModelScope.launch {
val clanBattleList = clanBattleRepository.getClanBattleList(clanBattleId, phase)
_uiState.update {
it.copy(
clanBattleList = clanBattleList
)
}
if (clanBattleList.isNotEmpty()) {
val clanBattleValue = clanBattleList[0]
getAllBossAttr(clanBattleValue.enemyIdList)
getMultiEnemyAttr(clanBattleValue.targetCountDataList)
}
}
}
/**
* 获取 BOSS 属性
*
* @param enemyIds boss编号列表
*/
private fun getAllBossAttr(enemyIds: List<Int>) {
viewModelScope.launch {
val list = enemyRepository.getEnemyAttrList(enemyIds)
_uiState.update {
it.copy(
bossDataList = list
)
}
}
}
/**
* 获取多目标部位属性
*/
private fun getMultiEnemyAttr(targetCountDataList: List<ClanBattleTargetCountData>) {
viewModelScope.launch {
val map = enemyRepository.getMultiEnemyAttr(targetCountDataList)
_uiState.update {
it.copy(
partEnemyMap = map
)
}
}
}
/**
* 切换选择阶段
*/
fun changeSelect(phaseIndex: Int) {
viewModelScope.launch {
_uiState.update {
it.copy(
phaseIndex = phaseIndex
)
}
reloadData(phaseIndex)
}
}
}
| 0 | Kotlin | 3 | 62 | 7a72025b20aaebc465eb4e1f49d0970161b18e4f | 4,876 | pcr-tool | Apache License 2.0 |
level3/app/src/main/java/com/example/junior/AnimalFragment.kt | Kirill-Pg4 | 673,106,920 | false | null | package com.example.junior
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class AnimalFragment : Fragment() {
private lateinit var animalAdapter: AnimalAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_animal, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
fetchAnimalsData()
}
private fun setupRecyclerView() {
animalAdapter = AnimalAdapter(emptyList())
view?.findViewById<RecyclerView>(R.id.animalRecyclerView)?.apply {
layoutManager = LinearLayoutManager(requireContext())
adapter = animalAdapter
}
}
private fun fetchAnimalsData() {
val retrofit = Retrofit.Builder()
.baseUrl("https://shibe.online/api/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val animalApi = retrofit.create(AnimalApi::class.java)
val call = animalApi.getShibes(count = 10, urls = true, httpsUrls = true)
call.enqueue(object : Callback<List<String>> {
override fun onResponse(call: Call<List<String>>, response: Response<List<String>>) {
if (response.isSuccessful) {
val animals = response.body()
animals?.let {
animalAdapter = AnimalAdapter(it)
view?.findViewById<RecyclerView>(R.id.animalRecyclerView)?.adapter = animalAdapter
}
}
}
override fun onFailure(call: Call<List<String>>, t: Throwable) {
// Handle failure
}
})
}
}
| 0 | Kotlin | 0 | 0 | 721767a5730365112a2e7046ced2cc18b7665bff | 2,235 | Tasks_Android | Apache License 2.0 |
app/src/main/kotlin/io/trewartha/positional/ui/sun/DuskFragment.kt | mtrewartha | 62,930,438 | false | null | package io.trewartha.positional.ui.sun
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.hilt.navigation.fragment.hiltNavGraphViewModels
import dagger.hilt.android.AndroidEntryPoint
import io.trewartha.positional.R
import io.trewartha.positional.databinding.DuskFragmentBinding
@AndroidEntryPoint
class DuskFragment : Fragment() {
private var _viewBinding: DuskFragmentBinding? = null
private val viewBinding get() = _viewBinding!!
private val viewModel: SunViewModel by hiltNavGraphViewModels(R.id.nav_graph)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_viewBinding = DuskFragmentBinding.inflate(inflater, container, false)
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewModel.sunState.observe(viewLifecycleOwner, ::observeSunState)
}
override fun onDestroyView() {
super.onDestroyView()
_viewBinding = null
}
private fun observeSunState(sunState: SunViewModel.SunState) {
with(viewBinding) {
progressIndicator.animate()
.alpha(0f)
.withEndAction { progressIndicator.visibility = View.GONE }
dateTextView.text = sunState.date
astronomicalValueTextView.text = sunState.astronomicalDusk
nauticalValueTextView.text = sunState.nauticalDusk
civilValueTextView.text = sunState.civilDusk
sunsetValueTextView.text = sunState.sunset
}
}
}
| 1 | Kotlin | 2 | 18 | 63f1e5813ae5351459c970f46c1c8dd77f66a8b5 | 1,712 | positional | MIT License |
src/main/java/tech/sirwellington/alchemy/test/hamcrest/HamcrestMatchers.kt | SirWellington | 41,982,466 | false | {"Java": 154368, "Kotlin": 14289} | /*
* Copyright © 2019. <NAME>.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("HamcrestMatchers")
package tech.sirwellington.alchemy.test.hamcrest
import com.natpryce.hamkrest.*
import java.util.Objects
/**
* Fails if the object is not `null`.
* @author SirWellington
*/
val isNull: Matcher<Any?> = Matcher(Objects::isNull)
/**
* Fails if the object is `null`.
*
* @author SirWellington
*/
val notNull: Matcher<Any?> = !isNull
/**
* Fails if the collection is empty and has no elements in it.
*
* @author SirWellington
*/
val notEmpty: Matcher<Collection<Any>?> = present(!isEmpty)
/**
* Fails if the collection is not empty (has elements present).
*
* @author SirWellington
*/
val isNullOrEmpty: Matcher<Collection<Any>?> = isNull.or(isEmpty as Matcher<Collection<Any>?>)
/**
* Fails if the collection is null or empty.
*
* @author SirWellington
*/
val notNullOrEmpty: Matcher<Collection<Any>?> = present(notEmpty)
/**
* Fails if the string is empty or `null`.
*
* @author SirWellington
*/
val emptyString: Matcher<CharSequence?> = notNull and isEmptyString as Matcher<CharSequence?>
/**
* Fails if the string is empty or null.
*
* @author SirWellington
*/
val nonEmptyString: Matcher<CharSequence?> = notNull and !emptyString
val isNullOrEmptyString: Matcher<CharSequence?> = isNull or (isEmptyString as Matcher<CharSequence?>)
val notNullOrEmptyString: Matcher<CharSequence?> = !tech.sirwellington.alchemy.test.hamcrest.isNullOrEmptyString
/**
* Fails if the [Boolean] value is `false`.
*/
val isTrue: Matcher<Boolean?> = notNull and equalTo(true)
/**
* Fails if the [Boolean] value is `true`.
*/
val isFalse: Matcher<Boolean?> = notNull and equalTo(false)
/**
* Fails if the [Collection] does not have a size of [size].
*/
fun hasSize(size: Int): Matcher<Collection<*>?> = Matcher(Collection<*>?::hasSize, size)
private fun Collection<*>?.hasSize(size: Int): Boolean
{
return this?.size == size
}
/**
* Fails if the element is not in the [collection].
*/
fun <T> isContainedIn(collection: Collection<T>) = object : Matcher.Primitive<T?>()
{
override fun invoke(actual: T?) = match(actual in collection) {"${describe(actual)} was not in ${describe(collection)}"}
override val description: String get() = "is in ${describe(collection)}"
override val negatedDescription: String get() = "is not in ${describe(collection)}"
}
private fun match(comparisonResult: Boolean, describeMismatch: () -> String): MatchResult
{
return if (comparisonResult)
{
MatchResult.Match
}
else
{
MatchResult.Mismatch(describeMismatch())
}
} | 0 | Java | 0 | 2 | 4814f1df92652941dbdad558a98680342b391e4b | 3,172 | alchemy-test | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent/day11/Day11.kt | michaelbull | 225,205,583 | false | null | package com.github.michaelbull.advent.day11
import com.github.michaelbull.advent.intcode.Intcode
import com.github.michaelbull.advent.intcode.toIntcode
import kotlinx.coroutines.runBlocking
fun readProgram(): Intcode {
return ClassLoader.getSystemResourceAsStream("day11.txt")
.bufferedReader()
.readLine()
.toIntcode()
}
suspend fun Intcode.part1(): Int {
val robot = Robot()
val hull = Hull()
return robot.paint(hull, this).size
}
suspend fun Intcode.part2(): String {
val robot = Robot()
val hull = Hull()
hull[robot.position] = PanelColor.White
robot.paint(hull, this)
return hull.prettyPrint()
}
fun main() = runBlocking {
val program = readProgram()
println("part 1 = ${program.part1()}")
println("part 2 = \n${program.part2()}")
}
| 0 | Kotlin | 0 | 2 | d271a7c43c863acd411bd1203a93fd10485eade6 | 815 | advent-2019 | ISC License |
app/src/main/java/com/example/androiddevchallenge/data/DogInfo.kt | CaojingCode | 343,275,338 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.data
import androidx.annotation.DrawableRes
import com.example.androiddevchallenge.R
import java.io.Serializable
data class DogInfo(
val name: String = "安琪拉baby", /* 名字 */
val alias: String = "泰迪", /* 别名 */
val breed: String = "贵宾犬", /* 品种 */
val introduce: String = "最常见的是红色(也叫棕色)中小体型的贵宾犬 除此之外还有黑色、灰色、白色等颜色的贵宾犬 其体型也有茶杯体贵宾至巨型贵宾之分 此类犬是小型犬中智商最高者 性格活泼 且最大的优点就是不会像其他汪星人一样大量掉毛 但也正因为如此 它需要定期理毛修毛", /* 介绍 */
@DrawableRes var imageId: Int = R.drawable.ic_launcher_background
) : Serializable
| 0 | Kotlin | 0 | 1 | 10ed9c52c359d3f014873e927e251af6cf325342 | 1,422 | ComposePuppyAdoption | Apache License 2.0 |
src/main/kotlin/me/steven/indrev/blockentities/farms/FisherBlockEntity.kt | ryleu | 570,693,908 | true | {"Kotlin": 991867, "Java": 56861} | package me.steven.indrev.blockentities.farms
import it.unimi.dsi.fastutil.objects.Object2IntArrayMap
import it.unimi.dsi.fastutil.objects.Object2IntMap
import me.steven.indrev.api.machines.Tier
import me.steven.indrev.blockentities.MachineBlockEntity
import me.steven.indrev.blockentities.crafters.EnhancerProvider
import me.steven.indrev.config.BasicMachineConfig
import me.steven.indrev.inventories.inventory
import me.steven.indrev.items.upgrade.Enhancer
import me.steven.indrev.registry.MachineRegistry
import me.steven.indrev.utils.component1
import me.steven.indrev.utils.component2
import me.steven.indrev.utils.toVec3d
import net.minecraft.block.BlockState
import net.minecraft.item.FishingRodItem
import net.minecraft.loot.context.LootContext
import net.minecraft.loot.context.LootContextParameters
import net.minecraft.loot.context.LootContextTypes
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.Identifier
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
class FisherBlockEntity(tier: Tier, pos: BlockPos, state: BlockState)
: MachineBlockEntity<BasicMachineConfig>(tier, MachineRegistry.FISHER_REGISTRY, pos, state), EnhancerProvider {
override val backingMap: Object2IntMap<Enhancer> = Object2IntArrayMap()
override val enhancerSlots: IntArray = intArrayOf(6, 7, 8, 9)
override val availableEnhancers: Array<Enhancer> = Enhancer.DEFAULT
init {
this.inventoryComponent = inventory(this) {
input {
slot = 1
filter { (_, item), _ -> item is FishingRodItem }
}
output { slots = intArrayOf(2, 3, 4, 5) }
}
}
private var cooldown = config.processSpeed
override val maxInput: Double = config.maxInput
override val maxOutput: Double = 0.0
override fun machineTick() {
val upgrades = getEnhancers()
if (!canUse(getEnergyCost())) return
val rodStack = inventoryComponent!!.inventory.getStack(1)
if (rodStack.isEmpty || rodStack.item !is FishingRodItem || !use(getEnergyCost())) return
cooldown += Enhancer.getSpeed(upgrades, this)
if (cooldown < config.processSpeed) return
cooldown = 0.0
Direction.values().forEach { direction ->
val pos = pos.offset(direction)
if (world?.isWater(pos) == true) {
val identifiers = getIdentifiers(tier)
val id = identifiers[world!!.random!!.nextInt(identifiers.size)]
val lootTable = (world as ServerWorld).server.lootManager.getTable(id)
val ctx = LootContext.Builder(world as ServerWorld).random(world!!.random)
.parameter(LootContextParameters.ORIGIN, pos.toVec3d())
.parameter(LootContextParameters.TOOL, rodStack)
.build(LootContextTypes.FISHING)
val loot = lootTable.generateLoot(ctx)
loot.forEach { stack -> inventoryComponent?.inventory?.output(stack) }
rodStack?.apply {
damage++
if (damage >= maxDamage) decrement(1)
}
}
}
}
override fun getEnergyCost(): Double {
val speedEnhancers = (getEnhancers().getInt(Enhancer.SPEED) * 2).coerceAtLeast(1)
return config.energyCost * speedEnhancers
}
private fun getIdentifiers(tier: Tier) = when (tier) {
Tier.MK2 -> arrayOf(FISH_IDENTIFIER)
Tier.MK3 -> arrayOf(FISH_IDENTIFIER, FISH_IDENTIFIER, JUNK_IDENTIFIER, JUNK_IDENTIFIER, TREASURE_IDENTIFIER)
else -> arrayOf(FISH_IDENTIFIER, FISH_IDENTIFIER, FISH_IDENTIFIER, TREASURE_IDENTIFIER)
}
override fun getEnergyCapacity(): Double = Enhancer.getBuffer(this)
override fun getBaseValue(enhancer: Enhancer): Double = when (enhancer) {
Enhancer.SPEED -> 1.0
Enhancer.BUFFER -> config.maxEnergyStored
else -> 0.0
}
override fun getMaxCount(enhancer: Enhancer): Int {
return if (enhancer == Enhancer.SPEED) return 4 else super.getMaxCount(enhancer)
}
companion object {
private val FISH_IDENTIFIER = Identifier("gameplay/fishing/fish")
private val JUNK_IDENTIFIER = Identifier("gameplay/fishing/junk")
private val TREASURE_IDENTIFIER = Identifier("gameplay/fishing/treasure")
}
} | 1 | Kotlin | 0 | 0 | d55cffe07daf5f4beec6375d8a53a9f96430b8bd | 4,389 | Industrial-Revolution | Apache License 2.0 |
src/main/kotlin/org/vorpal/research/kthelper/KtException.kt | AbdullinAM | 239,975,093 | false | {"Kotlin": 74479} | package org.vorpal.research.kthelper
import java.lang.Exception
@Suppress("unused")
open class KtException : Exception {
constructor(message: String) : super(message)
constructor(message: String, inner: Throwable) : super(message, inner)
}
| 0 | Kotlin | 0 | 0 | 82e53c297182981c6ae5dbf0c44a099718668534 | 250 | kt-helper | Apache License 2.0 |
app/src/main/java/com/sbma/linkup/connection/ConnectionViewModel.kt | ericaskari-metropolia | 694,027,591 | false | {"Kotlin": 323836, "HTML": 71958, "TypeScript": 19773, "Dockerfile": 577, "JavaScript": 256} | package com.sbma.linkup.connection
import androidx.lifecycle.ViewModel
import java.util.UUID
class ConnectionViewModel(
private val repository: IConnectionRepository,
) : ViewModel() {
fun allItemsStream(userId: UUID) = repository.getUserItemsStream(userId)
fun getItemStream(id: String) = repository.getItemStream(id)
} | 0 | Kotlin | 1 | 1 | 436d8f46fc76a9d6af2ab5e997dc673d9ee1bf08 | 335 | sbma | MIT License |
app/src/main/java/org/simple/clinic/forgotpin/createnewpin/ForgotPinCreateNewUpdate.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.forgotpin.createnewpin
import com.spotify.mobius.Next
import com.spotify.mobius.Update
import org.simple.clinic.mobius.dispatch
import org.simple.clinic.mobius.next
class ForgotPinCreateNewUpdate : Update<ForgotPinCreateNewModel, ForgotPinCreateNewEvent,
ForgotPinCreateNewEffect> {
override fun update(model: ForgotPinCreateNewModel, event: ForgotPinCreateNewEvent):
Next<ForgotPinCreateNewModel, ForgotPinCreateNewEffect> {
return when (event) {
is LoggedInUserLoaded -> next(model.userLoaded(event.user))
is CurrentFacilityLoaded -> next(model.facilityLoaded(event.facility))
is PinValidated -> pinValidated(model, event)
is ForgotPinCreateNewPinTextChanged -> next(model.pinChanged(event.pin), HideInvalidPinError)
ForgotPinCreateNewPinSubmitClicked -> dispatch(ValidatePin(model.pin))
}
}
private fun pinValidated(
model: ForgotPinCreateNewModel,
event: PinValidated
): Next<ForgotPinCreateNewModel, ForgotPinCreateNewEffect> {
return if (event.isValid)
dispatch(ShowConfirmPinScreen(model.pin!!))
else
dispatch(ShowInvalidPinError)
}
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 1,162 | simple-android | MIT License |
app/src/androidTest/java/com/adammcneilly/toa/MainActivityTest.kt | AdamMc331 | 402,227,056 | false | {"Kotlin": 240361, "Ruby": 1125, "Shell": 692} | package com.adammcneilly.toa
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import com.adammcneilly.toa.login.domain.model.AuthToken
import com.adammcneilly.toa.login.domain.model.RefreshToken
import com.adammcneilly.toa.login.domain.model.Token
import com.adammcneilly.toa.login.domain.repository.TokenRepository
import com.adammcneilly.toa.login.ui.LoginScreen
import com.adammcneilly.toa.tasklist.ui.TaskListScreen
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.inject.Inject
@OptIn(ExperimentalAnimationApi::class)
@HiltAndroidTest
class MainActivityTest {
@get:Rule
val hiltRule = HiltAndroidRule(this)
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Inject
lateinit var tokenRepository: TokenRepository
@Before
fun setUp() {
hiltRule.inject()
}
@Test
fun showLoginWhenNotLoggedIn() {
runBlocking {
// Clearing token simulates being logged out
tokenRepository.clearToken()
}
composeTestRule
.onNodeWithTag(LoginScreen.TEST_TAG)
.assertIsDisplayed()
}
@Test
fun showTaskListWhenLoggedIn() {
runBlocking {
// Storing a token simulates being logged in
tokenRepository.storeToken(
token = Token(
authToken = AuthToken("Test"),
refreshToken = RefreshToken("Test"),
),
)
}
composeTestRule
.onNodeWithTag(TaskListScreen.TEST_TAG)
.assertIsDisplayed()
}
}
| 41 | Kotlin | 18 | 141 | 15e99bbd2a082b7417c8a5253491eb2deab515e8 | 1,931 | TOA | MIT License |
compiler/testData/codegen/box/reflection/call/localClassMember.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM
// WITH_REFLECT
fun box(): String {
class Local {
fun result(s: String) = s
}
return Local::result.call(Local(), "OK")
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 166 | kotlin | Apache License 2.0 |
compiler/tests-spec/testData/psi/linked/expressions/constant-literals/integer-literals/hexadecimal-integer-literals/p-1/neg/1.2.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* KOTLIN PSI SPEC TEST (NEGATIVE)
*
* SPEC VERSION: 0.1-100
* MAIN LINK: expressions, constant-literals, integer-literals, hexadecimal-integer-literals -> paragraph 1 -> sentence 1
* NUMBER: 2
* DESCRIPTION: Hexadecimal integer literals with not allowed symbols.
*/
val value = 0x876L543
val value = 0xf876L543
val value = 0xx1234567890
val value = 0Xx23456789
val value = 0xX345678
val value = 0X45x67
val value = 0X50X6
val value = 0x60x5
val value = 0xXx7654
val value = 0XG
val value = 0xF1z
val value = 0x100M000
val value = 0XXXX1000001
val value = 0x00000010x
val value = 0xABCDEFXX
val value = 0Xabcdefghijklmnopqrstuvwxyz
val value = 0XABCDEFGHIJKLMNOPQRSTUVWXYZ
val value = 0Xа
val value = 0x10С10
val value = 0xeeeeеееее
val value = 0xxxxxxx
val value = 0X0XXXXXX
val value = 0X0x0
val value = 0x$
val value = 0x4$0x100
val value = 0x1val value = 2x^0x10
val value = 0X\n
val value = 0x@0x4
val value = 0x#0x1
val value = 0x!0X10
val value = 0X&0X10
val value = 0X|0X10
val value = 0X)(0X10
val value = 0x^0x10
val value = 0x<0X10>
val value = 0x\0X10
val value = 0X,0X10
val value = 0X:0x10
val value = 0X::0x10
val value = 0X'0x10
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,163 | kotlin | Apache License 2.0 |
app/src/main/java/com/wisnu/kurniawan/composetodolist/runtime/navigation/SearchNavHost.kt | ErasmoDev | 462,574,007 | true | {"Kotlin": 697836} | package com.wisnu.kurniawan.composetodolist.runtime.navigation
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi
import com.wisnu.kurniawan.composetodolist.features.todo.search.ui.SearchScreen
import com.wisnu.kurniawan.composetodolist.features.todo.search.ui.SearchViewModel
@OptIn(ExperimentalMaterialNavigationApi::class)
fun NavGraphBuilder.SearchNavHost(
navController: NavHostController,
) {
navigation(startDestination = SearchFlow.SearchScreen.route, route = SearchFlow.Root.route) {
composable(
route = SearchFlow.SearchScreen.route
) {
val viewModel = hiltViewModel<SearchViewModel>()
SearchScreen(
navController = navController,
viewModel = viewModel
)
}
}
}
| 0 | Kotlin | 0 | 0 | 18cd6f97d3a928230e238d975f12007472bf7685 | 1,048 | Compose-ToDo | Apache License 2.0 |
app/src/main/java/com/dldmswo1209/lunchrecommend/LoginActivitiy.kt | EJLee1209 | 512,658,460 | false | {"Kotlin": 20951} | package com.dldmswo1209.lunchrecommend
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.dldmswo1209.lunchrecommend.databinding.ActivityLoginActivitiyBinding
import com.dldmswo1209.lunchrecommend.databinding.ActivityMainBinding
import com.google.firebase.auth.FirebaseAuth
class LoginActivitiy : AppCompatActivity() {
var mBinding : ActivityLoginActivitiyBinding? = null
val binding get() = mBinding!!
lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityLoginActivitiyBinding.inflate(layoutInflater)
setContentView(binding.root)
auth = FirebaseAuth.getInstance()
onclickButton()
}
private fun onclickButton(){
binding.joinText.setOnClickListener {
startActivity(Intent(this, JoinActivity::class.java))
}
binding.loginButton.setOnClickListener {
auth.signInWithEmailAndPassword(binding.loginEmail.text.toString(), binding.loginPassword.text.toString())
.addOnSuccessListener {
val sharedPreferences = getSharedPreferences("isLogin", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("user_uid", auth.currentUser?.uid.toString())
editor.apply()
startActivity(Intent(this, MainActivity::class.java))
finish()
}
.addOnFailureListener {
Toast.makeText(this, "로그인 실패, 아이디와 비밀번호를 확인하세요.", Toast.LENGTH_SHORT).show()
}
}
}
} | 0 | Kotlin | 0 | 0 | e3892b15a9b44c8c5f280a8606bdafe3d7cbaa60 | 1,904 | LunchRecommendApplication | Apache License 2.0 |
src/main/kotlin/com/luzon/lexer/TokenMachine.kt | ch629 | 137,907,768 | false | {"Kotlin": 114802} | package com.luzon.lexer
import com.luzon.fsm.FiniteStateMachine
import com.luzon.lexer.TokenType.COMMENT
import com.luzon.lexer.TokenType.KEYWORD
import com.luzon.lexer.TokenType.LITERAL
import com.luzon.lexer.TokenType.SYMBOL
object TokenMachine {
private var finiteStateMachine: FiniteStateMachine<Char, Token.TokenEnum>? = null
fun getFSM(): FiniteStateMachine<Char, Token.TokenEnum> {
if (finiteStateMachine == null) finiteStateMachine = FiniteStateMachine.merge(
LITERAL.toFSM(),
KEYWORD.toFSM(),
SYMBOL.toFSM(),
COMMENT.toFSM()
)
return finiteStateMachine!!.copyOriginal()
}
fun clearFSM() {
finiteStateMachine = null
}
}
| 0 | Kotlin | 0 | 0 | b7a9babe867d6ed293a22e66380bfc4de6c492c2 | 733 | luzon | Apache License 2.0 |
modules/views-recyclerview/src/androidMain/kotlin/splitties/views/recyclerview/ListAdapterFactories.kt | LouisCAD | 65,558,914 | false | {"Kotlin": 682428, "Java": 1368, "Shell": 358} | package splitties.views.recyclerview
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import splitties.typesaferecyclerview.ViewHolder
import splitties.views.horizontalMargin
import splitties.views.recyclerview.*
import splitties.views.recyclerview.adapters.LinearListAdapter
import splitties.views.verticalMargin
internal typealias BindViewHolder<V, T> = (
viewHolder: RecyclerView.ViewHolder,
view: V,
item: T
) -> Unit
inline fun <T, VH : RecyclerView.ViewHolder> verticalListAdapter(
itemDiffCallback: DiffUtil.ItemCallback<T>,
horizontalMargin: Int = 0,
verticalMargin: Int = 0,
crossinline createViewHolder: (Context) -> VH,
reverseLayout: Boolean = false,
crossinline bindViewHolder: (viewHolder: VH, item: T) -> Unit
): LinearListAdapter<T, VH> = linearListAdapter(
itemDiffCallback = itemDiffCallback,
layoutManager = verticalLayoutManager(reverseLayout),
horizontalMargin = horizontalMargin,
verticalMargin = verticalMargin,
createViewHolder = createViewHolder,
bindViewHolder = bindViewHolder
)
inline fun <T, VH : RecyclerView.ViewHolder> horizontalListAdapter(
itemDiffCallback: DiffUtil.ItemCallback<T>,
horizontalMargin: Int = 0,
verticalMargin: Int = 0,
crossinline createViewHolder: (Context) -> VH,
reverseLayout: Boolean = false,
crossinline bindViewHolder: (viewHolder: VH, item: T) -> Unit
): LinearListAdapter<T, VH> = linearListAdapter(
itemDiffCallback = itemDiffCallback,
layoutManager = horizontalLayoutManager(reverseLayout),
horizontalMargin = horizontalMargin,
verticalMargin = verticalMargin,
createViewHolder = createViewHolder,
bindViewHolder = bindViewHolder
)
inline fun <T, VH : RecyclerView.ViewHolder> linearListAdapter(
itemDiffCallback: DiffUtil.ItemCallback<T>,
layoutManager: LinearLayoutManager,
horizontalMargin: Int = 0,
verticalMargin: Int = 0,
crossinline createViewHolder: (Context) -> VH,
crossinline bindViewHolder: (viewHolder: VH, item: T) -> Unit
): LinearListAdapter<T, VH> = object : LinearListAdapter<T, VH>(itemDiffCallback, layoutManager) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(parent.context).also {
it.itemView.layoutParams = layoutManager.fullSideListLayoutParams {
this.horizontalMargin = horizontalMargin
this.verticalMargin = verticalMargin
}
}
override fun onBindViewHolder(holder: VH, position: Int) {
bindViewHolder(holder, getItem(position))
}
}
@JvmName("verticalListAdapterWithViews")
inline fun <T, V : View> verticalListAdapter(
itemDiffCallback: DiffUtil.ItemCallback<T>,
horizontalMargin: Int = 0,
verticalMargin: Int = 0,
crossinline createView: (Context) -> V,
reverseLayout: Boolean = false,
crossinline bindViewHolder: BindViewHolder<V, T>
): LinearListAdapter<T, ViewHolder<V>> = linearListAdapter(
itemDiffCallback = itemDiffCallback,
layoutManager = verticalLayoutManager(reverseLayout),
horizontalMargin = horizontalMargin,
verticalMargin = verticalMargin,
createView = createView,
bindViewHolder = bindViewHolder
)
@JvmName("horizontalListAdapterWithViews")
inline fun <T, V : View> horizontalListAdapter(
itemDiffCallback: DiffUtil.ItemCallback<T>,
horizontalMargin: Int = 0,
verticalMargin: Int = 0,
crossinline createView: (Context) -> V,
reverseLayout: Boolean = false,
crossinline bindViewHolder: BindViewHolder<V, T>
): LinearListAdapter<T, ViewHolder<V>> = linearListAdapter(
itemDiffCallback = itemDiffCallback,
layoutManager = horizontalLayoutManager(reverseLayout),
horizontalMargin = horizontalMargin,
verticalMargin = verticalMargin,
createView = createView,
bindViewHolder = bindViewHolder
)
@JvmName("linearListAdapterWithViews")
inline fun <T, V : View> linearListAdapter(
itemDiffCallback: DiffUtil.ItemCallback<T>,
layoutManager: LinearLayoutManager,
horizontalMargin: Int = 0,
verticalMargin: Int = 0,
crossinline createView: (Context) -> V,
crossinline bindViewHolder: BindViewHolder<V, T>
): LinearListAdapter<T, ViewHolder<V>> = object : LinearListAdapter<T, ViewHolder<V>>(itemDiffCallback, layoutManager) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<V> {
return ViewHolder(createView(parent.context)).also {
it.itemView.layoutParams = layoutManager.fullSideListLayoutParams {
this.horizontalMargin = horizontalMargin
this.verticalMargin = verticalMargin
}
}
}
override fun onBindViewHolder(holder: ViewHolder<V>, position: Int) {
bindViewHolder(holder, holder.itemView, getItem(position))
}
}
| 51 | Kotlin | 158 | 2,433 | 1ed56ba2779f31dbf909509c955fce7b9768e208 | 4,992 | Splitties | Apache License 2.0 |
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/dbms/queries/operators/physical/definition/DataDefinitionPhysicalOperatorNode.kt | vitrivr | 160,775,368 | false | {"Kotlin": 2761435, "TypeScript": 98011, "Java": 97672, "HTML": 38965, "ANTLR": 23679, "CSS": 8582, "SCSS": 1690, "JavaScript": 1441, "Dockerfile": 548} | package org.vitrivr.cottontail.dbms.queries.operators.physical.definition
import org.vitrivr.cottontail.core.database.ColumnDef
import org.vitrivr.cottontail.core.queries.GroupId
import org.vitrivr.cottontail.core.queries.binding.Binding
import org.vitrivr.cottontail.core.queries.planning.cost.Cost
import org.vitrivr.cottontail.dbms.queries.context.QueryContext
import org.vitrivr.cottontail.dbms.queries.operators.basics.NullaryPhysicalOperatorNode
import org.vitrivr.cottontail.dbms.statistics.values.ValueStatistics
/**
* An abstract implementation of a [NullaryPhysicalOperatorNode] that is used to execute data definition language statements.
*
* @author <NAME>
* @version 1.0.0
*/
abstract class DataDefinitionPhysicalOperatorNode(override val name: String, val context: QueryContext, columns: List<ColumnDef<*>>): NullaryPhysicalOperatorNode() {
override val statistics: Map<ColumnDef<*>, ValueStatistics<*>> = emptyMap()
override val outputSize: Long = 1
override val groupId: GroupId = 0
override val columns: List<Binding.Column> = columns.map {
this.context.bindings.bind(it, null)
}
override val cost: Cost = Cost.ZERO
override fun canBeExecuted(ctx: QueryContext): Boolean = true
} | 21 | Kotlin | 19 | 28 | ca9ad89993dae6a4c7879ad2ab3ab1b4676b977a | 1,245 | cottontaildb | MIT License |
app/src/main/java/com/liaudev/jetstories/ui/screen/HomeScreen.kt | budiliauw87 | 572,058,629 | false | {"Kotlin": 59473} | package com.liaudev.jetstories.ui.screen
import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import com.liaudev.jetstories.components.StoryItem
import com.liaudev.jetstories.ui.viewmodel.StoryViewModel
/**
* Created by Budiliauw87 on 2022-11-29.
* budiliauw87.github.io
* <EMAIL>
*/
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HomeScreen(
modifier: Modifier,
viewModel: StoryViewModel,
navigateToDetail: (String) -> Unit,
) {
val lazyPagingItems = viewModel.storiesPager.collectAsLazyPagingItems()
val state: LazyListState = rememberLazyListState()
val refreshing = lazyPagingItems.loadState.refresh is LoadState.Loading
val pullRefreshState = rememberPullRefreshState(refreshing, { lazyPagingItems.refresh() })
Box(Modifier.pullRefresh(pullRefreshState)) {
LazyColumn(Modifier.fillMaxSize()) {
items(items = lazyPagingItems) { item ->
item?.let {
StoryItem(it, modifier,navigateToDetail)
}
}
lazyPagingItems.apply {
when {
loadState.refresh is LoadState.Loading -> {
Log.e("HomeScreen","State refresh")
}
loadState.append is LoadState.Loading -> { //loading when loadmore
Log.e("HomeScreen","loading item bottom")
}
loadState.refresh is LoadState.Error -> { // error when refresh
val e = lazyPagingItems.loadState.refresh as LoadState.Error
Log.e("HomeScreen",e.error.localizedMessage!!)
}
loadState.append is LoadState.Error -> { //error when load more
val e = lazyPagingItems.loadState.append as LoadState.Error
Log.e("HomeScreen",e.error.localizedMessage!!)
}
}
}
}
PullRefreshIndicator(refreshing, pullRefreshState, Modifier.align(Alignment.TopCenter))
}
}
| 0 | Kotlin | 0 | 0 | 100550aea6486ca93a79826c874c0455b93e92a9 | 2,769 | JetStoriesApp | Apache License 2.0 |
compiler/testData/asJava/lightClasses/lightClassByPsi/annotationInAnnotationParameters.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FILE: a/A.kt
package a
annotation class A
// FILE: b/B.kt
package b
import a.A
annotation class B(val param: A)
@B(param = A())
class C | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 146 | kotlin | Apache License 2.0 |
flexible-hilt-core/src/main/kotlin/dagger/hilt/flexible/FlexibleHiltUtils.kt | dewantawsif | 720,191,997 | false | {"Kotlin": 9577} | package dagger.hilt.flexible
inline fun <reified T : FlexibleHiltItem> getFromFlexibleHilt(): T {
return FlexibleHilt.getItems()[T::class.java]?.get() as? T
?: error(
"Couldn't find ${T::class.java} in 'FlexibleHiltGraph'. Make sure you have annotated " +
"the base class/interface with [MakeFlexible] and it inherits [FlexibleHiltItem]",
)
}
inline fun <reified T : FlexibleHiltItem> lazyFromFlexibleHilt(): Lazy<T> {
return lazy { getFromFlexibleHilt() }
}
| 0 | Kotlin | 0 | 0 | 7a8d7a475d26654573fe9ed5f0520ce7fe95b1ab | 513 | flexible-hilt | Mozilla Public License 2.0 |
bugsnag-plugin-android-exitinfo/src/test/java/com/bugsnag/android/TraceParserJavaStackframeTest.kt | bugsnag | 2,406,783 | false | {"Kotlin": 990225, "Java": 488572, "C": 454938, "Gherkin": 173861, "C++": 59962, "Ruby": 25810, "CMake": 5144, "Shell": 3323, "Makefile": 3222} | package com.bugsnag.android
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameter
import org.junit.runners.Parameterized.Parameters
import org.mockito.Mockito.mock
@RunWith(Parameterized::class)
class TraceParserJavaStackframeTest {
companion object {
@JvmStatic
@get:Parameters
val stackTraces
get() = listOf(
"at java.lang.Object.wait(Object.java:442)" to
Stackframe("java.lang.Object.wait", "Object.java", 442, null),
"at java.lang.Object.wait(Native method)" to
Stackframe("java.lang.Object.wait", "Native method", null, null),
"at com.example.bugsnag.android.BaseCrashyActivity.\$r8\$lambda\$1-82lPEn83zsSIVw12fUel9TE6s(unavailable:0)" to
Stackframe(
"com.example.bugsnag.android.BaseCrashyActivity.\$r8\$lambda\$1-82lPEn83zsSIVw12fUel9TE6s",
"unavailable",
0,
null
),
"at com.android.internal.os.RuntimeInit\$MethodAndArgsCaller.run(RuntimeInit.java:548)" to
Stackframe(
"com.android.internal.os.RuntimeInit\$MethodAndArgsCaller.run",
"RuntimeInit.java",
548,
null
),
)
}
private val traceParser = TraceParser(mock(Logger::class.java), emptySet())
@Parameter
lateinit var stackFrame: Pair<String, Stackframe>
@Test
fun testJavaFrame() {
val (line, expectedFrame) = stackFrame
val parsedFrame = traceParser.parseJavaFrame(line)
assertNotNull(parsedFrame)
assertEquals(expectedFrame.method, parsedFrame!!.method)
assertEquals(expectedFrame.file, parsedFrame.file)
assertEquals(expectedFrame.lineNumber, parsedFrame.lineNumber)
assertNull("inProject should be considered unknown", expectedFrame.inProject)
assertNull("no 'code' should be associated", expectedFrame.code)
assertNull("no columnNumber should be parsed", expectedFrame.columnNumber)
}
}
| 17 | Kotlin | 215 | 1,158 | cb0fa7c87fb6178b67a6df3d398e497ece1299a5 | 2,386 | bugsnag-android | MIT License |
app/src/main/java/com/sazib/pinboard/data/network/ApiHeader.kt | sazibislam | 200,559,159 | false | null | package com.sazib.pinboard.data.network
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.sazib.pinboard.di.AppKey
import com.sazib.pinboard.di.PackageName
import com.sazib.pinboard.di.VersionName
import javax.inject.Inject
class ApiHeader @Inject constructor(internal val authApiHeader: AuthApiHeader) {
data class AuthApiHeader @Inject constructor(
@AppKey @Expose @SerializedName("app_key") val _app_key: String,
@PackageName @Expose @SerializedName("package") val _package: String,
@VersionName @Expose @SerializedName("version") val _version: String
)
} | 0 | Kotlin | 0 | 0 | e6bf2d3c97c7fadcbd7acf9e422b47165f990ac0 | 630 | pin_board | Apache License 2.0 |
src/backend/common/common-auth/common-auth-sample/src/main/kotlin/com/tencent/devops/common/auth/AuthAutoConfiguration.kt | ffrankfeng | 246,024,266 | true | {"Kotlin": 5571771, "Vue": 2068319, "JavaScript": 700674, "CSS": 385435, "Go": 118041, "TSQL": 117834, "Lua": 111719, "Shell": 81621, "Java": 68498, "TypeScript": 30151, "HTML": 17924, "Batchfile": 2734} | /*
* Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
*
* A copy of the MIT License is included in this file.
*
*
* Terms of the MIT License:
* ---------------------------------------------------
* 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.tencent.devops.common.auth
import com.tencent.devops.common.auth.api.MockAuthPermissionApi
import com.tencent.devops.common.auth.api.MockAuthProjectApi
import com.tencent.devops.common.auth.api.MockAuthResourceApi
import com.tencent.devops.common.auth.api.MockAuthTokenApi
import com.tencent.devops.common.auth.code.BkBcsAuthServiceCode
import com.tencent.devops.common.auth.code.BkCodeAuthServiceCode
import com.tencent.devops.common.auth.code.BkEnvironmentAuthServiceCode
import com.tencent.devops.common.auth.code.BkPipelineAuthServiceCode
import com.tencent.devops.common.auth.code.BkProjectAuthServiceCode
import com.tencent.devops.common.auth.code.BkRepoAuthServiceCode
import com.tencent.devops.common.auth.code.BkTicketAuthServiceCode
import org.springframework.boot.autoconfigure.AutoConfigureOrder
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.core.Ordered
@Configuration
@ConditionalOnWebApplication
@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
class AuthAutoConfiguration {
@Bean
@Primary
fun authTokenApi() = MockAuthTokenApi()
@Bean
@Primary
fun authPermissionApi() = MockAuthPermissionApi()
@Bean
@Primary
fun authResourceApi(authTokenApi: MockAuthTokenApi) = MockAuthResourceApi()
@Bean
@Primary
fun authProjectApi(bkAuthPermissionApi: MockAuthPermissionApi) = MockAuthProjectApi(bkAuthPermissionApi)
@Bean
fun bcsAuthServiceCode() = BkBcsAuthServiceCode()
@Bean
fun pipelineAuthServiceCode() = BkPipelineAuthServiceCode()
@Bean
fun codeAuthServiceCode() = BkCodeAuthServiceCode()
@Bean
fun projectAuthServiceCode() = BkProjectAuthServiceCode()
@Bean
fun environmentAuthServiceCode() = BkEnvironmentAuthServiceCode()
@Bean
fun repoAuthServiceCode() = BkRepoAuthServiceCode()
@Bean
fun ticketAuthServiceCode() = BkTicketAuthServiceCode()
} | 4 | Kotlin | 0 | 1 | cf5b49b17525befe6d3f84ffaafa0526eea74821 | 3,594 | bk-ci | MIT License |
core/sfc-core/src/test/kotlin/com/amazonaws/sfc/transformations/InvalidTransformationOperatorTest.kt | aws-samples | 700,380,828 | false | {"Kotlin": 2245850, "Python": 6111, "Dockerfile": 4679, "TypeScript": 4547, "JavaScript": 1171} |
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
package com.amazonaws.sfc.transformations
import com.amazonaws.sfc.config.ConfigurationException
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class InvalidTransformationOperatorTest {
private val operatorName = "Operator"
private val message = "Message"
private val item = "Item"
@Test
fun `can create instance with default operator name`() {
val op = InvalidTransformationOperator(message = message, item = item)
assertEquals("", op.operatorName)
assertEquals(item, op.item)
assertEquals(message, op.message)
}
@Test
fun `validate should throw exception`() {
assertThrows(ConfigurationException::class.java) {
InvalidTransformationOperator(operatorName = "", message = message, item = item).validate()
}
assertThrows(ConfigurationException::class.java) {
InvalidTransformationOperator(operatorName = operatorName, message = message, item = item).validate()
}
}
@Test
fun `test toString`() {
val operatorName = "Operator"
val message = "Message"
val item = "Item"
val op = InvalidTransformationOperator(operatorName = operatorName, message = message, item = item)
assertEquals("InvalidTransformationOperator(operatorName=$operatorName, message='$message)", op.toString())
}
@Test
fun `validate is always false`() {
val op = InvalidTransformationOperator(operatorName = operatorName, message = message, item = item)
assertFalse(op.validated)
try {
op.validate()
} catch (_: ConfigurationException) {
assertFalse(op.validated)
}
}
@Test
fun `invoke always returns null`() {
val op = InvalidTransformationOperator(operatorName = operatorName, message = message, item = item)
assertNull(op.invoke(""))
}
@Test
fun `input and result types are always Nothing`() {
val op = InvalidTransformationOperator(operatorName = operatorName, message = message, item = item)
assertEquals(Nothing::class.java, op.inputType)
assertEquals(Nothing::class.java, op.resultType)
}
} | 5 | Kotlin | 2 | 15 | fd38dbb80bf6be06c00261d9992351cc8a103a63 | 2,326 | shopfloor-connectivity | MIT No Attribution |
app/src/main/java/com/agenda/up/viewmodel/criartarefa/CriarTarefaViewModel.kt | Araujo-Alisson | 596,383,449 | false | null | package com.agenda.up.viewmodel.criartarefa
import android.content.Context
import androidx.lifecycle.ViewModel
import com.agenda.up.repositorio.CriarTarefaRepositorio
class CriarTarefaViewModel(private val repositorio: CriarTarefaRepositorio) : ViewModel() {
fun salvarTarefa(
ano: String, mes: String, dia: String, txtHrs: String, txtMin: String, editTitulo: String,
editDescricao1: String, editDetalhes1: String, prioridadeSalva: Int, context: Context
) {
repositorio.salvarTarefa(
ano,
mes,
dia,
txtHrs,
txtMin,
editTitulo,
editDescricao1,
editDetalhes1,
prioridadeSalva,
context
)
}
} | 1 | Kotlin | 0 | 0 | 1a74801e3a82982d024fb85defa664396ade2eb9 | 755 | Up | Apache License 2.0 |
app/app/src/main/java/com/weather/app/activity/MainActivity.kt | AndrewMalitchuk | 263,031,630 | false | null | package com.weather.app.activity
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.dynamitechetan.flowinggradient.FlowingGradientClass
import com.google.android.material.snackbar.Snackbar
import com.vivekkaushik.datepicker.OnDateSelectedListener
import com.weather.app.R
import com.weather.app.adapter.WeatherForDayAdapter
import com.weather.app.entity.detail.WeatherDetail
import com.weather.app.entity.detail.WeatherList
import com.weather.app.entity.summary.WeatherSummary
import com.weather.app.network.APIClient
import com.weather.app.network.APIInterface
import im.dacer.androidcharts.LineView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : AppCompatActivity() {
val TAG = "MainActivity"
val APP_PREFERENCES = "weather"
val APP_PREFERENCES_CITY = "city"
val APP_PREFERENCES_LAT = "lat"
val APP_PREFERENCES_LON = "lon"
lateinit var pref: SharedPreferences
private val list: ArrayList<WeatherList> = ArrayList<WeatherList>()
private val adapter: WeatherForDayAdapter = WeatherForDayAdapter(list)
lateinit var city: String
var lat: Float = (-1.0).toFloat()
var lon: Float = (-1.0).toFloat()
var isCityMode = false
var count = 0
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Set Toolbar
setSupportActionBar(toolbar)
// Set background
FlowingGradientClass()
.setBackgroundResource(R.drawable.translate)
.onLinearLayout(mainLayout)
.setTransitionDuration(4000)
.start()
refresh.isRefreshing = true
pref = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
if (pref.contains(APP_PREFERENCES_CITY)) {
city = pref.getString(APP_PREFERENCES_CITY, null).toString();
isCityMode = true
setContent(city)
} else if (pref.contains(APP_PREFERENCES_LAT) && pref.contains(APP_PREFERENCES_LON)) {
lat = pref.getFloat(APP_PREFERENCES_LAT, -1.0.toFloat());
lon = pref.getFloat(APP_PREFERENCES_LON, -1.0.toFloat());
isCityMode = false
setContent(lat, lon)
}else{
startActivity(Intent(applicationContext, LocationActivity::class.java))
}
refresh.setOnRefreshListener {
if (isCityMode) {
setContent(city)
} else {
setContent(lat, lon)
}
}
val date: LocalDateTime
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
date = LocalDateTime.now()
datePickerTimeline.setInitialDate(
date.getYear(),
date.getMonthValue() - 1,
date.getDayOfMonth()
)
}
datePickerTimeline.setOnDateSelectedListener(object : OnDateSelectedListener {
override fun onDateSelected(year: Int, month: Int, day: Int, dayOfWeek: Int) {
val date = Date()
date.year = year - 1900
date.month = month
date.date = day
refresh.isRefreshing = true
val formated = SimpleDateFormat("dd.MM.yyyy").format(date)
var res = APIClient.client?.create(APIInterface::class.java)
var content: Observable<WeatherDetail>
if (isCityMode) {
content = res?.getDetail(city, APIClient.appid, "metric")!!
} else {
content = res?.getDetail(lat, lon, APIClient.appid, "metric")!!
}
content?.observeOn(AndroidSchedulers.mainThread())
?.subscribeOn(Schedulers.io())
?.doOnComplete {
chartWeatherCard.visibility = View.VISIBLE
refresh.isRefreshing = false
adapter.notifyDataSetChanged()
}
?.subscribe({
setWeatherForDate(it, formated)
}, {
Snackbar.make(
refresh,
resources.getText(R.string.network_error),
Snackbar.LENGTH_LONG
)
.show()
})
adapter.notifyDataSetChanged()
}
override fun onDisabledDateSelected(
year: Int,
month: Int,
day: Int,
dayOfWeek: Int,
isDisabled: Boolean
) {
}
})
weatherIcon.setOnClickListener {
count++
if (count == 10) {
Toast.makeText(this@MainActivity, R.string.easter, Toast.LENGTH_LONG).show()
count = 0
}
}
}
private fun setWeatherForDate(content: WeatherDetail, currentDate: String) {
recyclerView.apply {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = WeatherForDayAdapter(list)
}
list.clear()
var counter = 0
for (weatherItem in content.list) {
val date =
SimpleDateFormat("dd.MM.yyyy").format(Date(weatherItem.dt.toLong() * 1000))
if (date.equals(currentDate)) {
list.add(weatherItem)
counter++
}
}
if (counter == 0) {
Snackbar.make(
refresh,
resources.getText(R.string.no_data),
Snackbar.LENGTH_LONG
)
.show()
detailWeatherCard.visibility = View.GONE
} else {
detailWeatherCard.visibility = View.VISIBLE
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun setContent(city: String) {
refresh.isRefreshing = true
var res = APIClient.client?.create(APIInterface::class.java)
res?.getSummary(city, APIClient.appid, "metric")
?.observeOn(AndroidSchedulers.mainThread())
?.subscribeOn(Schedulers.io())
?.doOnComplete {
chartWeatherCard.visibility = View.VISIBLE
}
?.subscribe({
setSummaryContent(it)
}, {
Snackbar.make(
refresh,
resources.getText(R.string.network_error),
Snackbar.LENGTH_LONG
)
.show()
})
res?.getDetail(city, APIClient.appid, "metric")
?.observeOn(AndroidSchedulers.mainThread())
?.subscribeOn(Schedulers.io())
?.doOnComplete {
chartWeatherCard.visibility = View.VISIBLE
refresh.isRefreshing = false
}
?.subscribe({
setDetailContent(it.list)
setWeatherForDate(
it,
DateTimeFormatter.ofPattern("dd.MM.yyyy").format(LocalDateTime.now())
)
}, {
Snackbar.make(
refresh,
resources.getText(R.string.network_error),
Snackbar.LENGTH_LONG
)
.show()
})
}
@RequiresApi(Build.VERSION_CODES.O)
private fun setContent(lat: Float, lon: Float) {
refresh.isRefreshing = true
var res = APIClient.client?.create(APIInterface::class.java)
res?.getSummary(lat, lon, APIClient.appid, "metric")
?.observeOn(AndroidSchedulers.mainThread())
?.subscribeOn(Schedulers.io())
?.doOnComplete {
chartWeatherCard.visibility = View.VISIBLE
}
?.subscribe({
setSummaryContent(it)
}, {
Snackbar.make(
refresh,
resources.getText(R.string.network_error),
Snackbar.LENGTH_LONG
)
.show()
})
res?.getDetail(lat, lon, APIClient.appid, "metric")
?.observeOn(AndroidSchedulers.mainThread())
?.subscribeOn(Schedulers.io())
?.doOnComplete {
chartWeatherCard.visibility = View.VISIBLE
refresh.isRefreshing = false
}
?.subscribe({
setDetailContent(it.list)
setWeatherForDate(
it,
DateTimeFormatter.ofPattern("dd.MM.yyyy").format(LocalDateTime.now())
)
}, {
Snackbar.make(
refresh,
resources.getText(R.string.network_error),
Snackbar.LENGTH_LONG
)
.show()
})
}
private fun setSummaryContent(content: WeatherSummary) {
toolbar.title = content.name
weatherStatus.text = content.weather[0].main
weatherDescription.text = "(" + content.weather[0].description + ")"
weatherTemp.setText("\uD83C\uDF21️ " + content.main.temp + " °С")
weatherWind.setText("\uD83D\uDCA8 " + content.wind.speed + " m/s")
tempMax.text = "⬆️ " + content.main.temp_max + " °С"
tempMin.text = "⬇️ " + content.main.temp_min + " °С"
val weatherId = content.weather[0].id
if (weatherId >= 200 && weatherId <= 232) {
weatherIcon.setImageResource(R.drawable.thunderstorm)
} else if (weatherId >= 300 && weatherId <= 321) {
weatherIcon.setImageResource(R.drawable.shower_rain)
} else if (weatherId >= 500 && weatherId <= 531) {
weatherIcon.setImageResource(R.drawable.rain)
} else if (weatherId >= 600 && weatherId <= 622) {
weatherIcon.setImageResource(R.drawable.snow)
} else if (weatherId >= 701 && weatherId <= 781) {
weatherIcon.setImageResource(R.drawable.mist)
} else if (weatherId == 800) {
weatherIcon.setImageResource(R.drawable.clear_sky)
} else if (weatherId >= 801 && weatherId <= 804) {
weatherIcon.setImageResource(R.drawable.broken_clouds)
}
refresh.isRefreshing = false
mainWeatherCard.visibility = View.VISIBLE
calendarWeatherCard.visibility = View.VISIBLE
detailWeatherCard.visibility = View.VISIBLE
chartWeatherCard.visibility = View.VISIBLE
info.visibility = View.VISIBLE
}
private fun setDetailContent(content: List<WeatherList>) {
val axisX = ArrayList<String>()
val axisY = ArrayList<Float>()
for (weatherItem in content) {
axisX.add(SimpleDateFormat("HH:mm (dd.MM)").format(Date(weatherItem.dt.toLong() * 1000)))
axisY.add(weatherItem.main.temp.toFloat())
}
val dataLists: ArrayList<ArrayList<Float>> = ArrayList()
dataLists.add(axisY)
lineView.setBottomTextList(axisX)
lineView.setColorArray(
intArrayOf(
R.color.black
)
)
lineView.setDrawDotLine(true)
lineView.setShowPopup(LineView.SHOW_POPUPS_MAXMIN_ONLY)
lineView.setFloatDataList(dataLists)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_change_city -> {
startActivity(Intent(applicationContext, LocationActivity::class.java))
}
}
return super.onOptionsItemSelected(item)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return super.onCreateOptionsMenu(menu)
}
} | 0 | Kotlin | 0 | 0 | 5921b8b4c8cbde81294cd65b94deaa12af38d166 | 12,525 | yet-another-weather-app | Apache License 2.0 |
domain/src/main/java/tin/thurein/domain/repositories/JobRepository.kt | ThuReinTin | 234,569,820 | false | null | package tin.thurein.domain.repositories
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
import tin.thurein.domain.models.Job
interface JobRepository {
fun getRemoteJobs(): Observable<List<Job>>
fun getLocalJobs(): Flowable<List<Job>>
fun getLocalJobsByIsAccepted(isAccepted: Boolean): Flowable<List<Job>>
fun saveLocalJobs(jobs: List<Job>): List<Long>
fun deleteAll(): Int
fun updateJob(job: Job): Single<Int>
} | 0 | Kotlin | 0 | 0 | 9fd5671ef2f18846624153c14fef5b053a2cc1e7 | 507 | haulio-test | MIT License |
intellij.tools.ide.starter/src/com/intellij/ide/starter/ci/teamcity/TeamCityCIServer.kt | JetBrains | 499,194,001 | false | {"Kotlin": 426021, "C++": 3610, "Makefile": 713} | package com.intellij.ide.starter.ci.teamcity
import com.intellij.ide.starter.ci.CIServer
import com.intellij.ide.starter.di.di
import com.intellij.tools.ide.util.common.logOutput
import org.kodein.di.direct
import org.kodein.di.instance
import java.net.URI
import java.nio.file.Path
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import kotlin.io.path.Path
import kotlin.io.path.bufferedReader
import kotlin.math.min
fun CIServer.asTeamCity(): TeamCityCIServer = this as TeamCityCIServer
open class TeamCityCIServer(
private val systemPropertiesFilePath: Path? = try {
Path(System.getenv("TEAMCITY_BUILD_PROPERTIES_FILE"))
}
catch (_: Exception) {
null
}
) : CIServer {
override fun publishArtifact(source: Path, artifactPath: String, artifactName: String) {
TeamCityClient.publishTeamCityArtifacts(source = source, artifactPath = artifactPath, artifactName = artifactName)
}
fun reportTest(testName: String, message: String, details: String, isFailure: Boolean) {
val flowId = UUID.randomUUID().toString()
val generifiedTestName = testName.processStringForTC()
logOutput(String.format("##teamcity[testStarted name='%s' flowId='%s' nodeId='%s' parentNodeId='0']", generifiedTestName, flowId, generifiedTestName))
if (isFailure) {
logOutput(String.format(
"##teamcity[testFailed name='%s' message='%s' details='%s' flowId='%s' nodeId='%s' parentNodeId='0']",
generifiedTestName, message.processStringForTC(), details.processStringForTC(), flowId, generifiedTestName
))
}
logOutput(String.format("##teamcity[testFinished name='%s' flowId='%s' nodeId='%s' parentNodeId='0']", generifiedTestName, flowId, generifiedTestName))
}
override fun reportTestFailure(testName: String, message: String, details: String) {
reportTest(testName, message, details, isFailure = true)
}
fun reportPassedTest(testName: String, message: String, details: String) {
reportTest(testName, message, details, isFailure = false)
}
override fun ignoreTestFailure(testName: String, message: String, details: String) {
val flowId = UUID.randomUUID().toString()
val generifiedTestName = testName.processStringForTC()
logOutput(String.format(
"##teamcity[testIgnored name='%s' message='%s' details='%s' flowId='%s']",
generifiedTestName, message.processStringForTC(), details.processStringForTC(), flowId
))
}
override fun isTestFailureShouldBeIgnored(message: String): Boolean {
listOfPatternsWhichShouldBeIgnored.forEach { pattern ->
if (pattern.containsMatchIn(message)) {
return true
}
}
return false
}
val buildStartTime: String by lazy {
if(buildId == LOCAL_RUN_ID) {
ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME)
} else {
val fullUrl = TeamCityClient.guestAuthUri.resolve("builds/id:${buildId}?fields=startDate")
TeamCityClient.get(fullUrl).fields().asSequence().firstOrNull { it.key == "startDate" }?.value?.asText()?.let {
runCatching {
ZonedDateTime.parse(it, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX")).format(DateTimeFormatter.RFC_1123_DATE_TIME)
}.getOrNull()
}
?: ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME)
}
}
private val listOfPatternsWhichShouldBeIgnored by lazy {
val ignoredPattern = System.getenv("IGNORED_TEST_FAILURE_PATTERN")
val patterns = mutableListOf(
"No files have been downloaded for .+:.+".toRegex(),
"Library '.+' resolution failed".toRegex(),
"Too many IDE internal errors. Monitoring stopped.".toRegex(),
"Invalid folding descriptor detected".toRegex()
)
if (ignoredPattern != null && ignoredPattern.isNotBlank()) {
logOutput("Add $ignoredPattern ignored pattern from env")
patterns.add(ignoredPattern.toRegex())
}
patterns
}
private fun loadProperties(propertiesPath: Path): Map<String, String> =
try {
propertiesPath.bufferedReader().use {
val map = mutableMapOf<String, String>()
val ps = Properties()
ps.load(it)
ps.forEach { k, v ->
if (k != null && v != null) {
map[k.toString()] = v.toString()
}
}
map
}
}
catch (t: Throwable) {
emptyMap()
}
private val systemProperties by lazy {
val props = mutableMapOf<String, String>()
systemPropertiesFilePath?.let { props.putAll(loadProperties(it)) }
props.putAll(System.getProperties().map { it.key.toString() to it.value.toString() })
props
}
/**
* @return String or Null if parameters isn't found
*/
private fun getBuildParam(name: String, impreciseNameMatch: Boolean = false): String? {
val totalParams = systemProperties.plus(buildParams)
val paramValue = if (impreciseNameMatch) {
val paramCandidates = totalParams.filter { it.key.contains(name) }
if (paramCandidates.size > 1) System.err.println("Found many parameters matching $name. Candidates: $paramCandidates")
paramCandidates[paramCandidates.toSortedMap().firstKey()]
}
else totalParams[name]
return paramValue
}
override val isBuildRunningOnCI = System.getenv("TEAMCITY_VERSION") != null
override val buildNumber by lazy { System.getenv("BUILD_NUMBER") ?: "" }
override val branchName by lazy { buildParams["teamcity.build.branch"] ?: "" }
val configurationName by lazy { getBuildParam("teamcity.buildConfName") }
val buildVcsNumber by lazy {getBuildParam("build.vcs.number") ?: "Unknown"}
val buildConfigName: String? by lazy {getBuildParam("teamcity.buildConfName")}
override val buildParams by lazy {
val configurationPropertiesFile = systemProperties["teamcity.configuration.properties.file"]
if (configurationPropertiesFile.isNullOrBlank()) return@lazy emptyMap()
loadProperties(Path(configurationPropertiesFile))
}
/** Root URI of the server */
val serverUri: URI by lazy {
return@lazy di.direct.instance<URI>(tag = "teamcity.uri")
}
val userName: String by lazy { getBuildParam("teamcity.auth.userId")!! }
val password: String by lazy { getBuildParam("teamcity.auth.password")!! }
private val isDefaultBranch by lazy {
//see https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html#PredefinedBuildParameters-Branch-RelatedParameters
hasBooleanProperty("teamcity.build.branch.is_default", default = false)
}
val isPersonalBuild by lazy {
getBuildParam("build.is.personal").equals("true", ignoreCase = true)
}
val buildId: String by lazy {
getBuildParam("teamcity.build.id") ?: LOCAL_RUN_ID
}
val teamcityAgentName by lazy { getBuildParam("teamcity.agent.name") }
val teamcityCloudProfile by lazy { getBuildParam("system.cloud.profile_id") }
val buildTypeId: String? by lazy { getBuildParam("teamcity.buildType.id") }
fun buildUrl(): String = "$serverUri/buildConfiguration/$buildTypeId/$buildId?buildTab=tests"
val isSpecialBuild: Boolean
get() {
if (!isBuildRunningOnCI) {
logOutput("[Metrics Publishing] Not running build on TeamCity => DISABLED")
return true
}
if (isPersonalBuild) {
logOutput("[Metrics Publishing] Personal builds are ignored => DISABLED")
return true
}
if (!isDefaultBranch) {
logOutput("[Metrics Publishing] Non default branches builds are ignored => DISABLED")
return true
}
return false
}
private fun hasBooleanProperty(key: String, default: Boolean) = getBuildParam(key)?.equals("true", ignoreCase = true) ?: default
fun isSafePush(): Boolean {
val isSafePush = System.getenv("SAFE_PUSH")
return (isSafePush != null && isSafePush == "true")
}
companion object {
const val LOCAL_RUN_ID = "LOCAL_RUN_SNAPSHOT"
fun String.processStringForTC(): String {
return this.substring(0, min(7000, this.length))
.replace("\\|", "||")
.replace("\\[", "|[")
.replace("]", "|]")
.replace("\n", "|n")
.replace("'", "|'")
.replace("\r", "|r")
}
fun setStatusTextPrefix(text: String) {
logOutput(" ##teamcity[buildStatus text='$text {build.status.text}'] ")
}
fun reportTeamCityStatistics(key: String, value: Int) {
logOutput(" ##teamcity[buildStatisticValue key='${key}' value='${value}']")
}
fun reportTeamCityStatistics(key: String, value: Long) {
logOutput(" ##teamcity[buildStatisticValue key='${key}' value='${value}']")
}
fun reportTeamCityMessage(text: String) {
logOutput(" ##teamcity[message text='$text']")
}
fun testSuiteStarted(suiteName: String, flowId: String) {
println("##teamcity[testSuiteStarted name='${suiteName.processStringForTC()}' flowId='$flowId']")
}
fun testSuiteFinished(suiteName: String, flowId: String) {
println("##teamcity[testSuiteFinished name='${suiteName.processStringForTC()}' flowId='$flowId']")
}
fun testStarted(testName: String, flowId: String) {
println("##teamcity[testStarted name='${testName.processStringForTC()}' flowId='$flowId']")
}
fun testFinished(testName: String, flowId: String) {
println("##teamcity[testFinished name='${testName.processStringForTC()}' flowId='$flowId']")
}
fun testIgnored(testName: String, message: String, flowId: String) {
println("##teamcity[testIgnored name='${testName.processStringForTC()}' message='${message.processStringForTC()}' flowId='$flowId']")
}
fun testFailed(testName: String, message: String, flowId: String) {
println("##teamcity[testFailed name='${testName.processStringForTC()}' message='${message.processStringForTC()}' flowId='$flowId']")
}
fun addTextMetadata(testName: String, value: String, flowId: String) {
addTestMetadata(testName, TeamCityMetadataType.TEXT, flowId, null, value)
}
fun addTestMetadata(testName: String, type: TeamCityMetadataType, flowId: String, name: String?, value: String) {
val nameAttr = if(name != null) { "name='${name.processStringForTC()}'" } else ""
println("##teamcity[testMetadata testName='${testName.processStringForTC()}' type='${type.name.lowercase()}' ${nameAttr} value='${value.processStringForTC()}' flowId='$flowId']")
}
}
enum class TeamCityMetadataType {
NUMBER,
TEXT,
LINK,
ARTIFACT,
IMAGE
}
} | 0 | Kotlin | 2 | 8 | 79dad83d28351750817d8e0c49ec516941b7c248 | 10,469 | intellij-ide-starter | Apache License 2.0 |
app/src/main/java/com/reza/rezagithub/MainActivity.kt | rezakhmf | 150,864,056 | false | null | package com.reza.rezagithub
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import butterknife.BindView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.DrawableTransformation
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.reza.rezagithub.base.BaseActivity
import com.reza.rezagithub.viewmodel.UserViewModel
class MainActivity : BaseActivity() {
@BindView(R.id.activity_main_avatar) lateinit var imageViewAvator: ImageView
@BindView(R.id.activity_root_view) lateinit var swipeRefreshLayout: SwipeRefreshLayout
@BindView(R.id.activity_main_name) lateinit var textViewName: TextView
@BindView(R.id.activity_main_company) lateinit var textViewCompany: TextView
@BindView(R.id.activity_main_blog) lateinit var textViewBlog: TextView
private lateinit var viewModel: UserViewModel
override fun getLayoutById(): Int = R.layout.activity_main
override fun configureDesign() {
this.configureRefreshLayout()
this.configureViewModel()
this.observeData()
this.fetchUserOnGithubApi()
}
private fun configureRefreshLayout() {
this.swipeRefreshLayout.setOnRefreshListener { this.fetchUserOnGithubApi() }
}
private fun configureViewModel() {
this.viewModel = ViewModelProviders.of(this, viewModelFactory)[UserViewModel::class.java]
}
private fun observeData() {
this.viewModel.user
.observe(this, Observer { it?.let { this.updateUI(it) } })
this.viewModel.isLoading
.observe(this, Observer { it?.let { this.updateRefreshLayout(it)} })
this.viewModel.errorMessage
.observe(this, Observer { it?.let { Log.e("TAG", "Throw an error : $it") } })
}
private fun fetchUserOnGithubApi() {
this.viewModel.getUser()
}
private fun updateUI(user: User) {
this.textViewName.text = user.name
this.textViewCompany.text = user.compnay
this.textViewBlog.text = user.blog
Glide.with(this).load(user.avatarUrl).apply(RequestOptions().circleCrop()).transition(DrawableTransitionOptions.withCrossFade()).into(this.imageViewAvator)
}
private fun updateRefreshLayout(isRefreshing: Boolean) {
this.swipeRefreshLayout.isRefreshing = isRefreshing
}
}
| 0 | Kotlin | 0 | 0 | 0bfcdb7d39822d376d7e4fcae8575ba89a4c7783 | 2,642 | rezagithub | MIT License |
library/src/test/java/renetik/android/core/logging/CSAndroidLoggerTest.kt | renetik | 506,035,450 | false | {"Kotlin": 155505} | package renetik.android.core.logging
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import renetik.android.core.kotlin.primitives.leaveEndOfLength
import renetik.android.core.logging.CSLog.init
import renetik.android.core.logging.CSLog.logDebug
import renetik.android.core.logging.CSLog.logInfo
import renetik.android.core.logging.CSLog.logWarn
import renetik.android.core.logging.CSLogLevel.*
@RunWith(RobolectricTestRunner::class)
class CSAndroidLoggerTest {
private var event: CSLogLevel? = null
private var message: String? = null
private val listener = { event: CSLogLevel, message: String, _: Throwable? ->
this.event = event
this.message = message
}
@Test
fun logWithListener() {
init(CSAndroidLogger(tag = "TestLog", level = Debug, listener))
logWarn { "test" }
assertEquals(Warn, event)
val messageEnd =
"renetik.android.core.logging.CSAndroidLoggerTest\$logWithListener(CSAndroidLoggerTest.kt:27) test"
assertTrue(message!!.endsWith(messageEnd))
}
@Test
fun logEmpty() {
init(CSAndroidLogger(tag = "TestLog", level = Debug, listener))
logInfo()
assertEquals(Info, event)
val messageEnd =
"renetik.android.core.logging.CSAndroidLoggerTest\$logEmpty(CSAndroidLoggerTest.kt:37)"
assertEquals(messageEnd, message?.leaveEndOfLength(messageEnd.length))
}
@Test
fun isDebug() {
init(CSAndroidLogger(tag = "TestLog", level = Info, listener))
logDebug { "test" }
assertNull(event)
assertNull(message)
init(CSAndroidLogger(tag = "TestLog", level = Debug, listener))
logDebug { "test2" }
assertEquals(Debug, event)
val messageEnd =
"renetik.android.core.logging.CSAndroidLoggerTest\$isDebug(CSAndroidLoggerTest.kt:52) test2"
assertTrue(message!!.endsWith(messageEnd))
}
} | 0 | Kotlin | 1 | 1 | 577b964541c328ddecacc62040508e5e9d490676 | 2,011 | renetik-android-core | MIT License |
photomanipulator/src/androidTest/java/com/guhungry/photomanipulator/BitmapUtilsAndroidTest.kt | guhungry | 175,389,166 | false | null | package com.guhungry.photomanipulator
import android.graphics.*
import android.util.DisplayMetrics
import androidx.annotation.DrawableRes
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.guhungry.photomanipulator.test.R
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
internal class BitmapUtilsAndroidTest {
private var background: Bitmap? = null
private var overlay: Bitmap? = null
private var output: Bitmap? = null
@After
fun tearDown() {
background?.recycle()
background = null
overlay?.recycle()
overlay = null
output?.recycle()
output = null
}
@Test
fun crop_should_have_correct_size() {
FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.background)).use {
output = BitmapUtils.crop(it, CGRect(79, 45, 32, 96), BitmapFactory.Options())
assertThat(output!!.width, equalTo(32))
assertThat(output!!.height, equalTo(96))
}
}
@Test
fun cropAndResize_when_portrait_should_have_correct_size() {
FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.background)).use {
output = BitmapUtils.cropAndResize(it, CGRect(79, 45, 32, 96), CGSize(19, 48), BitmapFactory.Options())
assertThat(output!!.width, equalTo(19))
assertThat(output!!.height, equalTo(48))
}
}
@Test
fun cropAndResize_when_landscape_should_have_correct_size() {
FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.background)).use {
output = BitmapUtils.cropAndResize(it, CGRect(79, 45, 32, 96), CGSize(15, 48), BitmapFactory.Options())
assertThat(output!!.width, equalTo(15))
assertThat(output!!.height, equalTo(48))
}
}
@Test
fun getCorrectOrientationMatrix_should_return_correctly() {
val matrix = FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.issue_exif)).use {
BitmapUtils.getCorrectOrientationMatrix(it)
}
val actual = FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.issue_exif)).use {
BitmapUtils.cropAndResize(it, CGRect(400, 45, 32, 96), CGSize(19, 48), BitmapFactory.Options(), matrix)
.getPixel(1, 1)
}
val original = FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.background)).use {
BitmapUtils.cropAndResize(it, CGRect(400, 45, 32, 96), CGSize(19, 48), BitmapFactory.Options())
.getPixel(1, 1)
}
val bad = FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.issue_exif)).use {
BitmapUtils.cropAndResize(it, CGRect(400, 45, 32, 96), CGSize(19, 48), BitmapFactory.Options())
.getPixel(1, 1)
}
assertThat(actual, equalTo(original))
assertThat(actual, not(equalTo(bad)))
}
@Test
fun overlay_should_overlay_image_at_correct_location() {
val options = BitmapFactory.Options().apply {
inMutable = true
inTargetDensity = DisplayMetrics.DENSITY_DEFAULT
inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB)
}
background = TestHelper.drawableBitmap(R.drawable.background, options)
overlay = TestHelper.drawableBitmap(R.drawable.overlay, options)
BitmapUtils.overlay(background!!, overlay!!, PointF(75f, 145f))
assertThat(background!!.colorSpace, equalTo(overlay!!.colorSpace))
assertThat(background!!.getPixel(75 + 96, 145 + 70), equalTo(overlay!!.getPixel(96, 70)))
}
@Test
fun printText_when_some_values_should_text_correctly() {
val options = BitmapFactory.Options().apply {
inMutable = true
inTargetDensity = DisplayMetrics.DENSITY_DEFAULT
inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB)
}
background = TestHelper.drawableBitmap(R.drawable.background, options)
BitmapUtils.printText(background!!, "My Text Print", PointF(12f, 5f), Color.GREEN, 23f)
assertThat(background!!.getPixel(14, 5), equalTo(Color.GREEN))
}
@Test
fun printText_when_all_values_should_text_correctly() {
val options = BitmapFactory.Options().apply {
inMutable = true
inTargetDensity = DisplayMetrics.DENSITY_DEFAULT
inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB)
}
background = TestHelper.drawableBitmap(R.drawable.background, options)
BitmapUtils.printText(background!!, "My Text Print", PointF(12f, 5f), Color.GREEN, 23f, Typeface.DEFAULT_BOLD, thickness = 1f)
assertThat(background!!.getPixel(14, 0), equalTo(Color.GREEN))
}
@Test
fun printText_when_multiline_should_text_correctly() {
val options = BitmapFactory.Options().apply {
inMutable = true
inTargetDensity = DisplayMetrics.DENSITY_DEFAULT
inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB)
}
background = TestHelper.drawableBitmap(R.drawable.background, options)
BitmapUtils.printText(background!!, "My Text\nPrint", PointF(12f, 5f), Color.GREEN, 23f, Typeface.DEFAULT_BOLD, thickness = 5f)
BitmapUtils.printText(background!!, "My\nText\nPrint", PointF(200f, 5f), Color.YELLOW, 23f, Typeface.DEFAULT_BOLD, thickness = 1f, alignment = Paint.Align.CENTER)
assertThat(background!!.getPixel(14, 0), equalTo(Color.GREEN))
}
/**
* Fix Issue For
* https://github.com/react-native-community/react-native-image-editor/issues/27
*/
@Test
fun cropAndResize_when_bug_scaledown_should_have_correct_size() {
FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.issue27)).use {
output = BitmapUtils.cropAndResize(it, CGRect(0, 0, 2160, 3840), CGSize(16, 16), BitmapFactory.Options())
assertThat(output!!.width, equalTo(16))
assertThat(output!!.height, equalTo(16))
}
}
/**
* Must handle orientation in EXIF data correctly
*/
@Test
fun openBitmapInputStream_must_when_no_orientation_should_do_nothing() {
FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.background)).use {
val actual = BitmapUtils.getCorrectOrientationMatrix(it)
assertThat(actual, nullValue())
}
}
@Test
fun openBitmapInputStream_must_when_orientation_should_return_correctly() {
FileUtils.openBitmapInputStream(TestHelper.context(), TestHelper.drawableUri(R.drawable.issue_exif)).use {
val actual = BitmapUtils.getCorrectOrientationMatrix(it)
assertThat(actual, not(equalTo(Matrix())))
}
}
@Test
fun readImageDimensions_should_return_correct_dimension() {
assertReadImageDimensions(R.drawable.background, 800, 530)
assertReadImageDimensions(R.drawable.overlay, 200, 141)
}
private fun assertReadImageDimensions(@DrawableRes res: Int, width: Int, height: Int) {
val file = TestHelper.drawableUri(res)
FileUtils.openBitmapInputStream(TestHelper.context(), file).use {
val size = BitmapUtils.readImageDimensions(it)
assertThat(size, equalTo(CGSize(width, height)))
}
}
} | 0 | Kotlin | 0 | 4 | 0b64c388bebe672bd54bddabe5c1503e50148459 | 7,703 | android-photo-manipulator | MIT License |
benchmarks/src/org/jetbrains/kotlin/benchmarks/ManyImplicitReceiversBenchmark.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. 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.benchmarks
import org.openjdk.jmh.annotations.*
import org.openjdk.jmh.infra.Blackhole
import java.util.concurrent.TimeUnit
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
open class ManyImplicitReceiversBenchmark : AbstractSimpleFileBenchmark() {
@Param("1", "10", "50")
private var size: Int = 0
@Benchmark
fun benchmark(bh: Blackhole) {
analyzeGreenFile(bh)
}
override fun buildText(): String {
return buildString {
appendLine("inline fun <T, R> with(receiver: T, block: T.() -> R): R = block()")
for (i in 1..size) {
appendLine("interface A$i {")
appendLine(" fun foo$i()")
appendLine("}")
appendLine()
}
appendLine()
append("fun test(")
append((1..size).joinToString(", ") { "a$it: A$it" })
appendLine(" {")
for (i in 1..size) {
appendLine("with(a$i) {")
}
for (i in 1..size) {
appendLine("foo$i()")
}
for (i in 1..size) {
appendLine("}")
}
appendLine("}")
}
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,494 | kotlin | Apache License 2.0 |
datacapturegallery/src/main/java/com/google/android/fhir/datacapture/gallery/QuestionnaireViewModel.kt | kunjan8794 | 347,886,623 | true | {"Kotlin": 335436, "Shell": 1101} | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.google.android.fhir.datacapture.gallery
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.SavedStateHandle
class QuestionnaireViewModel(application: Application, private val state: SavedStateHandle) :
AndroidViewModel(application) {
var questionnaireJson: String? = null
val questionnaire: String
get() {
if (questionnaireJson == null) {
questionnaireJson = getApplication<Application>().assets
.open(state[QuestionnaireActivity.QUESTIONNAIRE_FILE_PATH_KEY]!!)
.bufferedReader()
.use { it.readText() }
}
return questionnaireJson!!
}
}
| 0 | Kotlin | 0 | 1 | b338ed4fdad4bf61fec751fc4a6a4001fb7d8c7f | 1,336 | android-fhir | Apache License 2.0 |
agp-7.1.0-alpha01/tools/base/wizard/template-impl/src/com/android/tools/idea/wizard/template/impl/fragments/googleAdMobAdsFragment/src/app_package/adMobBannerAdFragmentJava.kt | jomof | 374,736,765 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.wizard.template.impl.fragments.googleAdMobAdsFragment.src.app_package
import com.android.tools.idea.wizard.template.Language
import com.android.tools.idea.wizard.template.getMaterialComponentName
import com.android.tools.idea.wizard.template.impl.activities.common.findViewById
import com.android.tools.idea.wizard.template.impl.activities.common.importViewBindingClass
import com.android.tools.idea.wizard.template.impl.activities.common.layoutToViewBindingClass
import com.android.tools.idea.wizard.template.renderIf
fun adMobBannerAdFragmentJava(
applicationPackage: String?,
fragmentClass: String,
layoutName: String,
packageName: String,
useAndroidX: Boolean,
isViewBindingSupported: Boolean
): String {
val onCreateViewBlock = if (isViewBindingSupported) """
binding = ${layoutToViewBindingClass(layoutName)}.inflate(inflater, container, false);
return binding.getRoot();
""" else "return inflater.inflate(R.layout.$layoutName, container, false);"
return """
package ${packageName};
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import ${getMaterialComponentName("android.support.annotation.NonNull", useAndroidX)};
import ${getMaterialComponentName("android.support.annotation.Nullable", useAndroidX)};
import ${getMaterialComponentName("android.support.v4.app.Fragment", useAndroidX)};
import android.os.Bundle;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
${renderIf(applicationPackage != null) { "import ${applicationPackage}.R;" }}
${importViewBindingClass(isViewBindingSupported, packageName, layoutName, Language.Java)}
public class ${fragmentClass} extends Fragment {
// Remove the below line after defining your own ad unit ID.
private static final String TOAST_TEXT = "Test ads are being shown. "
+ "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";
${renderIf(isViewBindingSupported) {"""
private ${layoutToViewBindingClass(layoutName)} binding;
"""}}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
$onCreateViewBlock
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Load an ad into the AdMob banner view.
AdView adView = ${findViewById(
Language.Java,
isViewBindingSupported = isViewBindingSupported,
id = "ad_view",
parentView = "view")};
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
adView.loadAd(adRequest);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity() == null || getActivity().getApplicationContext() == null) return;
final Context appContext = getActivity().getApplicationContext();
// Toasts the test ad message on the screen.
// Remove this after defining your own ad unit ID.
Toast.makeText(appContext, TOAST_TEXT, Toast.LENGTH_LONG).show();
}
${renderIf(isViewBindingSupported) {"""
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
"""}}
}"""
}
| 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 4,253 | CppBuildCacheWorkInProgress | Apache License 2.0 |
app/src/main/java/com/example/sunflower/data/UnsplashPhoto.kt | oroblesr | 295,872,028 | false | null | package com.example.sunflower.data
import com.google.gson.annotations.SerializedName
data class UnsplashPhoto(
@field:SerializedName("id") val id: String,
@field:SerializedName("urls") val urls: UnsplashPhotoUrls,
@field:SerializedName("user") val user: UnsplashUser
)
| 0 | Kotlin | 0 | 0 | ae7322995269bd1670a3ad6ae29c6452b31ff7e6 | 283 | AndroidSunflower | Creative Commons Attribution 3.0 Unported |
yaorm.android/src/main/java/org/roylance/yaorm/android/AndroidProtoCursor.kt | roylanceMichael | 43,471,745 | false | null | package org.roylance.yaorm.android
import android.database.Cursor
import android.util.Log
import org.roylance.yaorm.YaormModel
import org.roylance.yaorm.services.ICursor
import org.roylance.yaorm.services.IStreamer
import org.roylance.yaorm.utilities.YaormUtils
import java.util.*
import kotlin.collections.HashMap
class AndroidProtoCursor(
private val definitionModel: YaormModel.TableDefinition,
private val cursor: Cursor) : ICursor {
private val namesToAvoid = HashSet<String>()
private val columnNamesNormalized = HashMap<String, String>()
fun moveNext() : Boolean {
return cursor.moveToNext()
}
fun getRecord(): YaormModel.Record {
val newInstance = YaormModel.Record.newBuilder()
definitionModel
.columnDefinitionsList
.distinctBy { it.name }
.forEach {
if (this.namesToAvoid.contains(it.name)) {
val propertyHolder = YaormUtils.buildColumn(YaormUtils.EmptyString, it)
newInstance.addColumns(propertyHolder)
}
else if (columnNamesNormalized.containsKey(it.name)) {
try {
val index = cursor.getColumnIndex(columnNamesNormalized[it.name]!!)
val newValue = cursor.getString(index)
val propertyHolder = YaormUtils.buildColumn(newValue, it)
newInstance.addColumns(propertyHolder)
}
catch (e: Exception) {
// if we can't see this name for w/e reason, we'll print to the console, but continue on
// e.printStackTrace()
Log.e("sqlite", e.message)
this.namesToAvoid.add(it.name)
val propertyHolder = YaormUtils.buildColumn(YaormUtils.EmptyString, it)
newInstance.addColumns(propertyHolder)
}
}
else {
val propertyHolder = YaormUtils.buildColumn(YaormUtils.EmptyString, it)
newInstance.addColumns(propertyHolder)
}
}
return newInstance.build()
}
override fun getRecords(): YaormModel.Records {
var i = 0
while (i < cursor.columnCount) {
val sqliteColumnName = cursor.getColumnName(i)
val sqliteColumnNameNormalized = sqliteColumnName.toLowerCase()
definitionModel.columnDefinitionsList
.filter { it.name.toLowerCase() == sqliteColumnNameNormalized }
.forEach {
columnNamesNormalized[it.name] = sqliteColumnName
}
i++
}
val returnItems = YaormModel.Records.newBuilder()
while (this.moveNext()) {
returnItems.addRecords(this.getRecord())
}
this.cursor.close()
return returnItems.build()
}
override fun getRecordsStream(streamer: IStreamer) {
while (this.moveNext()) {
streamer.stream(this.getRecord())
}
this.cursor.close()
}
} | 1 | Kotlin | 0 | 0 | df672db4e16d84885ec3aa84e74c57e1e9bc1ce3 | 3,319 | yaorm | MIT License |
ktor-core/test/org/jetbrains/ktor/tests/session/SessionTest.kt | cy6erGn0m | 40,906,748 | true | {"Kotlin": 635453} | package org.jetbrains.ktor.tests.session
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.sessions.*
import org.jetbrains.ktor.testing.*
import org.jetbrains.ktor.tests.*
import org.jetbrains.ktor.util.*
import org.junit.*
import kotlin.test.*
class SessionTest {
@Test
fun testSessionInlineValue() {
withTestApplication {
application.withSessions<TestUserSession> {
withCookieByValue()
}
application.routing {
get("/0") {
response.sendText("It should be no session started")
}
get("/1") {
var session: TestUserSession? = sessionOrNull()
assertNull(session)
assertFailsWith(IllegalArgumentException::class) {
session<TestUserSession>() // no no-arg constructor
}
assertFailsWith(IllegalArgumentException::class) {
session<EmptySession>() // bad class
}
session(TestUserSession("id1", emptyList()))
session = session()
assertNotNull(session)
response.sendText("ok")
}
get("/2") {
assertEquals(TestUserSession("id1", emptyList()), session<TestUserSession>())
response.sendText("ok, ${session<TestUserSession>().userId}")
}
}
handleRequest(HttpMethod.Get, "/0").let { response ->
assertNull(response.response.cookies["SESSION"], "It should be no session set by default")
}
var sessionParam: String = ""
handleRequest(HttpMethod.Get, "/1").let { response ->
val sessionCookie = response.response.cookies["SESSION"]
assertNotNull(sessionCookie, "No session cookie found")
sessionParam = sessionCookie!!.value
assertEquals(TestUserSession("id1", emptyList()), autoSerializerOf<TestUserSession>().deserialize(sessionParam))
}
handleRequest(HttpMethod.Get, "/2") {
addHeader(HttpHeaders.Cookie, "SESSION=${encodeURLQueryComponent(sessionParam)}")
}.let { response ->
assertEquals("ok, id1", response.response.content)
}
}
}
@Test
fun testDigestSession() {
withTestApplication {
application.withSessions<TestUserSession> {
withCookieByValue {
settings = SessionCookiesSettings(transformers = listOf(
SessionCookieTransformerDigest()
))
}
}
application.routing {
get("/1") {
session(TestUserSession("id2", emptyList()))
response.sendText("ok")
}
get("/2") {
response.sendText("ok, ${sessionOrNull<TestUserSession>()?.userId}")
}
}
var sessionId = ""
handleRequest(HttpMethod.Get, "/1").let { response ->
val sessionCookie = response.response.cookies["SESSION"]
assertNotNull(sessionCookie, "No session cookie found")
sessionId = sessionCookie!!.value
}
handleRequest(HttpMethod.Get, "/2") {
addHeader(HttpHeaders.Cookie, "SESSION=${encodeURLQueryComponent(sessionId)}")
}.let { response ->
assertEquals("ok, id2", response.response.content)
}
handleRequest(HttpMethod.Get, "/2") {
// addHeader(HttpHeaders.Cookie, "SESSION=$sessionId")
}.let { response ->
assertEquals("ok, null", response.response.content)
}
handleRequest(HttpMethod.Get, "/2") {
val brokenSession = sessionId.mapIndexed { i, c -> if (i == sessionId.lastIndex) 'x' else c }.joinToString("")
addHeader(HttpHeaders.Cookie, "SESSION=${encodeURLQueryComponent(brokenSession)}")
}.let { response ->
assertEquals("ok, null", response.response.content)
}
}
}
@Test
fun testMacSession() {
val key = hex("03515606058610610561058")
withTestApplication {
application.withSessions<TestUserSession> {
withCookieByValue {
settings = SessionCookiesSettings(transformers = listOf(
SessionCookieTransformerMessageAuthentication(key)
))
}
}
application.routing {
get("/1") {
session(TestUserSession("id2", emptyList()))
response.sendText("ok")
}
get("/2") {
response.sendText("ok, ${sessionOrNull<TestUserSession>()?.userId}")
}
}
var sessionId = ""
handleRequest(HttpMethod.Get, "/1").let { response ->
val sessionCookie = response.response.cookies["SESSION"]
assertNotNull(sessionCookie, "No session cookie found")
sessionId = sessionCookie!!.value
}
handleRequest(HttpMethod.Get, "/2") {
addHeader(HttpHeaders.Cookie, "SESSION=${encodeURLQueryComponent(sessionId)}")
}.let { response ->
assertEquals("ok, id2", response.response.content)
}
handleRequest(HttpMethod.Get, "/2") {
// addHeader(HttpHeaders.Cookie, "SESSION=$sessionId")
}.let { response ->
assertEquals("ok, null", response.response.content)
}
handleRequest(HttpMethod.Get, "/2") {
val brokenSession = sessionId.mapIndexed { i, c -> if (i == sessionId.lastIndex) 'x' else c }.joinToString("")
addHeader(HttpHeaders.Cookie, "SESSION=${encodeURLQueryComponent(brokenSession)}")
}.let { response ->
assertEquals("ok, null", response.response.content)
}
}
}
@Test
fun testRoutes() {
withTestApplication {
application.routing {
route("/") {
withSessions<TestUserSession> {
withCookieByValue()
}
get("/0") {
response.sendText("It should be no session started")
}
get("/1") {
var session: TestUserSession? = sessionOrNull()
assertNull(session)
assertFailsWith(IllegalArgumentException::class) {
session<TestUserSession>() // no no-arg constructor
}
assertFailsWith(IllegalArgumentException::class) {
session<EmptySession>() // bad class
}
session(TestUserSession("id1", emptyList()))
session = session()
assertNotNull(session)
response.sendText("ok")
}
get("/2") {
assertEquals(TestUserSession("id1", emptyList()), session<TestUserSession>())
response.sendText("ok, ${session<TestUserSession>().userId}")
}
}
}
handleRequest(HttpMethod.Get, "/0").let { response ->
assertNull(response.response.cookies["SESSION"], "It should be no session set by default")
}
var sessionParam: String = ""
handleRequest(HttpMethod.Get, "/1").let { response ->
val sessionCookie = response.response.cookies["SESSION"]
assertNotNull(sessionCookie, "No session cookie found")
sessionParam = sessionCookie!!.value
assertEquals(TestUserSession("id1", emptyList()), autoSerializerOf<TestUserSession>().deserialize(sessionParam))
}
handleRequest(HttpMethod.Get, "/2") {
addHeader(HttpHeaders.Cookie, "SESSION=${encodeURLQueryComponent(sessionParam)}")
}.let { response ->
assertEquals("ok, id1", response.response.content)
}
}
}
}
class EmptySession
data class TestUserSession(val userId: String, val cart: List<String>)
| 0 | Kotlin | 0 | 0 | 2d3b4f0b813b05370b22fae4c0d83d99122f604f | 8,751 | ktor | Apache License 2.0 |
app/src/main/java/com/bogdan/codeforceswatcher/features/problems/ProblemsAdapter.kt | jpappdesigns | 296,574,266 | true | {"Kotlin": 159563, "Swift": 125794, "Ruby": 2495} | package com.bogdan.codeforceswatcher.features.problems
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bogdan.codeforceswatcher.R
import io.xorum.codeforceswatcher.features.problems.models.Problem
import io.xorum.codeforceswatcher.features.problems.redux.requests.ProblemsRequests
import kotlinx.android.synthetic.main.view_problem_item.view.*
import io.xorum.codeforceswatcher.redux.store
import java.util.*
class ProblemsAdapter(
private val context: Context,
private val itemClickListener: (Problem) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), Filterable {
private var showingItems: MutableList<Problem> = mutableListOf()
private var items: List<Problem> = listOf()
private var isFavouriteStatus = false
override fun getItemCount() = showingItems.size + if (showingItems.isEmpty()) 1 else 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
when (viewType) {
STUB_ALL_PROBLEMS_VIEW_TYPE -> {
val layout = LayoutInflater.from(context).inflate(R.layout.view_all_problems_stub, parent, false)
StubViewHolder(layout)
}
STUB_FAVOURITE_PROBLEMS_VIEW_TYPE -> {
val layout = LayoutInflater.from(context).inflate(R.layout.view_favourite_problems_stub, parent, false)
StubViewHolder(layout)
}
else -> {
val layout = LayoutInflater.from(context).inflate(R.layout.view_problem_item, parent, false)
ProblemViewHolder(layout)
}
}
override fun getItemViewType(position: Int): Int {
return when {
showingItems.isEmpty() && store.state.problems.isFavourite -> STUB_FAVOURITE_PROBLEMS_VIEW_TYPE
showingItems.isEmpty() -> STUB_ALL_PROBLEMS_VIEW_TYPE
else -> PROBLEM_VIEW_TYPE
}
}
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
if (showingItems.isEmpty()) return
val problemViewHolder = viewHolder as ProblemViewHolder
with(problemViewHolder) {
with(showingItems[adapterPosition]) {
tvProblemName.text = context.getString(R.string.problem_name_with_index, contestId, index, name)
tvContestName.text = contestName
ivFavourite.setColorFilter(ContextCompat.getColor(
context, if (isFavourite) R.color.colorAccent else R.color.dark_gray)
)
onClickListener = { itemClickListener(this) }
onFavouriteClickListener = {
store.dispatch(ProblemsRequests.ChangeStatusFavourite(this.copy()))
when (isFavouriteStatus) {
false -> notifyItemChanged(adapterPosition).also { changeProblem(this) }
true -> notifyItemRemoved(adapterPosition).also { removeProblem(this) }
}
}
}
}
}
private fun changeProblem(problem: Problem) {
problem.isFavourite = problem.isFavourite.not()
}
private fun removeProblem(problem: Problem) {
items.minus(problem)
showingItems.remove(problem)
}
fun setItems(problemsList: List<Problem>, constraint: String, isFavourite: Boolean) {
this.isFavouriteStatus = isFavourite
items = problemsList
showingItems = buildFilteredList(constraint)
notifyDataSetChanged()
}
private val problemFilter: Filter = object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val filteredList = mutableListOf<Problem>()
filteredList.addAll(
if (constraint.isNullOrEmpty()) items else buildFilteredList(constraint.toString())
)
return FilterResults().apply { values = filteredList }
}
override fun publishResults(constraint: CharSequence, results: FilterResults) {
showingItems.clear()
showingItems.addAll(results.values as List<Problem>)
notifyDataSetChanged()
}
}
private fun buildFilteredList(constraint: String): MutableList<Problem> {
val lowerCaseConstraint = constraint.lowercase()
val filteredList = mutableListOf<Problem>()
for (problem in items) {
val fullProblemNameEn = "${problem.contestId}${problem.index}: ${problem.enName.lowercase()}"
val fullProblemNameRu = "${problem.contestId}${problem.index}: ${problem.ruName.lowercase()}"
if (fullProblemNameEn.kmpContains(lowerCaseConstraint)
|| fullProblemNameRu.kmpContains(lowerCaseConstraint)
|| problem.contestName.lowercase().kmpContains(lowerCaseConstraint)) {
filteredList.add(problem)
}
}
return filteredList
}
private fun String.lowercase() = this.toLowerCase(Locale.getDefault())
private fun String.kmpContains(searchString: String): Boolean {
val findingStringLength = searchString.length
val cmpStr = "$searchString%$this"
val prefixArray = IntArray(cmpStr.length)
var currentIndexOfBlock = 0
prefixArray[0] = 0
for (i in 1 until cmpStr.length) {
while (currentIndexOfBlock > 0 && cmpStr[currentIndexOfBlock] != cmpStr[i]) {
currentIndexOfBlock = prefixArray[currentIndexOfBlock - 1]
}
if (cmpStr[currentIndexOfBlock] == cmpStr[i]) {
currentIndexOfBlock++
}
prefixArray[i] = currentIndexOfBlock
if (prefixArray[i] == findingStringLength) {
return true
}
}
return false
}
override fun getFilter() = problemFilter
class ProblemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvProblemName: TextView = view.tvProblemName
val tvContestName: TextView = view.tvContestName
val ivFavourite: ImageView = view.ivFavourite
var onClickListener: (() -> Unit)? = null
var onFavouriteClickListener: (() -> Unit)? = null
init {
view.setOnClickListener { onClickListener?.invoke() }
view.ivFavourite.setOnClickListener { onFavouriteClickListener?.invoke() }
}
}
data class StubViewHolder(val view: View) : RecyclerView.ViewHolder(view)
companion object {
const val STUB_ALL_PROBLEMS_VIEW_TYPE = 0
const val STUB_FAVOURITE_PROBLEMS_VIEW_TYPE = 2
const val PROBLEM_VIEW_TYPE = 1
}
}
| 0 | Kotlin | 0 | 1 | d6d84e1c26667e0c220b3386f5b6354ffae99336 | 7,009 | codeforces_watcher | MIT License |
src/main/kotlin/com/ort/howlingwolf/fw/interceptor/HowlingWolfAccessContextInterceptor.kt | h-orito | 176,481,255 | false | null | package com.ort.howlingwolf.fw.interceptor
import com.ort.howlingwolf.fw.HowlingWolfDateUtil
import com.ort.howlingwolf.fw.HowlingWolfUserInfoUtil
import com.ort.howlingwolf.fw.security.HowlingWolfUser
import com.ort.howlingwolf.fw.security.getIpAddress
import org.dbflute.hook.AccessContext
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class HowlingWolfAccessContextInterceptor : HandlerInterceptorAdapter() {
@Throws(Exception::class)
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
// [アクセス日時]
val accessLocalDateTime = HowlingWolfDateUtil.currentLocalDateTime()
// [アクセスユーザ]
val userInfo: HowlingWolfUser? = HowlingWolfUserInfoUtil.getUserInfo()
val accessUser = userInfo?.username ?: "not_login_user"
val context = AccessContext()
context.accessLocalDateTime = accessLocalDateTime
context.accessUser = "$accessUser: ${request.getIpAddress()}"
AccessContext.setAccessContextOnThread(context)
// Handlerメソッドを呼び出す場合はtrueを返却する
return true
}
} | 0 | Kotlin | 1 | 3 | 7ef6d01ade6cfeb96935d6430a1a404bd67ae54e | 1,289 | howling-wolf-api | MIT License |
ktor-http/ktor-http-cio/src/io/ktor/http/cio/websocket/PingPong.kt | trevorwhitney | 150,153,302 | true | {"Kotlin": 1775415, "Java": 62081, "Lua": 280, "HTML": 35} | package io.ktor.http.cio.websocket
import io.ktor.cio.*
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.*
import kotlinx.coroutines.experimental.channels.Channel
import io.ktor.util.*
import kotlinx.io.pool.*
import java.nio.*
import java.nio.charset.*
import java.time.*
import java.util.concurrent.*
import java.util.concurrent.CancellationException
import kotlin.coroutines.experimental.*
/**
* Launch a ponger actor job on the [coroutineContext] for websocket [session].
* It is acting for every client's ping frame and replying with corresponding pong
*/
fun ponger(
coroutineContext: CoroutineContext,
session: WebSocketSession,
pool: ObjectPool<ByteBuffer> = KtorDefaultPool
): SendChannel<Frame.Ping> = actor(coroutineContext, 5, CoroutineStart.LAZY) {
consumeEach { frame ->
val buffer = frame.buffer.copy(pool)
session.send(Frame.Pong(buffer, object : DisposableHandle {
override fun dispose() {
pool.recycle(buffer)
}
}))
}
}
/**
* Launch pinger coroutine on [coroutineContext] websocket for [session] that is sending ping every specified [period],
* waiting for and verifying client's pong frames. It is also handling [timeout] and sending timeout close frame
* to the dedicated [out] channel in case of failure
*/
fun pinger(
coroutineContext: CoroutineContext,
session: WebSocketSession,
period: Duration,
timeout: Duration,
out: SendChannel<Frame>,
pool: ObjectPool<ByteBuffer> = KtorDefaultPool
): SendChannel<Frame.Pong> = actor(coroutineContext, Channel.UNLIMITED, CoroutineStart.LAZY) {
val buffer = pool.borrow()
val periodMillis = period.toMillis()
val timeoutMillis = timeout.toMillis()
val encoder = Charsets.ISO_8859_1.newEncoder()
try {
while (!isClosedForReceive) {
// drop pongs during period delay as they are irrelevant
// here timeout is expected so ignore it
withTimeoutOrNull(periodMillis, TimeUnit.MILLISECONDS) {
while (true) {
receive() // timeout causes loop to break on receive
}
}
val pingMessage = "[ping ${nextNonce()} ping]"
val rc = withTimeoutOrNull(timeoutMillis, TimeUnit.MILLISECONDS) {
session.sendPing(buffer, encoder, pingMessage)
// wait for valid pong message
while (true) {
val msg = receive()
if (msg.buffer.decodeString(Charsets.ISO_8859_1) == pingMessage) break
}
}
if (rc == null) {
// timeout
// we were unable to send ping or hadn't get valid pong message in time
// so we are triggering close sequence (if already started then the following close frame could be ignored)
val closeFrame = Frame.Close(CloseReason(CloseReason.Codes.UNEXPECTED_CONDITION, "Ping timeout"))
out.send(closeFrame)
break
}
}
} catch (ignore: CancellationException) {
} catch (ignore: ClosedReceiveChannelException) {
} catch (ignore: ClosedSendChannelException) {
} finally {
pool.recycle(buffer)
}
}
private suspend fun WebSocketSession.sendPing(
buffer: ByteBuffer,
encoder: CharsetEncoder,
content: String
) = with(buffer) {
clear()
encoder.reset()
encoder.encode(CharBuffer.wrap(content), this, true).apply {
if (this.isError) throwException()
else if (this.isOverflow) throwException()
}
flip()
send(Frame.Ping(this))
}
| 0 | Kotlin | 0 | 0 | f79c076b41ca4475bda14de226690484ed87dfb7 | 3,703 | ktor | Apache License 2.0 |
app/src/main/java/io/homeassistant/companion/android/qs/TileExtensions.kt | nesror | 328,856,313 | true | null | package io.homeassistant.companion.android.qs
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Icon
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.graphics.drawable.toBitmap
import com.maltaisn.icondialog.pack.IconPack
import com.maltaisn.icondialog.pack.IconPackLoader
import com.maltaisn.iconpack.mdi.createMaterialDesignIconPack
import dagger.hilt.android.AndroidEntryPoint
import io.homeassistant.companion.android.common.data.integration.IntegrationRepository
import io.homeassistant.companion.android.database.AppDatabase
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
import io.homeassistant.companion.android.common.R as commonR
@RequiresApi(Build.VERSION_CODES.N)
@AndroidEntryPoint
abstract class TileExtensions : TileService() {
abstract fun getTile(): Tile?
abstract fun getTileId(): String
@Inject
lateinit var integrationUseCase: IntegrationRepository
override fun onClick() {
super.onClick()
if (getTile() != null) {
setTileData(applicationContext, getTileId(), getTile()!!, integrationUseCase)
tileClicked(applicationContext, getTileId(), getTile()!!, integrationUseCase)
}
}
override fun onTileAdded() {
super.onTileAdded()
Log.d(TAG, "Tile: ${getTileId()} added")
if (getTile() != null)
setTileData(applicationContext, getTileId(), getTile()!!, integrationUseCase)
}
override fun onStartListening() {
super.onStartListening()
Log.d(TAG, "Tile: ${getTileId()} is in view")
if (getTile() != null)
setTileData(applicationContext, getTileId(), getTile()!!, integrationUseCase)
}
companion object {
private const val TAG = "TileExtensions"
private var iconPack: IconPack? = null
private val toggleDomains = listOf(
"cover", "fan", "humidifier", "input_boolean", "light",
"media_player", "remote", "siren", "switch"
)
@RequiresApi(Build.VERSION_CODES.N)
fun setTileData(context: Context, tileId: String, tile: Tile, integrationUseCase: IntegrationRepository): Boolean {
Log.d(TAG, "Attempting to set tile data for tile ID: $tileId")
val tileDao = AppDatabase.getInstance(context).tileDao()
val tileData = tileDao.get(tileId)
try {
return if (tileData != null) {
tile.label = tileData.label
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
tile.subtitle = tileData.subtitle
}
if (tileData.entityId.split('.')[0] in toggleDomains) {
val state = runBlocking { integrationUseCase.getEntity(tileData.entityId) }
tile.state = if (state?.state == "on" || state?.state == "open") Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
} else
tile.state = Tile.STATE_INACTIVE
val iconId = tileData.iconId
if (iconId != null) {
val icon = getTileIcon(iconId, context)
tile.icon = Icon.createWithBitmap(icon)
}
Log.d(TAG, "Tile data set for tile ID: $tileId")
tile.updateTile()
true
} else {
Log.d(TAG, "No tile data found for tile ID: $tileId")
tile.state = Tile.STATE_UNAVAILABLE
tile.updateTile()
false
}
} catch (e: Exception) {
Log.e(TAG, "Unable to set tile data for tile ID: $tileId", e)
return false
}
}
@RequiresApi(Build.VERSION_CODES.N)
fun tileClicked(
context: Context,
tileId: String,
tile: Tile,
integrationUseCase: IntegrationRepository
) {
Log.d(TAG, "Click detected for tile ID: $tileId")
val tileDao = AppDatabase.getInstance(context).tileDao()
val tileData = tileDao.get(tileId)
val hasTile = setTileData(context, tileId, tile, integrationUseCase)
if (hasTile) {
tile.state = Tile.STATE_ACTIVE
tile.updateTile()
runBlocking {
try {
integrationUseCase.callService(
tileData?.entityId?.split(".")!![0],
if (tileData.entityId.split(".")[0] in toggleDomains) "toggle" else "turn_on",
hashMapOf("entity_id" to tileData.entityId)
)
Log.d(TAG, "Service call sent for tile ID: $tileId")
} catch (e: Exception) {
Log.e(TAG, "Unable to call service for tile ID: $tileId", e)
Toast.makeText(context, commonR.string.service_call_failure, Toast.LENGTH_SHORT)
.show()
}
}
tile.state = Tile.STATE_INACTIVE
tile.updateTile()
} else {
tile.state = Tile.STATE_UNAVAILABLE
tile.updateTile()
Log.d(TAG, "No tile data found for tile ID: $tileId")
Toast.makeText(context, commonR.string.tile_data_missing, Toast.LENGTH_SHORT).show()
}
}
private fun getTileIcon(tileIconId: Int, context: Context): Bitmap? {
// Create an icon pack and load all drawables.
if (iconPack == null) {
val loader = IconPackLoader(context)
iconPack = createMaterialDesignIconPack(loader)
iconPack!!.loadDrawables(loader.drawableLoader)
}
val iconDrawable = iconPack?.icons?.get(tileIconId)?.drawable
if (iconDrawable != null) {
return DrawableCompat.wrap(iconDrawable).toBitmap()
}
return null
}
}
}
| 10 | Kotlin | 15 | 61 | b36bb0f67fd884b0f8c938c048b51134063784f2 | 6,556 | Home-Assistant-Companion-for-Android | Apache License 2.0 |
src/main/kotlin/app/trian/cashierservice/repository/InvoicesRepository.kt | trianapp | 442,201,785 | false | {"Kotlin": 46957} | package app.trian.cashierservice.repository
import app.trian.cashierservice.entity.Invoices
import org.springframework.data.repository.PagingAndSortingRepository
/**
* Created By <NAME>
* https://github.com/triandamai
* Created At 01/01/22 20.17
*/
interface InvoicesRepository:PagingAndSortingRepository<Invoices,Long> {
} | 0 | Kotlin | 1 | 5 | ad93de4d75851f8abfda89b979a093efc6203997 | 333 | CashierBackend | MIT License |
behind/src/main/kotlin/com/yourssu/behind/controller/comment/CommentController.kt | mornings9047 | 328,353,294 | false | null | package com.yourssu.behind.controller.comment
import com.yourssu.behind.model.dto.comment.request.CreateOrUpdateRequestCommentDto
import com.yourssu.behind.model.dto.comment.response.ResponseCommentDto
import com.yourssu.behind.service.comment.CommentService
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/comments")
class CommentController @Autowired constructor(val commentService: CommentService) {
@ApiOperation(value = "댓글 작성")
@PostMapping("/post/{postId}")
@ResponseStatus(HttpStatus.CREATED)
fun createComment(@PathVariable postId: Long, @RequestBody createOrUpdateRequestCommentDto: CreateOrUpdateRequestCommentDto) {
return commentService.createComment(postId, createOrUpdateRequestCommentDto)
}
@ApiOperation(value = "대 댓글 작성")
@PostMapping("/post/{postId}/recomment/{commentId}")
@ResponseStatus(HttpStatus.CREATED)
fun createReComment(@PathVariable postId: Long, @PathVariable commentId: Long, @RequestBody createOrUpdateRequestCommentDto: CreateOrUpdateRequestCommentDto) {
commentService.createRecomment(postId, createOrUpdateRequestCommentDto, commentId)
}
@ApiOperation("게시물의 댓글 가져오기")
@GetMapping("/post/{postId}")
fun getComment(@PathVariable postId: Long): List<ResponseCommentDto> {
return commentService.getComment(postId)
}
@ApiOperation("댓글 신고하기")
@GetMapping("/report/{commentId}")
fun reportComment(@PathVariable commentId: Long) {
return commentService.reportComment(commentId)
}
@ApiOperation("댓글 삭제하기")
@DeleteMapping("/{commentId}")
fun deleteComment(@PathVariable commentId: Long) {
return commentService.deleteComment(commentId)
}
}
| 1 | Kotlin | 0 | 0 | fd17c0e8d39fda5ed07b5444024786559aaa7102 | 1,946 | behind-backend | MIT License |
src/jsMain/kotlin/dev/inmo/jsuikit/modifiers/UIKitPadding.kt | InsanusMokrassar | 440,777,301 | false | {"Kotlin": 150272, "Shell": 731} | package dev.inmo.jsuikit.modifiers
sealed class UIKitPadding(suffix: String?) : UIKitModifier {
override val classes: Array<String> = arrayOf("uk-padding${suffix ?.let { "-$it" } ?: ""}")
sealed class Size(suffix: String?) : UIKitPadding(suffix) {
object Small : Size("small")
object Large : Size("large")
companion object : Size(null) {
val Default
get() = this
}
}
sealed class Remove(suffix: String?) : UIKitPadding("remove${suffix ?.let { "-$it" } ?: ""}") {
object Top : Remove("top")
object Bottom : Remove("bottom")
object Left : Remove("left")
object Right : Remove("right")
object Vertical : Remove("vertical")
object Horizontal : Remove("horizontal")
companion object : Remove(null)
}
companion object : Size(null)
}
| 1 | Kotlin | 1 | 4 | 2e665a841116b220ec9dc40f76dc7355ab491b1e | 878 | JSUIKitKBindings | MIT License |
src/chapter03/nooverridetuozhan/Button.kt | xu33liang33 | 252,216,839 | false | null | package chapter03.nooverridetuozhan
class Button : View() {
override fun click() = println("Button Clicked")
} | 0 | Kotlin | 0 | 1 | cdc74e445c8c487023fbc7917183d47e73ff4bc8 | 115 | actioninkotlin | Apache License 2.0 |
android-client/buildSrc/src/main/kotlin/com/sergey_y/simpletweets/benchmark/BenchmarkParser.kt | desugar-64 | 425,652,414 | false | {"Kotlin": 144726, "Shell": 1044} | package com.sergey_y.simpletweets.benchmark
import com.sergey_y.simpletweets.benchmark.model.BenchmarkReport
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
class BenchmarkParser(private val benchmarkReport: String) {
val json = Json {
ignoreUnknownKeys = true
useAlternativeNames = true
}
fun parse(): BenchmarkReport {
return json.decodeFromString(benchmarkReport)
}
} | 0 | Kotlin | 0 | 17 | 76765c92d33faec0dc3d75ffa316c9b41232d779 | 449 | android-compose-performance-test | MIT License |
features/account/account-impl/src/commonMain/kotlin/io/spherelabs/accountimpl/presentation/AccountState.kt | getspherelabs | 687,455,894 | false | {"Kotlin": 917584, "Ruby": 6814, "Swift": 1128, "Shell": 1048} | package io.spherelabs.accountimpl.presentation
import androidx.compose.runtime.Immutable
import io.spherelabs.accountapi.model.AccountUser
@Immutable
data class AccountState(
val sizeOfStrongPassword: Int = 0,
val sizeOfWeakPassword: Int = 0,
val sizeOfTotalPassword: Int = 0,
val isFingerPrintEnabled: Boolean = false,
val isRestrictScreenshotEnabled: Boolean = false,
val user: AccountUser? = null,
val isLogout: Boolean = false
) {
companion object {
val Empty = AccountState()
}
}
| 18 | Kotlin | 24 | 188 | 902a0505c5eaf0f3848a5e06afaec98c1ed35584 | 523 | anypass-kmp | Apache License 2.0 |
compiler/fir/java/src/org/jetbrains/kotlin/fir/java/deserialization/JvmClassFileBasedSymbolProvider.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.java.deserialization
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.ThreadSafeMutableState
import org.jetbrains.kotlin.fir.builder.toMutableOrEmpty
import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin
import org.jetbrains.kotlin.fir.declarations.getDeprecationsProvider
import org.jetbrains.kotlin.fir.deserialization.AbstractFirDeserializedSymbolProvider
import org.jetbrains.kotlin.fir.deserialization.FirDeserializationContext
import org.jetbrains.kotlin.fir.deserialization.ModuleDataProvider
import org.jetbrains.kotlin.fir.deserialization.PackagePartsCacheData
import org.jetbrains.kotlin.fir.expressions.FirAnnotation
import org.jetbrains.kotlin.fir.java.FirJavaFacade
import org.jetbrains.kotlin.fir.java.declarations.FirJavaClass
import org.jetbrains.kotlin.fir.languageVersionSettings
import org.jetbrains.kotlin.fir.resolve.transformers.setLazyPublishedVisibility
import org.jetbrains.kotlin.fir.scopes.FirKotlinScopeProvider
import org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol
import org.jetbrains.kotlin.load.kotlin.*
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmFlags
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.serialization.deserialization.IncompatibleVersionErrorData
import org.jetbrains.kotlin.serialization.deserialization.builtins.BuiltInSerializerProtocol
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerAbiStability
import org.jetbrains.kotlin.utils.toMetadataVersion
import java.nio.file.Path
import java.nio.file.Paths
// This symbol provider loads JVM classes, reading extra info from Kotlin `@Metadata` annotations
// if present. Use it for library and incremental compilation sessions. For source sessions use
// `JavaSymbolProvider`, as Kotlin classes should be parsed first.
@ThreadSafeMutableState
class JvmClassFileBasedSymbolProvider(
session: FirSession,
moduleDataProvider: ModuleDataProvider,
kotlinScopeProvider: FirKotlinScopeProvider,
private val packagePartProvider: PackagePartProvider,
private val kotlinClassFinder: KotlinClassFinder,
private val javaFacade: FirJavaFacade,
defaultDeserializationOrigin: FirDeclarationOrigin = FirDeclarationOrigin.Library
) : AbstractFirDeserializedSymbolProvider(
session, moduleDataProvider, kotlinScopeProvider, defaultDeserializationOrigin, BuiltInSerializerProtocol
) {
private val annotationsLoader = AnnotationsLoader(session, kotlinClassFinder)
private val ownMetadataVersion: JvmMetadataVersion = session.languageVersionSettings.languageVersion.toMetadataVersion()
private val reportErrorsOnPreReleaseDependencies = with(session.languageVersionSettings) {
!getFlag(AnalysisFlags.skipPrereleaseCheck) && !isPreRelease() && !KotlinCompilerVersion.isPreRelease()
}
override fun computePackagePartsInfos(packageFqName: FqName): List<PackagePartsCacheData> =
packagePartProvider.findPackageParts(packageFqName.asString()).mapNotNull { partName ->
computePackagePartInfo(packageFqName, partName)
}
private fun computePackagePartInfo(packageFqName: FqName, partName: String): PackagePartsCacheData? {
if (partName in KotlinBuiltins) return null
val classId = ClassId.topLevel(JvmClassName.byInternalName(partName).fqNameForTopLevelClassMaybeWithDollars)
if (!javaFacade.hasTopLevelClassOf(classId)) return null
val (kotlinClass, byteContent) =
kotlinClassFinder.findKotlinClassOrContent(classId, ownMetadataVersion) as? KotlinClassFinder.Result.KotlinClass ?: return null
val facadeName = kotlinClass.classHeader.multifileClassName?.takeIf { it.isNotEmpty() }
val facadeFqName = facadeName?.let { JvmClassName.byInternalName(it).fqNameForTopLevelClassMaybeWithDollars }
val facadeBinaryClass = facadeFqName?.let {
kotlinClassFinder.findKotlinClass(ClassId.topLevel(it), ownMetadataVersion)
}
val moduleData = moduleDataProvider.getModuleData(kotlinClass.containingLibrary.toPath()) ?: return null
val header = kotlinClass.classHeader
val data = header.data ?: header.incompatibleData ?: return null
val strings = header.strings ?: return null
val (nameResolver, packageProto) = parseProto(kotlinClass) {
JvmProtoBufUtil.readPackageDataFrom(data, strings)
} ?: return null
val source = JvmPackagePartSource(
kotlinClass, packageProto, nameResolver, kotlinClass.incompatibility, kotlinClass.isPreReleaseInvisible,
kotlinClass.abiStability,
)
return PackagePartsCacheData(
packageProto,
FirDeserializationContext.createForPackage(
packageFqName, packageProto, nameResolver, moduleData,
JvmBinaryAnnotationDeserializer(session, kotlinClass, kotlinClassFinder, byteContent),
FirJvmConstDeserializer(session, facadeBinaryClass ?: kotlinClass, BuiltInSerializerProtocol),
source
),
)
}
override fun computePackageSetWithNonClassDeclarations(): Set<String> = packagePartProvider.computePackageSetWithNonClassDeclarations()
override fun knownTopLevelClassesInPackage(packageFqName: FqName): Set<String>? = javaFacade.knownClassNamesInPackage(packageFqName)
private val KotlinJvmBinaryClass.incompatibility: IncompatibleVersionErrorData<JvmMetadataVersion>?
get() {
if (session.languageVersionSettings.getFlag(AnalysisFlags.skipMetadataVersionCheck)) return null
if (classHeader.metadataVersion.isCompatible(ownMetadataVersion)) return null
return IncompatibleVersionErrorData(
actualVersion = classHeader.metadataVersion,
compilerVersion = JvmMetadataVersion.INSTANCE,
languageVersion = ownMetadataVersion,
expectedVersion = ownMetadataVersion.lastSupportedVersionWithThisLanguageVersion(classHeader.metadataVersion.isStrictSemantics),
filePath = location,
classId = classId
)
}
/**
* @return true if the class is invisible because it's compiled by a pre-release compiler, and this compiler is either released
* or is run with a released language version.
*/
private val KotlinJvmBinaryClass.isPreReleaseInvisible: Boolean
get() = reportErrorsOnPreReleaseDependencies && classHeader.isPreRelease
private val KotlinJvmBinaryClass.abiStability: DeserializedContainerAbiStability
get() = when {
session.languageVersionSettings.getFlag(AnalysisFlags.allowUnstableDependencies) -> DeserializedContainerAbiStability.STABLE
classHeader.isUnstableJvmIrBinary -> DeserializedContainerAbiStability.UNSTABLE
else -> DeserializedContainerAbiStability.STABLE
}
override fun extractClassMetadata(classId: ClassId, parentContext: FirDeserializationContext?): ClassMetadataFindResult? {
// Kotlin classes are annotated Java classes, so this check also looks for them.
if (!javaFacade.hasTopLevelClassOf(classId)) return null
val result = kotlinClassFinder.findKotlinClassOrContent(classId, ownMetadataVersion)
if (result !is KotlinClassFinder.Result.KotlinClass) {
if (parentContext != null || (classId.isNestedClass && getClass(classId.outermostClassId)?.fir !is FirJavaClass)) {
// Nested class of Kotlin class should have been a Kotlin class.
return null
}
val knownContent = (result as? KotlinClassFinder.Result.ClassFileContent)?.content
val javaClass = javaFacade.findClass(classId, knownContent) ?: return null
return ClassMetadataFindResult.NoMetadata { symbol ->
javaFacade.convertJavaClassToFir(symbol, classId.outerClassId?.let(::getClass), javaClass)
}
}
val kotlinClass = result.kotlinJvmBinaryClass
if (kotlinClass.classHeader.kind != KotlinClassHeader.Kind.CLASS || kotlinClass.classId != classId) return null
val data = kotlinClass.classHeader.data ?: kotlinClass.classHeader.incompatibleData ?: return null
val strings = kotlinClass.classHeader.strings ?: return null
val (nameResolver, classProto) = parseProto(kotlinClass) {
JvmProtoBufUtil.readClassDataFrom(data, strings)
} ?: return null
return ClassMetadataFindResult.Metadata(
nameResolver,
classProto,
JvmBinaryAnnotationDeserializer(session, kotlinClass, kotlinClassFinder, result.byteContent),
moduleDataProvider.getModuleData(kotlinClass.containingLibrary?.toPath()),
KotlinJvmBinarySourceElement(
kotlinClass, kotlinClass.incompatibility, kotlinClass.isPreReleaseInvisible, kotlinClass.abiStability,
),
classPostProcessor = { loadAnnotationsFromClassFile(result, it) }
)
}
override fun isNewPlaceForBodyGeneration(classProto: ProtoBuf.Class): Boolean =
JvmFlags.IS_COMPILED_IN_JVM_DEFAULT_MODE.get(classProto.getExtension(JvmProtoBuf.jvmClassFlags))
override fun getPackage(fqName: FqName): FqName? =
javaFacade.getPackage(fqName)
private fun loadAnnotationsFromClassFile(
kotlinClass: KotlinClassFinder.Result.KotlinClass,
symbol: FirRegularClassSymbol
) {
val annotations = mutableListOf<FirAnnotation>()
var hasPublishedApi = false
kotlinClass.kotlinJvmBinaryClass.loadClassAnnotations(
object : KotlinJvmBinaryClass.AnnotationVisitor {
override fun visitAnnotation(classId: ClassId, source: SourceElement): KotlinJvmBinaryClass.AnnotationArgumentVisitor? {
if (classId == StandardClassIds.Annotations.PublishedApi) {
hasPublishedApi = true
}
return annotationsLoader.loadAnnotationIfNotSpecial(classId, annotations)
}
override fun visitEnd() {
}
},
kotlinClass.byteContent,
)
symbol.fir.run {
replaceAnnotations(annotations.toMutableOrEmpty())
replaceDeprecationsProvider(symbol.fir.getDeprecationsProvider(session))
setLazyPublishedVisibility(hasPublishedApi, null, session)
}
}
private fun String?.toPath(): Path? {
return this?.let { Paths.get(it).normalize() }
}
private inline fun <T : Any> parseProto(klass: KotlinJvmBinaryClass, block: () -> T): T? =
try {
block()
} catch (e: Throwable) {
if (session.languageVersionSettings.getFlag(AnalysisFlags.skipMetadataVersionCheck) ||
klass.classHeader.metadataVersion.isCompatible(ownMetadataVersion)
) {
throw if (e is InvalidProtocolBufferException)
IllegalStateException("Could not read data from ${klass.location}", e)
else e
}
null
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 12,117 | kotlin | Apache License 2.0 |
compiler/testData/integration/smoke/helloAppFQMain/hello.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | package Hello
fun main(args: kotlin.Array<kotlin.String>) {
args.size
System.out.println("Hello from fully qualified main!")
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 136 | kotlin | Apache License 2.0 |
app/src/main/java/info/hannes/liveedgedetection/demo/StartActivity.kt | prahlad-dev | 341,799,904 | false | {"Java": 1201072, "Kotlin": 78358, "Shell": 935} | package info.hannes.liveedgedetection.demo
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import info.hannes.liveedgedetection.ScanConstants
import info.hannes.liveedgedetection.activity.ScanActivity
import kotlinx.android.synthetic.main.activity_start.*
import java.io.File
class StartActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_start)
buttonScan.setOnClickListener { startActivity(Intent(this, MainActivity::class.java)) }
}
}
| 0 | Java | 0 | 0 | a2a69fdfeab85bf823122b6ed59eac6008fc02a7 | 982 | DocScan | Apache License 2.0 |
src/main/kotlin/no/nav/helse/brreg/Application.kt | navikt | 249,670,167 | false | {"Kotlin": 33949, "Dockerfile": 771} | package no.nav.helse.brreg
import io.ktor.http.*
import io.ktor.server.application.Application
import io.ktor.server.application.call
import io.ktor.server.application.install
import io.ktor.server.metrics.micrometer.*
import io.ktor.server.response.*
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import io.micrometer.core.instrument.Clock
import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics
import io.micrometer.core.instrument.binder.system.ProcessorMetrics
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.common.TextFormat
import org.slf4j.LoggerFactory
import java.io.StringWriter
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
private val collectorRegistry = CollectorRegistry.defaultRegistry
internal val instrumentation = Instrumentation(collectorRegistry)
private val log = LoggerFactory.getLogger("no.nav.helse.brreg.Application")
fun Application.brregModule(
enhetsregisteret: EnhetsregisteretOffline =
EnhetsregisteretOffline(
instrumentation = instrumentation,
alleEnheter = EnhetsregisterIndexedJson(brregEmbeddedJsonAlleEnheter),
alleUnderenheter = EnhetsregisterIndexedJson(brregEmbeddedJsonAlleUnderenheter)
),
enableDownloadScheduler: Boolean = true
) {
install(MicrometerMetrics) {
registry = PrometheusMeterRegistry(
PrometheusConfig.DEFAULT,
collectorRegistry,
Clock.SYSTEM
)
meterBinders = listOf(
ClassLoaderMetrics(),
JvmMemoryMetrics(),
JvmGcMetrics(),
ProcessorMetrics(),
JvmThreadMetrics()
)
}
if (enableDownloadScheduler) setupDownloadScheduler(enhetsregisteret, instrumentation.downloadAndIndexTimeObserver)
routing {
get("/enhetsregisteret/api/underenheter/{orgnr}") {
log.info("get underenheter")
val orgnr = try {
OrgNr(call.parameters["orgnr"]!!)
} catch (ex: IllegalArgumentException) {
call.respond(HttpStatusCode.BadRequest, "ugyldig orgnr")
return@get
}
val data = enhetsregisteret.hentUnderenhet(orgnr)
if (null == data) {
call.respond(HttpStatusCode.NotFound, "fant ikke organisasjon")
return@get
}
call.respondText(data.toString(),
ContentType("application", "json"))
}
get("/enhetsregisteret/api/enheter/{orgnr}") {
log.info("get enheter")
val orgnr = try {
OrgNr(call.parameters["orgnr"]!!)
} catch (ex: IllegalArgumentException) {
call.respond(HttpStatusCode.BadRequest, "ugyldig orgnr")
return@get
}
val data = enhetsregisteret.hentEnhet(orgnr)
if (null == data) {
call.respond(HttpStatusCode.NotFound, "fant ikke organisasjon")
return@get
}
call.respondText(data.toString(),
ContentType("application", "json"))
}
get("/enhetsregisteret/api/underenheter_for_overordnet/{overordnet_orgnr}") {
log.info("get underenheter_for_overordnet")
val orgnr = try {
OrgNr(call.parameters["overordnet_orgnr"]!!)
} catch (ex: IllegalArgumentException) {
call.respond(HttpStatusCode.BadRequest, "ugyldig orgnr")
return@get
}
val data = enhetsregisteret.hentUnderenheterHvorOverordnetEr(orgnr)
call.respondText(data.toString(),
ContentType("application", "json"))
}
get("/enhetsregisteret/api/enheter_for_overordnet/{overordnet_orgnr}") {
log.info("get enheter_for_overordnet")
val orgnr = try {
OrgNr(call.parameters["overordnet_orgnr"]!!)
} catch (ex: IllegalArgumentException) {
call.respond(HttpStatusCode.BadRequest, "ugyldig orgnr")
return@get
}
val data = enhetsregisteret.hentEnheterHvorOverordnetEr(orgnr)
call.respondText(data.toString(),
ContentType("application", "json"))
}
get("/isalive") {
call.respondText("ALIVE", ContentType.Text.Plain)
}
get("/isready") {
call.respondText("READY", ContentType.Text.Plain)
}
get("/metrics") {
val names = call.request.queryParameters.getAll("name[]")?.toSet() ?: emptySet()
val text = StringWriter()
TextFormat.write004(text, collectorRegistry.filteredMetricFamilySamples(names))
call.respondText(text = text.toString(), contentType = ContentType.parse(TextFormat.CONTENT_TYPE_004))
}
}
}
| 1 | Kotlin | 0 | 0 | ca4c213511a050388de5d98a4922e435e3e6d5df | 5,235 | helse-brreg | MIT License |
app/src/main/java/com/kirakishou/photoexchange/service/PushNotificationReceiverService.kt | K1rakishou | 109,590,033 | false | null | package com.kirakishou.photoexchange.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.kirakishou.photoexchange.PhotoExchangeApplication
import com.kirakishou.photoexchange.helper.Constants
import com.kirakishou.photoexchange.helper.database.repository.SettingsRepository
import com.kirakishou.photoexchange.mvrx.model.NewReceivedPhoto
import com.kirakishou.photoexchange.ui.activity.PhotosActivity
import com.kirakishou.photoexchange.usecases.StorePhotoFromPushNotificationUseCase
import kotlinx.coroutines.runBlocking
import timber.log.Timber
import javax.inject.Inject
class PushNotificationReceiverService : FirebaseMessagingService() {
private val TAG = "PushNotificationReceiverService"
@Inject
lateinit var settingsRepository: SettingsRepository
@Inject
lateinit var storePhotoFromPushNotificationUseCase: StorePhotoFromPushNotificationUseCase
override fun onCreate() {
super.onCreate()
(application as PhotoExchangeApplication).applicationComponent
.inject(this)
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
Timber.tag(TAG).d("onMessageReceived called")
if (remoteMessage == null) {
Timber.tag(TAG).w("Null remoteMessage has been received!")
return
}
val newReceivedPhoto = try {
extractData(remoteMessage)
} catch (error: Throwable) {
Timber.tag(TAG).e(error)
null
}
if (newReceivedPhoto != null) {
Timber.tag(TAG).d("Got new photo from someone")
runBlocking {
if (!storePhotoFromPushNotificationUseCase.storePhotoFromPushNotification(newReceivedPhoto)) {
Timber.tag(TAG).w("Could not store newReceivedPhoto")
return@runBlocking
}
showNotification(newReceivedPhoto)
sendPhotoReceivedBroadcast(newReceivedPhoto)
}
}
}
override fun onNewToken(token: String?) {
Timber.tag(TAG).d("onNewToken called")
if (token == null) {
Timber.tag(TAG).w("Null token has been received!")
return
}
runBlocking {
try {
if (!settingsRepository.saveNewFirebaseToken(token)) {
throw RuntimeException("Could not update new firebase token")
}
Timber.tag(TAG).d("Successfully updated firebase token")
} catch (error: Throwable) {
Timber.tag(TAG).e(error, "Could not update new firebase token")
}
}
}
private fun extractData(remoteMessage: RemoteMessage): NewReceivedPhoto {
val data = remoteMessage.data
val uploadedPhotoName = data.get(NewReceivedPhoto.uploadedPhotoNameField)
if (uploadedPhotoName.isNullOrEmpty()) {
throw PushNotificationExctractionException("Could not extract uploadedPhotoName")
}
val receivedPhotoName = data.get(NewReceivedPhoto.receivedPhotoNameField)
if (receivedPhotoName.isNullOrEmpty()) {
throw PushNotificationExctractionException("Could not extract receivedPhotoName")
}
val receiverLon = data.get(NewReceivedPhoto.receiverLonField)?.toDoubleOrNull()
if (receiverLon == null) {
throw PushNotificationExctractionException("Could not extract receiverLon")
}
val receiverLat = data.get(NewReceivedPhoto.receiverLatField)?.toDoubleOrNull()
if (receiverLat == null) {
throw PushNotificationExctractionException("Could not extract receiverLat")
}
val uploadedOn = data.get(NewReceivedPhoto.uploadedOnField)?.toLongOrNull()
if (uploadedOn == null) {
throw PushNotificationExctractionException("Could not extract uploadedOn")
}
return NewReceivedPhoto(
uploadedPhotoName,
receivedPhotoName,
receiverLon,
receiverLat,
uploadedOn
)
}
private fun sendPhotoReceivedBroadcast(newReceivedPhoto: NewReceivedPhoto) {
Timber.tag(TAG).d("sendPhotoReceivedBroadcast called")
val intent = Intent().apply {
action = PhotosActivity.newPhotoReceivedAction
val bundle = Bundle()
newReceivedPhoto.toBundle(bundle)
putExtra(PhotosActivity.receivedPhotoExtra, bundle)
}
sendBroadcast(intent)
}
private fun showNotification(newReceivedPhoto: NewReceivedPhoto) {
Timber.tag(TAG).d("showNotification called")
val intent = Intent(this, PhotosActivity::class.java).apply {
val bundle = Bundle()
newReceivedPhoto.toBundle(bundle)
putExtra(PhotosActivity.receivedPhotoExtra, bundle)
}
val pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_ONE_SHOT
)
val notificationBuilder = NotificationCompat.Builder(this, Constants.CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setContentTitle("You got a new photo from someone")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
Constants.CHANNEL_ID,
Constants.CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
)
channel.enableLights(true)
channel.vibrationPattern = vibrationPattern
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
}
class PushNotificationExctractionException(msg: String) : Exception(msg)
companion object {
private val vibrationPattern = LongArray(4).apply {
this[0] = 0L
this[1] = 300L
this[2] = 200L
this[3] = 300L
}
const val NOTIFICATION_ID = 3
}
} | 0 | Kotlin | 1 | 4 | 15f67029376a98353a01b5523dfb42d183a26bf2 | 5,972 | photoexchange-android | Do What The F*ck You Want To Public License |
sources-jvm/traits/MExecutable.kt | fluidsonic | 168,738,824 | false | null | package io.fluidsonic.meta
public interface MExecutable {
public val jvmSignature: MJvmMemberSignature.Method?
public val valueParameters: List<MValueParameter>
public companion object
}
| 0 | Kotlin | 2 | 12 | 4ee8c2f3bbc9e0de7cefbd1f72244d46080ccdf1 | 195 | fluid-meta | Apache License 2.0 |
javascript/js-type-analysis/src/org/jetbrains/dukat/js/type/constraint/composite/UnionTypeConstraint.kt | Kotlin | 159,510,660 | false | {"Kotlin": 2656346, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333} | package org.jetbrains.dukat.js.type.constraint.composite
import org.jetbrains.dukat.js.type.constraint.Constraint
import org.jetbrains.dukat.js.type.constraint.immutable.ImmutableConstraint
import org.jetbrains.dukat.js.type.constraint.immutable.resolved.NoTypeConstraint
import org.jetbrains.dukat.js.type.constraint.immutable.resolved.RecursiveConstraint
import org.jetbrains.dukat.js.type.constraint.immutable.resolved.ThrowConstraint
class UnionTypeConstraint(
val types: List<Constraint>
) : ImmutableConstraint {
override fun resolve(resolveAsInput: Boolean): Constraint {
val resolvedTypes = types.map { it.resolve(resolveAsInput) }.filter { it != RecursiveConstraint && it != ThrowConstraint }
return when (resolvedTypes.size) {
0 -> NoTypeConstraint
1 -> resolvedTypes[0]
else -> UnionTypeConstraint(resolvedTypes)
}
}
}
| 242 | Kotlin | 43 | 508 | 55213ea607fb42ff13b6278613c8fbcced9aa418 | 909 | dukat | Apache License 2.0 |
app/src/main/java/com/johnnym/recyclerviewanimations/common/MarginItemDecoration.kt | johnnymartinovic | 167,826,424 | false | null | package com.johnnym.recyclerviewanimations.common
import android.graphics.Rect
import androidx.recyclerview.widget.RecyclerView
import android.view.View
class MarginItemDecoration(
private val margin: Int
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
outRect.top = margin
outRect.bottom = margin
outRect.left = margin
outRect.right = margin
}
}
| 0 | Kotlin | 9 | 48 | a7ecde352da6a48d60a0e2235b1cc9f349d7756c | 492 | RecyclerViewAnimations | The Unlicense |
compiler/testData/ir/irText/declarations/parameters/genericInnerClass.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
class Outer<T1> {
inner class Inner<T2> {
fun foo(x1: T1, x2: T2) {}
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 107 | kotlin | Apache License 2.0 |
src/main/kotlin/org/bois/htmlGenerator/NamespacePageCreator.kt | nokt0 | 256,224,023 | false | null | package org.bois.htmlGenerator
import org.bois.parser.HeaderType
import org.bois.parser.ParsedClass
import java.io.File
class NamespacePageCreator(val namespaceName: String) : AbstractPageCreator(){
private val types = HashSet<HeaderType>()
private fun createContainTypes(parsedClasses: ArrayList<ParsedClass>) {
for (item in parsedClasses) {
if (item.type != null) {
types.add(item.type)
}
}
}
fun create(parsedClasses: ArrayList<ParsedClass>) {
readTemplate(namespacePageTemplate())
createContainTypes(parsedClasses)
val firstChild = body?.getElementById("heading-container")
val containers = addTypeContainers(parsedClasses)
if (firstChild != null) {
firstChild.after(containers)
}
deleteTemplateThrash()
}
private fun addTypeContainers(parsedClasses: ArrayList<ParsedClass>): String {
var containers = ""
for (type in types) {
val header = when (type) {
HeaderType.ABSTRACT_CLASS -> "Abstract Class"
HeaderType.ENUM -> "Enum"
HeaderType.CLASS -> "Class"
HeaderType.INTERFACE -> "Interface"
HeaderType.STRUCT -> "Struct"
else -> throw Exception()
}
val filtered = parsedClasses.filter { it.type == type }
val nameDescription = createNameDescription(filtered)
containers += createTypeContainer(header, nameDescription)
}
return containers;
}
private fun createClassRow(className: String, description: String): String {
return "<tr>\n" +
" <td style=\"font-size: 14px;\"><a href=\"./class.html\">$className</a></td>\n" +
" <td style=\"font-size: 14px;\">$description<br /></td>\n" +
"</tr>"
}
private fun createTypeContainer(header: String, classDescription: ArrayList<Pair<String, String>>): String {
var classes = ""
for ((name, description) in classDescription) {
classes += createClassRow(name, description)
}
return "<div class=\"container\">\n" +
" <div class=\"table-responsive\">\n" +
" <table class=\"table\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th class=\"table-header-name\">$header Summary</th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>$header</strong></td>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Description</strong></td>\n" +
" </tr>\n" +
" $classes" +
" </tbody>\n" +
" </table>\n" +
" </div>\n" +
"</div>"
}
fun namespacePageTemplate(): String {
return "<!DOCTYPE html>\n" +
"<html>\n" +
"\n" +
"<head>\n" +
" <meta charset=\"utf-8\">\n" +
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, shrink-to-fit=no\">\n" +
" <title>Rider-DocGenerator</title>\n" +
" <link rel=\"stylesheet\" href=\"../assets/bootstrap/css/bootstrap.min.css\">\n" +
" <link rel=\"stylesheet\" href=\"../assets/css/styles.min.css\">\n" +
"</head>\n" +
"\n" +
"<body>\n" +
" <nav class=\"navbar navbar-light navbar-expand-md\" style=\"background-color: #93b7d1;padding-top: 0px;padding-bottom: 0px;\">\n" +
" <div class=\"container-fluid\"><a class=\"navbar-brand text-light\" href=\"./index.html\" style=\"margin-right: 30px;\"><img src=\"../assets/img/pluginIcon.svg\" width=\"64px\">Rider-DocGenerator</a><button data-toggle=\"collapse\" class=\"navbar-toggler\" data-target=\"#navcol-1\"><span class=\"sr-only\">Toggle navigation</span><span class=\"navbar-toggler-icon\"></span></button>\n" +
" <div\n" +
" class=\"collapse navbar-collapse\" id=\"navcol-1\">\n" +
" <ul class=\"nav navbar-nav\">\n" +
" <li class=\"nav-item\" role=\"presentation\"><a class=\"nav-link active\" href=\"./index.html\">Namespaces</a></li>\n" +
" <li class=\"nav-item\" role=\"presentation\"><a class=\"nav-link active\" href=\"#\">Tree</a></li>\n" +
" </ul>\n" +
" </div>\n" +
" </div>\n" +
" </nav>\n" +
" <main>\n" +
" <div class=\"container\" id=\"heading-container\">\n" +
" <h1 id=\"namespace-title\">Namespace name</h1>\n" +
" </div>\n" +
" <div class=\"container\" id=\"template-stub\">\n" +
" <div class=\"table-responsive\" style=\"margin-top: 10px;\">\n" +
" <table class=\"table\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th class=\"table-header-name\">Interface Summary</th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Interface</strong></td>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Description</strong></td>\n" +
" </tr>\n" +
" <tr id=\"template-stub\">\n" +
" <td style=\"font-size: 14px;\"><a href=\"class.html\">Interface1</a></td>\n" +
" <td style=\"font-size: 14px;\">Description of Interafce</td>\n" +
" </tr>\n" +
" </tbody>\n" +
" </table>\n" +
" </div>\n" +
" </div>\n" +
" <div class=\"container\" id=\"template-stub\">\n" +
" <div class=\"table-responsive\">\n" +
" <table class=\"table\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th class=\"table-header-name\">Abstract Class Summary</th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Abstract Class</strong></td>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Description</strong></td>\n" +
" </tr>\n" +
" <tr id=\"template-stub\">\n" +
" <td style=\"font-size: 14px;\"><a href=\"class.html\">AbstractClass1</a></td>\n" +
" <td style=\"font-size: 14px;\">Description of Abstract class<br></td>\n" +
" </tr>\n" +
" </tbody>\n" +
" </table>\n" +
" </div>\n" +
" </div>\n" +
" <div class=\"container\" id=\"template-stub\">\n" +
" <div class=\"table-responsive\">\n" +
" <table class=\"table\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th class=\"table-header-name\">Enum Summary</th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Enum</strong></td>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Description</strong></td>\n" +
" </tr>\n" +
" <tr id=\"template-stub\">\n" +
" <td style=\"font-size: 14px;\"><a href=\"class.html\">Enum</a></td>\n" +
" <td style=\"font-size: 14px;\">Description of Enum<br></td>\n" +
" </tr>\n" +
" </tbody>\n" +
" </table>\n" +
" </div>\n" +
" </div>\n" +
" <div class=\"container\" id=\"template-stub\">\n" +
" <div class=\"table-responsive\">\n" +
" <table class=\"table\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th class=\"table-header-name\">Struct Summary</th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Struct</strong></td>\n" +
" <td class=\"table-secondary table-secondary-header\"><strong>Description</strong></td>\n" +
" </tr>\n" +
" <tr id=\"template-stub\">\n" +
" <td style=\"font-size: 14px;\"><a href=\"class.html\">Struct</a></td>\n" +
" <td style=\"font-size: 14px;\">Description of Struct<br></td>\n" +
" </tr>\n" +
" </tbody>\n" +
" </table>\n" +
" </div>\n" +
" </div>\n" +
" </main>\n" +
" <script src=\"../assets/js/jquery.min.js\"></script>\n" +
" <script src=\"../assets/bootstrap/js/bootstrap.min.js\"></script>\n" +
"</body>\n" +
"\n" +
"</html>"
}
} | 0 | Kotlin | 0 | 0 | 5b9d9b46fafe24419a83e6398b93b02c3087e670 | 11,503 | Rider-DocGenerator | Apache License 2.0 |
compiler/testData/codegen/bytecodeText/optimizedDelegatedProperties/lazy.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
val topLevelLazyVal by lazy { 1 }
class C {
val memberLazyVal by lazy { 2 }
}
fun box(): String {
val localLazyVal by lazy { 3 }
if (topLevelLazyVal != 1) throw AssertionError()
if (C().memberLazyVal != 2) throw AssertionError()
if (localLazyVal != 3) throw AssertionError()
return "OK"
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 332 | kotlin | Apache License 2.0 |
recycler/build.gradle.kts | AniTrend | 155,243,365 | false | {"Kotlin": 385489} | plugins {
id("co.anitrend.arch")
}
android {
namespace = "co.anitrend.arch.recycler"
}
dependencies {
implementation(project(":extension"))
implementation(project(":core"))
implementation(project(":theme"))
implementation(project(":domain"))
implementation(libs.google.android.material)
implementation(libs.androidx.swipeRefreshLayout)
implementation(libs.androidx.recyclerView)
} | 4 | Kotlin | 1 | 7 | 03d83e948a90e4164823ab9e966e787704eef677 | 420 | support-arch | Apache License 2.0 |
common/src/commonMain/kotlin/io/xorum/codeforceswatcher/network/responses/ContestsResponse.kt | jpappdesigns | 296,574,266 | true | {"Kotlin": 173256, "Swift": 99541, "Ruby": 2480} | package io.xorum.codeforceswatcher.network.responses
import com.soywiz.klock.DateFormat
import com.soywiz.klock.parse
import io.xorum.codeforceswatcher.features.contests.models.Contest
import io.xorum.codeforceswatcher.features.contests.models.Platform
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ContestResponse(
val name: String,
val url: String,
@SerialName("start_time") val startTime: String,
val duration: Double,
val status: String,
@SerialName("site") val platform: String
) {
fun toContest(): Contest {
val dateFormat = DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
return Contest(0L, name, dateFormat.parse(startTime).local.unixMillisLong, duration.toLong() * 1000, status, parsePlatform(platform)).apply { link = url }
}
private fun parsePlatform(platform: String) = when (platform) {
"CodeForces" -> Platform.CODEFORCES
"CodeForces::Gym" -> Platform.CODEFORCES_GYM
"TopCoder" -> Platform.TOPCODER
"AtCoder" -> Platform.ATCODER
"CS Academy" -> Platform.CS_ACADEMY
"CodeChef" -> Platform.CODECHEF
"HackerRank" -> Platform.HACKERRANK
"HackerEarth" -> Platform.HACKEREARTH
"Kick Start" -> Platform.KICK_START
"LeetCode" -> Platform.LEETCODE
"A2OJ" -> Platform.CODEFORCES
else -> Platform.CODEFORCES
}
}
| 0 | Kotlin | 0 | 1 | d6d84e1c26667e0c220b3386f5b6354ffae99336 | 1,450 | codeforces_watcher | MIT License |
users/src/main/java/com.addhen.github.users/UserItemViewModel.kt | eyedol | 144,961,411 | false | null | package com.addhen.github.users
import androidx.lifecycle.ViewModel
import com.addhen.github.AppNavigation
import com.addhen.github.user.model.User
class UserItemViewModel(val user: User, val appNavigation: AppNavigation) : ViewModel() {
fun onUserClick() {
appNavigation.navigateToUser(user.username)
}
}
| 1 | Kotlin | 0 | 0 | 9308cd2f6ade8e66040266b920d83335dac53acf | 325 | github-android-client | Apache License 2.0 |
compiler/testData/asJava/lightClasses/lightClassByFqName/ideRegression/ImplementingMutableSet.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // SmartSet
class SmartSet<T> private constructor() : AbstractSet<T>(), MutableSet<T> {
companion object {
private val ARRAY_THRESHOLD = 5
@JvmStatic
fun <T> create() = SmartSet<T>()
@JvmStatic
fun <T> create(set: Collection<T>): SmartSet<T> = TODO()
}
private var data: Any? = null
override var size: Int = 0
override fun iterator(): MutableIterator<T> = TODO()
override fun add(element: T): Boolean = TODO()
override fun clear() {
data = null
size = 0
}
}
// COMPILATION_ERRORS | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 578 | kotlin | Apache License 2.0 |
app/src/main/java/com/oliverspryn/medium/androidunittests/mvc/ObservableViewMvc.kt | oliverspryn | 218,304,493 | false | null | package com.oliverspryn.medium.androidunittests.mvc
interface ObservableViewMvc<Listener> : ViewMvc {
fun getListeners(): List<Listener>
fun registerListener(listener: Listener)
fun unregisterListener(listener: Listener)
}
| 0 | Kotlin | 0 | 0 | 8700a987abe890eb54a112bd95bbcad3694f03be | 243 | android-unit-tests | MIT License |
native/objcexport-header-generator/impl/analysis-api/test/org/jetbrains/kotlin/objcexport/testUtils/InlineSourceCodeAnalysisExtension.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.objcexport.testUtils
import org.intellij.lang.annotations.Language
import org.jetbrains.kotlin.psi.KtFile
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.ExtensionContext.Namespace
import org.junit.jupiter.api.extension.ParameterContext
import org.junit.jupiter.api.extension.ParameterResolver
import java.io.File
import java.nio.file.Files
/**
* Provides ability to quickly write tests with 'inline source code' aka passing Kotlin source code as String.
*
* This interface can be injected into any test class constructor.
*
* ### Example
* ```
* class MyTest(
* private val inlineSourceCodeAnalysis: InlineSourceCodeAnalysis
* ) {
* @Test
* fun `test - something important`() {
* val myFile = inlineSourceCodeAnalysis.createKtFile("class Foo")
* analyze(myFile) {
* // Use analysis session to write advanced tests
* }
* }
* }
* ```
*/
interface InlineSourceCodeAnalysis {
fun createKtFile(@Language("kotlin") sourceCode: String): KtFile
}
/**
* Extension used to inject an instance of [InlineSourceCodeAnalysis] into tests.
*/
class InlineSourceCodeAnalysisExtension : ParameterResolver, AfterEachCallback {
private companion object {
val namespace: Namespace = Namespace.create(Any())
val tempDirKey = Any()
}
override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean {
return parameterContext.parameter.type == InlineSourceCodeAnalysis::class.java
}
override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any {
val temporaryDirectory = Files.createTempDirectory("inlineSourceCode").toFile()
extensionContext.getStore(namespace.append(extensionContext.requiredTestClass)).put(tempDirKey, temporaryDirectory)
return InlineSourceCodeAnalysisImpl(temporaryDirectory)
}
override fun afterEach(context: ExtensionContext) {
context.getStore(namespace.append(context.requiredTestClass))?.get(tempDirKey, File::class.java)?.deleteRecursively()
}
}
/**
* Simple implementation [InlineSourceCodeAnalysis]
*/
private class InlineSourceCodeAnalysisImpl(private val tempDir: File) : InlineSourceCodeAnalysis {
override fun createKtFile(@Language("kotlin") sourceCode: String): KtFile {
return createStandaloneAnalysisApiSession(tempDir, listOf(sourceCode))
.modulesWithFiles.entries.single()
.value.single() as KtFile
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,870 | kotlin | Apache License 2.0 |
compiler/tests-spec/testData/diagnostics/linked/type-inference/smart-casts/smart-cast-sink-stability/p-5/pos/1.1.fir.kt | android | 263,405,600 | true | null | // !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_VARIABLE -ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE -UNUSED_VALUE -UNUSED_PARAMETER -UNUSED_EXPRESSION
// SKIP_TXT
// TESTCASE NUMBER: 1
class Case1() {
class E(val plus: Inv? = null, val value: Inv? = null)
class Inv() {
operator fun invoke(value: Int) = Case1()
}
fun foo(e: E) {
if (e.value != null) {
run { e.value(1) }
/*
[UNSAFE_CALL] (nok)
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Case1.Inv?
*/
e.value(1)
}
}
}
| 34 | Kotlin | 49 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 641 | kotlin | Apache License 2.0 |
src/main/kotlin/org/polystat/j2eo/translator/Blocks.kt | polystat | 393,459,176 | false | {"Java": 411876, "Kotlin": 185484, "ANTLR": 27247, "XSLT": 2574, "Python": 1978, "Dockerfile": 1907, "Shell": 1573} | package org.polystat.j2eo.translator
import arrow.core.None
import org.polystat.j2eo.eotree.EOBndExpr
import org.polystat.j2eo.eotree.EOCopy
import org.polystat.j2eo.eotree.EOObject
import org.polystat.j2eo.eotree.eoDot
import tree.Statement.Block
import tree.Statement.BlockStatement
/**
* In order to map Java block into EO, all variable declarations are separated out as memory objects and then seq
* contains all the logic.
*/
fun mapBlock(
block: Block,
context: Context,
name: String? = null,
firstStmts: List<Pair<String, List<EOBndExpr>>>? = null,
lastStmts: List<Pair<String, List<EOBndExpr>>>? = null,
paramList: List<String>? = null
): List<EOBndExpr> {
if (name != null) {
return listOf(
EOBndExpr(
EOObject(
paramList ?: listOf(),
None,
mapBlock(block, context, firstStmts = firstStmts, lastStmts = lastStmts)
),
name
)
)
}
val statementsNames = block.block.blockStatements.associateWith { getBlockStmtName(it, context) }
val parsedStatements = block.block.blockStatements
.associate { statementsNames[it]!! to mapBlockStatement(it, statementsNames[it]!!, context) }
return listOf(
EOBndExpr(
EOCopy(
"seq",
(firstStmts?.map { it.first.eoDot() } ?: listOf()) +
if (parsedStatements.isNotEmpty())
parsedStatements.keys.map { it.eoDot() }
else {
if (firstStmts == null && lastStmts == null) {
listOf("TRUE".eoDot())
} else {
listOf()
}
} +
(lastStmts?.map { it.first.eoDot() } ?: listOf())
),
"@"
)
) + (firstStmts?.map { it.second }?.flatten() ?: listOf()) +
parsedStatements.values.toList().flatten() +
(lastStmts?.map { it.second }?.flatten() ?: listOf())
}
fun getBlockStmtName(blockStatement: BlockStatement, context: Context): String {
return if (blockStatement.statement != null) {
context.genUniqueEntityName(blockStatement.statement)
} else if (blockStatement.expression != null) {
context.genUniqueEntityName(blockStatement.expression)
} else if (blockStatement.declaration != null) {
context.genUniqueEntityName(blockStatement.declaration)
} else {
throw java.lang.IllegalArgumentException("Invalid block statement!")
}
}
fun mapBlockStatement(blockStatement: BlockStatement, name: String, context: Context): List<EOBndExpr> {
return if (blockStatement.statement != null) {
mapStatement(blockStatement.statement, name, context)
} else if (blockStatement.expression != null) {
mapExpression(blockStatement.expression, name, context)
} else if (blockStatement.declaration != null) {
mapDeclaration(blockStatement.declaration, name, context)
} else {
throw java.lang.IllegalArgumentException("Invalid block statement!")
}
}
| 52 | Java | 11 | 11 | f44117420060653e27248f793637a7280b1d7ae4 | 3,193 | j2eo | MIT License |
cryptoapi/src/main/java/io/pixelplex/mobile/cryptoapi/CryptoApiFramework.kt | cryptoapi-project | 245,105,614 | false | null | package io.pixelplex.mobile.cryptoapi
import io.pixelplex.mobile.cryptoapi.core.CryptoApi
import io.pixelplex.mobile.cryptoapi.generation.*
import io.pixelplex.mobile.cryptoapi.wrapper.CryptoApiConfiguration
import io.pixelplex.mobile.cryptoapi.wrapper.InstanceHolder
/**
* Delegates all logic to specific wrapper services which associated
* Crypto API calls
*
* @author <NAME>
*/
class CryptoApiFramework constructor(
cryptoApiParams: CryptoApiConfiguration
) {
private val cryptoApi: CryptoApi =
CryptoApi(
cryptoApiParams
)
val coinsApi: CoinApi = CoinApiImpl(cryptoApi)
val coinsAsyncApi: CoinAsyncApi = CoinAsyncApiImpl(cryptoApi)
val ratesApi: RatesApi = RatesApiImpl(cryptoApi)
val ratesAsyncApi: RatesAsyncApi = RatesAsyncApiImpl(cryptoApi)
val ethereumApi: EthApi = EthApiImpl(cryptoApi)
val ethereumAsyncApi: EthAsyncApi = EthAsyncApiImpl(cryptoApi)
val bitcoinApi: BtcApi = BtcApiImpl(cryptoApi)
val bitcoinAsyncApi: BtcAsyncApi = BtcAsyncApiImpl(cryptoApi)
val bitcoinCashApi: BchApi = BchApiImpl(cryptoApi)
val bitcoinCashAsyncApi: BchAsyncApi = BchAsyncApiImpl(cryptoApi)
val litecoinApi: LtcApi = LtcApiImpl(cryptoApi)
val litecoinAsyncApi: LtcAsyncApi = LtcAsyncApiImpl(cryptoApi)
companion object :
InstanceHolder<CryptoApiFramework, CryptoApiConfiguration>(::CryptoApiFramework)
} | 0 | Kotlin | 0 | 0 | 8362c0cd1fed18c67edbb7e98087beae0c023ac7 | 1,424 | cryptoapi-kotlin | MIT License |
common/src/main/java/com/theone/common/ext/LogExt.kt | Theoneee | 391,850,188 | false | null | package com.theone.common.ext
import android.util.Log
var TAG = "TheBase"
private var LOG_ENABLE = true
fun LogInit(enable: Boolean, tag: String = "TheBase") {
LOG_ENABLE = enable
TAG = tag
}
private enum class LEVEL {
V, D, I, W, E
}
fun String.logV(tag: String = TAG) =
log(
LEVEL.V,
tag,
this
)
fun String.logD(tag: String = TAG) =
log(
LEVEL.D,
tag,
this
)
fun String.logI(tag: String = TAG) =
log(
LEVEL.I,
tag,
this
)
fun String.logW(tag: String = TAG) =
log(
LEVEL.W,
tag,
this
)
fun String.logE(tag: String = TAG) =
log(
LEVEL.E,
tag,
this
)
private fun log(level: LEVEL, tag: String, message: String) {
if (LOG_ENABLE)
when (level) {
LEVEL.V -> Log.v(tag, message)
LEVEL.D -> Log.d(tag, message)
LEVEL.I -> Log.i(tag, message)
LEVEL.W -> Log.w(tag, message)
LEVEL.E -> Log.e(tag, message)
}
} | 0 | Kotlin | 1 | 5 | 311f6e6caeae747b4fd99fc237c6b2bca1770aa6 | 1,063 | TheDemo-MVVM | Apache License 2.0 |
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/skills/slayer/slayer.plugin.kts | 2011Scape | 578,880,245 | false | {"Kotlin": 8100267, "Dockerfile": 1354} | package gg.rsmod.plugins.content.skills.slayer
import gg.rsmod.game.model.attr.KILLER_ATTR
/**
* @author Alycia <https://github.com/alycii>
*/
set_slayer_logic {
// Cast the pawn to an Npc and check if it has the KILLER_ATTR attribute
val npc = pawn as Npc
if (pawn.attr.has(KILLER_ATTR)) {
// Get the most damaging entity from the npc's damageMap and cast it to a Player
val player = npc.damageMap.getMostDamage() as? Player
// If the entity is a Player and has the same slayer assignment as the NPC, decrese the amount
if (player != null && player.getSlayerAssignment() != null) {
if(player.getSlayerAssignment() == npc.combatDef.slayerAssignment) {
player.handleDecrease(npc)
}
}
}
} | 30 | Kotlin | 100 | 26 | 72de83aa7764b0bb0691da0b4f5716cbf0cae79e | 787 | game | Apache License 2.0 |
app/src/main/java/com/bogdan801/weatheraggregator/presentation/composables/SelectDataSourcesSheet.kt | bogdan801 | 532,269,157 | false | {"Kotlin": 273047} | package com.bogdan801.weatheraggregator.presentation.composables
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.bogdan801.weatheraggregator.R
import com.bogdan801.weatheraggregator.domain.model.Location
import com.bogdan801.weatheraggregator.domain.model.WeatherSourceDomain
import okhttp3.internal.toImmutableList
@Composable
fun SelectDataSourcesSheet(
modifier: Modifier = Modifier,
location: Location,
onSourcesSelected: (List<WeatherSourceDomain>) -> Unit = {},
selectedDomains: List<WeatherSourceDomain> = listOf()
) {
val dataSourcesList by remember {
val list = WeatherSourceDomain.values().filter { source ->
when(source){
WeatherSourceDomain.Meta -> true
WeatherSourceDomain.Sinoptik -> location.sinoptikLink.isNotBlank()
WeatherSourceDomain.OpenWeather -> location.lat > 0 && location.lon >0
WeatherSourceDomain.Average -> false
}
}.toList()
mutableStateOf(list)
}
var selectionList by rememberSaveable{
mutableStateOf(dataSourcesList.map{ selectedDomains.contains(it) })
}
val isButtonEnabled by remember {
derivedStateOf {
selectionList.contains(true)
}
}
val updateItemState = { id: Int ->
val newList = selectionList.toMutableList().apply { this[id] = !this[id] }.toImmutableList()
selectionList = newList
}
Column(
modifier = modifier,
){
Box(
modifier = Modifier
.fillMaxWidth()
.height(46.dp),
contentAlignment = Alignment.Center
){
Text(
text = stringResource(R.string.selectDataSources),
style = MaterialTheme.typography.subtitle2,
color = MaterialTheme.colors.onSurface
)
}
Box(
modifier = Modifier
.padding(horizontal = 8.dp)
.fillMaxWidth()
.height(0.5.dp)
.clip(MaterialTheme.shapes.small)
.background(MaterialTheme.colors.onSurface.copy(alpha = 0.3f))
)
Box(modifier = Modifier.fillMaxSize()){
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = 80.dp)
){
itemsIndexed(dataSourcesList){id, source ->
DataSourceItem(
modifier = Modifier
.fillMaxWidth()
.height(80.dp),
domain = source,
state = selectionList[id],
onStateChanged = { updateItemState(id) }
)
}
}
Button(
modifier = Modifier
.padding(bottom = 58.dp)
.size(190.dp, 40.dp)
.align(Alignment.BottomCenter),
onClick = {
val outputList = dataSourcesList.filterIndexed { index, _ ->
selectionList[index]
}
onSourcesSelected(outputList)
},
shape = MaterialTheme.shapes.medium,
elevation = ButtonDefaults.elevation(
defaultElevation = 5.dp,
pressedElevation = 7.dp,
disabledElevation = 0.dp
),
enabled = isButtonEnabled
) {
Text(
text = stringResource(R.string.select),
style = MaterialTheme.typography.body2,
color = if(isButtonEnabled) MaterialTheme.colors.onSecondary else MaterialTheme.colors.onSurface
)
}
}
}
}
@Composable
fun DataSourceItem(
modifier: Modifier = Modifier,
domain: WeatherSourceDomain = WeatherSourceDomain.Meta,
state: Boolean = false,
onStateChanged: (prevState: Boolean) -> Unit = {}
) {
val colorState by animateColorAsState(
targetValue = if(state) MaterialTheme.colors.secondary else MaterialTheme.colors.onPrimary,
animationSpec = tween(200)
)
Row(
modifier = modifier
.background(colorState)
.clickable(
interactionSource = remember{ MutableInteractionSource() },
indication = null,
onClick = {
onStateChanged(state)
}
)
) {
Box(
modifier = Modifier
.fillMaxHeight()
.width(80.dp),
contentAlignment = Alignment.Center
){
Image(
modifier = Modifier.size(48.dp),
painter = when(domain){
WeatherSourceDomain.Meta -> painterResource(id = R.drawable.ic_meta)
WeatherSourceDomain.Sinoptik -> painterResource(id = R.drawable.ic_sinoptik)
WeatherSourceDomain.OpenWeather -> painterResource(id = R.drawable.ic_open_weather)
WeatherSourceDomain.Average -> painterResource(id = R.drawable.ic_average)
},
contentDescription = null
)
}
Row(
modifier = Modifier
.fillMaxHeight()
.weight(1f),
verticalAlignment = Alignment.CenterVertically
){
Column {
Text(
text = domain.toString(),
color = MaterialTheme.colors.onSurface,
style = MaterialTheme.typography.overline
)
Text(
text = domain.domain,
color = MaterialTheme.colors.onSurface.copy(0.65f),
style = MaterialTheme.typography.caption
)
}
}
Box(
modifier = Modifier
.fillMaxHeight()
.width(80.dp),
contentAlignment = Alignment.Center
){
Checkbox(
modifier = Modifier.align(Alignment.Center),
checked = state,
onCheckedChange = onStateChanged,
colors = CheckboxDefaults.colors(
checkedColor = MaterialTheme.colors.primary,
checkmarkColor = MaterialTheme.colors.onPrimary,
uncheckedColor = MaterialTheme.colors.primary
)
)
}
}
} | 0 | Kotlin | 0 | 0 | c703ac328c8a87d6d901053c7081aec8b9838f19 | 7,410 | WeatherAggregator | MIT License |
libraries/stdlib/jvm/src/kotlin/collections/builders/ListBuilder.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2020 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 kotlin.collections.builders
internal class ListBuilder<E> private constructor(
private var array: Array<E>,
private var offset: Int,
private var length: Int,
private var isReadOnly: Boolean,
private val backing: ListBuilder<E>?,
private val root: ListBuilder<E>?
) : MutableList<E>, RandomAccess, AbstractMutableList<E>() {
constructor() : this(10)
constructor(initialCapacity: Int) : this(
arrayOfUninitializedElements(initialCapacity), 0, 0, false, null, null)
fun build(): List<E> {
if (backing != null) throw IllegalStateException() // just in case somebody casts subList to ListBuilder
checkIsMutable()
isReadOnly = true
return this
}
override val size: Int
get() = length
override fun isEmpty(): Boolean = length == 0
override fun get(index: Int): E {
AbstractList.checkElementIndex(index, length)
return array[offset + index]
}
override operator fun set(index: Int, element: E): E {
checkIsMutable()
AbstractList.checkElementIndex(index, length)
val old = array[offset + index]
array[offset + index] = element
return old
}
override fun indexOf(element: E): Int {
var i = 0
while (i < length) {
if (array[offset + i] == element) return i
i++
}
return -1
}
override fun lastIndexOf(element: E): Int {
var i = length - 1
while (i >= 0) {
if (array[offset + i] == element) return i
i--
}
return -1
}
override fun iterator(): MutableIterator<E> = Itr(this, 0)
override fun listIterator(): MutableListIterator<E> = Itr(this, 0)
override fun listIterator(index: Int): MutableListIterator<E> {
AbstractList.checkPositionIndex(index, length)
return Itr(this, index)
}
override fun add(element: E): Boolean {
checkIsMutable()
addAtInternal(offset + length, element)
return true
}
override fun add(index: Int, element: E) {
checkIsMutable()
AbstractList.checkPositionIndex(index, length)
addAtInternal(offset + index, element)
}
override fun addAll(elements: Collection<E>): Boolean {
checkIsMutable()
val n = elements.size
addAllInternal(offset + length, elements, n)
return n > 0
}
override fun addAll(index: Int, elements: Collection<E>): Boolean {
checkIsMutable()
AbstractList.checkPositionIndex(index, length)
val n = elements.size
addAllInternal(offset + index, elements, n)
return n > 0
}
override fun clear() {
checkIsMutable()
removeRangeInternal(offset, length)
}
override fun removeAt(index: Int): E {
checkIsMutable()
AbstractList.checkElementIndex(index, length)
return removeAtInternal(offset + index)
}
override fun remove(element: E): Boolean {
checkIsMutable()
val i = indexOf(element)
if (i >= 0) removeAt(i)
return i >= 0
}
override fun removeAll(elements: Collection<E>): Boolean {
checkIsMutable()
return retainOrRemoveAllInternal(offset, length, elements, false) > 0
}
override fun retainAll(elements: Collection<E>): Boolean {
checkIsMutable()
return retainOrRemoveAllInternal(offset, length, elements, true) > 0
}
override fun subList(fromIndex: Int, toIndex: Int): MutableList<E> {
AbstractList.checkRangeIndexes(fromIndex, toIndex, length)
return ListBuilder(array, offset + fromIndex, toIndex - fromIndex, isReadOnly, this, root ?: this)
}
@OptIn(ExperimentalStdlibApi::class)
private fun ensureCapacity(minCapacity: Int) {
if (backing != null) throw IllegalStateException() // just in case somebody casts subList to ListBuilder
if (minCapacity > array.size) {
val newSize = ArrayDeque.newCapacity(array.size, minCapacity)
array = array.copyOfUninitializedElements(newSize)
}
}
override fun equals(other: Any?): Boolean {
return other === this ||
(other is List<*>) && contentEquals(other)
}
override fun hashCode(): Int {
return array.subarrayContentHashCode(offset, length)
}
override fun toString(): String {
return array.subarrayContentToString(offset, length)
}
// ---------------------------- private ----------------------------
private fun checkIsMutable() {
if (isReadOnly || root != null && root.isReadOnly) throw UnsupportedOperationException()
}
private fun ensureExtraCapacity(n: Int) {
ensureCapacity(length + n)
}
private fun contentEquals(other: List<*>): Boolean {
return array.subarrayContentEquals(offset, length, other)
}
private fun insertAtInternal(i: Int, n: Int) {
ensureExtraCapacity(n)
array.copyInto(array, startIndex = i, endIndex = offset + length, destinationOffset = i + n)
length += n
}
private fun addAtInternal(i: Int, element: E) {
if (backing != null) {
backing.addAtInternal(i, element)
array = backing.array
length++
} else {
insertAtInternal(i, 1)
array[i] = element
}
}
private fun addAllInternal(i: Int, elements: Collection<E>, n: Int) {
if (backing != null) {
backing.addAllInternal(i, elements, n)
array = backing.array
length += n
} else {
insertAtInternal(i, n)
var j = 0
val it = elements.iterator()
while (j < n) {
array[i + j] = it.next()
j++
}
}
}
private fun removeAtInternal(i: Int): E {
if (backing != null) {
val old = backing.removeAtInternal(i)
length--
return old
} else {
val old = array[i]
array.copyInto(array, startIndex = i + 1, endIndex = offset + length, destinationOffset = i)
array.resetAt(offset + length - 1)
length--
return old
}
}
private fun removeRangeInternal(rangeOffset: Int, rangeLength: Int) {
if (backing != null) {
backing.removeRangeInternal(rangeOffset, rangeLength)
} else {
array.copyInto(array, startIndex = rangeOffset + rangeLength, endIndex = length, destinationOffset = rangeOffset)
array.resetRange(fromIndex = length - rangeLength, toIndex = length)
}
length -= rangeLength
}
/** Retains elements if [retain] == true and removes them it [retain] == false. */
private fun retainOrRemoveAllInternal(rangeOffset: Int, rangeLength: Int, elements: Collection<E>, retain: Boolean): Int {
if (backing != null) {
val removed = backing.retainOrRemoveAllInternal(rangeOffset, rangeLength, elements, retain)
length -= removed
return removed
} else {
var i = 0
var j = 0
while (i < rangeLength) {
if (elements.contains(array[rangeOffset + i]) == retain) {
array[rangeOffset + j++] = array[rangeOffset + i++]
} else {
i++
}
}
val removed = rangeLength - j
array.copyInto(array, startIndex = rangeOffset + rangeLength, endIndex = length, destinationOffset = rangeOffset + j)
array.resetRange(fromIndex = length - removed, toIndex = length)
length -= removed
return removed
}
}
private class Itr<E> : MutableListIterator<E> {
private val list: ListBuilder<E>
private var index: Int
private var lastIndex: Int
constructor(list: ListBuilder<E>, index: Int) {
this.list = list
this.index = index
this.lastIndex = -1
}
override fun hasPrevious(): Boolean = index > 0
override fun hasNext(): Boolean = index < list.length
override fun previousIndex(): Int = index - 1
override fun nextIndex(): Int = index
override fun previous(): E {
if (index <= 0) throw NoSuchElementException()
lastIndex = --index
return list.array[list.offset + lastIndex]
}
override fun next(): E {
if (index >= list.length) throw NoSuchElementException()
lastIndex = index++
return list.array[list.offset + lastIndex]
}
override fun set(element: E) {
check(lastIndex != -1) { "Call next() or previous() before replacing element from the iterator." }
list.set(lastIndex, element)
}
override fun add(element: E) {
list.add(index++, element)
lastIndex = -1
}
override fun remove() {
check(lastIndex != -1) { "Call next() or previous() before removing element from the iterator." }
list.removeAt(lastIndex)
index = lastIndex
lastIndex = -1
}
}
}
internal fun <E> arrayOfUninitializedElements(size: Int): Array<E> {
require(size >= 0) { "capacity must be non-negative." }
@Suppress("UNCHECKED_CAST")
return arrayOfNulls<Any?>(size) as Array<E>
}
private fun <T> Array<out T>.subarrayContentToString(offset: Int, length: Int): String {
val sb = StringBuilder(2 + length * 3)
sb.append("[")
var i = 0
while (i < length) {
if (i > 0) sb.append(", ")
sb.append(this[offset + i])
i++
}
sb.append("]")
return sb.toString()
}
private fun <T> Array<T>.subarrayContentHashCode(offset: Int, length: Int): Int {
var result = 1
var i = 0
while (i < length) {
val nextElement = this[offset + i]
result = result * 31 + nextElement.hashCode()
i++
}
return result
}
private fun <T> Array<T>.subarrayContentEquals(offset: Int, length: Int, other: List<*>): Boolean {
if (length != other.size) return false
var i = 0
while (i < length) {
if (this[offset + i] != other[i]) return false
i++
}
return true
}
internal fun <T> Array<T>.copyOfUninitializedElements(newSize: Int): Array<T> {
@Suppress("UNCHECKED_CAST")
return copyOf(newSize) as Array<T>
}
internal fun <E> Array<E>.resetAt(index: Int) {
@Suppress("UNCHECKED_CAST")
(this as Array<Any?>)[index] = null
}
internal fun <E> Array<E>.resetRange(fromIndex: Int, toIndex: Int) {
for (index in fromIndex until toIndex) resetAt(index)
} | 34 | Kotlin | 49 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 11,011 | kotlin | Apache License 2.0 |
Legacy/src/main/java/cn/afternode/matrilib/enjoythebans/EnjoyTheBans.kt | tumuidle | 609,710,313 | false | null | package cn.afternode.matrilib.enjoythebans
import cn.afternode.matrilib.core.AbstractPlatform
object EnjoyTheBans: AbstractPlatform() {
override val name: String = "EnjoyTheBans"
override val version: String = "0.6"
override val originalAuthor: String = "ETB"
override val description: String = "Very old client"
} | 0 | Kotlin | 0 | 1 | 6910f67cf552e95c7460717007f43279dfcf95a6 | 332 | MatriLib | MIT License |