path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
executioncontext/projectview/src/main/java/org/jetbrains/bsp/bazel/projectview/generator/DefaultProjectViewGenerator.kt
steveniemitz
485,935,051
true
{"Shell": 3, "Markdown": 10, "Java": 138, "Kotlin": 46, "C++": 1, "Scala": 10}
package org.jetbrains.bsp.bazel.projectview.generator import io.vavr.control.Try import org.jetbrains.bsp.bazel.projectview.generator.sections.ProjectViewBazelPathSectionGenerator import org.jetbrains.bsp.bazel.projectview.generator.sections.ProjectViewBuildFlagsSectionGenerator import org.jetbrains.bsp.bazel.projectview.generator.sections.ProjectViewDebuggerAddressSectionGenerator import org.jetbrains.bsp.bazel.projectview.generator.sections.ProjectViewJavaPathSectionGenerator import org.jetbrains.bsp.bazel.projectview.generator.sections.ProjectViewTargetsSectionGenerator import org.jetbrains.bsp.bazel.projectview.model.ProjectView import java.nio.file.Files import java.nio.file.Path class DefaultProjectViewGenerator : ProjectViewGenerator { override fun generatePrettyStringAndSaveInFile(projectView: ProjectView, filePath: Path): Try<Void> = writeStringToFile(filePath, generatePrettyString(projectView)) private fun writeStringToFile(destinationPath: Path, string: String): Try<Void> { return Try.run { Files.createDirectories(destinationPath.parent) Files.writeString(destinationPath, string) } } override fun generatePrettyString(projectView: ProjectView): String = listOfNotNull( targetsGenerator.generatePrettyString(projectView.targets), bazelPathGenerator.generatePrettyString(projectView.bazelPath), debuggerAddressGenerator.generatePrettyString(projectView.debuggerAddress), javaPathSectionGenerator.generatePrettyString(projectView.javaPath), buildFlagsGenerator.generatePrettyString(projectView.buildFlags), ).joinToString(separator = "\n\n", postfix = "\n") private companion object { private val targetsGenerator = ProjectViewTargetsSectionGenerator() private val debuggerAddressGenerator = ProjectViewDebuggerAddressSectionGenerator() private val bazelPathGenerator = ProjectViewBazelPathSectionGenerator() private val javaPathSectionGenerator = ProjectViewJavaPathSectionGenerator() private val buildFlagsGenerator = ProjectViewBuildFlagsSectionGenerator() } }
0
null
0
0
36b98966249b6616f86c035b7f48c8ca816d3188
2,183
bazel-bsp
Apache License 2.0
generator/bin/main/com/laidpack/sourcerer/generator/index/ClassSymbolDescription.kt
dpnolte
151,090,095
false
null
package com.laidpack.sourcerer.generator.index import com.laidpack.sourcerer.generator.resources.Widget import com.squareup.kotlinpoet.ClassName data class ClassSymbolDescription ( val targetClassName: ClassName, val widget: Widget?, val classCategory : ClassCategory, val isViewGroup: Boolean, val superClassNames: List<ClassName>, val xdDeclaredType: XdDeclaredType )
8
Kotlin
1
0
9513bbc54768e9248c450b0aba125b433c447e68
420
sourcerer
Apache License 2.0
app/src/main/java/com/example/rental_mobil/Repository/SopirRepository.kt
mrAldirs
691,938,449
false
{"Kotlin": 333860}
package com.example.rental_mobil.Repository import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.rental_mobil.Model.Sopir import com.google.firebase.firestore.FirebaseFirestore class SopirRepository { private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance() fun detail(id: String): LiveData<Sopir> { val resultLiveData = MutableLiveData<Sopir>() firestore.collection("sopir") .document(id) .get() .addOnSuccessListener { doc -> if (doc != null && doc.exists()) { val data = Sopir( doc.get("alamat").toString(), doc.get("created").toString(), doc.get("deleted").toString(), doc.get("email").toString(), doc.get("foto_ktp").toString(), doc.get("foto_profil").toString(), doc.get("foto_sim").toString(), doc.get("hp").toString(), doc.get("id_sopir").toString(), doc.get("nama").toString(), doc.get("nik").toString(), doc.get("sim").toString(), doc.get("status").toString(), doc.get("tanggal_lahir").toString(), doc.get("tempat_lahir").toString(), doc.get("updated").toString() ) resultLiveData.value = data } else { } } .addOnFailureListener { exception -> } return resultLiveData } }
1
Kotlin
0
2
624e82b43797c514a0f424ef025d66c4eab53ee8
1,749
kotlin-rent-car-app
Apache License 2.0
app/src/main/java/com/gsabr/assetscare/GerenciarOsActivity.kt
darian-catalin-cucer
558,810,429
true
{"Kotlin": 32645}
package com.gsabr.assetscare import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.volley.Request import com.android.volley.toolbox.JsonArrayRequest import com.android.volley.toolbox.Volley import com.google.gson.Gson import kotlinx.android.synthetic.main.activity_revisao.* import java.util.* import kotlin.collections.ArrayList class GerenciarOsActivity : AppCompatActivity() { private lateinit var osRecyclerview: RecyclerView private lateinit var osArrayList: ArrayList<Order> lateinit var p: Order override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_gerenciar_os) osRecyclerview = findViewById(R.id.recyclerView) osRecyclerview.layoutManager = LinearLayoutManager(this) osRecyclerview.setHasFixedSize(true) osArrayList = arrayListOf<Order>() //getUserData() objectRequestOrders("http://192.168.110.239:8080/api_manutencao/api/listar_os") } //Obtendo lista de OS private fun objectRequestOrders(url: String) { val queue = Volley.newRequestQueue(this) val jsonArrayRequest = JsonArrayRequest( Request.Method.GET, url, null, { response -> // var arrayListPecas = arrayListOf<String>() //arrayListPecas.add("00 ; NENHUMA") for (i in 0 until response.length()) { val orderJsonObject = response.getJSONObject(i) p = Gson().fromJson(orderJsonObject.toString(), Order::class.java) osArrayList.add(p) osRecyclerview.adapter = MyAdapter(osArrayList) } Toast.makeText( applicationContext, "OS's carregadas!", Toast.LENGTH_SHORT ).show() }, { Toast.makeText(this , "Erro, verifique o acesso à rede e tente novamente!", Toast.LENGTH_SHORT).show() } ) queue.add(jsonArrayRequest) queue.cache.clear() } //... // // private fun getUserData() { // // for(i in num_os.indices){ // // val oss = Order("Num. OS: " + num_os[i], "Data: " + datafim[i]) // osArrayList.add(oss) // // osRecyclerview.adapter = MyAdapter(osArrayList) // } // } }
0
null
0
1
8380546e7bd02cedc49d2b52d78b604c0e32b6b0
2,701
AssetsCare
MIT License
app/src/main/java/com/gsabr/assetscare/GerenciarOsActivity.kt
darian-catalin-cucer
558,810,429
true
{"Kotlin": 32645}
package com.gsabr.assetscare import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.volley.Request import com.android.volley.toolbox.JsonArrayRequest import com.android.volley.toolbox.Volley import com.google.gson.Gson import kotlinx.android.synthetic.main.activity_revisao.* import java.util.* import kotlin.collections.ArrayList class GerenciarOsActivity : AppCompatActivity() { private lateinit var osRecyclerview: RecyclerView private lateinit var osArrayList: ArrayList<Order> lateinit var p: Order override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_gerenciar_os) osRecyclerview = findViewById(R.id.recyclerView) osRecyclerview.layoutManager = LinearLayoutManager(this) osRecyclerview.setHasFixedSize(true) osArrayList = arrayListOf<Order>() //getUserData() objectRequestOrders("http://192.168.110.239:8080/api_manutencao/api/listar_os") } //Obtendo lista de OS private fun objectRequestOrders(url: String) { val queue = Volley.newRequestQueue(this) val jsonArrayRequest = JsonArrayRequest( Request.Method.GET, url, null, { response -> // var arrayListPecas = arrayListOf<String>() //arrayListPecas.add("00 ; NENHUMA") for (i in 0 until response.length()) { val orderJsonObject = response.getJSONObject(i) p = Gson().fromJson(orderJsonObject.toString(), Order::class.java) osArrayList.add(p) osRecyclerview.adapter = MyAdapter(osArrayList) } Toast.makeText( applicationContext, "OS's carregadas!", Toast.LENGTH_SHORT ).show() }, { Toast.makeText(this , "Erro, verifique o acesso à rede e tente novamente!", Toast.LENGTH_SHORT).show() } ) queue.add(jsonArrayRequest) queue.cache.clear() } //... // // private fun getUserData() { // // for(i in num_os.indices){ // // val oss = Order("Num. OS: " + num_os[i], "Data: " + datafim[i]) // osArrayList.add(oss) // // osRecyclerview.adapter = MyAdapter(osArrayList) // } // } }
0
null
0
1
8380546e7bd02cedc49d2b52d78b604c0e32b6b0
2,701
AssetsCare
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/SquareO.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.SquareO: ImageVector get() { if (_squareO != null) { return _squareO!! } _squareO = Builder(name = "SquareO", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(18.5f, 0.0f) lineTo(5.5f, 0.0f) curveTo(2.467f, 0.0f, 0.0f, 2.467f, 0.0f, 5.5f) verticalLineToRelative(13.0f) curveToRelative(0.0f, 3.032f, 2.467f, 5.5f, 5.5f, 5.5f) horizontalLineToRelative(13.0f) curveToRelative(3.033f, 0.0f, 5.5f, -2.468f, 5.5f, -5.5f) lineTo(24.0f, 5.5f) curveToRelative(0.0f, -3.033f, -2.467f, -5.5f, -5.5f, -5.5f) close() moveTo(21.0f, 18.5f) curveToRelative(0.0f, 1.379f, -1.122f, 2.5f, -2.5f, 2.5f) lineTo(5.5f, 21.0f) curveToRelative(-1.378f, 0.0f, -2.5f, -1.121f, -2.5f, -2.5f) lineTo(3.0f, 5.5f) curveToRelative(0.0f, -1.378f, 1.122f, -2.5f, 2.5f, -2.5f) horizontalLineToRelative(13.0f) curveToRelative(1.378f, 0.0f, 2.5f, 1.122f, 2.5f, 2.5f) verticalLineToRelative(13.0f) close() moveTo(12.0f, 5.0f) curveToRelative(-3.314f, 0.0f, -6.011f, 2.713f, -6.011f, 6.048f) verticalLineToRelative(1.903f) curveToRelative(0.0f, 3.335f, 2.696f, 6.048f, 6.011f, 6.048f) reflectiveCurveToRelative(5.989f, -2.713f, 5.989f, -6.048f) verticalLineToRelative(-1.903f) curveToRelative(0.0f, -3.335f, -2.687f, -6.048f, -5.989f, -6.048f) close() moveTo(14.989f, 12.952f) curveToRelative(0.0f, 1.709f, -1.313f, 3.048f, -2.989f, 3.048f) curveToRelative(-1.66f, 0.0f, -3.011f, -1.367f, -3.011f, -3.048f) verticalLineToRelative(-1.903f) curveToRelative(0.0f, -1.681f, 1.351f, -3.048f, 3.011f, -3.048f) curveToRelative(1.676f, 0.0f, 2.989f, 1.339f, 2.989f, 3.048f) verticalLineToRelative(1.903f) close() } } .build() return _squareO!! } private var _squareO: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,195
icons
MIT License
app/src/main/java/org/openmrs/android/fhir/data/IdentifierTypeManager.kt
icrc
792,320,820
false
{"Kotlin": 212982, "Shell": 148}
import android.annotation.SuppressLint import android.content.Context import androidx.datastore.preferences.core.edit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import okhttp3.Request import org.json.JSONObject import org.openmrs.android.fhir.FhirApplication import org.openmrs.android.fhir.auth.dataStore import org.openmrs.android.fhir.data.PreferenceKeys import org.openmrs.android.fhir.data.database.model.IdentifierType class IdentifierTypeManager private constructor(private val context: Context) { private var restApiClient: RestApiManager = FhirApplication.restApiClient(context) private val database = FhirApplication.roomDatabase(context) private val ENDPOINT = FhirApplication.openmrsRestUrl(context) + "idgen/autogenerationoption?v=default" companion object { @SuppressLint("StaticFieldLeak") private lateinit var instance: IdentifierTypeManager suspend fun fetchIdentifiers(context: Context) { withContext(Dispatchers.IO) { instance = IdentifierTypeManager(context) val newIdentifiers = instance.fetchIdentifierFromEndpoint() if(newIdentifiers!= null){ instance.storeIdentifiers(newIdentifiers) instance.selectRequiredIdentifiers(newIdentifiers) } } } } private suspend fun storeIdentifiers(identifierTypes: List<IdentifierType>) { withContext(Dispatchers.IO){ database.dao().insertAllIdentifierTypeModel(identifierTypes) } } private suspend fun selectRequiredIdentifiers(identifierTypes: List<IdentifierType>) { withContext(Dispatchers.IO){ val selectedIdentifierTypes = instance.context.dataStore.data.first()[PreferenceKeys.SELECTED_IDENTIFIER_TYPES] ?.toMutableSet() ?: mutableSetOf() val requiredIdentifierTypes = identifierTypes.filter { it.required } if(requiredIdentifierTypes.isNotEmpty()){ requiredIdentifierTypes.forEach { selectedIdentifierTypes.add(it.uuid) } } instance.context.dataStore.edit { preferences -> preferences[PreferenceKeys.SELECTED_IDENTIFIER_TYPES] = selectedIdentifierTypes } } } suspend fun fetchIdentifierFromEndpoint(): List<IdentifierType>? { return withContext(Dispatchers.IO) { try { val requestBuilder = Request.Builder() .url(ENDPOINT) .get() val response = restApiClient.call(requestBuilder) val identifierIdSet = mutableSetOf<String>() if (response.isSuccessful) { val resArray = mutableListOf<IdentifierType>() val jsonResponse = JSONObject(response.body?.string() ?: "") val identifiers = jsonResponse.getJSONArray("results") for (i in 0..<identifiers.length()) { val autoGeneratedObject: JSONObject = identifiers.getJSONObject(i) val identifierTypeObject = autoGeneratedObject.getJSONObject("identifierType") if(identifierTypeObject["uuid"].toString() !in identifierIdSet){ identifierIdSet.add(identifierTypeObject["uuid"].toString()) var sourceId = "" if(autoGeneratedObject.getBoolean("automaticGenerationEnabled")){ val sourceObject = autoGeneratedObject.getJSONObject("source") sourceId = sourceObject["uuid"].toString() } resArray.add(IdentifierType( identifierTypeObject["uuid"].toString(), identifierTypeObject["display"].toString(), autoGeneratedObject.getBoolean("automaticGenerationEnabled"), identifierTypeObject.getBoolean("required"), sourceId )) } } resArray.toList() } else { null } } catch (e: Exception) { null } } } }
6
Kotlin
3
2
62f1a7dc4801d93c0a7f6d3f870477aa7226649b
4,533
openmrs-android-fhir
Apache License 2.0
src/main/kotlin/com/inteligenciadigital/bookmarket/models/Customer.kt
GabrielIFPB
436,716,510
false
null
package com.inteligenciadigital.bookmarket.models import org.hibernate.Hibernate import java.time.LocalDate import java.util.UUID import javax.persistence.* @Entity @Table(name = "customer") data class Customer( @Column(name = "name", length = 64, nullable = false) var name: String, @Column(name = "birthdate") var birthdate: LocalDate ) { @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long = 0 @Column(name = "uid", unique = true) var uid: String = "" init { val uid: UUID = UUID.randomUUID() this.uid = this.uid.ifEmpty { uid.toString() } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false other as Customer return id == other.id } override fun hashCode(): Int = javaClass.hashCode() @Override override fun toString(): String { return this::class.simpleName + "(id = $id , name = $name , birthdate = $birthdate , uid = $uid )" } } // objects for requests parameters data class CustomerBirthdate( var birthdate: LocalDate, ) {} data class CustomerName( var name: String, ) {}
0
Kotlin
0
0
56bf7d6058951639f5d6c8d23daf1039e9f0e1a0
1,151
book-market
MIT License
presentation/src/main/java/com/heady/test/modules/products/models/ProductVariantModel.kt
praveen-kanwar
237,142,130
false
null
package com.heady.test.modules.products.models import com.heady.test.common.models.IModel /** * Product Variant Model Class * * Created by Praveen. */ data class ProductVariantModel( var id: Int, var color: String, var size: Int, var price: Double ) : IModel
0
Kotlin
0
0
6e04500a6911946a612bed5786364980b294183a
280
Heady-AT
MIT License
polyfill/src/main/kotlin/me/xx2bab/polyfill/VariantExtension.kt
2BAB
150,435,649
false
null
package me.xx2bab.polyfill import com.android.Version import com.android.build.api.component.analytics.AnalyticsEnabledApplicationVariant import com.android.build.api.component.analytics.AnalyticsEnabledLibraryVariant import com.android.build.api.component.impl.ApkCreationConfigImpl import com.android.build.api.variant.ApplicationVariant import com.android.build.api.variant.LibraryVariant import com.android.build.api.variant.Variant import com.android.build.api.variant.impl.ApplicationVariantImpl import com.android.build.api.variant.impl.LibraryVariantImpl import com.android.build.gradle.internal.scope.GlobalScope import com.android.build.gradle.internal.scope.MutableTaskContainer import com.android.sdklib.BuildToolInfo import me.xx2bab.polyfill.tools.SemanticVersionLite import org.gradle.api.provider.Provider import org.gradle.api.tasks.TaskProvider import org.gradle.configurationcache.extensions.capitalized ////////// Common Variant ////////// /** * `kotlin-dsl` has compatible issues with replaceFirstChar(), * so we use this deprecated method instead as a workaround. * To capitalized first letter for task name usage. */ fun Variant.getCapitalizedName() = name.capitalized() /** * To get current Android Gradle Plugin version. */ fun Variant.getAgpVersion() = SemanticVersionLite(Version.ANDROID_GRADLE_PLUGIN_VERSION) /** * To get BuildToolInfo instance provider, later you can use like below to retrieve some tools' information. * `buildToolInfoProvider.get().getPath(BuildToolInfo.PathId.AAPT2)` * * @return [BuildToolInfo] wrapped by [Provider]. */ fun Variant.getBuildToolInfo(): Provider<BuildToolInfo> { val globalScope = when (this) { is ApplicationVariant -> { this.getGlobalScope() } is LibraryVariant -> { this.getGlobalScope() } else -> { throw UnsupportedOperationException("Can not convert $this to either ApplicationVariantImpl or LibraryVariantImpl.") } } return globalScope.versionedSdkLoader.flatMap { it.buildToolInfoProvider } } ////////// ApplicationVariant ////////// /** * Casting ApplicationVariant to its actual implementation. * This is helpful as Variant instance is one of the most important public API * for us to interact with AGP. It contains a bunch of tools / data providers * to access more intermediates of the Android build. * * @return [ApplicationVariantImpl] */ fun ApplicationVariant.getApplicationVariantImpl(): ApplicationVariantImpl { return when (this) { is ApplicationVariantImpl -> { this } is AnalyticsEnabledApplicationVariant -> { this.delegate as ApplicationVariantImpl } else -> { throw UnsupportedOperationException("Can not convert $this to ApplicationVariantImpl.") } } } /** * Indirect implementation of [com.android.build.gradle.internal.component.ApkCreationConfig]. * The [ApkCreationConfigImpl.config] provides internal Artifacts APIs that can be consumed * for more intermediate files. * * @return [ApkCreationConfigImpl] */ fun ApplicationVariant.getApkCreationConfigImpl() = getApplicationVariantImpl().delegate /** * [GlobalScope] contains some build services / data providers. It's a supplementary entry * to our hooks, because some of its scope has been replaced by other components. This is a * common object that can be seen in all plugins. * * @return [GlobalScope] */ fun ApplicationVariant.getGlobalScope() = getApkCreationConfigImpl().globalScope /** * To access partial common used AGP [TaskProvider]s. * For example the [MutableTaskContainer.assembleTask]. * * @return [MutableTaskContainer] */ fun ApplicationVariant.getTaskContainer() = getApkCreationConfigImpl().config.taskContainer ////////// LibraryVariant ////////// /** * Same as [getApplicationVariantImpl], but is used for LibraryVariant. * * @return [LibraryVariantImpl] */ fun LibraryVariant.getLibraryVariantImpl(): LibraryVariantImpl { return when (this) { is LibraryVariantImpl -> { this } is AnalyticsEnabledLibraryVariant -> { this.delegate as LibraryVariantImpl } else -> { throw UnsupportedOperationException("Can not convert $this to LibraryVariantImpl.") } } } //fun LibraryVariant.getLibCreationConfigImpl() = getLibraryVariantImpl() fun LibraryVariant.getGlobalScope() = getLibraryVariantImpl().globalScope
1
Kotlin
4
68
ffd96c102aa5c5aa28f3d4e0078298d028d5f1d4
4,508
Polyfill
Apache License 2.0
app/src/main/java/dev/zezula/books/domain/CreateOrUpdateNoteUseCase.kt
zezulaon
589,699,261
false
{"Kotlin": 556103}
package dev.zezula.books.domain import dev.zezula.books.data.NotesRepository import dev.zezula.books.data.model.note.Note import dev.zezula.books.data.model.note.NoteFormData import dev.zezula.books.domain.model.Response import dev.zezula.books.domain.model.asResponse import timber.log.Timber class CreateOrUpdateNoteUseCase(private val notesRepository: NotesRepository) { suspend operator fun invoke(noteId: String?, noteFormData: NoteFormData, bookId: String): Response<Note> { return asResponse { notesRepository.addOrUpdateNote(noteId = noteId, bookId = bookId, noteFormData = noteFormData) } .onError { Timber.e(it, "Failed to add the shelf.") } } }
1
Kotlin
0
6
84750e18ee62d57081096275936ded053b64e6f1
735
my-library
Apache License 2.0
src/main/kotlin/fr/medicapp/plugins/Security.kt
Renarde-dev
738,557,006
false
{"Kotlin": 13056}
package fr.medicapp.plugins import fr.medicapp.dao.DaoUser import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.configureSecurity() { authentication { basic(name = "authenticationAPI") { realm = "User login" validate { credentials -> val tryUser = DaoUser.INSTANCE.getByEmail(credentials.name) if (tryUser == null){ null }else { if (tryUser.passwordHash == credentials.password) { UserIdPrincipal(tryUser.id) } else { null } } } } } routing { /*authenticate("authenticationAPI") { get("/protected/route/basic") { val principal = call.principal<UserIdPrincipal>()!! call.respondText("Hello ${principal.name}") } }*/ TODO("Routing des Users, exemple ci-dessus") } }
0
Kotlin
0
2
4c5dec80191b0662118d5e49cebecdf13162af5d
1,100
MedicApp-API
MIT License
src/main/java/uk/ac/shef/tracker/core/monitors/BatteryMonitor.kt
oakgroup
630,448,719
false
{"Kotlin": 383102}
/* * Copyright (c) 2023. This code was developed by <NAME>, The University of Sheffield. All rights reserved. No part of this code can be used without the explicit written permission by the author */ package uk.ac.shef.tracker.core.monitors import android.content.Context import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import uk.ac.shef.tracker.core.database.models.TrackerDBBattery import uk.ac.shef.tracker.core.database.tables.TrackerTableBatteries import uk.ac.shef.tracker.core.tracker.TrackerService import uk.ac.shef.tracker.core.utils.Logger import uk.ac.shef.tracker.core.utils.TrackerUtils import uk.ac.shef.tracker.core.utils.background import kotlin.coroutines.CoroutineContext /** * This class monitors the batteries data and save them into the database */ class BatteryMonitor(val context: Context) : CoroutineScope { override val coroutineContext: CoroutineContext get() = Dispatchers.Default private var lastBatterySentMillis: Long = 0L /** * API method to be called to stop the monitor and its restarter controller */ fun insertData() { if (lastBatterySentMillis != 0L) { // do not save too many batteries data, one every hour maximum if ((System.currentTimeMillis() - lastBatterySentMillis) > 3600000) { saveBatteryData() } else { Logger.i("Too early to write battery data") } } else { saveBatteryData() } } private fun saveBatteryData() { background { val dbBattery = TrackerDBBattery() dbBattery.timeInMillis = System.currentTimeMillis() dbBattery.batteryPercent = TrackerUtils.getBatteryPercentage(context) dbBattery.isCharging = TrackerUtils.isCharging(context) TrackerTableBatteries.insert(context, dbBattery) Logger.d("Writing battery to database ${dbBattery.description()}") lastBatterySentMillis = dbBattery.timeInMillis } } }
0
Kotlin
0
0
78e517e98a63e8d0f379b33a4e410db7dd5abf45
2,062
android-bhf-tracker
MIT License
app/src/main/java/com/angelo/destinystatusapp/domain/usecase/FetchBungieHelpUpdatesUseCaseImpl.kt
angelorohit
777,418,508
false
{"Kotlin": 59270, "Shell": 455}
package com.angelo.destinystatusapp.domain.usecase import com.angelo.destinystatusapp.domain.State import com.angelo.destinystatusapp.domain.map import com.angelo.destinystatusapp.domain.model.BungieHelpUpdate import com.angelo.destinystatusapp.domain.repository.DestinyStatusRepository import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList class FetchBungieHelpUpdatesUseCaseImpl( private val repository: DestinyStatusRepository, ) : FetchBungieHelpUpdatesUseCase { override suspend operator fun invoke(): State<ImmutableList<BungieHelpUpdate>> { return repository.fetchBungieHelpUpdates().map { it.toImmutableList() } } }
0
Kotlin
0
0
7ce01586037172584f4ff28b9d878ae4ebe8b48a
716
DestinyStatusApp
MIT License
app/src/main/java/online/taxcore/pos/data/realm/TaxesSettings.kt
Data-Tech-International
581,201,452
false
{"Kotlin": 357648, "Java": 64900}
package online.taxcore.pos.data.realm import io.realm.RealmObject open class TaxesSettings : RealmObject() { var code: String = "" // tax label var isChecked = false var name: String = "-" var rate: Double = 0.0 var value: String = "" }
3
Kotlin
3
4
62ff854a1bd16bd85f755065760c9389460bda5e
259
Taxcore-MobilePOS-Android
MIT License
src/main/kotlin/pro/darc/cake/module/menu/dsl/pagination/slot/PaginationSlotEventHandler.kt
LittleLightMC
378,219,935
false
null
package pro.darc.cake.module.menu.dsl.pagination.slot import org.bukkit.entity.Player import org.bukkit.inventory.Inventory import pro.darc.cake.module.menu.Menu import pro.darc.cake.module.menu.slot.* typealias MenuPlayerSlotPageChangeEvent<T> = MenuPlayerSlotPageChange.(T?) -> Unit typealias MenuPlayerPageSlotInteractEvent<T> = MenuPlayerSlotInteract.(T?) -> Unit typealias MenuPlayerPageSlotRenderEvent<T> = MenuPlayerSlotRender.(T?) -> Unit typealias MenuPlayerPageSlotUpdateEvent<T> = MenuPlayerSlotUpdate.(T?) -> Unit class PaginationSlotEventHandler<T> { val pageChangeCallbacks = mutableListOf<MenuPlayerSlotPageChangeEvent<T>>() val interactCallbacks = mutableListOf<MenuPlayerPageSlotInteractEvent<T>>() val renderCallbacks = mutableListOf<MenuPlayerPageSlotRenderEvent<T>>() val updateCallbacks = mutableListOf<MenuPlayerPageSlotUpdateEvent<T>>() fun handlePageChange(currentItem: T?, pageChange: MenuPlayerSlotPageChange) { for (callback in pageChangeCallbacks) { callback(pageChange, currentItem) } } fun handleRender(currentItem: T?, render: MenuPlayerSlotRender) { for (callback in renderCallbacks) { callback(render, currentItem) } } fun handleUpdate(currentItem: T?, update: MenuPlayerSlotUpdate) { for (callback in updateCallbacks) { callback(update, currentItem) } } fun handleInteract(currentItem: T?, interact: MenuPlayerSlotInteract) { for (callback in interactCallbacks) { callback(interact, currentItem) } } } class MenuPlayerSlotPageChange( override val menu: Menu<*>, override val slotPos: Int, override val slot: Slot, override val player: Player, override val inventory: Inventory ) : MenuPlayerInventorySlot
5
Kotlin
0
3
71e7277cdacb58e9309de08a658dd89f99cd874b
1,827
CakeAPI
MIT License
vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedAction.kt
tchapgouv
340,329,238
false
{"Kotlin": 15176162, "HTML": 82783, "Shell": 61484, "Java": 28011, "Python": 25839, "FreeMarker": 7662, "JavaScript": 6854, "Ruby": 1587}
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.home.room.list.actions import androidx.annotation.DrawableRes import androidx.annotation.StringRes import im.vector.app.R import im.vector.app.core.platform.VectorSharedAction import im.vector.lib.strings.CommonStrings sealed class RoomListQuickActionsSharedAction( @StringRes val titleRes: Int, @DrawableRes val iconResId: Int?, val destructive: Boolean = false ) : VectorSharedAction { data class NotificationsAllNoisy(val roomId: String) : RoomListQuickActionsSharedAction( CommonStrings.room_list_quick_actions_notifications_all_noisy, R.drawable.ic_room_actions_notifications_all_noisy ) data class NotificationsAll(val roomId: String) : RoomListQuickActionsSharedAction( CommonStrings.room_list_quick_actions_notifications_all, R.drawable.ic_room_actions_notifications_all ) data class NotificationsMentionsOnly(val roomId: String) : RoomListQuickActionsSharedAction( CommonStrings.room_list_quick_actions_notifications_mentions, R.drawable.ic_room_actions_notifications_mentions ) data class NotificationsMute(val roomId: String) : RoomListQuickActionsSharedAction( CommonStrings.room_list_quick_actions_notifications_mute, R.drawable.ic_room_actions_notifications_mutes ) data class Settings(val roomId: String) : RoomListQuickActionsSharedAction( CommonStrings.room_list_quick_actions_settings, R.drawable.ic_room_actions_settings ) data class LowPriority(val roomId: String) : RoomListQuickActionsSharedAction( CommonStrings.room_list_quick_actions_low_priority_add, R.drawable.ic_low_priority_24 ) data class Favorite(val roomId: String) : RoomListQuickActionsSharedAction( CommonStrings.room_list_quick_actions_favorite_add, R.drawable.ic_tchap_unpinned ) data class Leave(val roomId: String, val showIcon: Boolean = true) : RoomListQuickActionsSharedAction( CommonStrings.room_list_quick_actions_leave, if (showIcon) R.drawable.ic_room_actions_leave else null, true ) }
95
Kotlin
7
20
965b02bf4cf51d317456a3334ceab57aae5e58ce
2,811
tchap-android
Apache License 2.0
rsocket-core/src/commonMain/kotlin/io/rsocket/kotlin/operation/ResponderRequestResponseOperation.kt
rsocket
109,894,810
false
{"Kotlin": 628647, "JavaScript": 203}
/* * Copyright 2015-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rsocket.kotlin.operation import io.rsocket.kotlin.* import io.rsocket.kotlin.frame.* import io.rsocket.kotlin.payload.* import kotlinx.coroutines.* internal class ResponderFireAndForgetOperation( private val requestJob: Job, private val responder: RSocket, ) : ResponderOperation { override suspend fun execute(outbound: OperationOutbound, requestPayload: Payload) { responder.fireAndForget(requestPayload) } override fun shouldReceiveFrame(frameType: FrameType): Boolean = frameType === FrameType.Cancel override fun receiveCancelFrame() { requestJob.cancel("Request was cancelled by remote party") } }
23
Kotlin
37
550
b7f27ba4c3a0d639d375731231f347e595ed307c
1,285
rsocket-kotlin
Apache License 2.0
samples/demo-app/app/src/main/java/cash/z/wallet/sdk/demoapp/demos/home/HomeFragment.kt
CHMEX
234,180,004
true
{"Kotlin": 212444, "Rust": 75835}
package cash.z.wallet.sdk.demoapp.demos.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import cash.z.wallet.sdk.ext.twig import cash.z.wallet.sdk.demoapp.App import cash.z.wallet.sdk.demoapp.R import cash.z.wallet.sdk.ext.ZcashSdk class HomeFragment : Fragment() { private lateinit var homeViewModel: HomeViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { homeViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java) val root = inflater.inflate(R.layout.fragment_home, container, false) val textView: TextView = root.findViewById(R.id.text_home) homeViewModel.text.observe(viewLifecycleOwner, Observer { textView.text = it }) return root } override fun onResume() { super.onResume() twig("CLEARING DATA: Visiting the home screen clears the default databases, for sanity" + " sake, because each demo is intended to be self-contained.") App.instance.getDatabasePath("unusued.db").parentFile.listFiles().forEach { it.delete() } } }
0
Kotlin
0
0
320e87fe075176a2a36ae10a7e7f030dedcb6605
1,408
zcash-android-wallet-sdk
Apache License 2.0
analysis/analysis-api/testData/symbols/singleSymbolByPsi/destructuring/entryInScriptDestructuringDeclaration.kts
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// LOOK_UP_FOR_ELEMENT_OF_TYPE: KtDestructuringDeclarationEntry // DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE data class X(val a: Int, val b: Int) val (<expr>c</expr>, d) = X(1, 2)
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
176
kotlin
Apache License 2.0
app/src/main/java/com/has/copa/GrupoD.kt
acrrf
573,949,661
false
{"Kotlin": 6776}
package com.has.copa import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.RecyclerView import com.has.copa.adapter.DinamarcaAdapter import com.has.copa.data.Datasource class GrupoD : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_grupo_d) val myDataset = Datasource().loadDinamarca() val recyclerView = findViewById<RecyclerView>(R.id.recycler_view) recyclerView.adapter = DinamarcaAdapter(this, myDataset) recyclerView.setHasFixedSize(true) } }
0
Kotlin
0
0
3930ca3f9467aee8c44b1b026512a44e66885398
661
copa-do-mundo
The Unlicense
app/weather/src/main/java/jp/co/mixi/androidtraining/weather/ui/WeatherViewModel.kt
mixigroup
776,812,769
false
{"Kotlin": 31815}
package jp.co.mixi.androidtraining.weather.ui import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import jp.co.mixi.androidtraining.weather.data.repository.DefaultWeatherRepository import jp.co.mixi.androidtraining.weather.data.repository.WeatherRepository import kotlinx.coroutines.launch class WeatherViewModel( private val repository: WeatherRepository = DefaultWeatherRepository(), ) : ViewModel() { var uiState by mutableStateOf(WeatherUiState()) fun getWeather() { viewModelScope.launch { uiState = uiState.copy(isLoading = true) val weather = repository.getWeather() uiState = uiState.copy(weather = weather, isLoading = false) } } }
0
Kotlin
0
0
397828f021528e6b254e5fa105651746ff781945
867
2024AndroidTraining
Apache License 2.0
magic/src/jsMain/kotlin/enchant/magic/Utils.kt
TeraThought
432,392,027
false
{"Kotlin": 103646, "Swift": 2320, "Ruby": 119}
package enchant.magic import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers actual val Dispatchers.Background: CoroutineDispatcher get() = Dispatchers.Default
0
Kotlin
4
0
76314d5b30afa0896ee5cf593cbff7886fae163a
190
magic
Apache License 2.0
app/src/main/java/com/example/tdmpa_1p_pr01_dvla/MainActivity.kt
onlydonos
699,563,625
false
{"Kotlin": 3954}
package com.example.tdmpa_1p_pr01_dvla import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.RadioGroup import android.widget.TextView import android.widget.Toast import com.bumptech.glide.Glide class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ElegirConversion() var btnCambiar = findViewById<Button>(R.id.btnCambiar) btnCambiar.setOnClickListener{ CambiarFondo() } } fun ElegirConversion (){ var txtValor = findViewById<TextView>(R.id.txtCantidad) var txtResultado = findViewById<TextView>(R.id.txtResultado) val radioGroup = findViewById<RadioGroup>(R.id.rbtnGrupo) var resultado = 0.0 radioGroup.setOnCheckedChangeListener{ _, checkedld -> when (checkedld) { R.id.rbtCentimetros -> { if (ValidarValor()) { resultado = (txtValor.text.toString().toDouble()) / 2.54 txtResultado.text = "${resultado.toString()} in." } } R.id.rbtnPulgadas -> { if (ValidarValor()) { resultado = (txtValor.text.toString().toDouble()) * 2.54 txtResultado.text = "${resultado.toString()} cm." } } R.id.rbtnMetros -> { if (ValidarValor()) { resultado = (txtValor.text.toString().toDouble()) * 3.281 txtResultado.text = "${resultado.toString()} ft." } } R.id.rbtnPies -> { if (ValidarValor()) { resultado = (txtValor.text.toString().toDouble()) / 3.281 txtResultado.text = "${resultado.toString()} m." } } } } } fun ValidarValor(): Boolean { var valor = findViewById<TextView>(R.id.txtCantidad) if (valor.text.toString().isEmpty()) { Toast.makeText(this@MainActivity, "El campo esta vacio ", Toast.LENGTH_SHORT).show() return false } else { return true } } fun CambiarFondo() { var urlFondo = "https://images.wallpapersden.com/image/download/super-mario-bros-movie-poster_bW1oa2eUmZqaraWkpJRpbWWtaW1l.jpg" val urlParseFondo : Uri = Uri.parse(urlFondo) var imgFondo = findViewById<ImageView>(R.id.imgBack) Glide.with(applicationContext).load(urlParseFondo).into(imgFondo) Toast.makeText(this@MainActivity, "Se realizó el cambio", Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
0
a2f5ab8a78e100ddaa912e0860b6d548fef27fa6
2,912
Android_PR01_1P
MIT License
api/src/jvmMain/kotlin/net/kigawa/kutil/kutil/api/io/DefaultIo.jvm.kt
kigawa01
421,088,101
false
{"Kotlin": 56828, "Java": 914}
package net.kigawa.kutil.kutil.api.io import kotlinx.coroutines.channels.Channel import net.kigawa.kutil.kutil.api.concurrent.Coroutines actual object DefaultIo { actual val error: WriterIo<String> actual val out: WriterIo<String> init { val infoChannel = Channel<String>() val errorChannel = Channel<String>() out = ChannelWriterIo(infoChannel) error = ChannelWriterIo(errorChannel) infoChannel.dispatchForEach(Coroutines.defaultIoContext) { println(it) } errorChannel.dispatchForEach(Coroutines.defaultIoContext) { System.err.println(it) } } }
0
Kotlin
0
0
d7a00a5a63cb3c10509f6ee6352c864e867f203f
602
kutil
MIT License
server/src/main/kotlin/net/eiradir/server/player/event/HeadlessJoinedEvent.kt
Eiradir
635,460,745
false
null
package net.eiradir.server.player.event import com.badlogic.ashley.core.Entity data class HeadlessJoinedEvent(val connection: Entity)
12
Kotlin
0
0
7ae18b87a37ebd9f20766796b9fa94e2dd6dafc6
135
eiradir-server
MIT License
src/main/kotlin/io/mustelidae/otter/sumatrana/api/domain/slack/Slack.kt
otter-world
595,030,375
false
null
package io.mustelidae.otter.sumatrana.api.domain.slack import io.mustelidae.otter.sumatrana.api.domain.tunneling.SentryToSlackTunneling import javax.persistence.CascadeType import javax.persistence.Column import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.Id import javax.persistence.Index import javax.persistence.OneToMany import javax.persistence.Table @Entity @Table( indexes = [ Index(name = "IDX_SLACK_KEYCODE", columnList = "keyCode", unique = true), ] ) class Slack( @Column(name = "keyCode") val key: String, val type: Type, /** * If the type is bot, there is token information. * If the type is webhook, there is a url path. */ @Column(name = "variable") val value: String ) { @Id @GeneratedValue var id: Long? = null protected set @OneToMany(cascade = [CascadeType.ALL], mappedBy = "slack") var sentryToSlackTunnelings: MutableList<SentryToSlackTunneling> = arrayListOf() fun addBy(sentryToSlackTunneling: SentryToSlackTunneling) { sentryToSlackTunnelings.add(sentryToSlackTunneling) if (sentryToSlackTunneling.slack != this) sentryToSlackTunneling.setBySlack(this) } enum class Type { BOT, WEBHOOK } }
0
Kotlin
0
0
dc22b11823bace8b21c3fcf12bb1eb53f6a3db71
1,308
sumatrana-otter
MIT License
app/src/main/java/me/tylerbwong/stack/data/persistence/dao/UserDao.kt
cdubthecoolcat
208,213,243
true
{"Kotlin": 307183}
package me.tylerbwong.stack.data.persistence.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import me.tylerbwong.stack.data.persistence.entity.UserEntity @Dao interface UserDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(users: List<UserEntity>) @Query("SELECT * FROM user WHERE userId = :userId") suspend fun get(userId: Int): UserEntity }
0
Kotlin
0
0
e2eeaed0acd96ea6260e3208c066c54e29d6f08a
463
stack
Apache License 2.0
src/main/kotlin/archives/tater/netherarchives/NetherArchives.kt
JosiahFu
711,624,418
false
{"Kotlin": 68510, "Java": 10019}
package archives.tater.netherarchives import archives.tater.netherarchives.block.NetherArchivesBlocks import archives.tater.netherarchives.block.entity.NetherArchivesBlockEntities import archives.tater.netherarchives.entity.NetherArchivesEntities import archives.tater.netherarchives.item.NetherArchivesItems import archives.tater.netherarchives.modification.ModifyLootTables import archives.tater.netherarchives.modification.ModifyWorldGen import net.fabricmc.api.ModInitializer import org.slf4j.Logger import org.slf4j.LoggerFactory object NetherArchives : ModInitializer { const val NAMESPACE = "netherarchives" @JvmField val logger: Logger = LoggerFactory.getLogger(NAMESPACE) val config = NetherArchivesConfig(true).load() as NetherArchivesConfig override fun onInitialize() { // This code runs as soon as Minecraft is in a mod-load-ready state. // However, some things (like resources) may still be uninitialized. // Proceed with mild caution. logger.info("Eyes: {}", config.skeletonEyes) NetherArchivesBlocks.register() NetherArchivesBlockEntities.register() NetherArchivesItems.registerItemGroups() NetherArchivesEntities.register() ModifyWorldGen() ModifyLootTables() } }
0
Kotlin
0
0
5366abcd00d958d62206e8df0f90e36e659a446d
1,291
NetherArchives
MIT License
core/src/main/kotlin/io/github/serpro69/kfaker/provider/Zelda.kt
serpro69
174,969,439
false
{"Kotlin": 618723, "Shell": 6190, "Makefile": 5561, "Java": 3978, "Groovy": 1144}
package io.github.serpro69.kfaker.provider import io.github.serpro69.kfaker.* import io.github.serpro69.kfaker.dictionary.* import io.github.serpro69.kfaker.provider.unique.LocalUniqueDataProvider import io.github.serpro69.kfaker.provider.unique.UniqueProviderDelegate /** * [FakeDataProvider] implementation for [YamlCategory.GAMES] category. */ @Suppress("unused") class Zelda internal constructor(fakerService: FakerService) : YamlFakeDataProvider<Zelda>(fakerService) { override val yamlCategory = YamlCategory.GAMES override val secondaryCategory: Category = Category.ofName("ZELDA") override val localUniqueDataProvider = LocalUniqueDataProvider<Zelda>() override val unique by UniqueProviderDelegate(localUniqueDataProvider) init { fakerService.load(yamlCategory, secondaryCategory) } fun games() = resolve("zelda", "games") fun characters() = resolve("zelda", "characters") fun locations() = resolve("zelda", "locations") fun items() = resolve("zelda", "items") }
33
Kotlin
39
393
1b6f7c9c29e775e1cd36fe5cd3188311346f71e9
1,026
kotlin-faker
MIT License
english/language-rooms/src/main/kotlin/by/jprof/telegram/bot/english/language_rooms/model/LanguageRoom.kt
JavaBy
367,980,780
false
null
package by.jprof.telegram.bot.english.language_rooms.model enum class Language { ENGLISH, } enum class Violence { POLITE, MOTHERFUCKER, } data class LanguageRoom( val chatId: Long, val threadId: Long?, val language: Language, val violence: Violence, val urbanWordOfTheDay: Boolean, )
21
Kotlin
2
2
7e0f2c68e3acc9ff239effa34f5823e4ef8212c9
319
jprof_by_bot
MIT License
app/src/main/kotlin/com/slesarew/cv/cvscreen/view/CvActivity.kt
sliskiCode
261,400,312
false
null
package com.slesarew.cv.cvscreen.view import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import com.slesarew.cv.R import com.slesarew.cv.cvscreen.model.CvAction import com.slesarew.cv.cvscreen.model.CvAction.OnMediumClickedAction import com.slesarew.cv.cvscreen.model.CvAction.OnScreenCreateAction import com.slesarew.cv.cvscreen.model.CvAction.OnStackOverflowClickedAction import com.slesarew.cv.cvscreen.model.CvAction.OnYouTubeClickedAction import com.slesarew.cv.cvscreen.model.CvViewModel import com.slesarew.cv.cvscreen.view.renderer.CvRenderer import kotlinx.android.synthetic.main.activity_content.* import org.koin.android.ext.android.inject import org.koin.android.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class CvActivity : AppCompatActivity() { private val viewModel by viewModel<CvViewModel> { parametersOf(this@CvActivity) } private val renderer by inject<CvRenderer>() @ExperimentalStdlibApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_content) renderer.prepare(content) viewModel.connect { renderer.render(it) } if (savedInstanceState == null) viewModel.sendAction(OnScreenCreateAction) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.cv_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.medium -> sendAction(OnMediumClickedAction) R.id.stackoverflow -> sendAction(OnStackOverflowClickedAction) R.id.youtube -> sendAction(OnYouTubeClickedAction) else -> super.onOptionsItemSelected(item) } private fun sendAction(action: CvAction) = viewModel.sendAction(action).let { true } }
4
Kotlin
0
1
8861b3d220bffd1c241b6f28b40a5b0c2359ffe7
1,950
CV
Apache License 2.0
src/main/kotlin/de/sambalmueslie/eventorg/game/api/UnitSlotAPI.kt
sambalmueslie
363,757,768
false
{"Kotlin": 73386, "PLpgSQL": 5480}
package de.sambalmueslie.eventorg.game.api import de.sambalmueslie.eventorg.common.CrudAPI interface UnitSlotAPI : CrudAPI<UnitSlot, UnitSlotChangeRequest> { }
0
Kotlin
0
1
f7442ed15a42dfd37f94fc87ac83e2eea6704b52
164
event-organizer-server
Apache License 2.0
src/main/kotlin/be/zvz/alsong/dto/SearchResult.kt
JellyBrick
373,705,678
false
null
package be.zvz.alsong.dto import be.zvz.alsong.serializer.DateSerializer import kotlinx.serialization.Serializable import java.util.Date @Serializable data class SearchResult( val lyricId: Long, val playtime: Long, val artist: String, val album: String, val title: String, @Serializable(with = DateSerializer::class) val registerDate: Date? = null, )
2
Kotlin
0
6
a3d105933b46b4f89e4bfd869fb685b61ec195d0
381
alsong-kt
Apache License 2.0
app/src/main/java/com/simples/j/worldtimealarm/WakeUpActivity.kt
ladroshan
272,342,211
true
{"Kotlin": 478985, "Java": 16869}
package com.simples.j.worldtimealarm import android.app.NotificationManager import android.content.* import android.os.Build import android.os.Bundle import android.os.Vibrator import android.text.format.DateFormat import android.text.method.ScrollingMovementMethod import android.util.Log import android.view.View import android.view.WindowManager import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.preference.PreferenceManager import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.MobileAds import com.simples.j.worldtimealarm.etc.AlarmItem import com.simples.j.worldtimealarm.etc.C import com.simples.j.worldtimealarm.utils.AlarmController import com.simples.j.worldtimealarm.utils.DatabaseCursor import com.simples.j.worldtimealarm.utils.MediaCursor import com.simples.j.worldtimealarm.utils.WakeUpService import kotlinx.android.synthetic.main.activity_wake_up.* import java.util.* class WakeUpActivity : AppCompatActivity(), View.OnClickListener { private lateinit var notificationManager: NotificationManager private lateinit var dbCursor: DatabaseCursor private lateinit var sharedPref: SharedPreferences private var item: AlarmItem? = null private var actionBroadcastReceiver: BroadcastReceiver? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_wake_up) if(!intent.hasExtra(AlarmReceiver.OPTIONS)) { Log.d(C.TAG, "Received Alarm came without information, Finish activity.") finish() } MobileAds.setRequestConfiguration(C.getAdsTestConfig()) MobileAds.initialize(applicationContext, resources.getString(R.string.ad_app_id)) adViewWakeUp.loadAd(AdRequest.Builder().build()) @Suppress("DEPRECATION") window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager dbCursor = DatabaseCursor(applicationContext) sharedPref = PreferenceManager.getDefaultSharedPreferences(applicationContext) clock.format12Hour = MediaCursor.getLocalizedTimeFormat() clock_date.format12Hour = DateFormat.getBestDateTimePattern(Locale.getDefault(), "yyyy-MMM-d EEEE") val option = intent.getBundleExtra(AlarmReceiver.OPTIONS) item = if(option != null && !option.isEmpty) option.getParcelable(AlarmReceiver.ITEM) else null item.let { Log.d(C.TAG, "Alarm alerted : ID(${it?.notiId?.plus(1)})") if(it == null) { label.visibility = View.VISIBLE label.text = getString(R.string.error_message) } else { // Show selected time zone's time, but not print if time zone is default val timeZone = it.timeZone.replace(" ", "_") if(TimeZone.getDefault().id != TimeZone.getTimeZone(timeZone).id) { time_zone_clock_layout.visibility = View.VISIBLE val name = getNameForTimeZone(it.timeZone) time_zone_clock_title.text = name time_zone_clock_time.timeZone = timeZone time_zone_clock_time.format12Hour = MediaCursor.getLocalizedTimeFormat() time_zone_clock_date.timeZone = timeZone time_zone_clock_date.format12Hour = DateFormat.getBestDateTimePattern(Locale.getDefault(), "yyyy-MMM-d EEEE") } // Show label if(!it.label.isNullOrEmpty()) { label.visibility = View.VISIBLE label.text = it.label label.movementMethod = ScrollingMovementMethod() } if(it.snooze > 0) { snooze.visibility = View.VISIBLE } else { snooze.visibility = View.GONE } } } snooze.setOnClickListener(this) dismiss.setOnClickListener(this) actionBroadcastReceiver = object: BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { // Can be extended later, for now this broadcast receiver is only for finish activity. finish() } } val actionIntentFilter = IntentFilter().apply { addAction(ACTION_ACTIVITY_FINISH) } registerReceiver(actionBroadcastReceiver, actionIntentFilter) } override fun onDestroy() { super.onDestroy() val vibrator = applicationContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibrator.cancel() stopService(Intent(applicationContext, WakeUpService::class.java)) unregisterReceiver(actionBroadcastReceiver) } override fun onBackPressed() { super.onBackPressed() Toast.makeText(applicationContext, getString(R.string.alarm_dismissed), Toast.LENGTH_SHORT).show() } override fun onClick(view: View) { when(view.id) { R.id.dismiss -> { finish() } R.id.snooze -> { AlarmController.getInstance().scheduleLocalAlarm(applicationContext, item, AlarmController.TYPE_SNOOZE) val minutes = getString(R.string.minutes, item?.snooze?.div((60 * 1000))) Toast.makeText(applicationContext, getString(R.string.alarm_on, minutes), Toast.LENGTH_SHORT).show() val serviceActionIntent = Intent(WakeUpService.REQUEST_SERVICE_ACTION).apply { putExtra(WakeUpService.SERVICE_ACTION, AlarmReceiver.ACTION_SNOOZE) } sendBroadcast(serviceActionIntent) finish() } } } private fun getNameForTimeZone(timeZoneId: String?): String { return if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { MediaCursor.getBestNameForTimeZone(android.icu.util.TimeZone.getTimeZone(timeZoneId)) } else timeZoneId?.split("/").let { if(it != null) { if(it.size > 1) it[it.lastIndex] else it[0] } else null }?.replace("_", " ") ?: getString(R.string.time_zone_unknown) } companion object { // const val ALARM_NOTIFICATION_ID = 0 // const val SHARED_ALARM_NOTIFICATION_ID = 132562 const val ACTION_ACTIVITY_FINISH = "ACTION_ACTIVITY_FINISH" } }
0
null
0
0
ad3790f0c297cffec42c2755ed10ad2dd6708cf2
6,867
WorldTimeAlarm
Apache License 2.0
features/home/src/main/java/com/fappslab/features/home/presentation/viewmodel/HomeViewAction.kt
F4bioo
693,834,465
false
{"Kotlin": 304361, "Python": 2171, "Shell": 900}
package com.fappslab.features.home.presentation.viewmodel import com.fappslab.features.common.navigation.DetailsArgs internal sealed class HomeViewAction { object Add : HomeViewAction() data class AdapterItem(val args: DetailsArgs) : HomeViewAction() }
0
Kotlin
0
0
3a4247596555400bf2128ded9f54aaa9491de0a8
263
Seedcake
MIT License
app/src/test/java/com/viniciusjanner/android_github_actions_sonar_cloud/util/LiveDataTestUtil.kt
viniciusjanner
686,749,263
false
{"Kotlin": 28916}
package com.viniciusjanner.android_github_actions_sonar_cloud.util import androidx.lifecycle.LiveData import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit object LiveDataTestUtil { fun <T> getValue(liveData: LiveData<T>): T { val data = arrayOfNulls<Any>(1) val latch = CountDownLatch(1) liveData.observeForever { t -> data[0] = t latch.countDown() } latch.await(2, TimeUnit.SECONDS) @Suppress("UNCHECKED_CAST") return data[0] as T } }
0
Kotlin
0
0
591a00ee87abc6cc048f1ebf1075a365696bfe03
556
android_github_actions_sonar_cloud
Apache License 2.0
kittybot/src/main/kotlin/org/bezsahara/kittybot/telegram/classes/messages/reactions/MessageReactionCountUpdated.kt
bezsahara
846,146,531
false
{"Kotlin": 752625}
package org.bezsahara.kittybot.telegram.classes.messages.reactions import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.bezsahara.kittybot.telegram.classes.chats.Chat import org.bezsahara.kittybot.telegram.classes.reactions.ReactionCount /** * This object represents reaction changes on a message with anonymous reactions. * * *[link](https://core.telegram.org/bots/api#messagereactioncountupdated)*: https://core.telegram.org/bots/api#messagereactioncountupdated * * @param chat The chat containing the message * @param messageId Unique message identifier inside the chat * @param date Date of the change in Unix time * @param reactions List of reactions that are present on the message */ @Serializable data class MessageReactionCountUpdated( val chat: Chat, @SerialName("message_id") val messageId: Long, val date: Long, val reactions: List<ReactionCount> )
0
Kotlin
1
5
a0b831c9f4ad00f681b2bfba5376e321766a8cfe
933
TelegramKitty
MIT License
i18n4k-core/src/commonMain/kotlin/de/comahe/i18n4k/strings/StringTools.kt
comahe-de
340,499,429
false
{"Kotlin": 657212}
package de.comahe.i18n4k.strings /** * Returns a copy (if needed) of this string having its first letter titlecased using the rules of * the default locale, or the original string if it's empty or already starts with a title case * letter. * * This function does not support one-to-many character mapping. If needed, see [capitalizeFull]. * * Implemented because the Kotlin-Std-Lib capitalize is duplicated */ fun String.capitalize(): String { if (isEmpty()) return this if (!this[0].isLowerCase()) return this return replaceFirstChar { it.titlecaseChar() } } /** * Returns a copy (if needed) of this string having its first letters are titlecased using the rules * of the default locale, or the original string if it's empty or already starts with a title case * letter. * * This function supports one-to-many character mapping, thus the length of the returned string * can be greater than one. For example, `'\uFB00'.titlecase()` returns `"\u0046\u0066"`, where * `'\uFB00'` is the LATIN SMALL LIGATURE FF character (`ff`). If this character has no title case * mapping, the result of [uppercase] is returned instead. * * @see Char.titlecase */ fun String.capitalizeFull(): String { if (isEmpty()) return this if (!this[0].isLowerCase()) return this return replaceFirstChar { it.titlecase() } }
4
Kotlin
9
70
b5b5b3751f22da683682bd4464494e00e7db67b3
1,372
i18n4k
Apache License 2.0
data/RF00639/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF00639" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 2 to 5 93 to 96 } value = "#530efe" } color { location { 19 to 24 73 to 78 } value = "#995425" } color { location { 28 to 29 70 to 71 } value = "#609e3c" } color { location { 31 to 32 67 to 68 } value = "#c194d6" } color { location { 36 to 39 60 to 63 } value = "#5f2b3c" } color { location { 6 to 18 79 to 92 } value = "#dbe3a9" } color { location { 25 to 27 72 to 72 } value = "#c6317b" } color { location { 30 to 30 69 to 69 } value = "#dbb512" } color { location { 33 to 35 64 to 66 } value = "#0b30d7" } color { location { 40 to 59 } value = "#6592a6" } color { location { 1 to 1 } value = "#8fe99b" } color { location { 97 to 97 } value = "#ab6996" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
1,939
Rfam-for-RNArtist
MIT License
subscriptions/subscriptions-api/src/main/java/com/duckduckgo/subscriptions/api/PrivacyProUnifiedFeedback.kt
duckduckgo
78,869,127
false
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
/* * Copyright (c) 2024 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.subscriptions.api interface PrivacyProUnifiedFeedback { /** * @return `true` if for the given source, we should allow the usage of unified feedback flow or `false` otherwise */ suspend fun shouldUseUnifiedFeedback(source: PrivacyProFeedbackSource): Boolean enum class PrivacyProFeedbackSource { DDG_SETTINGS, SUBSCRIPTION_SETTINGS, VPN_MANAGEMENT, VPN_EXCLUDED_APPS, UNKNOWN, } }
67
Kotlin
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
1,070
Android
Apache License 2.0
src/main/kotlin/com/randolphledesma/gad/managers/ContactServiceManager.kt
randop
251,366,857
false
null
package com.randolphledesma.gad.managers import com.randolphledesma.gad.ApplicationContext import com.randolphledesma.gad.EventStoreEvent import com.randolphledesma.gad.EventStoreResource import com.randolphledesma.gad.models.Account import com.randolphledesma.gad.models.Contact import com.randolphledesma.gad.models.ContactGroup import com.randolphledesma.gad.services.ContactService import io.reactivex.Single import io.vertx.core.json.JsonObject import java.util.* import javax.inject.Inject class ContactServiceManager @Inject constructor(private val applicationContext: ApplicationContext): ContactService { private val eventStore = applicationContext.eventStore override suspend fun addContact(account: Account, contact: Contact): Contact { val json = JsonObject.mapFrom(contact) val event = EventStoreEvent(contact.contactId.toString(), "ContactCreated", json) val resource = EventStoreResource("contacts_${account.accountId.toString()}", event) eventStore.writeToStream(resource) return contact } override suspend fun addGroup(account: Account, contactGroup: ContactGroup): ContactGroup { val json = JsonObject.mapFrom(contactGroup) val event = EventStoreEvent(contactGroup.contactGroupId.toString(), "ContactGroupCreated", json) val resource = EventStoreResource("contacts_${account.accountId.toString()}", event) eventStore.writeToStream(resource) return contactGroup } override suspend fun addContactAtGroup(account: Account, contact: Contact, contactGroup: ContactGroup): ContactGroup { val json = JsonObject() json.put("contactId", contact.contactId.toString()) json.put("contactGroupId", contactGroup.contactGroupId.toString()) val event = EventStoreEvent(UUID.randomUUID().toString(), "ContactGrouped", json) val resource = EventStoreResource("contacts_${account.accountId.toString()}", event) eventStore.writeToStream(resource) return contactGroup } }
0
Kotlin
0
0
15d52e6e1ae43b56bbc58256d2344acc609fee21
2,037
kotlin-vertx
MIT License
src/main/kotlin/gay/pizza/pkg/apk/core/ApkSupportedArches.kt
azenla
590,581,912
false
null
package gay.pizza.pkg.apk.core interface ApkSupportedArches { fun read(): List<String> fun write(arches: List<String>) }
0
Kotlin
0
1
79c5e8708a43e8663f1243d51893a2b7fb0fc27a
126
apk-tools
MIT License
app/src/main/java/com/example/inventory/ItemDetailFragment.kt
huuhieu2905
740,658,657
false
{"Kotlin": 26964}
/* * Copyright (C) 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 * * 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.example.inventory import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.example.inventory.data.Student import com.example.inventory.databinding.FragmentItemDetailBinding import com.google.android.material.dialog.MaterialAlertDialogBuilder /** * [ItemDetailFragment] displays the details of the selected item. */ class ItemDetailFragment : Fragment() { private val navigationArgs: ItemDetailFragmentArgs by navArgs() lateinit var student: Student private val viewModel: InventoryViewModel by activityViewModels { InventoryViewModelFactory( (activity?.application as InventoryApplication).database.studentDao() ) } private var _binding: FragmentItemDetailBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentItemDetailBinding.inflate(inflater, container, false) return binding.root } /** * Binds views with the passed in item data. */ private fun bind(item: Student) { binding.apply { studentMssv.text = item.mssv.toString() studentName.text = item.hoten studentBirth.text = item.ngaysinh studentLive.text = item.quequan deleteItem.setOnClickListener { showConfirmationDialog() } editItem.setOnClickListener { editItem() } } } /** * Navigate to the Edit item screen. */ private fun editItem() { val action = ItemDetailFragmentDirections.actionItemDetailFragmentToAddItemFragment( getString(R.string.edit_fragment_title), student.mssv ) this.findNavController().navigate(action) } /** * Displays an alert dialog to get the user's confirmation before deleting the item. */ private fun showConfirmationDialog() { MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(android.R.string.dialog_alert_title)) .setMessage(getString(R.string.delete_question)) .setCancelable(false) .setNegativeButton(getString(R.string.no)) { _, _ -> } .setPositiveButton(getString(R.string.yes)) { _, _ -> deleteItem() } .show() } /** * Deletes the current item and navigates to the list fragment. */ private fun deleteItem() { viewModel.deleteItem(student) findNavController().navigateUp() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val id = navigationArgs.itemId // Retrieve the item details using the itemId. // Attach an observer on the data (instead of polling for changes) and only update the // the UI when the data actually changes. viewModel.retrieveItem(id).observe(this.viewLifecycleOwner) { selectedItem -> student = selectedItem bind(student) } } /** * Called when fragment is destroyed. */ override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
9a3563e0b205006f781222db23209c24dc8328aa
4,155
StudentManagement
Apache License 2.0
src/main/kotlin/bvanseg/kotlincommons/io/net/http/rest/endpoint/Endpoint.kt
bvanseg
211,717,677
false
null
/* * MIT License * * Copyright (c) 2021 Boston Vanseghi * * 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 bvanseg.kotlincommons.io.net.http.rest.endpoint import bvanseg.kotlincommons.io.net.http.HttpMethod import bvanseg.kotlincommons.io.net.http.KCHttpRequestBuilder import bvanseg.kotlincommons.io.net.http.httpRequestBuilder import bvanseg.kotlincommons.io.net.http.rest.RestClient import bvanseg.kotlincommons.io.net.http.rest.impl.RestActionImpl import com.fasterxml.jackson.core.type.TypeReference import java.net.http.HttpRequest /** * @author Boston Vanseghi * @since 2.11.0 */ class Endpoint<T>( val restClient: RestClient, path: String, val type: Class<T>, private val typeReference: TypeReference<T> ) : DeleteEndpoint<T>, GetEndpoint<T>, PatchEndpoint<T>, PostEndpoint<T>, PutEndpoint<T> { val fullPath = restClient.baseURL + path private fun buildRestActionImpl( httpMethod: HttpMethod, body: Any?, callback: KCHttpRequestBuilder.() -> Unit = {} ): RestActionImpl<T> { val requestBuilder = httpRequestBuilder(fullPath).apply(restClient.defaultBuilderCallback) val bodyPublisher = body?.let { restClient.factory.bodyPublisherCallback(body) } ?: HttpRequest.BodyPublishers.noBody() when (httpMethod) { HttpMethod.DELETE -> requestBuilder.delete(callback) HttpMethod.GET -> requestBuilder.get(callback) HttpMethod.PATCH -> requestBuilder.patch(bodyPublisher, callback) HttpMethod.POST -> requestBuilder.post(bodyPublisher, callback) HttpMethod.PUT -> requestBuilder.put(bodyPublisher, callback) } val rest = restClient.factory.create(requestBuilder, type, typeReference) return rest.onFailure(restClient.defaultFailure) as RestActionImpl<T> } override fun delete(callback: KCHttpRequestBuilder.() -> Unit): RestActionImpl<T> = buildRestActionImpl(HttpMethod.DELETE, null, callback) override fun get(callback: KCHttpRequestBuilder.() -> Unit): RestActionImpl<T> = buildRestActionImpl(HttpMethod.GET, null, callback) override fun patch(body: Any?, callback: KCHttpRequestBuilder.() -> Unit): RestActionImpl<T> = buildRestActionImpl(HttpMethod.PATCH, body, callback) override fun post(body: Any?, callback: KCHttpRequestBuilder.() -> Unit): RestActionImpl<T> = buildRestActionImpl(HttpMethod.POST, body, callback) override fun put(body: Any?, callback: KCHttpRequestBuilder.() -> Unit): RestActionImpl<T> = buildRestActionImpl(HttpMethod.PUT, body, callback) }
0
Kotlin
0
1
f02d97922c743fffc0c520ed2be30ad6b95dd8a3
3,654
KotlinCommons
MIT License
src/nativeGen/kotlin/godot/ARVRCamera.kt
piiertho
237,614,467
true
{"Kotlin": 5300589}
// DO NOT EDIT, THIS FILE IS GENERATED FROM api.json package godot import gdnative.godot_method_bind import godot.core.Godot import godot.core.Variant import godot.core.VariantArray import kotlin.reflect.KCallable import kotlinx.cinterop.CFunction import kotlinx.cinterop.COpaquePointer import kotlinx.cinterop.cstr import kotlinx.cinterop.invoke import kotlinx.cinterop.memScoped import kotlinx.cinterop.reinterpret open class ARVRCamera( _handle: COpaquePointer ) : Camera(_handle) { companion object { fun new(): ARVRCamera = memScoped { val fnPtr = checkNotNull(Godot.gdnative.godot_get_class_constructor)("ARVRCamera".cstr.ptr) requireNotNull(fnPtr) { "No instance found for ARVRCamera" } val fn = fnPtr.reinterpret<CFunction<() -> COpaquePointer>>() ARVRCamera( fn() ) } fun from(ptr: COpaquePointer): ARVRCamera = ARVRCamera(ptr) /** * Container for method_bind pointers for ARVRCamera */ private object __method_bind } }
0
null
0
1
3a8c598040f9b47b2b8cf8f5432543f61d6f83e8
1,005
godot-kotlin
MIT License
product/web3modal/src/main/kotlin/com/walletconnect/web3/modal/ui/routes/account/AccountState.kt
WalletConnect
435,951,419
false
{"Kotlin": 1615883, "Java": 4358}
package com.walletconnect.web3.modal.ui.routes.account import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.navigation.NavController import com.walletconnect.android.internal.common.wcKoinApp import com.walletconnect.foundation.util.Logger import com.walletconnect.web3.modal.client.Modal import com.walletconnect.web3.modal.client.Web3Modal import com.walletconnect.web3.modal.domain.model.AccountData import com.walletconnect.web3.modal.domain.usecase.DeleteSessionDataUseCase import com.walletconnect.web3.modal.domain.usecase.GetIdentityUseCase import com.walletconnect.web3.modal.domain.usecase.GetSelectedChainUseCase import com.walletconnect.web3.modal.domain.usecase.GetSessionTopicUseCase import com.walletconnect.web3.modal.domain.usecase.ObserveSelectedChainUseCase import com.walletconnect.web3.modal.domain.usecase.SaveChainSelectionUseCase import com.walletconnect.web3.modal.ui.model.UiState import com.walletconnect.web3.modal.utils.getAddress import com.walletconnect.web3.modal.utils.getChains import com.walletconnect.web3.modal.utils.getSelectedChain import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @Composable internal fun rememberAccountState( coroutineScope: CoroutineScope, navController: NavController ): AccountState = remember(coroutineScope, navController) { AccountState(coroutineScope, navController) } internal class AccountState( private val coroutineScope: CoroutineScope, private val navController: NavController ) { private val logger: Logger = wcKoinApp.koin.get() private val getSessionTopicUseCase: GetSessionTopicUseCase = wcKoinApp.koin.get() private val deleteSessionDataUseCase: DeleteSessionDataUseCase = wcKoinApp.koin.get() private val saveChainSelectionUseCase: SaveChainSelectionUseCase = wcKoinApp.koin.get() private val getSelectedChainUseCase: GetSelectedChainUseCase = wcKoinApp.koin.get() private val observeSelectedChainUseCase: ObserveSelectedChainUseCase = wcKoinApp.koin.get() private val getIdentityUseCase: GetIdentityUseCase = wcKoinApp.koin.get() private val accountFlow = flow { val activeSession = getSessionTopicUseCase()?.let { Web3Modal.getActiveSessionByTopic(it) } if (activeSession != null) { val chains = activeSession.getChains() val selectedChain = chains.getSelectedChain(getSelectedChainUseCase()) val address = activeSession.getAddress(selectedChain) val identity = getIdentityUseCase(address, selectedChain.id) accountData = AccountData( topic = activeSession.topic, address = address, balance = "", chains = chains, identity = identity ) emit(UiState.Success(accountData)) } else { emit(UiState.Error(Throwable("Active session not found"))) } }.catch { logger.error(it) emit(UiState.Error(it)) } .flowOn(Dispatchers.IO) lateinit var accountData: AccountData val accountState = accountFlow.stateIn(coroutineScope, started = SharingStarted.Lazily, initialValue = UiState.Loading()) val selectedChain = observeSelectedChainUseCase().map { savedChainId -> Web3Modal.chains.find { it.id == savedChainId } ?: Web3Modal.getSelectedChainOrFirst() } fun disconnect( topic: String, onSuccess: () -> Unit ) { Web3Modal.disconnect( disconnect = Modal.Params.Disconnect(topic), onSuccess = { coroutineScope.launch { deleteSessionDataUseCase() } coroutineScope.launch(Dispatchers.Main) { onSuccess() } }, onError = { logger.error(it.throwable) } ) } fun changeActiveChain(chain: Modal.Model.Chain) = coroutineScope.launch { saveChainSelectionUseCase(chain.id).also { Web3Modal.selectedChain = chain } } }
154
Kotlin
61
161
198ac87ef4d5d5a698c875761c0b544faf5f7d0b
4,302
WalletConnectKotlinV2
Apache License 2.0
chatbot/src/main/kotlin/io/github/lunarwatcher/chatbot/bot/commands/basic/HelpCommand.kt
LunarWatcher
123,192,353
false
null
package io.github.lunarwatcher.chatbot.bot.commands.basic import com.google.common.base.Strings import io.github.lunarwatcher.chatbot.NO_DEFINED_RANK import io.github.lunarwatcher.chatbot.bot.ReplyBuilder import io.github.lunarwatcher.chatbot.bot.chat.Message import io.github.lunarwatcher.chatbot.bot.chat.ReplyMessage import io.github.lunarwatcher.chatbot.bot.command.CommandCenter import io.github.lunarwatcher.chatbot.bot.commands.AbstractCommand import io.github.lunarwatcher.chatbot.bot.commands.ICommand import io.github.lunarwatcher.chatbot.bot.commands.learn.LearnedCommand import io.github.lunarwatcher.chatbot.getMaxLen import io.github.lunarwatcher.chatbot.utils.Utils class HelpCommand : AbstractCommand("help", listOf("halp", "hilfen", "help"), "Lists all the commands the bot has", "Use `" + CommandCenter.TRIGGER + "help` to list all the commands and `" + CommandCenter.TRIGGER + "help [command name]` to get more info about a specifc command\n" + "Call `${CommandCenter.TRIGGER}help trucated` for a small version of the help command, or `${CommandCenter.TRIGGER}help full` for the full version. " + "Note that not passing full or trucated leads to it defaulting to the site specific settings", rankRequirement = 1){ override fun handleCommand(message: Message): List<ReplyMessage>? { val center = message.chat.commands val `in` = splitCommand(message.content) if(`in`.size == 1 || (`in`.size == 2 && `in`.containsKey("content") && (`in`["content"] == "truncated" || `in`["content"] == "full") )){ val content = `in`["content"] val truncated = if(content == null) message.chat.truncated else content == "truncated" var commands: MutableMap<String, String> = mutableMapOf() val learnedCommands: MutableList<String> = mutableListOf() var listeners: MutableMap<String, String> = mutableMapOf(); if (!message.chat.commands.getCommands(message.chat).isEmpty()) { for (command: ICommand in center.getCommands(message.chat)) { commands[command.name] = command.desc; } } if (!CommandCenter.tc.commands.isEmpty()) { for (cmd: LearnedCommand in CommandCenter.tc.commands) { learnedCommands.add(cmd.name) } } if (!center.listeners.isEmpty()) { for (listener in center.listeners) { listeners[listener.name] = listener.description; } } listeners = listeners.toSortedMap() commands = commands.toSortedMap() if(!truncated) { val reply = ReplyBuilder(message.chat.name == "discord"); reply.fixedInput().append("###################### Help ######################") .nl().fixedInput().nl(); val names: MutableList<String> = mutableListOf() names.addAll(commands.keys); names.addAll(learnedCommands.toSet()) names.addAll(listeners.keys); val maxLen = getMaxLen(names); if (!commands.isEmpty()) { reply.fixedInput().append("==================== Commands").nl() for (command in commands) { reply.fixedInput().append(CommandCenter.TRIGGER + command.key); reply.append(Strings.repeat(" ", maxLen - command.key.length + 2) + "| ") .append(command.value).nl(); } } if (!learnedCommands.isEmpty()) { reply.fixedInput().append("==================== Learned Commands").nl() reply.fixedInput(); for (i in 0 until CommandCenter.tc.commands.size) { val command = CommandCenter.tc.commands[i] if (command.nsfw && !message.nsfwSite) { continue } reply.append(command.name); if (command.nsfw) reply.append(" - NSFW"); if (i < CommandCenter.tc.commands.size - 1) reply.append(", ") } } reply.fixedInput().newLine() if (!listeners.isEmpty()) { reply.fixedInput().append("==================== Listeners").newLine() for (listener in listeners) { reply.fixedInput().append(listener.key); reply.append(Strings.repeat(" ", maxLen - listener.key.length + 2) + "| ") .append(listener.value).nl(); } } return listOf(ReplyMessage(reply.toString(), false)); }else{ val builder = ReplyBuilder() builder.append("**Commands**: ") builder.append(commands.keys.joinToString(", ")) .append(". **User taught commands:** ") .append(learnedCommands.toSortedSet().joinToString(", ")) .append(". **Listeners**: " + listeners.keys.joinToString(", ")) return listOf(ReplyMessage(builder.toString(), false)); } }else{ val cmd = (`in`["content"] ?: return listOf(ReplyMessage("in[content] == null. /cc @Zoe", false))).toLowerCase(); val desc: String val help: String val name: String val aliases: String //No clue what to call this thing val d: String; val rank: Int val nsfw: Boolean val chat = message.chat when { center.isBuiltIn(cmd, chat) -> { desc = center[cmd, chat]!!.desc; help = center[cmd, chat]!!.help; name = center[cmd, chat]!!.name; val aliasBuffer = center[cmd, message.chat]!!.aliases aliases = if(aliasBuffer.isEmpty()) "None" else aliasBuffer.joinToString(", ") rank = center[cmd, chat]!!.rankRequirement d = "Built in command. " nsfw = center[cmd, chat]!!.nsfw } CommandCenter.tc.doesCommandExist(cmd) -> { desc = CommandCenter.tc.get(cmd)!!.desc; help = CommandCenter.tc.get(cmd)!!.help; name = CommandCenter.tc.get(cmd)!!.name; d = "Taught command. (Taught to the bot by user " + CommandCenter.tc.get(cmd)?.creator + " on " + CommandCenter.tc.get(cmd)?.site + "). " aliases = "None. " rank = 1 nsfw = CommandCenter.tc.get(cmd)!!.nsfw } else -> return listOf(ReplyMessage("The command you tried finding help for (`$cmd`) does not exist. Make sure you've got the name right", true)) } val reply = ReplyBuilder(message.chat.name == "discord"); if(nsfw && !message.nsfwSite){ return listOf(ReplyMessage("The command is not available here", true)) } reply.fixedInput().append(d).append("`${CommandCenter.TRIGGER}") .append(name) .append(if(nsfw) "` (NSFW)" else "`") .append(": $desc") .nl().fixedInput().append(help) .nl().fixedInput().append("Known aliases: $aliases") .nl().fixedInput().append("Rank required: " + "${if(rank == NO_DEFINED_RANK) "1 (WARNING: Undefined in code. Actual rank may differ from listed)" else rank.toString()} " + "(your rank: ${Utils.getRank(message.user.userID, message.chat.config)})") return listOf(ReplyMessage(reply.toString(), true)); } } }
0
Kotlin
2
11
f72194b98900bad53839e99326eaabed035ecf5b
8,362
NN-chatbot
Apache License 2.0
data/src/main/kotlin/com/ilgiz/kitsu/data/remote/dtos/manga/Installments.kt
ilgiz05
493,248,856
false
null
package com.ilgiz.kitsu.data.remote.dtos.manga import com.google.gson.annotations.SerializedName import com.ilgiz.kitsu.domain.models.manga.InstallmentsModel data class Installments( @SerializedName("links") val links: LinksXXXX ) fun Installments.toDomain() = InstallmentsModel(links.toDomain())
0
Kotlin
0
0
f9d4b4b9899bc2faa3fc992233c3187774d3d8d8
312
kitsuApi
MIT License
src/commonMain/kotlin/com/github/kotlinizer/mqtt/internal/connection/packet/received/PubRec.kt
kotlinizer
182,853,094
false
null
package com.github.kotlinizer.mqtt.internal.connection.packet.received internal data class PubRec(override val packetIdentifier: Short) : MqttReceivedPacket
0
Kotlin
3
3
02fa88d75c676f55d33ae7df213b009982b7dc1d
157
kotlin-mqtt-client
Apache License 2.0
src/main/kotlin/saarland/cispa/frontmatter/analyses/CollectMetadata.kt
uds-se
384,046,711
false
null
package saarland.cispa.frontmatter.analyses import mu.KLogging import saarland.cispa.frontmatter.ActivityClass import saarland.cispa.frontmatter.ApkInfo import saarland.cispa.frontmatter.FrontmatterSettings import saarland.cispa.frontmatter.LanguageDetector import saarland.cispa.frontmatter.Utils.getSuperclasses import soot.Scene import soot.SootClass import soot.jimple.infoflow.android.manifest.ProcessManifest data class FrontmatterMetadata(val pkg: String, val pkgVersionName: String, val pkgVersionCode: Int, val boomerangTimeout: Int, val version: String, val type: AppPlatform, val defaultLanguage: String) class CollectMetadata(val sceneV: Scene, val apkInfo: ApkInfo, val manifest: ProcessManifest, val settings: FrontmatterSettings) { companion object : KLogging() val meta = run { val boomerangTimeout = settings.boomerangTimeout val version = javaClass.getPackage().implementationVersion ?: "" val platform = identifyPlatform(manifest, apkInfo) val language = if (platform.isAnalysable && settings.detectLang) LanguageDetector().detect(apkInfo.resourceParser) else "none" if (isNotEnglish(language) && settings.detectLang) { logger.info("Non-english app detected: $language") } val pkg = manifest.packageName val pkgVersionCode = manifest.versionCode val pkgVersionName = manifest.versionName ?: "" FrontmatterMetadata(pkg, pkgVersionName, pkgVersionCode, boomerangTimeout, version, platform, language) } private fun isNotEnglish(language: String) = language !in setOf("en", "none") private fun identifyPlatform(manifest: ProcessManifest, apkInfo: ApkInfo): AppPlatform = when { isNativeCode(manifest, apkInfo.declaredActivities) -> { logger.info("Is packaged") AppPlatform.NATIVE } isUnity(apkInfo.mainActivities) -> { logger.info("Is unity based game") AppPlatform.UNITY } isXamarin(apkInfo.mainActivities) -> { logger.info("Is built with xamarin") AppPlatform.XAMARIN } isMono(sceneV) -> { logger.info("Is built with mono") AppPlatform.MONO } isCordova(apkInfo.mainActivities) -> { logger.info("Is built with apache cordova") AppPlatform.CORDOVA } else -> { logger.info("Is regular app") AppPlatform.NORMAL } } private fun isXamarin(mainActivities: Set<ActivityClass>): Boolean { val pattern = "^md5[0-9a-f]{32}".toRegex() return mainActivities.any { pattern.containsMatchIn(it.name) } } private fun isUnity(mainActivities: Collection<SootClass>): Boolean { return mainActivities.any { it.name.startsWith("com.unity3d") } } private fun isNativeCode(manifest: ProcessManifest, declaredActivities: Set<ActivityClass>): Boolean { return declaredActivities.isEmpty() || (declaredActivities.size < manifest.allActivities.size / 2 && manifest.allActivities.size > 3) } private fun isMono(sceneV: Scene): Boolean { return sceneV.applicationClasses.any { it.name.startsWith("mono.android") } } private fun isCordova(mainActivities: Collection<SootClass>): Boolean { return mainActivities.any { activity -> getSuperclasses(activity).any { it.name == "org.apache.cordova.CordovaActivity" } } } }
1
Kotlin
0
1
2ce4b52fc84e4c837749a205c9b32d48b9423c4c
3,457
Frontmatter
MIT License
app/src/main/java/com/example/buynow/data/local/room/item/ItemDao.kt
Shanan23
794,368,317
false
{"Kotlin": 210564}
package com.example.buynow.data.local.room.item import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update @Dao interface ItemDao { @Query("SELECT * FROM items order by Item_ID asc") fun getAll(): LiveData<List<ItemEntity>> @Query("SELECT * FROM items WHERE Item_User_ID = :userId order by Item_ID asc") fun getByUserId(vararg userId: String): LiveData<List<ItemEntity>> @Query("SELECT * FROM items WHERE Item_ID = :itemId order by Item_ID asc") fun getByItemId(itemId: String): LiveData<ItemEntity> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(vararg item: ItemEntity) @Delete suspend fun delete(item: ItemEntity) @Update suspend fun update(vararg item: ItemEntity) }
0
Kotlin
0
0
adca126dd1a8e90dab6153963f3b7e2368b809db
899
ToSerba
MIT License
LuraPlayerSampleApp/src/main/java/com/akta/luraplayersampleapp/modern/custom/AssetsReader.kt
ramdevblim
816,915,917
false
{"Kotlin": 333757}
package com.akta.luraplayersampleapp.modern.custom import android.content.Context import com.akta.luraplayer.api.logger.LuraLog import com.akta.luraplayersampleapp.BuildConfig import com.akta.luraplayersampleapp.modern.data.Assets import com.akta.luraplayersampleapp.modern.data.Video import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json private val json = Json { ignoreUnknownKeys = true } private var dashboardCachedJsonData: String? = null private var verticalCachedJsonData: String? = null fun Context.getDashboardAssets(): Map<String, List<Video>> { if (dashboardCachedJsonData == null) { dashboardCachedJsonData = try { this.assets.open("videos.json").bufferedReader().use { it.readText() } } catch (e: Exception) { LuraLog.e("AssetsReader", e.message ?: "videos.json read error", e) return emptyMap() } } return try { val allAssets: MutableMap<String, List<Video>> = mutableMapOf() val jsonString = dashboardCachedJsonData ?: return emptyMap() json.decodeFromString<List<Assets>>(jsonString).forEach { if (!BuildConfig.DEBUG) { if (!it.debugOnly) { val videoList: MutableList<Video> = mutableListOf() it.configs.forEach { video -> if (!video.debugOnly) { videoList.add(video) } } allAssets[it.groupTitle] = videoList } } else { allAssets[it.groupTitle] = it.configs } } allAssets } catch (e: Exception) { LuraLog.e("AssetsReader", e.message ?: "", e) emptyMap() } } fun Context.getVerticalAssets(): List<Video> { if (verticalCachedJsonData == null) { verticalCachedJsonData = try { this.assets.open("vertical-videos.json").bufferedReader().use { it.readText() } } catch (e: Exception) { LuraLog.e("AssetsReader", e.message ?: "vertical-videos.json read error", e) return emptyList() } } return try { val videoList: MutableList<Video> = mutableListOf() val jsonString = verticalCachedJsonData ?: return emptyList() json.decodeFromString<List<Video>>(jsonString).forEach { if (!BuildConfig.DEBUG) { if (!it.debugOnly) { videoList.add(it) } } else { videoList.add(it) } } videoList } catch (e: Exception) { LuraLog.e("AssetsReader", e.message ?: "", e) emptyList() } }
0
Kotlin
0
0
708586303f1206d1eaa3515bf836ba725d248246
2,729
akta-v4-downloads
MIT License
email/src/commonTest/kotlin/EmailTest.kt
aSoft-Ltd
258,530,471
false
null
import tz.co.asoft.Email import kotlin.test.* class EmailTest { @Test fun should_pass() { assertEquals("<EMAIL>", Email("<EMAIL>").value) } @Test fun should_fail() { assertFails { Email("kitimtim") } assertFails { Email("test.com") } } }
0
Kotlin
3
1
8233558139144a26c40ae30526bfd0b26bc7b3cb
288
kotlin
MIT License
src/en/fmovies/src/eu/kanade/tachiyomi/animeextension/en/fmovies/FMoviesDto.kt
aniyomiorg
360,630,872
false
{"Kotlin": 4099794}
package eu.kanade.tachiyomi.animeextension.en.fmovies import kotlinx.serialization.Serializable @Serializable data class VrfResponse( val url: String, val vrfQuery: String? = null, ) @Serializable data class AjaxResponse( val result: String, ) @Serializable data class AjaxServerResponse( val result: UrlObject, ) { @Serializable data class UrlObject( val url: String, ) } @Serializable data class EpisodeInfo( val id: String, val url: String, ) @Serializable data class FMoviesSubs( val file: String, val label: String, ) @Serializable data class RawResponse( val rawURL: String, ) @Serializable data class VidsrcResponse( val result: ResultObject, ) { @Serializable data class ResultObject( val sources: List<SourceObject>, ) { @Serializable data class SourceObject( val file: String, ) } }
375
Kotlin
138
342
e4eb7cdf6379102c903338402d2b8b96b42d3fa7
921
aniyomi-extensions
Apache License 2.0
library/core/engine/src/main/kotlin/de/lise/fluxflow/engine/state/AssumingChangeDetector.kt
lisegmbh
740,936,659
false
{"Kotlin": 732949}
package de.lise.fluxflow.engine.state import de.lise.fluxflow.api.state.ChangeDetector /** * The [AssumingChangeDetector] always assumes that an entity did change if [assumedResult] is set to `true`. * If it is set to `false`, it always assumes that it did not change. */ class AssumingChangeDetector<in TEntity>( private val assumedResult: Boolean ): ChangeDetector<TEntity> { override fun hasChanged(oldVersion: TEntity, newVersion: TEntity): Boolean { return assumedResult } }
21
Kotlin
0
7
1ad9ce84c8aa3d87d6b7114125962db5b30801c9
504
fluxflow
Apache License 2.0
dashboard/dashboard_presentation/src/main/java/com/nstudiosappdev/games/dashboard/presentation/GameViewEntityMapper.kt
harrunisk
231,150,453
false
null
package com.nstudiosappdev.games.dashboard.presentation import com.nstudiosappdev.core.presentation.recyclerview.DisplayItem import com.nstudiosappdev.games.dashboard.domain.objects.Game import io.reactivex.functions.Function class GameViewEntityMapper : Function<Game, DisplayItem> { override fun apply(t:Game): DisplayItem{ return GameViewEntity( id = t.id, name = t.name, released = t.released, backgroundImage = t.backgroundImage, rating = t.rating ) } }
0
Kotlin
1
15
b0059ae52e7875b78815bfe80a9384adb213846e
547
Games
MIT License
app/src/main/java/com/starkbank/cocoatouch/uikit/UIStoryboard.kt
starkbank
542,751,615
false
{"Kotlin": 45758}
package com.starkbank.cocoatouch.uikit open class UIStoryboard: UIActivity() { // // Public instance methods // fun instantiateViewControllerWithIdentifier(identifier: Int): UIViewController { val viewController: UIViewController = this.viewControllerForIdentifier(identifier) viewController.setIdentifier(identifier) viewController.storyboard = this return viewController } // // Init // override fun initApplication() { val application = UIApplication.sharedApplication() application.activity = this application.storyboard = this application.delegate = this.applicationDelegate() application.delegate?.application(application, null) application.delegate?.applicationDidBecomeActive(application) val viewController = instantiateViewControllerWithIdentifier(this.initialViewControllerId()) this.navigationController.pushViewController(viewController, false) } // // Methods that needs to be override // open fun viewControllerForIdentifier(identifier: Int): UIViewController { return UIViewController() } open fun viewCellForIdentifier(identifier: Int): UITableViewCell { return UITableViewCell() } open fun applicationDelegate(): UIApplicationDelegate? { return null } }
0
Kotlin
0
0
f857b1c8e97342024f12959cebd6b9182f903f29
1,375
cocoatouch-for-android
MIT License
Weather/domain/src/main/java/com/farhan/domain/common/Mapper.kt
hfarhanahmed
438,925,610
false
null
package com.farhan.domain.common import io.reactivex.Observable abstract class Mapper<in From, To> { abstract fun mapFrom(from: From): To fun mapFromList(from: List<From>): List<To> { return from.map { mapFrom(it) } } fun observable(from: From): Observable<To> { return Observable.fromCallable { mapFrom(from) } } fun observable(from: List<From>): Observable<List<To>> { return Observable.fromCallable { mapFromList(from) } } }
0
Kotlin
0
0
b17bfc384364e7afc30dac684d9adb6eb9a0497a
485
WeatherApp
MIT License
app/src/main/java/com/gowittgroup/smartassist/util/NetworkUtil.kt
wittgroup-inc
606,868,969
false
{"Kotlin": 183771}
package com.gowittgroup.smartassist.util import android.content.Context import android.content.Context.CONNECTIVITY_SERVICE import android.net.ConnectivityManager import android.util.Log import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject class NetworkUtilImpl @Inject constructor(@ApplicationContext private val context: Context):NetworkUtil { override fun isDeviceOnline(): Boolean { val connManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = connManager.getNetworkCapabilities(connManager.activeNetwork) return if (networkCapabilities == null) { Log.d(TAG, "Device Offline") false } else { Log.d(TAG, "Device Online") true } } companion object{ private val TAG: String = NetworkUtil::class.java.simpleName } } interface NetworkUtil { fun isDeviceOnline(): Boolean }
0
Kotlin
0
0
eadf19e9852c213c607e9068d2685ba5e01720a3
977
smartassist
Apache License 2.0
src/main/kotlin/krayon/editor/base/command/ApplicationCommand.kt
draeger-lab
156,102,188
true
{"Kotlin": 800067, "Java": 123973, "CSS": 34315, "Inno Setup": 1574}
/* * Copyright (c) 2018 Roland Wiese * This software is licensed under the Apache License, Version 2.0 (the "License"); you may not use this software 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 krayon.editor.base.command import com.yworks.yfiles.graph.* import com.yworks.yfiles.view.ISelectionModel import com.yworks.yfiles.view.input.ICommand import krayon.editor.base.Application import krayon.editor.base.ui.* import krayon.editor.base.util.IconManager import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action import javax.swing.Icon import javax.swing.KeyStroke abstract class ApplicationCommand(final override val id: String, final override val scope: CommandScope = CommandScope.DEFAULT) : IApplicationCommand { var name:String? = null var keyStroke:KeyStroke? = null override var description:String? = null override var mouseGestureDescription: String? = null private val parameterizedActions = mutableListOf<ParameterizedAction>() val commandHandle = ICommand.createCommand(id)!! val graphComponent get() = Application.focusedGraphComponent!! val graph: IGraph get() = graphComponent.graph val selectedNodes: ISelectionModel<INode> get() = graphComponent.selection.selectedNodes val selectedEdges: ISelectionModel<IEdge> get() = graphComponent.selection.selectedEdges fun getNodes(param:Any?) = if(param is INode) listOf(param) else selectedNodes fun getUniqueNode(param:Any?) = param as? INode ?: with(graphComponent.selection.selectedNodes) { if(size() == 1) first() else null } fun getUniqueEdge(param:Any?) = param as? IEdge ?: with(graphComponent.selection.selectedEdges) { if(size() == 1) first() else null } fun getUniqueLabel(param:Any?) = param as? ILabel ?: with(graphComponent.selection.selectedLabels) { if(size() == 1) first() else null } fun getUniquePort(param:Any?) = param as? IPort ?: with(graphComponent.selection.selectedPorts) { if(size() == 1) first() else null } fun managedCanExecute(param:Any?):Boolean { if(Application.focusedGraphComponent == null) return false val result = canExecute(param) parameterizedActions.forEach { if (it.param == param) it.action.isEnabled = result } return result } internal data class ParameterizedAction(val action: Action, val param:Any? = null, val target:Any) fun getAction(target:Any, param:Any? = null): Action { val action = parameterizedActions.firstOrNull { it.param == param && it.target == target }?.action ?: createAction(target, param) action.isEnabled = managedCanExecute(param) return action } private fun createAction(target: Any, param:Any? = null): Action { val action = object: AbstractAction(name ?: id) { override fun actionPerformed(event: ActionEvent) { val parameter = getValue(Action.SELECTED_KEY)?.let { it } ?: param if(canExecute(parameter)) CommandManager.execute(this@ApplicationCommand, parameter, CommandManager.InvocationMethod.VIA_ACTION) } } parameterizedActions.add(ParameterizedAction(action, param, target)) return action.apply { shortcut = keyStroke tooltip = convertToHtmlTooltip(description ?: name ?: id) + ' ' + action.shortcutString icon = icon32 selectedIcon = selectedIcon32 } } private fun convertToHtmlTooltip(text:String, lineBreakLimit:Int=40):String { val words = text.split(' ') var lineLength = 0 val result = StringBuffer("<html>") words.forEach { word -> if(lineLength > 0 && lineLength + word.length > lineBreakLimit) { result.append("<br>$word") lineLength = word.length } else { result.append(" $word") lineLength += word.length + 1 } } return result.toString() } protected fun updateActionSelectionState(isSelected:Boolean) { parameterizedActions.forEach { it.action.isSelected = isSelected } } @Suppress("MemberVisibilityCanBePrivate") val icon32: Icon? get() = IconManager.iconMap["${scope.name}.$id"]?.icon32 @Suppress("MemberVisibilityCanBePrivate") val selectedIcon32: Icon? get() = IconManager.iconMap["${scope.name}.$id"]?.selectedIcon32 val icon16: Icon? get() = IconManager.iconMap["${scope.name}.$id"]?.icon16 val selectedIcon16: Icon? get() = IconManager.iconMap["${scope.name}.$id"]?.selectedIcon16 }
0
Kotlin
0
1
d40dc53b35367a81099b929a22b1b36f8f601a42
5,037
krayon4sbgn
Apache License 2.0
core/domain/src/main/java/com/halilozcan/animearch/core/domain/usecase/single/GetSingleCharacterUseCase.kt
halilozcan
572,966,235
false
null
package com.halilozcan.animearch.core.domain.usecase.single import com.halilozcan.animearch.core.common.NetworkResponseState import com.halilozcan.animearch.core.domain.entity.SingleAnimeEntity import kotlinx.coroutines.flow.Flow interface GetSingleCharacterUseCase { operator fun invoke(id: String): Flow<NetworkResponseState<SingleAnimeEntity>> }
1
Kotlin
8
97
5903644dbabf505702d488d8ec7bb19b78174467
354
AnimeArch
Apache License 2.0
module-domain/src/main/kotlin/io/klaytn/finder/domain/mysql/set4/GovernanceCouncilsInfo.kt
klaytn
678,353,482
false
{"Kotlin": 1783784, "Solidity": 71874, "Shell": 4003}
package io.klaytn.finder.domain.mysql.set4 import io.klaytn.finder.domain.mysql.BaseEntity import java.time.LocalDateTime import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Table @Entity @Table(name = "governance_councils_info") data class GovernanceCouncilsInfo ( @Column val squareId: Long, @Column var squareLink: String, @Column var name: String, @Column var thumbnail: String, @Column var website: String, @Column(columnDefinition = "TEXT") var summary: String?, @Column(columnDefinition = "TEXT") var description: String, @Column var apy: String, @Column var totalStaking: String, @Column(columnDefinition = "TINYINT") var isFoundation: Boolean, @Column var joinedAt: LocalDateTime?, @Column var activatedAt: LocalDateTime?, @Column var deactivatedAt: LocalDateTime? ): BaseEntity() { companion object { fun of( squareId: Long, squareLink: String, name: String, thumbnail: String, website: String, summary: String?, description: String, apy: String, totalStaking: String, isFoundation: Boolean, joinedAt: LocalDateTime ) = GovernanceCouncilsInfo( squareId = squareId, squareLink = squareLink, name = name, thumbnail = thumbnail, website = website, summary = summary, description = description, apy = apy, totalStaking = totalStaking, isFoundation = isFoundation, joinedAt = joinedAt, activatedAt = null, deactivatedAt = null ) } }
7
Kotlin
0
0
19229490436cf5c0096f25310959286645dc3914
1,813
finder-api
MIT License
sphinx/application/network/features/queries/feature-network-query-contact/src/main/java/chat/sphinx/feature_network_query_contact/model/GetLatestContactsRelayResponse.kt
stakwork
340,103,148
false
{"Kotlin": 4002700, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
package chat.sphinx.feature_network_query_contact.model import chat.sphinx.concept_network_query_contact.model.GetContactsResponse import chat.sphinx.concept_network_query_contact.model.GetLatestContactsResponse import chat.sphinx.concept_network_relay_call.RelayResponse import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) internal data class GetLatestContactsRelayResponse( override val success: Boolean, override val response: GetLatestContactsResponse?, override val error: String? ) : RelayResponse<GetLatestContactsResponse>()
99
Kotlin
11
18
01d4be42df107d5e4fa8d2411f5390aeea60ea74
566
sphinx-kotlin
MIT License
src/main/kotlin/no/acntech/easycontainers/util/lang/Validator.kt
acntech
739,332,140
false
{"Kotlin": 369659, "HTML": 485}
package no.acntech.easycontainers.util.lang /** * Interface for validating objects. */ interface Validator<T> { /** * Validates the given object. * * @param t the object to validate * @throws ValidationException if the object is not valid */ @Throws(ValidationException::class) fun validate(t: T) }
3
Kotlin
0
1
896e213887aee8c3baf8fe38fa4023b60c35be77
332
easycontainers
Apache License 2.0
app/src/main/java/ru/axcheb/spotifyapi/di/AppModule.kt
axcheb
402,218,865
false
null
package ru.axcheb.spotifyapi.di import dagger.Module @Module(includes = [NetworkModule::class]) object AppModule
0
Kotlin
0
0
a40c53cfe39d9e9b2ee58c09236e9b0d57e4462d
115
SpotifyBrowser
MIT License
shared/src/test/kotlin/com/egm/stellio/shared/model/ExpandedMembersTests.kt
stellio-hub
257,818,724
false
{"Kotlin": 1717826, "Dockerfile": 2088, "Shell": 1825}
package com.egm.stellio.shared.model import com.egm.stellio.shared.util.* import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_CREATED_AT_PROPERTY import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_MODIFIED_AT_PROPERTY import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_RELATIONSHIP_OBJECT import com.egm.stellio.shared.util.JsonLdUtils.buildExpandedPropertyValue import com.egm.stellio.shared.util.JsonLdUtils.buildExpandedRelationshipValue import kotlinx.coroutines.test.runTest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class ExpandedMembersTests { @Test fun `it should add createdAt information into an attribute`() { val attrPayload = mapOf("attribute" to buildExpandedPropertyValue(12.0)) val attrPayloadWithSysAttrs = attrPayload.addSysAttrs(true, ngsiLdDateTime(), null) assertThat(attrPayloadWithSysAttrs) .containsKey(NGSILD_CREATED_AT_PROPERTY) .doesNotContainKey(NGSILD_MODIFIED_AT_PROPERTY) } @Test fun `it should add createdAt and modifiedAt information into an attribute`() { val attrPayload = mapOf("attribute" to buildExpandedPropertyValue(12.0)) val attrPayloadWithSysAttrs = attrPayload.addSysAttrs(true, ngsiLdDateTime(), ngsiLdDateTime()) assertThat(attrPayloadWithSysAttrs) .containsKey(NGSILD_CREATED_AT_PROPERTY) .containsKey(NGSILD_MODIFIED_AT_PROPERTY) } @Test fun `it should not find an unknown attribute instance in a list of attributes`() = runTest { val entityFragment = """ { "brandName": { "value": "a new value" } } """.trimIndent() val expandedAttributes = JsonLdUtils.expandAttributes(entityFragment, NGSILD_TEST_CORE_CONTEXTS) assertNull(expandedAttributes.getAttributeFromExpandedAttributes("unknownAttribute", null)) } @Test fun `it should find an attribute instance from a list of attributes without multi-attributes`() = runTest { val entityFragment = """ { "brandName": { "value": "a new value", "observedAt": "2021-03-16T00:00:00.000Z" }, "name": { "value": 12 } } """.trimIndent() val expandedAttributes = JsonLdUtils.expandAttributes(entityFragment, NGSILD_TEST_CORE_CONTEXTS) val expandedBrandName = JsonLdUtils.expandJsonLdTerm("brandName", NGSILD_TEST_CORE_CONTEXTS) assertNotNull(expandedAttributes.getAttributeFromExpandedAttributes(expandedBrandName, null)) assertNull( expandedAttributes.getAttributeFromExpandedAttributes(expandedBrandName, "urn:datasetId".toUri()) ) } @Test fun `it should find an attribute instance from a list of attributes with multi-attributes`() = runTest { val entityFragment = """ { "brandName": [{ "value": "a new value", "observedAt": "2021-03-16T00:00:00.000Z" }, { "value": "a new value", "observedAt": "2021-03-16T00:00:00.000Z", "datasetId": "urn:datasetId:1" }], "name": { "value": 12, "datasetId": "urn:datasetId:1" } } """.trimIndent() val expandedAttributes = JsonLdUtils.expandAttributes(entityFragment, NGSILD_TEST_CORE_CONTEXTS) val expandedBrandName = JsonLdUtils.expandJsonLdTerm("brandName", NGSILD_TEST_CORE_CONTEXTS) val expandedName = JsonLdUtils.expandJsonLdTerm("name", NGSILD_TEST_CORE_CONTEXTS) assertNotNull(expandedAttributes.getAttributeFromExpandedAttributes(expandedBrandName, null)) assertNotNull( expandedAttributes.getAttributeFromExpandedAttributes(expandedBrandName, "urn:datasetId:1".toUri()) ) assertNull( expandedAttributes.getAttributeFromExpandedAttributes(expandedBrandName, "urn:datasetId:2".toUri()) ) assertNotNull( expandedAttributes.getAttributeFromExpandedAttributes(expandedName, "urn:datasetId:1".toUri()) ) assertNull(expandedAttributes.getAttributeFromExpandedAttributes(expandedName, null)) } @Test fun `it should return an error if a relationship has no object field`() { val relationshipValues = buildExpandedPropertyValue("something")[0] val result = relationshipValues.getRelationshipObject("isARelationship") assertTrue(result.isLeft()) result.mapLeft { assertEquals("Relationship isARelationship does not have an object field", it.message) } } @Test fun `it should return an error if a relationship has an empty object`() { val relationshipValues = mapOf( NGSILD_RELATIONSHIP_OBJECT to emptyList<Any>() ) val result = relationshipValues.getRelationshipObject("isARelationship") assertTrue(result.isLeft()) result.mapLeft { assertEquals("Relationship isARelationship is empty", it.message) } } @Test fun `it should return an error if a relationship has an invalid object type`() { val relationshipValues = mapOf( NGSILD_RELATIONSHIP_OBJECT to listOf("invalid") ) val result = relationshipValues.getRelationshipObject("isARelationship") assertTrue(result.isLeft()) result.mapLeft { assertEquals( "Relationship isARelationship has an invalid object type: class java.lang.String", it.message ) } } @Test fun `it should return an error if a relationship has object without id`() { val relationshipValues = mapOf( NGSILD_RELATIONSHIP_OBJECT to listOf( mapOf("@value" to "urn:ngsi-ld:T:misplacedRelationshipObject") ) ) relationshipValues.getRelationshipObject("isARelationship") .shouldFail { assertEquals("Relationship isARelationship has an invalid or no object id: null", it.message) } } @Test fun `it should extract the target object of a relationship`() { val relationshipObjectId = "urn:ngsi-ld:T:1" val relationshipValues = buildExpandedRelationshipValue(relationshipObjectId.toUri()) relationshipValues[0].getRelationshipObject("isARelationship") .shouldSucceedWith { assertEquals(relationshipObjectId.toUri(), it) } } }
35
Kotlin
11
27
a740e148f22e05c0add8b841fe976dccdb98cf59
6,881
stellio-context-broker
Apache License 2.0
app/src/main/java/com/luismunyoz/catalogue/ui/screens/main/di/MainActivityModule.kt
luismunyoz
129,391,557
false
null
package com.luismunyoz.catalogue.ui.screens.main.di import androidx.fragment.app.FragmentActivity import com.luismunyoz.catalogue.ui.screens.main.MainActivity import com.luismunyoz.catalogue.ui.screens.main.MainContract import com.luismunyoz.catalogue.ui.screens.main.MainPresenter import dagger.Binds import dagger.Module @Module abstract class MainActivityModule { @Binds abstract fun provideActivity(activity: MainActivity): FragmentActivity @Binds abstract fun provideMainPresenter(presenter: MainPresenter) : MainContract.Presenter }
0
Kotlin
1
0
8114e8359717aba467a71c2c5ddb70b51cbe5666
570
catalogue
Apache License 2.0
src/main/kotlin/com/imyvm/essentialCommandsImyvmAddition/EssentialEconomyConfig.kt
Dream-Rainy
708,880,142
false
{"Kotlin": 41443, "Java": 16503}
package com.imyvm.essentialCommandsImyvmAddition import com.fibermc.essentialcommands.EssentialCommands.LOGGER import dev.jpcode.eccore.config.Config import dev.jpcode.eccore.config.ConfigOption import dev.jpcode.eccore.config.Option import java.nio.file.Path import java.time.ZoneId class EssentialEconomyConfig(savePath: Path?, displayName: String?, documentationLink: String?) : Config<EssentialEconomyConfig?>(savePath, displayName, documentationLink) { @ConfigOption @JvmField val HOME_SET_PRICE = Option( "home_set_price", "x*10*2^x" ) { obj: String -> obj } @ConfigOption @JvmField val HOME_TP_PRICE = Option( "home_tp_price", "IF(x <= 2 ,0 , 5*2^(x-2))" ) { obj: String -> obj } @ConfigOption @JvmField val HOME_TP_COOLDOWN = Option( "home_tp_cooldown", "IF(x <= 2 ,0,IF(x >= 5,240,30*2^(x-2)))" ) { obj: String -> obj } @ConfigOption @JvmField val HOME_TP_DELAY = Option( "home_tp_delay", "IF(x <= 2,3,6)" ) { obj: String -> obj } @ConfigOption @JvmField val BACK_PRICE = Option( "back_price", "IF(x <= 2,0,5*2^(x-2))" ) { obj: String -> obj } @ConfigOption @JvmField val TPA_PRICE = Option( "tpa_price", "IF(x <= 2,0,7.5*2^(x-2))" ) { obj: String -> obj } @ConfigOption @JvmField val TPA_COOLDOWN = Option( "tpa_cooldown", "IF(x <= 2,0,IF(x >= 5,360,45*2^(x-2)))" ) { obj: String -> obj } @ConfigOption @JvmField val TPA_DELAY = Option( "tpa_delay", "IF(x <= 2,3,9)" ) { obj: String -> obj } @ConfigOption @JvmField val TIME_ZONE = Option( "timezone", ZoneId.systemDefault() ) { zoneId: String? -> ZoneId.of(zoneId) } @ConfigOption @JvmField val WARP_TP_PRICE = Option( "warp_tp_price", "30" ) { obj: String -> obj } @ConfigOption @JvmField val WARP_TP_COOLDOWN = Option( "warp_tp_cooldown", "1200" ) { obj: String -> obj } @ConfigOption @JvmField val WARP_TP_DELAY = Option( "warp_tp_delay", "6" ) { obj: String -> obj } @ConfigOption @JvmField val WARP_HOME_PRICE = Option( "warp_home_price", "0" ) { obj: String -> obj } @ConfigOption @JvmField val WARP_HOME_COOLDOWN = Option( "warp_home_cooldown", "0" ) { obj: String -> obj } @ConfigOption @JvmField val WARP_HOME_DELAY = Option( "warp_home_delay", "3" ) { obj: String -> obj } @ConfigOption @JvmField val WARP_SET_HOME_PRICE = Option( "warp_set_home_price", "150" ) { obj: String -> obj } companion object { fun <T> getValueSafe(option: Option<T>, defaultValue: T): T { try { return option.getValue() } catch (ex: Exception) { // Someone was getting an error with eccore/config/Option not being found when Option.getValue() was called // from within ServerPlayerEntityMixin. I can't reproduce, but /shrug // We're actually catching a ClassNotFoundException due to mixin weirdness, I think... LOGGER.error(ex) } return defaultValue } } }
0
Kotlin
0
1
447385aab7d88f03219e3f533ff34fb2517a602c
3,263
EssentialCommandsImyvmAddition
MIT License
app/src/main/java/com/jonathanlee/animation/SystemAnimationHelper.kt
jonathanlee06
374,100,648
false
null
package com.jonathanlee.animation import android.content.ContentResolver import android.content.Context import android.content.pm.PackageManager import android.provider.Settings import android.util.Log /** * A helper object to get/set system animation * * Note that this requires a system level permission, so must grant permission manually through ADB * * ]adb shell pm grant com.jonathanlee.animation android.permission.WRITE_SECURE_SETTINGS */ object SystemAnimationHelper { private const val TAG = "setAnimation" private const val WRITE_SECURE_PERMISSION = "android.permission.WRITE_SECURE_SETTINGS" private var isSetAnimationOn: Boolean? = null fun getAnimation(contentResolver: ContentResolver): Boolean { val animator = Settings.Global.getFloat( contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1F ) val transition = Settings.Global.getFloat( contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE, 1F ) val window = Settings.Global.getFloat( contentResolver, Settings.Global.WINDOW_ANIMATION_SCALE, 1F ) return (animator != 0F && transition != 0F && window != 0F) } fun setAnimation(contentResolver: ContentResolver, status: Boolean) { try { if (status) { Settings.Global.putFloat( contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1F ) Settings.Global.putFloat( contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE, 1F ) Settings.Global.putFloat( contentResolver, Settings.Global.WINDOW_ANIMATION_SCALE, 1F ) isSetAnimationOn = true } else { Settings.Global.putFloat( contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 0F ) Settings.Global.putFloat( contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE, 0F ) Settings.Global.putFloat( contentResolver, Settings.Global.WINDOW_ANIMATION_SCALE, 0F ) isSetAnimationOn = false } } catch (e: SecurityException) { Log.d(TAG, e.toString()) isSetAnimationOn = false } } fun isSetAnimationOn(): Boolean? { return isSetAnimationOn } fun isPermissionGiven(context: Context): Boolean { val permissionStatus = context.checkCallingOrSelfPermission(WRITE_SECURE_PERMISSION) return permissionStatus == PackageManager.PERMISSION_GRANTED } }
0
Kotlin
0
0
9d4169cab4a0ae1ef3e59d03386591ec3365e35a
2,725
AnimationToggle
MIT License
data/seasondetails/testing/src/commonMain/kotlin/com/thomaskioko/tvmaniac/seasondetails/testing/FakeSeasonDetailsRepository.kt
thomaskioko
361,393,353
false
{"Kotlin": 560203, "Swift": 94284}
package com.thomaskioko.tvmaniac.seasondetails.testing import com.thomaskioko.tvmaniac.core.db.SeasonEpisodeDetailsById import com.thomaskioko.tvmaniac.seasondetails.api.SeasonDetailsRepository import com.thomaskioko.tvmaniac.util.model.Either import com.thomaskioko.tvmaniac.util.model.Failure import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.receiveAsFlow class FakeSeasonDetailsRepository : SeasonDetailsRepository { private val seasonsResult: Channel<Either<Failure, List<SeasonEpisodeDetailsById>>> = Channel(Channel.UNLIMITED) private val cachedResult: Channel<List<SeasonEpisodeDetailsById>> = Channel(Channel.UNLIMITED) suspend fun setSeasonsResult(result: Either<Failure, List<SeasonEpisodeDetailsById>>) { seasonsResult.send(result) } suspend fun setCachedResults(result: List<SeasonEpisodeDetailsById>) { cachedResult.send(result) } override suspend fun fetchSeasonDetails( traktId: Long, ): List<SeasonEpisodeDetailsById> = cachedResult.receive() override fun observeSeasonDetailsStream( traktId: Long, ): Flow<Either<Failure, List<SeasonEpisodeDetailsById>>> = seasonsResult.receiveAsFlow() }
4
Kotlin
16
136
625b1bbab9aba4e5031778ba5020639106d4b4e9
1,246
tv-maniac
Apache License 2.0
screen/main/src/main/java/ru/maksonic/beresta/screen/main/presentation/core/MainSandbox.kt
maksonic
580,058,579
false
null
package ru.maksonic.beresta.screen.main.presentation.core import ru.maksonic.beresta.elm.Sandbox import ru.maksonic.beresta.elm.UpdatedModel /** * @Author maksonic on 16.01.2023 */ private typealias UpdateResult = UpdatedModel<Model, Set<Cmd>, Set<Eff>> class MainSandbox( mainProgram: MainProgram ) : Sandbox<Model, Msg, Cmd, Eff>( initialModel = Model(), initialCmd = setOf(Cmd.RunFetchingNotesCollection), subscriptions = listOf(mainProgram) ) { override fun update(msg: Msg, model: Model): UpdateResult = when (msg) { is Msg.Inner.FetchedNotesCollection -> fetchedNotes(model, msg) is Msg.Inner.FetchedError -> fetchedError(model, msg) is Msg.Ui.CreateNewNote -> onAddNoteClicked(model) is Msg.Inner.SetTopBarVisibility -> setTopBarVisibility(model, msg) is Msg.Inner.SetBottomVisibility -> setBottomBarVisibility(model, msg) is Msg.Inner.SetColoredTopBar -> setColoredTopBar(model, msg) is Msg.Ui.OnShareSelectedNotes -> onShareSelectedNotesClicked(model) is Msg.Ui.OnSettingsClicked -> onSettingsClicked(model) is Msg.Ui.OnTrashClicked -> onTrashClicked(model) is Msg.Ui.OnOpenFoldersClicked -> UpdatedModel(model) is Msg.Ui.OnSortNotesByClicked -> UpdatedModel(model) } private fun fetchedNotes(model: Model, msg: Msg.Inner.FetchedNotesCollection): UpdateResult = UpdatedModel( model.copy( base = model.base.copy(isLoading = false, isSuccessLoading = true, isError = false), notes = msg.data ) ) private fun fetchedError(model: Model, msg: Msg.Inner.FetchedError): UpdateResult = UpdatedModel( model.copy( base = model.base.copy( isLoading = false, isSuccessLoading = false, isError = true, errorMsg = msg.message ) ) ) private fun onAddNoteClicked(model: Model): UpdateResult = UpdatedModel(model, effects = setOf(Eff.NavigateToAddNewNote)) private fun setTopBarVisibility( model: Model, msg: Msg.Inner.SetTopBarVisibility ): UpdateResult = UpdatedModel(model.copy(isVisibleTopBar = msg.value)) private fun setBottomBarVisibility( model: Model, msg: Msg.Inner.SetBottomVisibility ): UpdateResult = UpdatedModel(model.copy(isVisibleBottomBar = msg.value)) private fun setColoredTopBar(model: Model, msg: Msg.Inner.SetColoredTopBar): UpdateResult = UpdatedModel(model.copy(isColoredTopBar = msg.value)) private fun onSettingsClicked(model: Model): UpdateResult = UpdatedModel(model, effects = setOf(Eff.NavigateToSettings)) private fun onShareSelectedNotesClicked(model: Model): UpdateResult = UpdatedModel(model) private fun onTrashClicked(model: Model): UpdateResult = UpdatedModel(model, effects = setOf(Eff.NavigateToTrash)) }
0
Kotlin
0
0
5704d413cd57a8eabe27b02a185a999fce2ca1e4
3,004
Beresta
MIT License
sample/src/main/kotlin/ru/github/pavelannin/sample/presentation/screen/menu/MenuFragment.kt
pavelannin
237,843,733
false
null
package ru.github.pavelannin.sample.presentation.screen.menu import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.observe import androidx.navigation.fragment.findNavController import com.jakewharton.rxbinding3.view.clicks import kotlinx.android.synthetic.main.fragment_menu.* import ru.github.pavelannin.sample.R class MenuFragment : Fragment(R.layout.fragment_menu) { private val viewModel: MenuViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.navigationState.observe(owner = this) { action -> findNavController().navigate(action.consume()) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fragmentMenuCounterButton.clicks() .map { MenuViewModel.Action.CountPressed } .subscribe(viewModel.actionSubject) fragmentMenuPaginationButton.clicks() .map { MenuViewModel.Action.PaginationPressed } .subscribe(viewModel.actionSubject) fragmentMenuDynamicAnimationButton.clicks() .map { MenuViewModel.Action.DynamicAnimationPressed } .subscribe(viewModel.actionSubject) } }
0
Kotlin
1
1
d1d0868735cccac4c31f7cbe268d5f106af0c10e
1,360
android-oneway
Apache License 2.0
scientist4k-core/src/main/kotlin/com/github/squirrelgrip/scientist4k/core/consumer/ConsoleConsumer.kt
SquirrelGrip
247,915,957
true
{"Kotlin": 234965, "JavaScript": 2164, "HTML": 1653, "CSS": 930}
package com.github.squirrelgrip.scientist4k.core.consumer import com.github.squirrelgrip.scientist4k.simple.model.SimpleExperimentResult import com.google.common.eventbus.Subscribe class ConsoleConsumer<T> { @Subscribe fun receiveResult(simpleExperimentResult: SimpleExperimentResult<T>) { println(simpleExperimentResult) } }
0
Kotlin
0
2
5c88eb2bf0275c1c8ad139a78c9a1222f499ce4e
348
Scientist4K
MIT License
app/src/main/kotlin/com/evastos/bux/inject/module/UtilModule.kt
eveey
147,939,147
false
null
package com.evastos.bux.inject.module import com.evastos.bux.ui.util.DateTimeUtil import com.evastos.bux.ui.util.NumberUtil import com.evastos.bux.ui.util.PriceUtil import dagger.Module import dagger.Provides import javax.inject.Singleton @Suppress("unused") @Module class UtilModule { @Provides @Singleton fun providesDateTimeUtil(): DateTimeUtil { return DateTimeUtil() } @Provides @Singleton fun providesPriceUtil(numberUtil: NumberUtil): PriceUtil { return PriceUtil(numberUtil) } @Provides @Singleton fun providesNumberUtil(): NumberUtil { return NumberUtil() } }
0
Kotlin
0
0
eb8d7fd92bc659e9da523941b4bd3c96a2797de5
646
BUXDemo
The Unlicense
parser/src/main/java/com/malt/parser/cert/pkcs7/SignerInfo.kt
MALTF
679,156,908
false
{"Kotlin": 288486}
package com.malt.parser.cert.pkcs7 import com.malt.parser.cert.asn1.Asn1Class import com.malt.parser.cert.asn1.Asn1Field import com.malt.parser.cert.asn1.Asn1OpaqueObject import com.malt.parser.cert.asn1.Asn1Tagging import com.malt.parser.cert.asn1.Asn1Type import java.nio.ByteBuffer /** * PKCS #7 `SignerInfo` as specified in RFC 5652. */ @Asn1Class(type = Asn1Type.SEQUENCE) class SignerInfo { @Asn1Field(index = 0, type = Asn1Type.INTEGER) var version = 0 @Asn1Field(index = 1, type = Asn1Type.CHOICE) var sid: SignerIdentifier? = null @Asn1Field(index = 2, type = Asn1Type.SEQUENCE) var digestAlgorithm: AlgorithmIdentifier? = null @Asn1Field( index = 3, type = Asn1Type.SET_OF, tagging = Asn1Tagging.IMPLICIT, tagNumber = 0, optional = true ) var signedAttrs: Asn1OpaqueObject? = null @Asn1Field(index = 4, type = Asn1Type.SEQUENCE) var signatureAlgorithm: AlgorithmIdentifier? = null @Asn1Field(index = 5, type = Asn1Type.OCTET_STRING) var signature: ByteBuffer? = null @Asn1Field( index = 6, type = Asn1Type.SET_OF, tagging = Asn1Tagging.IMPLICIT, tagNumber = 1, optional = true ) var unsignedAttrs: List<Attribute>? = null }
1
Kotlin
0
4
7aabf1d6d9741190d1527744dd168edd751911a4
1,287
APK-Parser
MIT License
fhg-repository/src/main/java/de/jbamberger/fhg/repository/api/FhgApiImpl.kt
radmat64
191,036,357
true
{"Kotlin": 129363, "HTML": 47474, "Java": 1378}
package de.jbamberger.fhg.repository.api import android.arch.lifecycle.LiveData import android.arch.lifecycle.MediatorLiveData import de.jbamberger.fhg.repository.data.FeedItem import de.jbamberger.fhg.repository.data.VPlan import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject /** * @author <NAME> (<EMAIL>) */ internal class FhgApiImpl @Inject constructor(private val endpoint: FhgEndpoint) : FhgApi { override fun getVPlan(): LiveData<ApiResponse<VPlan>> { val day1 = endpoint.getVPlanFrame1() val day2 = endpoint.getVPlanFrame2() val isLoaded = AtomicBoolean(false) val builder = VPlan.Builder() val merger = MediatorLiveData<ApiResponse<VPlan>>() merger.addSource(day1) { response -> merger.removeSource(day1) if (response != null && response.isSuccessful && response.body != null) { builder.addDay1(response.body) if (isLoaded.getAndSet(true)) { merger.value = ApiResponse(builder.build(), response) } } else { merger.removeSource(day2) if (response != null) { merger.setValue(ApiResponse(Throwable(response.errorMessage))) } else { merger.setValue(ApiResponse(Throwable("Network error"))) } } } merger.addSource(day2) { response -> merger.removeSource(day2) if (response != null && response.isSuccessful && response.body != null) { builder.addDay2(response.body) if (isLoaded.getAndSet(true)) { merger.value = ApiResponse(builder.build(), response) } } else { merger.removeSource(day1) if (response != null) { merger.setValue(ApiResponse(Throwable(response.errorMessage))) } else { merger.setValue(ApiResponse(Throwable("Network error"))) } } } return merger } override fun getFeed(): LiveData<ApiResponse<List<FeedItem>>> = endpoint.getFeed() }
0
Kotlin
0
0
4d95930b8f8df3cb3c734e1e11e47a08f182034e
2,373
fhg-android-app
MIT License
core/src/commonMain/kotlin/work/socialhub/kmastodon/entity/Field.kt
uakihir0
783,390,459
false
{"Kotlin": 168825, "Ruby": 2191, "Shell": 2164, "Makefile": 319}
package work.socialhub.kmastodon.entity import kotlinx.serialization.Serializable import kotlin.js.JsExport @JsExport @Serializable class Field { var name: String? = null var value: String? = null }
0
Kotlin
0
1
b1d48ee425c8a4724848d5686ce08f73edcc880d
210
kmastodon
MIT License
retrofitlivedatacalladapter/src/main/kotlin/com/aqrlei/open/retrofit/livedatacalladapter/LiveObservableSource.kt
AqrLei
163,495,242
false
null
package com.aqrlei.open.retrofit.livedatacalladapter /** * @author aqrlei on 2018/12/21 */ interface LiveObservableSource { fun cancel() }
0
Kotlin
0
0
7619a8552092f9098fdf12a34e4642fe596195a7
146
RetrofitLivedataCallAdapter
Apache License 2.0
app/src/main/java/com/fang/scroll/TypeAlias.kt
FangMessi
306,215,663
false
null
package com.fang.scroll /** * @author fangkw on 2020-10-23 **/ typealias MoreCallback = (Boolean) -> Unit
0
Kotlin
2
7
3d2c8e5c4806d0f68b6ef7d369d7a0d6d424328d
108
nested_scroll_demo
Apache License 2.0
app/src/main/java/at/shockbytes/dante/navigation/ActivityNavigator.kt
shockbytes
92,944,830
false
{"Kotlin": 790848}
package at.shockbytes.dante.navigation import android.content.Context import android.os.Bundle object ActivityNavigator { fun navigateTo( context: Context?, destination: Destination, transitionBundle: Bundle? = null, intentFlags: Int? = null ) { context?.let { ctx -> val intent = destination.provideIntent(ctx) intentFlags?.let(intent::setFlags) ctx.startActivity(intent, transitionBundle) } } }
21
Kotlin
7
73
626fd7c12691be646fcd7b55a9c46539073af675
498
Dante
Apache License 2.0
core/network/src/commonMain/kotlin/com/cdcoding/network/client/ton/TonTransactionStatusClient.kt
Christophe-DC
822,562,468
false
{"Kotlin": 728291, "Ruby": 4739, "Swift": 617}
package com.cdcoding.network.client.ton import com.cdcoding.model.Chain import com.cdcoding.model.HashChanges import com.cdcoding.model.TransactionChages import com.cdcoding.model.TransactionState import com.cdcoding.network.client.TransactionStatusClient import com.cdcoding.network.util.getOrNull import com.trustwallet.core.Base64 class TonTransactionStatusClient( private val apiClient: TonApiClient, ) : TransactionStatusClient { @OptIn(ExperimentalStdlibApi::class) override suspend fun getStatus(owner: String, txId: String): Result<TransactionChages> { val txHashData = Base64.decode(txId) val transaction = apiClient.transaction(txHashData?.toHexString() ?: "").getOrNull() val rawHash = transaction?.firstOrNull()?.hash ?: return Result.success( TransactionChages( TransactionState.Pending ) ) val newId = Base64.decode(rawHash)?.toHexString() ?: "" return Result.success( TransactionChages( TransactionState.Confirmed, hashChanges = HashChanges(old = txId, new = newId) ) ) } override fun maintainChain(): Chain = Chain.Ton }
0
Kotlin
0
0
bc7c3eb161ee18db83402ded314e2e0b72196974
1,212
secureWallet
Apache License 2.0
presentation/src/main/java/com/amaringo/presentation/feature/center_list/model/Location.kt
AdrianMarinGonzalez
329,634,066
false
null
package com.amaringo.presentation.feature.center_list.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Location(val latitude: Double, val longitude: Double): Parcelable
0
Kotlin
0
0
23375a1c62cdce702d81b65f1b70e0c198bd144b
218
CAM-care
The Unlicense
app/src/main/java/com/example/helloworld/MainActivity.kt
smrithy23
736,462,677
false
{"Kotlin": 1638}
package com.example.helloworld import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val helloB = findViewById<Button>(R.id.hellobutton) helloB.setOnClickListener{ Log.v("Hello world","Button clicked!") Toast.makeText(this, "Hello to you too!", Toast.LENGTH_SHORT).show() } } }
0
Kotlin
0
0
ecd07cca9c915d9e6776222bcd11d68c6edc7786
621
CP-HelloWorld
Apache License 2.0
src/main/kotlin/days/DayTempalte.kt
couturierb
728,250,155
false
{"Kotlin": 20183}
package days class DayTempalte : Day(11) { override fun partOne(): Any { return "" } override fun partTwo(): Any { return "" } }
0
Kotlin
0
0
264d5f5063cd1c738bc4e1d8b5cd52d5569a489a
166
adventofcode2023
Creative Commons Zero v1.0 Universal
app/src/main/java/com/yorick/cokotools/util/ApplicationUtils.kt
Yorick-Ryu
542,501,945
false
{"Kotlin": 179759, "Java": 13012}
package com.yorick.cokotools.util import android.annotation.SuppressLint import android.app.Application import android.os.Build import java.lang.reflect.InvocationTargetException object ApplicationUtils { var application: Application? = null val processName: String get() = if (Build.VERSION.SDK_INT >= 28) Application.getProcessName() else { try { @SuppressLint("PrivateApi") val activityThread = Class.forName("android.app.ActivityThread") @SuppressLint("DiscouragedPrivateApi") val method = activityThread.getDeclaredMethod("currentProcessName") method.invoke(null) as String } catch (e: ClassNotFoundException) { throw RuntimeException(e) } catch (e: NoSuchMethodException) { throw RuntimeException(e) } catch (e: IllegalAccessException) { throw RuntimeException(e) } catch (e: InvocationTargetException) { throw RuntimeException(e) } } }
1
Kotlin
0
3
6e2b0f838546aa940211287d01aa2f1e8da8b7ce
1,092
CokoTools
Apache License 2.0
app/src/main/java/uk/co/wedgetech/hostpinger/ui/common/HostCardHolder.kt
sfeatherstone
121,163,506
false
{"Kotlin": 30818}
package uk.co.wedgetech.hostpinger.ui.common import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.card_host.* import kotlinx.android.extensions.LayoutContainer import android.view.View import com.squareup.picasso.Picasso import io.reactivex.SingleObserver import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import uk.co.wedgetech.hostpinger.R import uk.co.wedgetech.hostpinger.model.Host import uk.co.wedgetech.hostpinger.model.tasks.Ping class HostCardHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { internal lateinit var host: Host fun bindHost(host: Host) { this.host = host host_text.text = host.name //Get image Picasso.with(containerView.context) .load(host.icon) .placeholder(R.drawable.ic_cloud_download) .into(image) //Update latency and get from cache if present updateLatency(false) //Click handler containerView.setOnClickListener{ _ -> updateLatency(true) } } fun updateLatency(forceUpdate : Boolean) { latency_avg_text.text = containerView.context.getString(R.string.loading_latency_text) val observable = Ping.getPing(host, forceUpdate) observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : SingleObserver<Long> { override fun onSuccess(t: Long) { latency_avg_text.text = containerView.context.getString(R.string.microsecond_formater, t) } override fun onError(e: Throwable) { latency_avg_text.text = containerView.context.getString(R.string.error_text) } override fun onSubscribe(d: Disposable) { } }) } }
0
Kotlin
0
0
d514913758d36ea207ec6ae9d4644996363ea8ca
2,055
HostPingerMVVM-vs-MVP
MIT License
api/src/main/kotlin/com/gmtkgamejam/models/posts/Skills.kt
GameMakersToolkit
388,757,910
false
{"TypeScript": 95359, "Kotlin": 64720, "CSS": 8095, "JavaScript": 2911, "Dockerfile": 1539, "Shell": 644, "HTML": 366}
package com.gmtkgamejam.models.posts enum class Skills { ART_2D, ART_3D, CODE, DESIGN_PRODUCTION, SFX, MUSIC, TESTING_SUPPORT, TEAM_LEAD, OTHER; }
11
TypeScript
7
12
f46e67944e18b7a52d827b5b02062bbb50a53d2d
184
team-finder
X11 License
app/src/main/java/com/domatix/yevbes/nucleus/core/utils/recycler/entities/LessViewHolder.kt
sm2x
234,568,179
true
{"Kotlin": 782306}
package com.domatix.yevbes.nucleus.core.utils.recycler.entities import android.support.v7.widget.RecyclerView import com.domatix.yevbes.nucleus.databinding.ItemViewRecyclerLessBinding class LessViewHolder( val binding: ItemViewRecyclerLessBinding ) : RecyclerView.ViewHolder(binding.root)
0
null
0
0
237e9496b5fb608f543e98111269da9b91a06ed3
299
nucleus
MIT License
app/src/main/java/com/bsuir/bsuirschedule/receiver/ScheduleUpdateAlarmHandler.kt
Saydullin
526,953,048
false
{"Kotlin": 678273, "HTML": 7301}
package com.bsuir.bsuirschedule.receiver import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import com.bsuir.bsuirschedule.service.ScheduleUpdateService import java.text.SimpleDateFormat import java.util.* class ScheduleUpdateAlarmHandler( private val context: Context ) { fun setAlarmManager() { val intent = Intent(context, ScheduleUpdateService::class.java) val sender: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.getBroadcast(context, 2, intent, PendingIntent.FLAG_IMMUTABLE) } else { PendingIntent.getBroadcast(context, 2, intent, PendingIntent.FLAG_UPDATE_CURRENT) } val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager val calendar = Calendar.getInstance(Locale("ru", "BY")) val calendarAlarm = Calendar.getInstance(Locale("ru", "BY")) val format = SimpleDateFormat("HH:mm") calendar.time = format.parse("20:00") as Date calendarAlarm.add(Calendar.DATE, 1) calendarAlarm.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY)) calendarAlarm.set(Calendar.HOUR, calendar.get(Calendar.HOUR)) calendarAlarm.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)) val timeInMillis = calendarAlarm.timeInMillis alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, sender) // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, sender) // } else { // alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, sender) // } } fun cancelAlarmManager() { val intent = Intent(context, ScheduleUpdateService::class.java) val sender: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.getBroadcast(context, 2, intent, PendingIntent.FLAG_IMMUTABLE) } else { PendingIntent.getBroadcast(context, 2, intent, 0) } val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.cancel(sender) } }
0
Kotlin
0
4
989325e764d14430d5d124efd063f7190b075f4a
2,275
BSUIR_Schedule
Creative Commons Zero v1.0 Universal
src/main/java/in/dragonbra/javasteam/steam/handlers/steamapps/callback/DepotKeyCallback.kt
Longi94
122,125,610
false
{"Java": 560633, "Kotlin": 420136, "JavaScript": 4778}
package `in`.dragonbra.javasteam.steam.handlers.steamapps.callback import `in`.dragonbra.javasteam.base.ClientMsgProtobuf import `in`.dragonbra.javasteam.base.IPacketMsg import `in`.dragonbra.javasteam.enums.EResult import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserver2.CMsgClientGetDepotDecryptionKeyResponse import `in`.dragonbra.javasteam.steam.handlers.steamapps.SteamApps import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg /** * This callback is received in response to calling [SteamApps.getDepotDecryptionKey] */ class DepotKeyCallback(packetMsg: IPacketMsg) : CallbackMsg() { /** * Gets the result of requesting this encryption key. */ val result: EResult /** * Gets the DepotID this encryption key is for. */ val depotID: Int /** * Gets the encryption key for this depot. */ val depotKey: ByteArray init { val keyResponse = ClientMsgProtobuf<CMsgClientGetDepotDecryptionKeyResponse.Builder>( CMsgClientGetDepotDecryptionKeyResponse::class.java, packetMsg ) val msg = keyResponse.body jobID = keyResponse.targetJobID result = EResult.from(msg.eresult) depotID = msg.depotId depotKey = msg.depotEncryptionKey.toByteArray() } }
8
Java
19
95
ad7377fdbaf7b1e48c7f0d74602268871ad2d698
1,336
JavaSteam
MIT License
imitate/src/main/java/com/engineer/imitate/interfaces/testinterfaces/SimpleJavaInterface1.kt
REBOOTERS
65,188,539
false
null
package com.engineer.imitate.interfaces.testinterfaces /** * @authro: Rookie * @since: 2019-05-30 */ interface SimpleJavaInterface1 { fun dooe() }
4
null
352
1,880
278998c8da1da2b47778dba3dbd3f2de1e12f2ed
155
AndroidAnimationExercise
Apache License 2.0
core/src/main/java/at/specure/util/ActiveFilter.kt
rtr-nettest
195,193,208
false
null
package at.specure.util import android.content.Context import at.rmbt.client.control.FilterOperatorOptionResponse import at.rmbt.client.control.FilterPeriodOptionResponse import at.rmbt.client.control.FilterProviderOptionResponse import at.rmbt.client.control.FilterStatisticOptionResponse import at.rmbt.client.control.FilterTechnologyOptionResponse import at.rmbt.client.control.MapTypeOptionsResponse import at.rmbt.client.control.data.MapFilterType import javax.inject.Inject import javax.inject.Singleton private const val KEY_TYPE = "TYPE" private const val KEY_SUBTYPE = "SUBTYPE" private const val KEY_STATISTICAL = "STATISTICAL" private const val KEY_TIME_RANGE = "TIME_RANGE" private const val KEY_OPERATOR = "OPERATOR" private const val KEY_PROVIDER = "PROVIDER" private const val KEY_TECHNOLOGY = "TECHNOLOGY" private const val KEY_TIME = "TIME" @Singleton class ActiveFilter @Inject constructor(context: Context, private val valuesStorage: FilterValuesStorage) { private val preferences = context.getSharedPreferences("map_filters.pref", Context.MODE_PRIVATE) var type: MapFilterType get() = MapFilterType.values()[preferences.getInt(KEY_TYPE, MapFilterType.MOBILE.ordinal)] set(value) = preferences.edit().putInt(KEY_TYPE, value.ordinal).apply() var subtype: MapTypeOptionsResponse get() = valuesStorage.findSubtype(preferences.getString(KEY_SUBTYPE, "Download"), type) set(value) = preferences.edit().putString(KEY_SUBTYPE, value.title).apply() var statistical: FilterStatisticOptionResponse get() = valuesStorage.findStatistical(preferences.getString(KEY_STATISTICAL, valuesStorage.findStatisticalDefault(type)), type) set(value) = preferences.edit().putString(KEY_STATISTICAL, value.title).apply() var timeRange: FilterPeriodOptionResponse get() = valuesStorage.findPeriod(preferences.getString(KEY_TIME_RANGE, valuesStorage.findPeriodDefault(type)), type) set(value) = preferences.edit().putString(KEY_TIME_RANGE, value.title).apply() var provider: FilterProviderOptionResponse get() = valuesStorage.findProvider(preferences.getString(KEY_PROVIDER, valuesStorage.findProviderDefault(type)), type) set(value) = preferences.edit().putString(KEY_PROVIDER, value.title).apply() var operator: FilterOperatorOptionResponse get() = valuesStorage.findOperator(preferences.getString(KEY_OPERATOR, valuesStorage.findOperatorDefault(type)), type) set(value) { preferences.edit().putString(KEY_OPERATOR, value.title).apply() } var technology: FilterTechnologyOptionResponse get() = valuesStorage.findTechnology(preferences.getString(KEY_TECHNOLOGY, valuesStorage.findTechnologyDefault(type)), type) set(value) = preferences.edit().putString(KEY_TECHNOLOGY, value.title).apply() /** * <month (1-based), year> */ var time: Pair<Int, Int> get() { val currentMonthYear = preferences.getString(KEY_TIME, valuesStorage.findTimeDefault()) val parsedYear = currentMonthYear?.split("-")?.get(1)?.toInt() ?: 0 val parsedMonth = currentMonthYear?.split("-")?.get(0)?.toInt() ?: 0 return Pair<Int, Int>(parsedMonth, parsedYear) } set(value) = preferences.edit().putString(KEY_TIME, "${value.first}-${value.second}").apply() }
1
Kotlin
8
6
a2d2bf493a12aceae2da96ce6536467be6038aca
3,386
open-rmbt-android
Apache License 2.0
collector/src/main/java/com/bitmovin/analytics/error/ExceptionMapper.kt
bitmovin
120,633,749
false
{"Kotlin": 1336909, "Java": 25098, "Shell": 13133}
package com.bitmovin.analytics.error import com.bitmovin.analytics.data.ErrorCode interface ExceptionMapper<in T> { fun map(throwable: T): ErrorCode }
1
Kotlin
6
9
c7c1b9a7016534c0e07620d3d7e863ca99575c86
157
bitmovin-analytics-collector-android
Amazon Digital Services License
core/src/main/kotlin/org/predicode/predicator/grammar/Printers.kt
robstoll
154,004,921
true
{"Markdown": 1, "Java": 53, "Kotlin": 23}
package org.predicode.predicator.grammar import org.predicode.predicator.terms.Term typealias CodePoint = Int fun printTerms(terms: Iterable<Term>): String = TermPrinter.printTerms(terms) fun printTerms(terms: Iterable<Term>, print: (CodePoint) -> Unit) = TermPrinter.printTerms(terms, print) fun StringBuilder.appendTerms(terms: Iterable<Term>) = apply { TermPrinter.printTerms(terms, this) } fun printTerms(vararg terms: Term, print: (CodePoint) -> Unit) = TermPrinter.printTerms(print, terms) fun printTerms(vararg terms: Term): String = TermPrinter.printTerms(*terms) fun StringBuilder.appendTerms(vararg terms: Term) = apply { TermPrinter.printTerms(this, *terms) } fun printName( name: CharSequence, quoted: QuotedName, quoting: QuotingStyle = QuotingStyle.AUTO_QUOTE) = quoting.printName(name, quoted) fun printName( name: CharSequence, quoted: QuotedName, quoting: QuotingStyle = QuotingStyle.AUTO_QUOTE, print: (CodePoint) -> Unit) = quoting.printName(name, quoted, print) fun StringBuilder.appendName( name: CharSequence, quoted: QuotedName, quoting: QuotingStyle = QuotingStyle.AUTO_QUOTE) = apply { quoting.printName(name, quoted, this) }
0
Java
1
0
bc229b1c574e7d1fe880f8a730e7bd6d759e9945
1,302
predicator
MIT License
android/src/main/java/com/arlocalizerrn/LocationList.kt
netguru
295,680,229
false
null
package com.arlocalizerrn import java.io.Serializable class LocationList(locationArray: java.util.ArrayList<Any>) : Serializable { var locations: java.util.ArrayList<HashMap<String,Double>> = locationArray as java.util.ArrayList<HashMap<String,Double>> }
0
Java
2
12
6d3b533b81271cc77959024bffbe3a39f63c0857
263
react-native-ar-localizer
MIT License
infobip-mobile-messaging-android-chat-sdk/src/main/java/org/infobip/mobile/messaging/chat/core/InAppChatWidgetError.kt
infobip
56,227,769
false
null
package org.infobip.mobile.messaging.chat.core import org.infobip.mobile.messaging.api.support.http.serialization.JsonSerializer import org.infobip.mobile.messaging.logging.MobileMessagingLogger data class InAppChatWidgetError( val message: String? = null, val code: Int? = null ) { companion object { private val serializer = JsonSerializer(false) fun fromJson(json: String): InAppChatWidgetError { return runCatching { serializer.deserialize(json, InAppChatWidgetError::class.java) }.onFailure { MobileMessagingLogger.e("Error parsing error message: $json", it) } .getOrDefault(InAppChatWidgetError(message = json)) } } }
6
null
17
51
87f9daa5e37c71a3591662190c31a22e263600c0
734
mobile-messaging-sdk-android
Apache License 2.0
Kotlin-Samples-Android/app/src/main/kotlin/samuel/urbanowicz/MainActivity.kt
PacktPublishing
126,314,798
false
null
package samuel.urbanowicz import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.GenericLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import com.example.unclesam.myapplication.R import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.delay import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.withContext class MainActivity: AppCompatActivity() { val sampleContextAwareViewProperty: View by LifecycleAwareLazy(lifecycle) { View(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) text_field.text = "Bonjour!" val job = launch { var counter = 1 while (true) { delay(1000) counter++ withContext(UI) { text_field.text = counter.toString() } } } cancel_btn.setOnClickListener { job.cancel() } } } class LifecycleAwareLazy<T>(lifecycle: Lifecycle, val initializer: () -> T): Lazy<T>, GenericLifecycleObserver { init { lifecycle.addObserver(this) } private object UNINITIALIZED_VALUE private var _value: Any? = UNINITIALIZED_VALUE override val value: T get() { if (_value === UNINITIALIZED_VALUE) { _value = initializer.invoke() } return _value as T } override fun isInitialized(): Boolean = _value != UNINITIALIZED_VALUE // GenericLifecycleObserver override fun onStateChanged(source: LifecycleOwner?, event: Lifecycle.Event?) { when (event) { Lifecycle.Event.ON_STOP -> { _value = UNINITIALIZED_VALUE } Lifecycle.Event.ON_DESTROY -> { } else -> return } } }
0
Kotlin
24
26
a9118396250ded6f4466c20fd0dc62ea6a598ed1
2,104
Kotlin-Standard-Library-Cookbook
MIT License
src/test/kotlin/ru/iopump/koproc/ExtensionKtIT.kt
kochetkov-ma
315,046,551
false
{"Gradle": 6, "Java Properties": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "INI": 2, "Java": 1, "Batchfile": 1, "Shell": 1, "Kotlin": 5, "YAML": 1, "Groovy": 1}
package ru.iopump.koproc import io.kotest.assertions.asClue import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldBeBlank import io.kotest.matchers.string.shouldContain import io.kotest.matchers.string.shouldNotBeBlank import io.kotest.matchers.types.shouldBeInstanceOf import kotlinx.coroutines.delay import org.junit.jupiter.api.assertThrows import org.slf4j.LoggerFactory import java.net.ConnectException import java.net.HttpURLConnection import java.net.URL import java.nio.file.Paths @Suppress("BlockingMethodInNonBlockingContext") class ExtensionKtIT : StringSpec() { private companion object { private val log = LoggerFactory.getLogger("koproc") } init { "Java process should started by 'startProcess', provide http access and stopped by 'close' method" { val jarPath = Paths.get(this::class.java.getResource("/koproc-sample.jar").toURI()) val jarAccessUrl = URL("http://localhost:8000/test") val koproc = "java -jar $jarPath".startProcess { timeoutSec = 5 } koproc.use { delay(500) log.info("[TEST] Call: $it") with(jarAccessUrl.openConnection() as HttpURLConnection) { responseCode shouldBe 200 inputStream.bufferedReader().readText() shouldBe "OK" } it.readAvailableOut.shouldNotBeBlank() log.info("[TEST] Out: ${it.readAvailableOut}") } assertThrows<ConnectException> { with(jarAccessUrl.openConnection() as HttpURLConnection) { responseCode shouldBe 404 } } koproc.result.out.shouldNotBeBlank() log.info("[TEST] Result: ${koproc.result}") } "Java process should started by 'startProcess' and closed after timeout with the 'KoprocResult'" { val jarPath = Paths.get(this::class.java.getResource("/koproc-sample.jar").toURI()) val koproc = "java -jar $jarPath".startProcess { timeoutSec = 1 } koproc.use { call -> delay(500) log.info("[TEST] Result: ${call.result}") call.result.asClue { it.code shouldBe 1 it.error.shouldBeInstanceOf<IllegalThreadStateException>() it.out.shouldNotBeBlank() it.errorOut.shouldBeBlank() } } } "Java should display version by 'startCommand' with exit code 0" { val koproc = "java -version".startCommand { timeoutSec = 5 } log.info("$koproc") koproc.asClue { it.code shouldBe 0 it.error.shouldBeNull() (it.out + it.errorOut).shouldContain("version") // Java may print to out or err } } "Shell or Cmd should print dirs" { val os = System.getProperty("os.name").toLowerCase() val cmd = if (os.contains("win")) Paths.get(this::class.java.getResource("/cmd.bat").toURI()) else "pwd" val koproc = "$cmd".startCommand { timeoutSec = 5 } koproc.asClue { it.code shouldBe 0 it.error.shouldBeNull() it.out.shouldNotBeBlank() it.errorOut.shouldBeBlank() } } "Fail start process" { assertThrows<RuntimeException> { "error".startCommand().throwOnAnyFailure() } } "Closing after success execution and get the result after closing" { val koproc = "java -version".startProcess { timeoutSec = 5 } koproc.use { it.waitResult() } koproc.result.asClue { it.code shouldBe 0 it.out.shouldBeBlank() it.errorOut.shouldNotBeBlank() it.error.shouldBeNull() it.throwOnUnSuccessCode() it.throwOnError() it.throwOnAnyFailure() } } "Default timeout [bug in 1.1.0]" { koprocDefaultStartCommandTimeoutSec = 1 val jarPath = Paths.get(this::class.java.getResource("/koproc-sample.jar").toURI()) "java -jar $jarPath".startCommand() koprocDefaultStartProcessTimeoutSec = 1 "java -jar $jarPath".startProcess().result } } }
0
Kotlin
0
6
fb80983ace117de1e5eccc1d11a30d8e82b16439
4,605
koproc
Apache License 2.0
src/test/kotlin/ru/iopump/koproc/ExtensionKtIT.kt
kochetkov-ma
315,046,551
false
{"Gradle": 6, "Java Properties": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "INI": 2, "Java": 1, "Batchfile": 1, "Shell": 1, "Kotlin": 5, "YAML": 1, "Groovy": 1}
package ru.iopump.koproc import io.kotest.assertions.asClue import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldBeBlank import io.kotest.matchers.string.shouldContain import io.kotest.matchers.string.shouldNotBeBlank import io.kotest.matchers.types.shouldBeInstanceOf import kotlinx.coroutines.delay import org.junit.jupiter.api.assertThrows import org.slf4j.LoggerFactory import java.net.ConnectException import java.net.HttpURLConnection import java.net.URL import java.nio.file.Paths @Suppress("BlockingMethodInNonBlockingContext") class ExtensionKtIT : StringSpec() { private companion object { private val log = LoggerFactory.getLogger("koproc") } init { "Java process should started by 'startProcess', provide http access and stopped by 'close' method" { val jarPath = Paths.get(this::class.java.getResource("/koproc-sample.jar").toURI()) val jarAccessUrl = URL("http://localhost:8000/test") val koproc = "java -jar $jarPath".startProcess { timeoutSec = 5 } koproc.use { delay(500) log.info("[TEST] Call: $it") with(jarAccessUrl.openConnection() as HttpURLConnection) { responseCode shouldBe 200 inputStream.bufferedReader().readText() shouldBe "OK" } it.readAvailableOut.shouldNotBeBlank() log.info("[TEST] Out: ${it.readAvailableOut}") } assertThrows<ConnectException> { with(jarAccessUrl.openConnection() as HttpURLConnection) { responseCode shouldBe 404 } } koproc.result.out.shouldNotBeBlank() log.info("[TEST] Result: ${koproc.result}") } "Java process should started by 'startProcess' and closed after timeout with the 'KoprocResult'" { val jarPath = Paths.get(this::class.java.getResource("/koproc-sample.jar").toURI()) val koproc = "java -jar $jarPath".startProcess { timeoutSec = 1 } koproc.use { call -> delay(500) log.info("[TEST] Result: ${call.result}") call.result.asClue { it.code shouldBe 1 it.error.shouldBeInstanceOf<IllegalThreadStateException>() it.out.shouldNotBeBlank() it.errorOut.shouldBeBlank() } } } "Java should display version by 'startCommand' with exit code 0" { val koproc = "java -version".startCommand { timeoutSec = 5 } log.info("$koproc") koproc.asClue { it.code shouldBe 0 it.error.shouldBeNull() (it.out + it.errorOut).shouldContain("version") // Java may print to out or err } } "Shell or Cmd should print dirs" { val os = System.getProperty("os.name").toLowerCase() val cmd = if (os.contains("win")) Paths.get(this::class.java.getResource("/cmd.bat").toURI()) else "pwd" val koproc = "$cmd".startCommand { timeoutSec = 5 } koproc.asClue { it.code shouldBe 0 it.error.shouldBeNull() it.out.shouldNotBeBlank() it.errorOut.shouldBeBlank() } } "Fail start process" { assertThrows<RuntimeException> { "error".startCommand().throwOnAnyFailure() } } "Closing after success execution and get the result after closing" { val koproc = "java -version".startProcess { timeoutSec = 5 } koproc.use { it.waitResult() } koproc.result.asClue { it.code shouldBe 0 it.out.shouldBeBlank() it.errorOut.shouldNotBeBlank() it.error.shouldBeNull() it.throwOnUnSuccessCode() it.throwOnError() it.throwOnAnyFailure() } } "Default timeout [bug in 1.1.0]" { koprocDefaultStartCommandTimeoutSec = 1 val jarPath = Paths.get(this::class.java.getResource("/koproc-sample.jar").toURI()) "java -jar $jarPath".startCommand() koprocDefaultStartProcessTimeoutSec = 1 "java -jar $jarPath".startProcess().result } } }
0
Kotlin
0
6
fb80983ace117de1e5eccc1d11a30d8e82b16439
4,605
koproc
Apache License 2.0