path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/systemtest/kotlin/de/unisaarland/cs/se/selab/systemtest/simulationtests/parserTests/MultiTasking.kt
Atharvakore
872,001,311
false
{"Kotlin": 614544}
package de.unisaarland.cs.se.selab.systemtest.simulationtests.parserTests import de.unisaarland.cs.se.selab.systemtest.utils.ExampleSystemTestExtension /** Test for Not Specified properties*/ class MultiTasking : ExampleSystemTestExtension() { override val map = "MultiTasking/smallMap1.json" override val corporations = "MultiTasking/corporations.json" override val scenario = "MultiTasking/scenario.json" override val description = "Checks when a land tile is near a deep ocean tile" override val maxTicks = 0 override val name = "LandNextDeep" override suspend fun run() { assertNextLine("Initialization Info: smallMap1.json successfully parsed and validated.") assertNextLine("Initialization Info: corporations.json successfully parsed and validated.") assertNextLine("Initialization Info: scenario.json is invalid.") assertEnd() } }
0
Kotlin
0
0
00f5a18e7d4c695f9d5e93451da2f864ebe77151
903
Save-The-Saardines
MIT License
view/mongo/src/main/kotlin/io/holunda/camunda/taskpool/view/mongo/repository/TaskWithDataEntriesRepositoryExtension.kt
kw-s
183,228,671
true
{"Kotlin": 389510, "HTML": 37402, "TypeScript": 15887, "JavaScript": 1831, "CSS": 733, "Shell": 694, "Dockerfile": 330}
package io.holunda.camunda.taskpool.view.mongo.repository import io.holunda.camunda.taskpool.view.auth.User import io.holunda.camunda.taskpool.view.mongo.service.Criterion import io.holunda.camunda.taskpool.view.mongo.service.EQUALS import io.holunda.camunda.taskpool.view.mongo.service.GREATER import io.holunda.camunda.taskpool.view.mongo.service.LESS import mu.KLogging import org.springframework.data.annotation.Id import org.springframework.data.annotation.TypeAlias import org.springframework.data.domain.Pageable import org.springframework.data.domain.Sort import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.data.mongodb.core.aggregation.Aggregation import org.springframework.data.mongodb.core.aggregation.AggregationResults import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.isEqualTo import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.stereotype.Repository import java.time.Instant import java.util.* @Repository interface TaskWithDataEntriesRepository : TaskWithDataEntriesRepositoryExtension, MongoRepository<TaskWithDataEntriesDocument, String> interface TaskWithDataEntriesRepositoryExtension { fun findAllFilteredForUser(user: User, criteria: List<Criterion>, pageable: Pageable? = null): List<TaskWithDataEntriesDocument> } open class TaskWithDataEntriesRepositoryExtensionImpl( private val mongoTemplate: MongoTemplate ) : TaskWithDataEntriesRepositoryExtension { companion object : KLogging() { val DEFAULT_SORT = Sort(Sort.Direction.DESC, TaskWithDataEntriesDocument::dueDate.name) } /** <pre> db.tasks.aggregate([ { $unwind: "$dataEntriesRefs" }, { $lookup: { from: "data-entries", localField: "dataEntriesRefs", foreignField: "_id", as: "data_entries" } }, { $sort: { "dueDate": 1 }}, { $match: { $and: [ // { $or: [{ $or: [ { 'assignee' : "kermit" }, { 'candidateUsers' : "kermit" } ] }, { 'candidateGroups' : "other" } ] }, { $or: [{ $or: [ { 'assignee' : "kermit" }, { 'candidateUsers' : "kermit" } ] }, { 'candidateGroups' : "other" } ] } // { $or: [ { 'businessKey': "3" } ] } ] }} ]) </pre> */ override fun findAllFilteredForUser(user: User, criteria: List<Criterion>, pageable: Pageable?): List<TaskWithDataEntriesDocument> { val sort = if (pageable != null) { pageable.getSortOr(DEFAULT_SORT) } else { DEFAULT_SORT } val filterPropertyCriteria = criteria.map { Criteria.where( when (it) { is Criterion.TaskCriterion -> it.name else -> "dataEntries.payload.${it.name}" } ).apply { when (it.operator) { EQUALS -> this.isEqualTo(value(it)) GREATER -> this.gt(value(it)) LESS -> this.lt(value(it)) else -> throw IllegalArgumentException("Unsupported operator ${it.operator}") } } }.toTypedArray() // { \$or: [{ \$or: [ { 'assignee' : ?0 }, { 'candidateUsers' : ?0 } ] }, { 'candidateGroups' : ?1} ] } val tasksForUserCriteria = Criteria() .orOperator( Criteria() .orOperator( Criteria.where("assignee").isEqualTo(user.username), Criteria.where("candidateUsers").isEqualTo(user.username) ), Criteria .where("candidateGroups") .`in`(user.groups) ) val filterCriteria = if (filterPropertyCriteria.isNotEmpty()) { Criteria() .andOperator( tasksForUserCriteria, Criteria() .orOperator(*filterPropertyCriteria)) } else { tasksForUserCriteria } val aggregations = mutableListOf( Aggregation.lookup(DataEntryDocument.NAME, "dataEntriesRefs", "_id", "dataEntries"), Aggregation.sort(sort), Aggregation.match(filterCriteria) ) val result: AggregationResults<TaskWithDataEntriesDocument> = mongoTemplate.aggregate( Aggregation.newAggregation(aggregations), "tasks", TaskWithDataEntriesDocument::class.java ) return result.mappedResults } } fun value(criterion: Criterion): Any = when (criterion.name) { "priority" -> criterion.value.toInt() "createTime", "dueDate", "followUpDate" -> Instant.parse(criterion.value) else -> criterion.value } @Document(collection = "tasks") @TypeAlias("task") data class TaskWithDataEntriesDocument( @Id val id: String, val sourceReference: ReferenceDocument, val taskDefinitionKey: String, val dataEntries: List<DataEntryDocument>, val payload: MutableMap<String, Any> = mutableMapOf(), val businessKey: String? = null, val name: String? = null, val description: String? = null, val formKey: String? = null, val priority: Int? = 0, val createTime: Date? = null, val candidateUsers: Set<String> = setOf(), val candidateGroups: Set<String> = setOf(), val assignee: String? = null, val owner: String? = null, val dueDate: Date? = null, val followUpDate: Date? = null )
0
Kotlin
0
0
9ff5dd3e8aff4a89859f75c9edfffe51bc83898d
5,107
camunda-bpm-taskpool
Apache License 2.0
src/test/kotlin/com/devstromo/structural/bridge/pattern/BridgePatternUnitTest.kt
devstromo
726,667,072
false
{"Kotlin": 35490}
package com.devstromo.structural.bridge.pattern import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.mockito.Mockito.* class BridgePatternUnitTest { @Test fun `Test draw with vector renderer`() { val renderer = mock<VectorRenderer>() val circle = Circle(renderer, 1.0) circle.draw() verify(renderer, times(1)).renderCircle(1.0) } @Test fun `Test draw with raster renderer`() { val renderer = mock<RasterRenderer>() val circle = Circle(renderer, 2.0) circle.draw() verify(renderer, times(1)).renderCircle(2.0) } @Test fun `Test resize and draw`() { val renderer = mock<VectorRenderer>() val circle = Circle(renderer, 1.0) circle.resize(2.0) circle.draw() assertEquals(2.0, circle.radius, 0.01) verify(renderer, times(1)).renderCircle(2.0) } }
0
Kotlin
0
0
f8e295b5dddafbf7cf2710f5356ffd1d6b9ded73
944
design-patterns-kotlin
MIT License
library/src/main/java/com/angcyo/library/canvas/element/MonitorRenderElement.kt
angcyo
229,037,615
false
{"Kotlin": 6714795, "JavaScript": 5194}
package com.angcyo.library.canvas.element import android.graphics.Canvas import android.graphics.Paint import com.angcyo.library.R import com.angcyo.library.canvas.core.ICanvasComponent import com.angcyo.library.canvas.core.ICanvasView import com.angcyo.library.canvas.core.IRenderOutside import com.angcyo.library.ex._color import com.angcyo.library.ex.createPaint import com.angcyo.library.ex.dp import kotlin.math.roundToInt /** * @author <a href="mailto:<EMAIL>">angcyo</a> * @since 2023/06/29 */ class MonitorRenderElement : IRenderOutside, ICanvasComponent { val paint = createPaint(_color(R.color.lib_theme_black)).apply { textSize = 9 * dp } /**偏移量*/ var offsetX = 0f var offsetY = 0f override var isEnableComponent: Boolean = true override fun renderOnOutside(iCanvasView: ICanvasView, canvas: Canvas) { if (isEnableComponent) { drawScaleText(iCanvasView, canvas, iCanvasView.getRawView().measuredHeight.toFloat()) } } /**绘制缩放比例文本*/ private fun drawScaleText(iCanvasView: ICanvasView, canvas: Canvas, bottom: Float) { val box = iCanvasView.getCanvasViewBox() val text = "${(box.getScale() * 100).roundToInt()}%" paint.style = Paint.Style.FILL val x = offsetX val y = bottom - paint.descent() - offsetY canvas.drawText(text, x, y, paint) } }
0
Kotlin
6
5
e1aeea2a677b585561879f3cdb0be6b1c6d1d458
1,388
UICore
MIT License
generator/src/main/kotlin/dev/drzepka/wikilinks/generator/flow/ProgressLogger.kt
drzpk
513,034,741
false
null
package dev.drzepka.wikilinks.generator.flow interface ProgressLogger { fun updateProgress(current: Int, total: Int, unit: String) }
0
Kotlin
0
1
ab55472076b04ff6cca0b8ae4777f074d6f7be73
138
wikilinks
Apache License 2.0
src/test/kotlin/de/diekautz/federationserver/FederationServerApplicationTests.kt
DieKautz
401,054,726
false
null
package de.diekautz.federationserver import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class FederationServerApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
5369792c7da820ee44660e794ee92dc7700b4313
226
stellar-federation-server
MIT License
gradle-plugin/src/main/kotlin/com/improve_future/harmonica/plugin/JarmonicaCreateTask.kt
KenjiOhtsuka
132,746,579
false
{"Kotlin": 227314}
/* * Harmonica: Kotlin Database Migration Tool * Copyright (c) 2022 <NAME> * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php */ package com.improve_future.harmonica.plugin open class JarmonicaCreateTask : JarmonicaMigrationTask() { override val taskType = JarmonicaTaskType.Create override fun exec() { val migrationName = if (project.hasProperty("migrationName")) project.properties["migrationName"] as String else "Migration" jvmArgs = listOf<String>() args = buildJarmonicaArgument(migrationName).toList() super.exec() } }
31
Kotlin
17
132
fbb6f54990451e4ffa9d4ad0d9edee4943ebae1a
683
harmonica
MIT License
src/main/kotlin/org/blocovermelho/mod/commands/ChangePasswordCommand.kt
blocovermelho
722,373,364
false
{"Kotlin": 84793, "Java": 4932}
package org.blocovermelho.mod.commands import com.mojang.brigadier.CommandDispatcher import net.minecraft.server.command.ServerCommandSource import org.blocovermelho.mod.api.Routes import org.blocovermelho.mod.api.handleErr import org.blocovermelho.mod.api.models.ChangePassword import org.blocovermelho.mod.ext.Commands.mudarSenha import org.blocovermelho.mod.ext.Helpers.hint import org.blocovermelho.mod.ext.Rich.colorize import org.blocovermelho.mod.ext.Rich.lineOf import org.blocovermelho.mod.ext.Rich.lines import org.blocovermelho.mod.ext.isLogged import org.blocovermelho.mod.ext.launch import org.blocovermelho.mod.ext.sendError import org.quiltmc.qkl.library.brigadier.argument.player import org.quiltmc.qkl.library.brigadier.argument.value import org.quiltmc.qkl.library.brigadier.argument.word import org.quiltmc.qkl.library.brigadier.register import org.quiltmc.qkl.library.brigadier.required import org.quiltmc.qkl.library.brigadier.util.player import org.quiltmc.qkl.library.brigadier.util.sendFeedback import org.quiltmc.qkl.library.text.* object ChangePasswordCommand { fun register(dispatcher: CommandDispatcher<ServerCommandSource>) { dispatcher.register("mudarSenha") { requires { it.isPlayer && it.player!!.isLogged() } required(word("senhaAntiga")) { oldpw -> required(word("senhaNova")) {newpw -> launch { val changed = Routes.Auth.ChangePassword(ChangePassword(player!!.uuid, player!!.ip, oldpw().value(), newpw().value())).handleErr { sendError(it, "verificando se sua conta existe") } ?: return@launch if (!changed) { sendFeedback { buildText { mudarSenha { lines( { lineOf( { translatable("bv.change_pass.failed") }, { translatable("bv.change_pass.verify", colorize("\"${oldpw().value()}\"", Color.YELLOW)) } ) }, { translatable("bv.login.forgot") } ) } } } } else { sendFeedback { buildText { mudarSenha { translatable("bv.change_pass.success") } } } } } } } } } }
0
Kotlin
0
0
887be5d51b37ed523b08879679ba4feda8bd8058
2,961
mod
Creative Commons Zero v1.0 Universal
app/src/main/java/com/ghostwan/babylontest/ui/posts/PostsContract.kt
ap7
200,812,194
false
null
package com.ghostwan.babylontest.ui.posts import com.ghostwan.babylontest.data.model.Post interface PostsContract { interface View { fun showLoadingIndicator() fun hideLoadingIndicator() fun showPosts(posts : List<Post>) fun showEmptyList() fun showPostDetail(post: Post) fun showError(throwable: Throwable) } interface Presenter { fun loadPosts() fun openPostDetails(post: Post) fun subscribe() fun unsubscribe() } }
0
Kotlin
0
0
e25b6bd2e9ed773df6f8ba0d9494db6485b253e3
517
BabylonTest
MIT License
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/filter.kt
ilaborie
239,104,338
true
{"Kotlin": 1972899, "HTML": 423, "Java": 153}
package io.kotest.property.arbitrary import io.kotest.property.RandomSource import io.kotest.property.Sample /** * Create a new [Arb] by keeping only instances of B generated by this gen. * This is useful if you have a type hierarchy and only want to retain * a particular subtype. */ @Suppress("UNCHECKED_CAST") inline fun <A, reified B : A> Arb<A>.filterIsInstance(): Arb<B> = object : Arb<B> { override fun edgecases(): List<B> = [email protected]().filterIsInstance<B>() override fun sample(rs: RandomSource): Sample<B> = sequence { yield([email protected](rs)) }.filter { it.value is B }.first() as Sample<B> }
0
null
0
0
5a114654d74ee675db44870749de94e63ff2d9de
659
kotlintest
Apache License 2.0
src/main/kotlin/net/phobot/parser/clause/nonterminal/OneOrMore.kt
psfblair
270,472,887
false
{"Maven POM": 1, "Text": 3, "Ignore List": 1, "Markdown": 1, "Java": 1, "Assembly": 1, "Kotlin": 32}
/* * // * // This file is part of the pika parser implementation allowing whitespace-sensitive syntax. It is based * // on the Java reference implementation at: * // * // https://github.com/lukehutch/pikaparser * // * // The pika parsing algorithm is described in the following paper: * // * // Pika parsing: reformulating packrat parsing as a dynamic programming algorithm solves the left recursion * // and error recovery problems. <NAME>, May 2020. * // https://arxiv.org/abs/2005.06444* // * // * // This software is provided under the MIT license: * // * // Copyright (c) 2020 <NAME> * // Based on pikaparser by <NAME>, also licensed with the MIT license. * // * // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * // documentation files (the "Software"), to deal in the Software without restriction, including without limitation * // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * // * // The above copyright notice and this permission notice shall be included in all copies or substantial portions * // of the Software. * // * // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * // DEALINGS IN THE SOFTWARE. * // * */ package net.phobot.parser.clause.nonterminal import net.phobot.parser.clause.Clause import net.phobot.parser.memotable.Match import net.phobot.parser.memotable.MemoKey import net.phobot.parser.memotable.MemoTable class OneOrMore(subClause: Clause) : Clause(subClause) { override fun determineWhetherCanMatchZeroChars() { if (labeledSubClauses[0].clause.canMatchZeroChars) { canMatchZeroChars = true } } override fun match(memoTable: MemoTable, memoKey: MemoKey, input: String): Match? { val labeledSubClause = labeledSubClauses[0].clause val subClauseMemoKey = MemoKey(labeledSubClause, memoKey.startPos) val subClauseMatch = memoTable.lookUpBestMatch(subClauseMemoKey) if (subClauseMatch != null) { // Perform right-recursive match of the same OneOrMore clause, so that the memo table doesn't // fill up with O(M^2) entries in the number of subclause matches M. // If there are two or more matches, tailMatch will be non-null. val subclauseLength = subClauseMatch.length val tailMatchMemoKey = MemoKey(clause = this, startPos = memoKey.startPos + subclauseLength) val tailMatch = memoTable.lookUpBestMatch(tailMatchMemoKey) // Return a new (right-recursive) match return if (tailMatch != null) { // There are two or more matches val length = subclauseLength + tailMatch.length val subClauseMatches = arrayOf<Match?>(subClauseMatch, tailMatch) Match(memoKey, length, subClauseMatches) } else { // There is only one match val subClauseMatches = arrayOf<Match?>(subClauseMatch) Match(memoKey, subclauseLength,subClauseMatches) } } else { // Zero matches at memoKey.startPos return null } } override fun toString(): String { return updateStringCacheIfNecessary { val firstLabeledSubClause = labeledSubClauses[0].toStringWithASTNodeLabel(parentClause = this) "${firstLabeledSubClause}+" } } }
0
Kotlin
0
0
15b793af07d12b90d0e99ae3cb4ad2c5221d12f9
4,004
pikaparser-kotlin
MIT License
extensions/workmanager/src/main/java/com/google/android/exoplayer2/ext/workmanager/package-info.kt
rezaulkhan111
589,317,131
false
{"Java Properties": 1, "Gradle": 47, "Markdown": 91, "Shell": 6, "Batchfile": 1, "Text": 16, "Ignore List": 1, "XML": 480, "Java": 1191, "Kotlin": 302, "YAML": 6, "INI": 1, "JSON": 5, "HTML": 1519, "Ruby": 1, "SVG": 43, "JavaScript": 40, "SCSS": 81, "CSS": 5, "GLSL": 15, "Starlark": 1, "Protocol Buffer Text Format": 1, "Makefile": 9, "C++": 10, "CMake": 2}
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ext.workmanager import androidx.work.WorkManager import com.google.android.exoplayer2.scheduler.Requirements import com.google.android.exoplayer2.ext.workmanager.WorkManagerScheduler import androidx.work.OneTimeWorkRequest import androidx.work.ExistingWorkPolicy import androidx.work.WorkerParameters import androidx.work.ListenableWorker import com.google.android.exoplayer2.util.Assertions import android.content.Intent import com.google.android.exoplayer2.ExoPlayerLibraryInfo import androidx.annotation.RequiresApi import com.google.android.exoplayer2.ext.workmanager.WorkManagerScheduler.SchedulerWorker
1
null
1
1
c467e918356f58949e0f7f4205e96f0847f1bcdb
1,268
ExoPlayer
Apache License 2.0
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/FollowersList200ResponseTest.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.openapitools.client.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import org.openapitools.client.models.FollowersList200Response import org.openapitools.client.models.UserSummary class FollowersList200ResponseTest : ShouldSpec() { init { // uncomment below to create an instance of FollowersList200Response //val modelInstance = FollowersList200Response() // to test the property `items` should("test items") { // uncomment below to test the property //modelInstance.items shouldBe ("TODO") } // to test the property `bookmark` should("test bookmark") { // uncomment below to test the property //modelInstance.bookmark shouldBe ("TODO") } } }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
1,082
pinterest-sdk
MIT License
app/src/main/java/com/dudu/weargpt/ui/MainActivity.kt
dudu-Dev0
613,962,020
false
{"Java": 96733, "Kotlin": 27192}
package com.dudu.weargpt.ui import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.dudu.weargpt.R import com.dudu.weargpt.utils.StartActivity import com.google.android.material.card.MaterialCardView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<MaterialCardView>(R.id.new_competition_card).setOnClickListener { StartActivity<CompetitionActivity> { } } findViewById<MaterialCardView>(R.id.history_card).setOnClickListener { StartActivity<HistoryActivity> { } } findViewById<MaterialCardView>(R.id.settings_card).setOnClickListener { StartActivity<SettingsActivity> { } } findViewById<MaterialCardView>(R.id.about_card).setOnClickListener { StartActivity<AboutActivity> { } } } }
1
null
1
1
2a5428ebb1a78d7701be8a2be9e940006ee573b1
982
WearGPT
MIT License
src/main/kotlin/Main.kt
xrrocha
715,337,265
false
{"Kotlin": 4981}
import info.debatty.java.stringsimilarity.Damerau import java.io.File import kotlin.math.max fun main(args: Array<String>) { val maxScore = 0.4 val damerau = Damerau() val baseDir = File("src/test/resources") val words = File(baseDir, "words.txt") .bufferedReader() .lineSequence() .map { it.split("\t")[0] } .toList() .distinct() println("Loaded ${words.size} words") val startTime = System.currentTimeMillis() class Score(val first: String, val second: String, val distance: Double) { val str by lazy { "$first $second $distance" } override fun toString() = str } val matrix = words.indices .flatMap { i -> (i + 1..<words.size) .map { j -> Score( words[i], words[j], damerau.distance(words[i], words[j]) / max(words[i].length, words[j].length).toDouble() ) } .filter { it.distance < maxScore } .flatMap { listOf( it, Score(it.second, it.first, it.distance) ) } } .groupBy { it.first } .mapValues { (word, values) -> values.associate { it.second to it.distance } + (word to 0.0) } File(baseDir, "word-matrix.txt").printWriter().use { out -> matrix .toList() .sortedBy { it.first } .forEach { (word, neighbors) -> val neighborStr = neighbors .toList() .sortedBy { (_, s) -> s } .joinToString(" ") { (w, s) -> "$w:$s" } out.println("$word $neighborStr") } out.flush() } val endTime = System.currentTimeMillis() println("Wrote ${matrix.size} scores in ${endTime - startTime} milliseconds") fun intraDistances(cluster: Collection<String>): List<Pair<String, Double>> = cluster .map { first -> first to cluster .map { second -> matrix[first]!![second]!! } .average() } .sortedBy { it.second } fun analyzeCluster(cluster: Collection<String>): Triple<List<String>, List<String>, Double> = intraDistances(cluster) .let { intraDistances -> val bestIntraDistance = intraDistances.first().second val medoids = intraDistances .takeWhile { it.second == bestIntraDistance } .map { it.first } .sorted() val avgIntraDistance = intraDistances.map { it.second }.average() val orderedCluster = intraDistances.sortedBy { it.second }.map { it.first } Triple(orderedCluster, medoids, avgIntraDistance) } class DistanceClusters( distance: Double, orderedCluster: List<String>, intraDistance: Double, medoids: List<String>, others: List<String> ) { val str by lazy { listOf( distance, intraDistance, medoids.size, medoids.joinToString(","), orderedCluster.size, orderedCluster.joinToString(","), others.size, others.joinToString(","), ) .joinToString(" ") } override fun toString() = str } val distances = matrix.values .flatMap { it.values.toSet() } .toSet().toList().sorted() val distanceClusters = distances .filter { it > 0.0 } .map { threshold -> threshold to matrix .map { (word, neighbors) -> word to neighbors .filter { (_, distance) -> distance <= threshold } .map { it.key } .toSet() } .groupBy { (_, profile) -> profile } .toList() .map { (profile, values) -> values.map { it.first }.toSet() to profile } .sortedBy { -it.first.size } } .flatMap { (distance, pairs) -> pairs .map { (cluster, profile) -> val others = profile.minus(cluster).sorted() val (orderedCluster, medoids, intraDistance) = analyzeCluster(cluster) DistanceClusters(distance, orderedCluster, intraDistance, medoids, others) } } File(baseDir, "word-distance-clusters.txt").printWriter().use { out -> distanceClusters.forEach(out::println) out.flush() } }
0
Kotlin
0
0
c571546a4ab09ec41be737d39524cec06fb9a213
4,981
grappolo-pg
Apache License 2.0
app/src/main/java/dev/tcode/thinmp/view/cell/GridCellView.kt
tcode-dev
392,735,283
false
null
package dev.tcode.thinmp.view.cell import androidx.compose.foundation.layout.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import dev.tcode.thinmp.constant.StyleConstant @Composable fun GridCellView( index: Int, colNumber: Int, itemSize: Dp, content: @Composable BoxScope.() -> Unit, ) { val even = (index % colNumber) == 0 val start = if (even) StyleConstant.PADDING_LARGE.dp else StyleConstant.PADDING_SMALL.dp val end = if (even) StyleConstant.PADDING_SMALL.dp else StyleConstant.PADDING_LARGE.dp Box( modifier = Modifier .width(itemSize) .padding(start = start, end = end, bottom = StyleConstant.PADDING_LARGE.dp), content = content ) }
0
Kotlin
0
6
109c6eefa240b38d9a8e776e83c85325c8037a7a
816
ThinMP_Android_Kotlin
MIT License
app/src/main/java/io/github/takusan23/tatimidroid/nicovideo/viewmodel/factory/NicoVideoSeriesListViewModelFactory.kt
ugokitakunai
420,580,612
false
null
package io.github.takusan23.tatimidroid.nicovideo.viewmodel.factory import android.app.Application import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.github.takusan23.tatimidroid.nicovideo.viewmodel.NicoVideoSeriesListViewModel /** * [NicoVideoSeriesListViewModel]を初期化するクラス * */ class NicoVideoSeriesListViewModelFactory(val application: Application, val userId: String?) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return NicoVideoSeriesListViewModel(application, userId) as T } }
0
null
0
0
745d6a4f0a00349c31e48403fa25488fe6bc346b
592
TatimiDroid
Apache License 2.0
brain/src/main/kotlin/fr/sdis64/brain/utilities/ComponentScopes.kt
ArchangelX360
705,188,698
false
{"Kotlin": 1253257, "JavaScript": 1614, "Dockerfile": 1112, "HTML": 496}
package fr.sdis64.brain.utilities import jakarta.annotation.PreDestroy import kotlinx.coroutines.* import java.util.concurrent.Executors open class CoroutineScopedComponent { protected val componentScope: CoroutineScope = CoroutineScope(CoroutineName("${this::class.simpleName}-coroutine") + SupervisorJob()) @PreDestroy fun cancelScope() { componentScope.cancel() } } open class AbstractScheduledFetcherService : CoroutineScopedComponent() { companion object { // this dispatcher is in the companion so it is shared by all fetchers private val fetcherDispatcher = Executors.newFixedThreadPool(5).asCoroutineDispatcher() } protected val scheduledFetcherScope: CoroutineScope = componentScope + fetcherDispatcher @PreDestroy fun cancelFetcherScope() { scheduledFetcherScope.cancel() } }
2
Kotlin
0
1
b731bef419e602e04650509f7423f1146a671596
874
sdis64-ctac
MIT License
brain/src/main/kotlin/fr/sdis64/brain/utilities/ComponentScopes.kt
ArchangelX360
705,188,698
false
{"Kotlin": 1253257, "JavaScript": 1614, "Dockerfile": 1112, "HTML": 496}
package fr.sdis64.brain.utilities import jakarta.annotation.PreDestroy import kotlinx.coroutines.* import java.util.concurrent.Executors open class CoroutineScopedComponent { protected val componentScope: CoroutineScope = CoroutineScope(CoroutineName("${this::class.simpleName}-coroutine") + SupervisorJob()) @PreDestroy fun cancelScope() { componentScope.cancel() } } open class AbstractScheduledFetcherService : CoroutineScopedComponent() { companion object { // this dispatcher is in the companion so it is shared by all fetchers private val fetcherDispatcher = Executors.newFixedThreadPool(5).asCoroutineDispatcher() } protected val scheduledFetcherScope: CoroutineScope = componentScope + fetcherDispatcher @PreDestroy fun cancelFetcherScope() { scheduledFetcherScope.cancel() } }
2
Kotlin
0
1
b731bef419e602e04650509f7423f1146a671596
874
sdis64-ctac
MIT License
modules/mynlp-transform/src/main/java/com/mayabot/nlp/transform/Simplified2Traditional.kt
xiuxiuxiaodi
210,184,385
true
{"Batchfile": 1, "Shell": 1, "Markdown": 3, "INI": 1, "Java": 206, "Kotlin": 65, "Java Properties": 2}
package com.mayabot.nlp.transform import java.util.* import javax.inject.Singleton /** * 简体转繁体的词典 * * @author jimichan */ @Singleton class Simplified2Traditional : BaseTransformDictionary() { override fun loadDictionary(): TreeMap<String, String> { return loadFromResource(RS_NAME) } companion object { private val RS_NAME = "ts-dict/s2t.txt" } }
0
null
0
0
bd835704f6eecf53001a5314ba37ec131de348a9
387
mynlp
Apache License 2.0
src/xqt-kotlinx-json-rpc/commonMain/xqt/kotlinx/rpc/json/serialization/Objects.kt
rhdunn
600,018,019
false
null
// Copyright (C) 2022-2023 <NAME>. SPDX-License-Identifier: Apache-2.0 package xqt.kotlinx.rpc.json.serialization import kotlinx.serialization.json.* import xqt.kotlinx.rpc.json.serialization.types.JsonProperty import xqt.kotlinx.rpc.json.serialization.types.JsonPropertyState import xqt.kotlinx.rpc.json.serialization.types.JsonTypedArray import xqt.kotlinx.rpc.json.serialization.types.JsonTypedObject /** * Returns a new read-only JSON object with the specified contents, given as a * list of pairs where the first value is the key and the second is the value. * * If multiple pairs have the same key, the resulting map will contain the value * from the last of those pairs. * * Entries of the map are iterated in the order they were specified. * * @since 1.0.0 */ fun jsonObjectOf(vararg pairs: Pair<String, JsonElement>): JsonObject = JsonObject(mapOf(*pairs)) /** * Deserialize the data type or object from the `json` element. * * @param key the name of the required key to deserialize. * @param serializer how to deserialize the JSON element value. * * @since 1.0.0 */ fun <T> JsonObject.get(key: String, serializer: JsonSerialization<T>): T { return serializer.deserialize(get(key) ?: missingKey(key)) } /** * Deserialize the data type or object from the `json` element. * * @param key the name of the required key to deserialize. * @param serializer how to deserialize the JSON element value. * * @since 1.1.0 */ fun <T> JsonObject.getProperty(key: String, serializer: JsonSerialization<T>): JsonProperty<T> { val value = get(key) ?: return JsonProperty.missing() return JsonProperty(serializer.deserializeOrNull(value)) } /** * Deserialize the nullable data type or object from the `json` element. * * @param key the name of the required key to deserialize. * @param serializer how to deserialize the JSON element value. * * @since 1.0.0 */ fun <T> JsonObject.getNullable(key: String, serializer: JsonSerialization<T>): T? { return serializer.deserializeOrNull(get(key) ?: missingKey(key)) } /** * Deserialize the data type or object from the `json` element. * * @param key the name of the required key to deserialize. * @param serializer how to deserialize the JSON element value. * * @since 1.0.0 */ fun <T> JsonObject.getOptional(key: String, serializer: JsonSerialization<T>): T? { return get(key)?.let { serializer.deserialize(it) } } /** * Deserialize the array of data types or objects from the `json` element. * * @param key the name of the optional key to deserialize. * @param serializer how to deserialize the JSON array value. * * @since 1.0.0 */ fun <T> JsonObject.getOptional(key: String, serializer: JsonTypedArray<T>): List<T> { val data = get(key) ?: return listOf() return serializer.deserialize(data) } /** * Deserialize the map of data types from the `json` element. * * @param key the name of the optional key to deserialize. * @param serializer how to deserialize the JSON object value. * * @since 1.0.0 */ fun <K, V> JsonObject.getOptional(key: String, serializer: JsonTypedObject<K, V>): Map<K, V> { val data = get(key) ?: return mapOf() return serializer.deserialize(data) } /** * Deserialize the data type or object from the `json` element. * * @param key the name of the required key to deserialize. * @param serializer how to deserialize the JSON element value. * * @since 1.0.0 */ @Deprecated( message = "Use get with a JsonProperty type.", replaceWith = ReplaceWith("get", "xqt.kotlinx.rpc.json.serialization.get") ) fun <T> JsonObject.getOptionalOrNullable(key: String, serializer: JsonSerialization<T>): T? { return get(key)?.let { serializer.deserializeOrNull(it) } } /** * Deserialize the array of data types or objects from the `json` element. * * @param key the name of the optional key to deserialize. * @param serializer how to deserialize the JSON array value. * * @since 1.0.0 */ @Deprecated( message = "Use get with a JsonProperty type.", replaceWith = ReplaceWith("get", "xqt.kotlinx.rpc.json.serialization.get") ) fun <T> JsonObject.getOptionalOrNullable(key: String, serializer: JsonTypedArray<T>): List<T> { val data = get(key) ?: return listOf() return serializer.deserializeOrNull(data) ?: listOf() } /** * Deserialize the map of data types from the `json` element. * * @param key the name of the optional key to deserialize. * @param serializer how to deserialize the JSON object value. * * @since 1.0.0 */ @Deprecated( message = "Use get with a JsonProperty type.", replaceWith = ReplaceWith("get", "xqt.kotlinx.rpc.json.serialization.get") ) fun <K, V> JsonObject.getOptionalOrNullable(key: String, serializer: JsonTypedObject<K, V>): Map<K, V> { val data = get(key) ?: return mapOf() return serializer.deserializeOrNull(data) ?: mapOf() } /** * Serialize the data type or object to the JSON element. * * @param key the name of the key to serialize to. * @param value the content of the array to serialize to. * @param serializer how to serialize the JSON element value. * * @since 1.0.0 */ fun <T> JsonObjectBuilder.put(key: String, value: T, serializer: JsonSerialization<T>) { put(key, serializer.serializeToJson(value)) } /** * Serialize the data type or object to the JSON element. * * @param key the name of the key to serialize to. * @param value the content of the array to serialize to. * @param serializer how to serialize the JSON element value. * * @since 1.1.0 */ fun <T> JsonObjectBuilder.putProperty(key: String, value: JsonProperty<T>, serializer: JsonSerialization<T>) { if (value.state == JsonPropertyState.Present) { put(key, serializer.serializeToJsonOrNull(value.value)) } } /** * Serialize the nullable data type or object to the JSON element. * * If the value is null, this will add it to the JSON element as a null. * * @param key the name of the key to serialize to. * @param value the content of the array to serialize to. * @param serializer how to serialize the JSON element value. * * @since 1.0.0 */ fun <T> JsonObjectBuilder.putNullable(key: String, value: T?, serializer: JsonSerialization<T>) { put(key, serializer.serializeToJsonOrNull(value)) } /** * Serialize the data type or object to the JSON element. * * If the value is null, this will not add it to the JSON element. * * @param key the name of the key to serialize to. * @param value the content of the array to serialize to. * @param serializer how to serialize the JSON element value. * * @since 1.0.0 */ fun <T> JsonObjectBuilder.putOptional(key: String, value: T?, serializer: JsonSerialization<T>) { value?.let { put(key, serializer.serializeToJson(it)) } } /** * Serialize the array of data types to the JSON element. * * If the list is empty, this will not add the array to the JSON element. * * @param key the name of the key to serialize to. * @param value the content of the array to serialize to. * @param serializer how to serialize the JSON array value. * * @since 1.0.0 */ fun <T> JsonObjectBuilder.putOptional(key: String, value: List<T>, serializer: JsonTypedArray<T>) { if (value.isNotEmpty()) { put(key, serializer.serializeToJson(value)) } } /** * Serialize the map of data types to the JSON element. * * If the map is empty, this will not add the object to the JSON element. * * @param key the name of the key to serialize to. * @param value the content of the map to serialize to. * @param serializer how to serialize the JSON map value. * * @since 1.0.0 */ fun <K, V> JsonObjectBuilder.putOptional(key: String, value: Map<K, V>, serializer: JsonTypedObject<K, V>) { if (value.isNotEmpty()) { put(key, serializer.serializeToJson(value)) } } /** * Checks the value of the `kind` property of a JSON object. * * @since 1.0.0 */ fun JsonElement.hasKindKey(value: String): Boolean = when (this) { is JsonObject -> this.hasKindKey(value) else -> false } /** * Checks the value of the `kind` property of a JSON object. * * @since 1.0.0 */ fun JsonObject.hasKindKey(value: String): Boolean { val kind = get("kind") return when { kind == null -> false kind !is JsonPrimitive -> false !kind.isString -> false else -> kind.content == value } } /** * Checks the JSON object contains all the specified keys. * * @since 1.0.0 */ fun JsonElement.containsKeys(vararg key: String): Boolean = when (this) { is JsonObject -> key.all { containsKey(it) } else -> false } /** * Checks the JSON object contains all the specified keys. * * @since 1.0.0 */ fun JsonObject.containsKeys(vararg key: String): Boolean = key.all { containsKey(it) }
0
Kotlin
1
2
b2208dfa9a25d31381f7d9d2d72e32fd6b6220fc
8,758
xqt-kotlinx-json-rpc
Apache License 2.0
src/main/kotlin/VideoList.kt
vks16
366,953,195
false
null
import kotlinx.browser.window import kotlinx.html.js.onClickFunction import org.w3c.dom.events.Event import react.* import react.dom.* @JsExport class VideoList: RComponent<VideoListProps, RState>() { override fun RBuilder.render() { for (video in props.videos) { p { key = video.id.toString() attrs { onClickFunction = { props.onSelectVideo(video) } } if(video == props.selectedVideo) { +"▶ " } +"${video.speaker}: ${video.title}" } } } } external interface VideoListProps: RProps { var videos: List<Video> var selectedVideo: Video? var onSelectVideo: (Video) -> Unit } //fun alert(video: Video): (Event) -> Unit { // window.alert("Clicked $video!") //} //fun RBuilder.videoList(handler: VideoListProps.() -> Unit): ReactElement { // return child(VideoList::class) { // this.attr(handler) // } //}
0
Kotlin
0
0
d4acd3d252971dbc7bd00787f195d474f38029f8
1,061
kotlinConfExplorer
Apache License 2.0
iminling-core/src/main/kotlin/com/iminling/core/config/filter/LoginFilter.kt
konghanghang
340,850,176
false
null
package com.iminling.core.config.filter /** * @author <EMAIL> * @since 2021/11/28 */ interface LoginFilter: Filter { }
0
Kotlin
0
1
9f2cb7d85ad7364ff3aa92bfd5eb15db9b23809a
124
base-iminling-core
MIT License
modules/views-dsl-appcompat/src/androidMain/kotlin/splitties/views/dsl/appcompat/experimental/AppCompatViewInstantiatorInjectProvider.kt
libern
348,960,224
true
{"Kotlin": 670012, "Java": 1368, "Shell": 358}
/* * Copyright 2019-2020 <NAME>. Use of this source code is governed by the Apache 2.0 license. */ package splitties.views.dsl.appcompat.experimental import splitties.initprovider.InitProvider import splitties.initprovider.ObsoleteContentProviderHack import splitties.views.dsl.core.experimental.ViewFactoryImpl @OptIn(ObsoleteContentProviderHack::class) internal class AppCompatViewInstantiatorInjectProvider : InitProvider() { //TODO: Replace this InitProvider with AndroidX Startup once its API is stable. override fun onCreate() = ViewFactoryImpl.appInstance.apply { add(::instantiateAppCompatView) addForThemeAttrStyled(::instantiateThemeAttrStyledAppCompatView) }.let { true } }
0
Kotlin
0
0
1507038d11a8209682298ac2939ee09bb949c724
719
Splitties
Apache License 2.0
core/src/commonMain/kotlin/it/krzeminski/fsynth/songs/PinkPantherThemeIntro.kt
fsynthlib
136,238,161
false
null
package it.krzeminski.fsynth.songs import it.krzeminski.fsynth.instruments.cymbals import it.krzeminski.fsynth.instruments.simpleDecayEnvelopeSynthesizer import it.krzeminski.fsynth.instruments.synthesizer import it.krzeminski.fsynth.types.MusicNote.* // ktlint-disable no-wildcard-imports import it.krzeminski.fsynth.types.by import it.krzeminski.fsynth.types.to import it.krzeminski.fsynth.types.song val pinkPantherThemeIntro = song(name = "Pink Panther Theme (intro)", beatsPerMinute = 120) { track(name = "Main melody", instrument = synthesizer, volume = 0.3f) { pause(1 by 1) pause(1 by 1) pause(1 by 1) pause(1 by 1) pause(11 by 12) note(1 by 12, Dsharp4) note(5 by 12, E4) note(1 by 12, Fsharp4) note(5 by 12, G4) note(1 by 12, Dsharp4) note(2 by 12, E4) note(1 by 12, Fsharp4) note(2 by 12, G4) note(1 by 12, C5) note(2 by 12, B4) note(1 by 12, E4) note(2 by 12, G4) note(1 by 12, B4) glissando(7 by 12, A4 to Asharp4) glissando(1 by 12, G4 to A4) note(1 by 12, G4) note(1 by 12, E4) note(1 by 12, D4) note(10 by 12, E4) pause(2 by 12) note(1 by 12, Dsharp4) note(5 by 12, E4) note(1 by 12, Fsharp4) note(5 by 12, G4) note(1 by 12, Dsharp4) note(2 by 12, E4) note(1 by 12, Fsharp4) note(2 by 12, G4) note(1 by 12, C5) note(2 by 12, B4) note(1 by 12, G4) note(2 by 12, B4) note(1 by 12, E5) note(1 by 1, Dsharp5) pause(1 by 1) pause(3 by 12) glissando(2 by 12, D5 to E5) note(1 by 12, D5) glissando(2 by 12, A4 to B4) note(1 by 12, A4) note(2 by 12, G4) note(1 by 12, E4) glissando(3 by 12, Asharp4 to A4) glissando(3 by 12, Asharp4 to A4) glissando(3 by 12, Asharp4 to A4) glissando(3 by 12, Asharp4 to A4) note(1 by 12, G4) note(1 by 12, E4) note(1 by 12, D4) note(1 by 12, E4) pause(1 by 12) note(7 by 12, E4) } track(name = "Chord background", instrument = synthesizer, volume = 0.1f) { repeat(2) { pause(8 by 12) chord(1 by 12, Csharp3, Gsharp3) chord(2 by 12, D3, A3) chord(1 by 12, Dsharp3, Asharp3) chord(1 by 1, E3, B3) } repeat(2) { pause(8 by 12) chord(1 by 12, Csharp3, Gsharp3) chord(2 by 12, D3, A3) chord(1 by 12, Dsharp3, Asharp3) chord(1 by 1, E3, B3) pause(8 by 12) chord(1 by 12, E3, B3) chord(2 by 12, Dsharp3, Asharp3) chord(1 by 12, D3, A3) chord(1 by 1, Csharp3, Gsharp3) } pause(8 by 12) chord(1 by 12, Csharp3, Gsharp3) chord(2 by 12, D3, A3) chord(1 by 12, Dsharp3, Asharp3) chord(1 by 4, E3, B3) pause(3 by 4) pause(1 by 1) chord(1 by 1, E3, B3) } track(name = "Bass", instrument = simpleDecayEnvelopeSynthesizer, volume = 0.1f) { pause(1 by 1) repeat(2) { note(1 by 2, E3) note(1 by 2, B2) note(1 by 2, E2) pause(1 by 2) } repeat(2) { note(1 by 2, E3) note(1 by 2, B2) note(1 by 2, E2) pause(1 by 2) note(1 by 2, Csharp3) note(1 by 2, Gsharp2) note(1 by 2, Csharp2) pause(1 by 2) } } track(name = "Percussion", instrument = cymbals, volume = 0.1f) { fun repeatingPattern() { note(1 by 12, A4) pause(2 by 12) note(1 by 12, A4) pause(1 by 12) note(1 by 24, A4) pause(1 by 24) } pause(1 by 1) repeat(24) { repeatingPattern() } note(1 by 12, A4) pause(11 by 12) pause(1 by 1) repeat(2) { repeatingPattern() } note(1 by 12, A4) } }
18
Kotlin
1
11
1f138bf5c5d46a80b23eca8bde589da1b865662a
4,227
fsynth
MIT License
kotlin-react-bootstrap/src/main/kotlin/react/bootstrap/components/nav/NavItems.kt
bjoernmayer
256,536,328
false
null
package react.bootstrap.components.nav import kotlinext.js.jsObject import kotlinx.html.DIV import kotlinx.html.HtmlBlockTag import kotlinx.html.LI import kotlinx.html.classes import react.RState import react.RStatics import react.bootstrap.helpers.addOrInit import react.bootstrap.lib.bootstrap.ClassNames import react.bootstrap.lib.component.AbstractComponent import react.bootstrap.lib.kotlinxhtml.loadGlobalAttributes import react.bootstrap.lib.react.identifiable.IdentifiableProps import react.bootstrap.lib.react.identifiable.mapComponents import react.bootstrap.lib.react.rprops.WithGlobalAttributes import react.bootstrap.lib.react.rprops.childrenArray import react.dom.RDOMBuilder import kotlin.reflect.KClass sealed class NavItems<P : NavItems.Props> : AbstractComponent<HtmlBlockTag, P, RState>() { class Li : NavItems<Li.Props>() { override val rendererTag: KClass<out HtmlBlockTag> = LI::class interface Props : NavItems.Props, IdentifiableProps<Li> companion object : RStatics<Props, RState, Li, Nothing>(Li::class) { init { Li.defaultProps = jsObject { componentType = Li::class } } } } class NavItem : NavItems<NavItem.Props>() { override val rendererTag: KClass<out HtmlBlockTag> = DIV::class interface Props : NavItems.Props, IdentifiableProps<NavItem> companion object : RStatics<Props, RState, NavItem, Nothing>(NavItem::class) { init { NavItem.defaultProps = jsObject { componentType = NavItem::class } } } } class DivItem : NavItems<DivItem.Props>() { override val rendererTag: KClass<out HtmlBlockTag> = DIV::class interface Props : NavItems.Props, IdentifiableProps<DivItem> companion object : RStatics<Props, RState, DivItem, Nothing>(DivItem::class) { init { DivItem.defaultProps = jsObject { componentType = DivItem::class } } } } override fun RDOMBuilder<HtmlBlockTag>.transferChildren() { if (props.activeLinkPredicate == null) { children() } else { childList.addAll( props.childrenArray.mapComponents<NavLink.Props, NavLink> { _, _ -> attrs { activeLinkPredicate = [email protected] } } ) } } override fun RDOMBuilder<HtmlBlockTag>.build() { attrs { loadGlobalAttributes(props) classes = props.classes.addOrInit(setOf(ClassNames.NAV_ITEM)) } } interface Props : WithGlobalAttributes { var activeLinkPredicate: (NavLink.Props.() -> Boolean)? } }
7
Kotlin
5
9
537f349dfaa8d6a3035acc61698889840b355855
2,886
kotlin-react-bootstrap
MIT License
core/src/commonMain/kotlin/io/github/aeckar/numerics/serializers/RationalSerializer.kt
aeckar
826,660,231
false
{"Kotlin": 160653, "Java": 248}
package io.github.aeckar.numerics.serializers import io.github.aeckar.numerics.Rational import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.descriptors.buildClassSerialDescriptor import kotlinx.serialization.descriptors.element import kotlinx.serialization.encoding.* /** * *kotlinx.serialization* serializer for rational numbers. */ public object RationalSerializer : KSerializer<Rational> { override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Rational") { element<Long>("numer") element<Long>("denom") element<Int>("scale") element<Int>("sign") } override fun deserialize(decoder: Decoder): Rational = decoder.decodeStructure(descriptor) { var numer = 0L var denom = 0L var scale = 0 var sign = 0 while (true) { when (val index = decodeElementIndex(descriptor)) { 0 -> numer = decodeLongElement(descriptor, 0) 1 -> denom = decodeLongElement(descriptor, 1) 2 -> scale = decodeIntElement(descriptor, 2) 3 -> sign = decodeIntElement(descriptor, 3) CompositeDecoder.DECODE_DONE -> break else -> error("Unexpected index: $index") } } Rational(numer, denom, scale, sign) } override fun serialize(encoder: Encoder, value: Rational) { encoder.encodeStructure(descriptor) { encodeLongElement(descriptor, 0, value.numer) encodeLongElement(descriptor, 1, value.denom) encodeIntElement(descriptor, 2, value.scale) encodeIntElement(descriptor, 3, value.sign) } } }
0
Kotlin
0
1
7d6698e7deda09ff2ff5334b6b93b0c4a1eac2f3
1,751
extended-numerics
MIT License
app/src/main/java/com/github/wanderwise_inc/app/model/location/Location.kt
WanderWise-Inc
775,382,316
false
{"Kotlin": 52414}
package com.github.wanderwise_inc.app.model.location import com.google.android.gms.maps.model.LatLng enum class LocationLabels(val dbLabel: String) { LAT("lat"), LONG("long"), } data class Location( val lat: Double, val long: Double, ) { fun toLatLng(): LatLng { return LatLng(lat, long) } /** * @return a map representation of a location */ fun toMap(): Map<String, Any> { return mapOf( LocationLabels.LAT.dbLabel to lat, LocationLabels.LONG.dbLabel to long ) } companion object { fun fromLatLng(latLng: LatLng): Location { return Location(latLng.latitude, latLng.longitude) } } }
40
Kotlin
0
0
0319446c9c43db0b1b87df3d02c4d50413a3dc12
716
app
MIT License
app/src/main/java/com/example/chefai/network/RetrofitApiFactory.kt
abenezermario
480,656,546
false
{"Kotlin": 32036}
package com.example.chefai.network import com.example.chefai.Constants import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class RetrofitApiFactory { companion object { fun retroInstance(): Retrofit { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY val client = OkHttpClient.Builder() client.addInterceptor(logging) return Retrofit.Builder() .baseUrl(Constants.BASE_URL) .client(client.build()) .addConverterFactory(GsonConverterFactory.create()) .build() } } }
0
Kotlin
1
0
f47f460d0268be3bebc3901b943c3ed802c8dbfd
761
Chefai
MIT License
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package64/Foo06440.kt
yamamotoj
163,851,411
false
{"Text": 1, "Ignore List": 30, "Markdown": 1, "Gradle": 34, "Java Properties": 11, "Shell": 6, "Batchfile": 6, "Proguard": 22, "Kotlin": 36021, "XML": 93, "INI": 1, "Java": 32, "Python": 2}
package com.github.yamamotoj.singlemoduleapp.package64 class Foo06440 { fun method0() { Foo06439().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
355
android_multi_module_experiment
Apache License 2.0
servers/graphql-kotlin-spring-server/src/test/kotlin/com/expediagroup/graphql/server/spring/execution/SpringGraphQLSubscriptionHandlerTest.kt
ExpediaGroup
148,706,161
false
null
/* * Copyright 2023 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.graphql.server.spring.execution import com.expediagroup.graphql.generator.SchemaGeneratorConfig import com.expediagroup.graphql.generator.TopLevelObject import com.expediagroup.graphql.generator.exceptions.GraphQLKotlinException import com.expediagroup.graphql.generator.execution.FlowSubscriptionExecutionStrategy import com.expediagroup.graphql.generator.toSchema import com.expediagroup.graphql.dataloader.KotlinDataLoaderRegistryFactory import com.expediagroup.graphql.dataloader.KotlinDataLoader import com.expediagroup.graphql.generator.extensions.toGraphQLContext import com.expediagroup.graphql.server.execution.GraphQLRequestHandler import com.expediagroup.graphql.server.extensions.getValueFromDataLoader import com.expediagroup.graphql.server.types.GraphQLRequest import graphql.GraphQL import graphql.GraphQLContext import graphql.schema.DataFetchingEnvironment import graphql.schema.GraphQLSchema import kotlinx.coroutines.reactor.asFlux import org.dataloader.DataLoader import org.dataloader.DataLoaderFactory import org.junit.jupiter.api.Test import reactor.core.publisher.Flux import reactor.kotlin.core.publisher.toFlux import reactor.kotlin.core.publisher.toMono import reactor.test.StepVerifier import java.time.Duration import java.util.concurrent.CompletableFuture import kotlin.random.Random import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue class SpringGraphQLSubscriptionHandlerTest { private val testSchema: GraphQLSchema = toSchema( config = SchemaGeneratorConfig(supportedPackages = listOf("com.expediagroup.graphql.server.spring.execution")), queries = listOf(TopLevelObject(BasicQuery())), subscriptions = listOf(TopLevelObject(BasicSubscription())) ) private val testGraphQL: GraphQL = GraphQL.newGraphQL(testSchema) .subscriptionExecutionStrategy(FlowSubscriptionExecutionStrategy()) .build() private val mockLoader: KotlinDataLoader<String, String> = object : KotlinDataLoader<String, String> { override val dataLoaderName: String = "MockDataLoader" override fun getDataLoader(graphQLContext: GraphQLContext): DataLoader<String, String> = DataLoaderFactory.newDataLoader { ids -> CompletableFuture.supplyAsync { ids.map { "$it:value" } } } } private val dataLoaderRegistryFactory = KotlinDataLoaderRegistryFactory(listOf(mockLoader)) private val subscriptionHandler = GraphQLRequestHandler(testGraphQL, dataLoaderRegistryFactory) @Test fun `verify subscription`() { val request = GraphQLRequest(query = "subscription { ticker }") val responseFlux = subscriptionHandler.executeSubscription( request, emptyMap<Any, Any>().toGraphQLContext() ).asFlux() StepVerifier.create(responseFlux) .thenConsumeWhile { response -> assertNotNull(response.data as? Map<*, *>) { data -> assertNotNull(data["ticker"] as? Int) } assertNull(response.errors) assertNull(response.extensions) true } .expectComplete() .verify() } @Test fun `verify subscription with data loader`() { val request = GraphQLRequest(query = "subscription { dataLoaderValue }") val responseFlux = subscriptionHandler.executeSubscription( request, emptyMap<Any, Any>().toGraphQLContext() ).asFlux() StepVerifier.create(responseFlux) .thenConsumeWhile { response -> assertNotNull(response.data as? Map<*, *>) { data -> assertNotNull(data["dataLoaderValue"] as? String) { value -> assertEquals("foo:value", value) } } assertNull(response.errors) assertNull(response.extensions) true } .expectComplete() .verify() } @Test fun `verify subscription with context map`() { val request = GraphQLRequest(query = "subscription { contextualMapTicker }") val graphQLContext = mapOf("foo" to "junitHandler").toGraphQLContext() val responseFlux = subscriptionHandler.executeSubscription(request, graphQLContext).asFlux() StepVerifier.create(responseFlux) .thenConsumeWhile { response -> assertNotNull(response.data as? Map<*, *>) { data -> assertNotNull(data["contextualMapTicker"] as? String) { tickerValue -> assertTrue(tickerValue.startsWith("junitHandler:")) assertNotNull(tickerValue.substringAfter("junitHandler:").toIntOrNull()) } } assertNull(response.errors) assertNull(response.extensions) true } .expectComplete() .verify() } @Test fun `verify subscription to failing publisher`() { val request = GraphQLRequest(query = "subscription { alwaysThrows }") val responseFlux = subscriptionHandler.executeSubscription( request, emptyMap<Any, Any>().toGraphQLContext() ).asFlux() StepVerifier.create(responseFlux) .assertNext { response -> assertNull(response.data) assertNotNull(response.errors) { errors -> assertEquals(1, errors.size) val error = errors.first() assertEquals("JUNIT subscription failure", error.message) } assertNull(response.extensions) } .expectComplete() .verify() } // GraphQL spec requires at least single query to be present as Query type is needed to run introspection queries // see: https://github.com/graphql/graphql-spec/issues/490 and https://github.com/graphql/graphql-spec/issues/568 class BasicQuery { @Suppress("Detekt.FunctionOnlyReturningConstant") fun query(): String = "hello" } class BasicSubscription { fun ticker(): Flux<Int> = Flux.range(1, 5) .delayElements(Duration.ofMillis(100)) .map { Random.nextInt() } fun alwaysThrows(): Flux<String> = Flux.error(GraphQLKotlinException("JUNIT subscription failure")) fun contextualMapTicker(dfe: DataFetchingEnvironment): Flux<String> = Flux.range(1, 5) .delayElements(Duration.ofMillis(100)) .map { "${dfe.graphQlContext.get<String>("foo")}:${Random.nextInt(100)}" } fun dataLoaderValue(dfe: DataFetchingEnvironment): Flux<String> = dfe.getValueFromDataLoader<String, String>("MockDataLoader", "foo").toMono().toFlux() } }
68
null
345
1,739
d3ad96077fc6d02471f996ef34c67066145acb15
7,554
graphql-kotlin
Apache License 2.0
app/src/main/java/space/fanbox/android/fanbox/model/Letter.kt
ayevbeosa
166,378,925
false
{"Kotlin": 30583}
package space.fanbox.android.fanbox.model import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Letter( @field:PrimaryKey val id: String, val subject: String, val body: String, val attachment: String, val closing: String, val recipient: String, val slug: String, val sender_name: String, val sender_id: String, val stamp_id: String, val category: String, val love: String, val hate: String, val views: String, val date_created: String, val tags: List<Tag> )
0
Kotlin
0
0
eef9ec2982982c4bc71299e444e87780ec8fb7f0
552
Fanbox
MIT License
features/product/data/src/main/kotlin/dev/chulwoo/nb/order/features/category/data/source/ProductRemoteSource.kt
chulwoo-park
323,356,084
false
null
package dev.chulwoo.nb.order.features.category.data.source import dev.chulwoo.nb.order.features.product.domain.model.Product interface ProductRemoteSource { suspend fun getProducts(): List<Product> }
0
Kotlin
0
0
c5b0e437ffe1328a2cbfc882c2da42eb24f4dff5
206
nb-order
Apache License 2.0
app/src/main/java/com/spookybrain/delegateexample/adapter/CommentAdapterItemType.kt
alexistamher
692,891,981
false
{"Kotlin": 11049}
package com.spookybrain.delegateexample.adapter enum class CommentAdapterItemType { ITEM { override val type: Int = 0 }, LOADING { override val type: Int = 1 }, GO_TO_TOP { override val type: Int = 2 }; abstract val type: Int }
0
Kotlin
0
0
01726dc2f9304d1ca6785d116b7cee3aa5c94c7c
281
AndroidDelegateExample
MIT License
feature/records/src/main/kotlin/com/xeladevmobile/medicalassistant/feature/records/AudioRecordItem.kt
Alexminator99
702,145,143
false
{"Kotlin": 434495}
package com.xeladevmobile.medicalassistant.feature.records import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.xeladevmobile.medicalassistant.core.formatCreatedDate import com.xeladevmobile.medicalassistant.core.formatDuration import com.xeladevmobile.medicalassistant.core.model.data.Audio import com.xeladevmobile.medicalassistant.core.model.data.audiosPreview @Composable fun AudioRecordItem( audio: Audio, onClick: () -> Unit, modifier: Modifier = Modifier, ) { Card( modifier = modifier .fillMaxWidth() .padding(8.dp) .clickable { onClick() }, elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), ) { Row( modifier = Modifier .padding(16.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Column(modifier = Modifier.weight(1f)) { Text( text = audio.path.substringAfterLast('/'), style = MaterialTheme.typography.titleMedium, ) Text( text = "Duration: ${formatDuration(audio.duration)}", style = MaterialTheme.typography.bodyMedium, ) Text( text = "Created: ${formatCreatedDate(audio.createdDate)}", style = MaterialTheme.typography.bodySmall, ) } // Add additional UI elements if needed, for example, an icon to play the audio } } } @Preview @Composable fun AudioRecordItemPreview() { AudioRecordItem( audio = audiosPreview.first(), onClick = {}, ) }
0
Kotlin
0
0
b0ad6aaf33ee2f3f5cddd3b669143cb7d8df1124
2,303
Medical_Assistant
MIT License
sample/src/main/java/de/nilsdruyen/snappysample/MainActivity.kt
nilsjr
515,922,214
false
{"Kotlin": 48168}
package de.nilsdruyen.snappysample import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.Settings import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import de.nilsdruyen.snappy.Snappy import de.nilsdruyen.snappy.models.SnappyConfig import de.nilsdruyen.snappy.models.SnappyResult import de.nilsdruyen.snappysample.file.FileUtils import de.nilsdruyen.snappysample.ui.SnappySampleTheme class MainActivity : ComponentActivity() { private val snappy = registerForActivityResult(Snappy(), ::setResult) private val filePermissionResult = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grandResults -> if (grandResults.isNotEmpty() && grandResults.all { it.value }) { launchSnappy() } } private val settingsResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> when (result.resultCode) { RESULT_OK -> { launchSnappy() } else -> { Log.i("MainActivity", result.toString()) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { SnappySampleTheme { Sample { if (checkPermission()) { launchSnappy() } else { requestPermission() } } } } } override fun onResume() { super.onResume() // logDirectories() } private fun launchSnappy() { snappy.launch(SnappyConfig(FileUtils.getSnappyDirectory())) } private fun checkPermission(): Boolean { val checkReadPermission = ContextCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED val checkWritePermission = ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED return when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { Environment.isExternalStorageManager() } else -> checkReadPermission && checkWritePermission } } private fun requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { try { val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) intent.addCategory("android.intent.category.DEFAULT") intent.data = Uri.parse("package:${applicationContext.packageName}") settingsResult.launch(intent) } catch (e: Exception) { Log.e("MainActivity", "error ${e.localizedMessage}") val intent = Intent() intent.action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION settingsResult.launch(intent) } } else { filePermissionResult.launch(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)) } } private fun setResult(result: SnappyResult) { Log.i("MainActivity", result.toString()) } }
6
Kotlin
0
73
08f68da30d3274d45e1c2a424cfa6ce3a714f2c3
3,258
Snappy
MIT License
app/src/main/java/ch/silvannellen/githubbrowser/model/github/api/ApiVersion.kt
snellen
253,709,850
false
null
package ch.silvannellen.githubbrowser.model.github.api sealed class ApiVersion(val versionString: String) { object v3 : ApiVersion("v3") }
0
Kotlin
0
1
e8f72e6aa50c35191960d1c5db18c88903404420
143
umvvm-demo
Apache License 2.0
app/src/main/java/com/rsd/roomvsrealm/MainActivity.kt
yozhik
708,193,480
false
{"Kotlin": 9308}
package com.rsd.roomvsrealm import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.room.Room import com.rsd.roomvsrealm.data.TestRoomDatabase import com.rsd.roomvsrealm.ui.theme.MyApplicationTheme import com.rsd.roomvsrealm.viewmodels.UserViewModel class MainActivity : ComponentActivity() { private val db by lazy { Room.databaseBuilder( applicationContext, TestRoomDatabase::class.java, "users.db" ).build() } private val viewModel by viewModels<UserViewModel>( factoryProducer = { object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return UserViewModel(db.userDao()) as T } } } ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.getUsersFromDb() viewModel.populateDataToDb() viewModel.getUsersFromDb() setContent { MyApplicationTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Room Sample") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { MyApplicationTheme { Greeting("Room Sample") } }
0
Kotlin
0
0
fcc8e3048074d6be8c580f0d60c1b6dfa4d67ec5
2,186
mvvm_room_db
Apache License 2.0
src/main/kotlin/dev/vstz/block/BlockStateModelProvider.kt
versustunez
650,197,872
false
null
package dev.vstz.block import net.minecraft.data.client.BlockStateModelGenerator interface BlockStateModelProvider { fun generateBlockStateModel(blockStateModelGenerator: BlockStateModelGenerator) { } }
0
Kotlin
0
0
94c82b94caf0fd146114000edf70292497c247fa
213
DatQuarry
Creative Commons Zero v1.0 Universal
core/data/src/main/java/com/vstudio/pixabay/core/data/di/DataModule.kt
svvok23
777,911,339
false
{"Kotlin": 108085}
package com.vstudio.pixabay.core.data.di import com.vstudio.pixabay.core.common.Mapper import com.vstudio.pixabay.core.data.mapper.ImageMapperDtoToEntity import com.vstudio.pixabay.core.data.mapper.ImageMapperDtoToModel import com.vstudio.pixabay.core.data.mapper.ImageMapperEntityToModel import com.vstudio.pixabay.core.data.repositories.CachedSearchQueriesRepository import com.vstudio.pixabay.core.data.repositories.CashedImageResourcesRepository import com.vstudio.pixabay.core.data.repositories.OfflineFirstImagesRepository import com.vstudio.pixabay.core.data.util.ConnectivityManagerNetworkMonitor import com.vstudio.pixabay.core.database.model.ImageEntity import com.vstudio.pixabay.core.domain.repository.ImagesRepository import com.vstudio.pixabay.core.domain.repository.NetworkMonitor import com.vstudio.pixabay.core.domain.repository.SearchQueriesRepository import com.vstudio.pixabay.core.domain.model.Image import com.vstudio.pixabay.core.domain.repository.ImageResourcesRepository import com.vstudio.pixabay.core.network.model.HitDto import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) internal abstract class DataModule { @Binds abstract fun bindsNetworkMonitor( networkMonitor: ConnectivityManagerNetworkMonitor, ): NetworkMonitor @Binds abstract fun bindsImagesRepository( imagesRepository: OfflineFirstImagesRepository, ): ImagesRepository @Binds abstract fun bindsSearchQueriesRepository( queriesRepository: CachedSearchQueriesRepository ): SearchQueriesRepository @Binds abstract fun bindsImageResourcesRepository( imageResourcesRepository: CashedImageResourcesRepository ): ImageResourcesRepository @Binds abstract fun bindsImageMapperDtoToModel( imageMapper: ImageMapperDtoToModel, ): Mapper<HitDto, Image> @Binds abstract fun bindsImageMapperDtoToEntity( imageMapper: ImageMapperDtoToEntity, ): Mapper<HitDto, ImageEntity> @Binds abstract fun bindsImageMapperEntityToModel( imageMapper: ImageMapperEntityToModel, ): Mapper<ImageEntity, Image> }
0
Kotlin
0
0
1eda7b90eb5675d9e90aa2acded8ee62a5944757
2,230
Pixabay-Searcher
Apache License 2.0
camera/src/main/java/com/ke/cameralibrary/FoucsView.kt
15510261060
142,523,752
false
null
package com.ke.cameralibrary import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.View import com.ke.cameralibrary.util.ScreenUtils class FoucsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val size: Int private var center_x: Int = 0 private var center_y: Int = 0 private var length: Int = 0 private val mPaint: Paint init { this.size = ScreenUtils.getScreenWidth(context) / 3 mPaint = Paint() mPaint.isAntiAlias = true mPaint.isDither = true mPaint.color = -0x11e951ea mPaint.strokeWidth = 4f mPaint.style = Paint.Style.STROKE } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) center_x = (size / 2.0).toInt() center_y = (size / 2.0).toInt() length = (size / 2.0).toInt() - 2 setMeasuredDimension(size, size) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawRect( (center_x - length).toFloat(), (center_y - length).toFloat(), (center_x + length).toFloat(), (center_y + length).toFloat(), mPaint ) canvas.drawLine( 2f, (height / 2).toFloat(), (size / 10).toFloat(), (height / 2).toFloat(), mPaint ) canvas.drawLine( (width - 2).toFloat(), (height / 2).toFloat(), (width - size / 10).toFloat(), (height / 2).toFloat(), mPaint ) canvas.drawLine((width / 2).toFloat(), 2f, (width / 2).toFloat(), (size / 10).toFloat(), mPaint) canvas.drawLine( (width / 2).toFloat(), (height - 2).toFloat(), (width / 2).toFloat(), (height - size / 10).toFloat(), mPaint ) } }
0
Kotlin
0
1
48dbf74223380a6f8ea988f413986ae2075a67b5
1,892
CameraView_ke
Apache License 2.0
buildSrc/src/main/java/dependencies/SupportDependencies.kt
ahmadaghazadeh
440,831,051
false
null
package dependencies.dependencies import dependencies.Versions object SupportDependencies { val appcompat = "androidx.appcompat:appcompat:${Versions.appcompat}" val constraintlayout = "androidx.constraintlayout:constraintlayout:${Versions.constraintlayout}" val material_design = "com.google.android.material:material:${Versions.material_design}" val transition = "androidx.transition:transition:${Versions.transition}" val swipe_refresh_layout = "androidx.swiperefreshlayout:swiperefreshlayout:${Versions.swipe_refresh_layout}" }
0
Kotlin
0
2
022024a7a8692da65cc08315b5766e56c6d8a7bb
556
KotlinCleanArchitecture
Apache License 2.0
android/libraries/rib-base/src/main/java/com/badoo/ribs/core/routing/action/RoutingAction.kt
ramzesrodriguez
196,456,514
true
{"Kotlin": 535795, "Swift": 402146, "Java": 112878, "Shell": 2571, "Ruby": 1955, "Objective-C": 814}
package com.badoo.ribs.core.routing.action import com.badoo.ribs.core.Node import com.badoo.ribs.core.view.RibView interface RoutingAction<V : RibView> { fun buildNodes() : List<Node.Descriptor> = emptyList() fun execute() { } fun cleanup() { } companion object { fun <V : RibView> noop(): RoutingAction<V> = object : RoutingAction<V> {} } }
0
Kotlin
0
0
cd5917a0d6b3a07cadcbb5ac02e576ec8b1f01f4
408
RIBs
Apache License 2.0
ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/AuthenticationSourceProvider.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.model.security /** * Defines the provider for an authentication source. * * @see net.nemerosa.ontrack.model.security.AuthenticationSource */ interface AuthenticationSourceProvider { /** * ID of this provider */ val id: String /** * Gets the sources from this provider */ val sources: List<AuthenticationSource> }
57
null
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
384
ontrack
MIT License
lol/app/src/main/java/com/tyhoo/android/lol/data/ItemsRepository.kt
cnwutianhao
600,592,169
false
null
package com.tyhoo.android.lol.data import com.tyhoo.android.lol.domain.ItemsResponse import com.tyhoo.android.lol.Result import okio.IOException import javax.inject.Inject interface ItemsRepository { suspend fun getItems(): Result<ItemsResponse> } class ItemsRepositoryImpl @Inject constructor( private val service: ApiService ) : ItemsRepository { override suspend fun getItems(): Result<ItemsResponse> { return try { val response = service.getItems() Result.Success(response) } catch (e: IOException) { Result.Error(e) } } }
0
Kotlin
0
0
1b0d042767b2ab45aff5407220817f103b88db5c
606
android
MIT License
app/src/main/java/com/brookes6/cloudmusic/ui/page/SplashPage.kt
brokes6
428,601,432
false
{"Kotlin": 636437, "Java": 1126}
package com.brookes6.cloudmusic.ui.page import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.imageResource import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import com.brookes6.cloudmusic.R import com.brookes6.cloudmusic.constant.AppConstant import com.brookes6.cloudmusic.constant.RouteConstant import com.brookes6.cloudmusic.utils.LogUtils import com.brookes6.cloudmusic.vm.MainViewModel import com.brookes6.cloudmusic.vm.TokenViewModel import com.brookes6.net.api.Api import com.brookes6.repository.model.UserModel import com.drake.net.Post import com.drake.net.utils.scopeNet import com.drake.serialize.serialize.serialize /** * @Author fuxinbo * @Date 2023/1/16 10:32 * @Description TODO */ @Preview(showSystemUi = true) @Composable fun SplashPage( navController: NavController? = null, mTokenVM: TokenViewModel? = null, viewModel: MainViewModel? = null ) { Box(modifier = Modifier.fillMaxSize()) { Image( bitmap = ImageBitmap.imageResource(id = R.mipmap.ic_splash_bg), null, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop ) } LaunchedEffect(true) { scopeNet { Post<UserModel>(Api.LOGIN_STATUS) { // param("timestamp", System.currentTimeMillis()) }.await().also { LogUtils.d("当前帐号状态为:${it}") if (it.account?.status == 0) { LogUtils.d("账号ID为 -> ${it.account?.id}") // 登录状态为已登录 serialize(AppConstant.IS_LOGIN to true) serialize(AppConstant.USER_ID to it.account?.id) viewModel?.state?.let { state -> state.isLogin.value = true state.isShowBottomTab.value = true } navController?.navigate(RouteConstant.HOME) { popUpTo(RouteConstant.SPLASH_PAGE) { inclusive = true } } } else { // 登录状态为未登录 serialize(AppConstant.IS_LOGIN to false) navController?.navigate(RouteConstant.LOGIN) { popUpTo(RouteConstant.SPLASH_PAGE) { inclusive = true } } } } } } }
0
Kotlin
3
18
3c18c4d8ece1a1b42a1b127e6385b6e9fa5de2ff
2,703
CloudMusic
Apache License 2.0
src/main/kotlin/com/github/mateusornelas/pluginandroid/services/MyApplicationService.kt
MateusONunes
293,637,619
false
null
package com.github.mateusornelas.pluginandroid.services import com.github.mateusornelas.pluginandroid.MyBundle class MyApplicationService { init { println(MyBundle.message("applicationService")) } }
0
Kotlin
0
0
009eee014550b498906dd34ab8dc439ef2ca21e4
218
PluginAndroid
Apache License 2.0
app/src/main/kotlin/co/touchlab/kampkit/android/ui/users/UsersList.kt
anhtuanBk
840,141,057
false
{"Kotlin": 87492, "Swift": 12925}
package co.touchlab.kampkit.android.ui.users import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import co.touchlab.kampkit.android.ui.coreUI.LoadingIndicator import co.touchlab.kampkit.android.ui.coreUI.RetryButton import co.touchlab.kampkit.domain.model.User import co.touchlab.kermit.Logger import com.hoc081098.flowext.ThrottleConfiguration import com.hoc081098.flowext.throttleTime import kotlin.time.Duration.Companion.milliseconds import kotlinx.collections.immutable.ImmutableList import kotlinx.coroutines.flow.filter private const val LOG_TAG = "UserItemsList" @Composable internal fun UsersList( items: ImmutableList<User>, isLoading: Boolean, error: Throwable?, hasReachedMax: Boolean, onRetry: () -> Unit, onLoadNextPage: () -> Unit, onItemClick: (User) -> Unit, modifier: Modifier = Modifier, lazyListState: LazyListState = rememberLazyListState() ) { val currentOnLoadNextPage by rememberUpdatedState(onLoadNextPage) val currentHasReachedMax by rememberUpdatedState(hasReachedMax) LaunchedEffect(lazyListState) { snapshotFlow { lazyListState.layoutInfo } .throttleTime( duration = 300.milliseconds, throttleConfiguration = ThrottleConfiguration.LEADING_AND_TRAILING ) .filter { val index = it.visibleItemsInfo.lastOrNull()?.index val totalItemsCount = it.totalItemsCount Logger.d( messageString = "lazyListState: currentHasReachedMax=$currentHasReachedMax " + "- lastVisible=$index" + " - totalItemsCount=$totalItemsCount", tag = LOG_TAG ) !currentHasReachedMax && index != null && index + 2 >= totalItemsCount } .collect { Logger.d( messageString = "load next page", tag = LOG_TAG ) currentOnLoadNextPage() } } LazyColumn( modifier = modifier .padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), state = lazyListState ) { items( items = items, key = { it.login }, contentType = { "user-row" } ) { item -> UserRow( modifier = Modifier .clickable { onItemClick(item) } .fillParentMaxWidth(), item = item ) } when { isLoading -> { item(contentType = "LoadingIndicator") { LoadingIndicator( modifier = Modifier.height(128.dp) ) } } error !== null -> { item(contentType = "RetryButton") { RetryButton( modifier = Modifier.height(128.dp), errorMessage = error.message.orEmpty(), onRetry = onRetry ) } } !hasReachedMax -> { item(contentType = "Spacer") { Spacer(modifier = Modifier.height(128.dp)) } } } } }
0
Kotlin
0
0
c7d9b40f9d0e7a382703a6270aa395600c23f290
4,151
github-users
Apache License 2.0
src/main/kotlin/org/crystal/intellij/psi/CrIfUnlessExpression.kt
asedunov
353,165,557
false
null
package org.crystal.intellij.psi import com.intellij.lang.ASTNode abstract class CrIfUnlessExpression(node: ASTNode) : CrExpressionImpl(node) { val isSuffix: Boolean get() = firstChild is CrThenClause }
16
Kotlin
3
30
41a6c84fd6b9d0c76e02657269e57d3089aaa2b6
216
intellij-crystal-lang
Apache License 2.0
plugins/kotlin/compiler-reference-index/tests/testData/compilerIndex/properties/fromObject/lateinit/Write.kt
ingokegel
72,937,917
false
null
package one.two fun write() { KotlinObject.lateinitVariable = KotlinObject }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
81
intellij-community
Apache License 2.0
src/main/kotlin/work/ruskonert/fentry/adapter/SerializeAdapter.kt
Ruskonert
185,143,383
false
null
/* Fentry: The Flexible-Serialization Entry Copyright (c) 2019 Ruskonert all rights reserved. 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 work.ruskonert.fentry.adapter import com.google.gson.JsonDeserializer import com.google.gson.JsonSerializer @Suppress("UNCHECKED_CAST") abstract class SerializeAdapter<T>(private var reference : Class<*>) : JsonDeserializer<T>, JsonSerializer<T> { fun setReference(c : Class<*>) { this.reference = c } fun getReference() : Class<*> { return this.reference } override fun hashCode(): Int { return reference.hashCode() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as SerializeAdapter<*> if (reference != other.reference) return false return true } }
1
Kotlin
1
2
2326b39ffe0eea256bcc2220f31b2b8be3b3e031
1,882
Fentry
MIT License
z2-kotlin-plugin/src/hu/simplexion/z2/kotlin/ir/localization/LocalizationResourceType.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1043299, "CSS": 127450, "Java": 7583, "HTML": 1560, "JavaScript": 975}
package hu.simplexion.z2.kotlin.ir.localization enum class LocalizationResourceType { Text, Icon }
0
Kotlin
0
1
75b93a7541c7609cd8101c3674b247726d1e2a14
107
z2
Apache License 2.0
prj-website/src/jsMain/kotlin/databinding/LocalDateTarget.kt
simonegiacomelli
473,571,649
false
{"Kotlin": 327484, "HTML": 123796, "TSQL": 4632, "CSS": 1467, "Shell": 301}
package databinding import kotlinx.datetime.LocalDate import kotlinx.datetime.toLocalDate import org.w3c.dom.HTMLElement class LocalDateTarget(override val target: HTMLElement) : TargetProperty<LocalDate?>, HtmlElementObservable { private val pb = HTMLElementBridge(target) override var value: LocalDate? get() = runCatching { pb.value.toLocalDate() }.run { if (isFailure) console.log(exceptionOrNull()) getOrNull() } set(value) = run { pb.value = "$value" } }
0
Kotlin
1
0
a9b9d5c2e96a6aa5afada957e0f6d55cc63801ed
520
kotlin-mpp-starter
Apache License 2.0
app/src/main/kotlin/me/wolszon/crowdie/android/ui/Navigator.kt
Albert221
138,158,098
false
{"Kotlin": 80250}
package me.wolszon.crowdie.android.ui import android.content.Context import android.content.Intent import me.wolszon.crowdie.android.ui.group.GroupActivity import me.wolszon.crowdie.android.ui.landing.LandingActivity class Navigator(private val context: Context) { fun openLandingActivity() { context.startActivity(Intent(context, LandingActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) }) } fun openGroupActivity() { context.startActivity(GroupActivity.createIntent(context).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) }) } }
12
Kotlin
0
8
5f3003f5f41221d2857ac7a007276457e9250450
696
crowdie-android
MIT License
jeorg-kotlin-crums/jeorg-kotlin-crums-3/src/main/kotlin/org/jesperancinha/ktd/crums3/crum13/InAndOutAndWhere.kt
jesperancinha
345,062,636
false
null
package org.jesperancinha.ktd.crums3.crum13 import org.jesperancinha.console.consolerizer.console.ConsolerizerComposer import org.slf4j.Logger import org.slf4j.LoggerFactory import kotlin.random.Random abstract class Ship { override fun toString(): String = "I'm a ship!" open fun addFuelGallons(liters: Long) = run { logger.info("Adding {} litter fuel to ship {} with plate {}", liters, this::class.java, this.hashCode()) } companion object { val logger: Logger = LoggerFactory.getLogger(Ship::class.java) } } class BattleShip : Ship() { override fun toString(): String = "I'm a battleship!" } class SpaceShip : Ship() { override fun toString(): String = "I'm a spaceship!" } /** * Output in short means that T can only be used as a return type */ class ShipWarehouse<out T : Ship>( val ships: List<T> ) { fun readShip(index: Int) = ships[index] } /** * Input in short means that T can only be used as an input type */ class ShipFuelStation<in T : Ship> { fun fuel(ship: T) { ship.addFuelGallons(Random(100).nextLong()) } } class InAndOuts { companion object { private val logger = object { fun info(logText: Any?) = ConsolerizerComposer.out().magenta(logText) fun infoText(logText: Any?) = ConsolerizerComposer.out().green(logText) fun infoTitle(logText: String) = ConsolerizerComposer.outSpace() .cyan(ConsolerizerComposer.title(logText)) } @JvmStatic fun main(args: Array<String> = emptyArray()) { logger.infoTitle("Crum 13 - In and Out") val shipWarehouse = ShipWarehouse(listOf(SpaceShip(), BattleShip())) val fuelStation = ShipFuelStation<Ship>() logger.info("Fueling both ships...") shipWarehouse.ships.forEach { fuelStation.fuel(it) } logger.info("Fueling battle ships...") val fuelStation1 = ShipFuelStation<BattleShip>() shipWarehouse.ships.forEach { try { fuelStation1.fuel(it as BattleShip) } catch (ex: ClassCastException) { logger.info("This ship failed to fuel because it is not a battleship! it is a ${it.javaClass.simpleName} instead!") } } logger.info(shipWarehouse.readShip(0)) logger.info(shipWarehouse.readShip(1)) logger.info("This warehouse only contains battleships") val battleShipWarehouse: ShipWarehouse<BattleShip> = ShipWarehouse(listOf(BattleShip(), BattleShip())) val battleShipFuelStation = ShipFuelStation<BattleShip>() battleShipWarehouse.ships.forEach { battleShipFuelStation.fuel(it) } logger.info(battleShipWarehouse.readShip(0)) logger.info(battleShipWarehouse.readShip(1)) logger.infoText("Kotlin has lots of principles about restrictions. in and out are mainly about restricting T to be used as an input parameter only or as an output parameter only.") } } }
0
Kotlin
1
3
63a9b6cf0998cb594a384d2e47e68ce076f628ef
3,149
jeorg-kotlin-test-drives
Apache License 2.0
openai-client/client/src/commonMain/kotlin/com/xebia/functional/openai/models/RunStepDetailsMessageCreationObject.kt
xebia-functional
629,411,216
false
{"Kotlin": 4211913, "TypeScript": 67083, "Mustache": 15021, "CSS": 6570, "Java": 4360, "JavaScript": 1935, "HTML": 395}
/** * Please note: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress("ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport") package com.xebia.functional.openai.models import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* /** * Details of the message creation by the run step. * * @param type Always `message_creation``. * @param messageCreation */ @Serializable data class RunStepDetailsMessageCreationObject( /* Always `message_creation``. */ @SerialName(value = "type") @Required val type: RunStepDetailsMessageCreationObject.Type, @SerialName(value = "message_creation") @Required val messageCreation: RunStepDetailsMessageCreationObjectMessageCreation ) { /** * Always `message_creation``. * * Values: messageCreation */ @Serializable enum class Type(val value: kotlin.String) { @SerialName(value = "message_creation") messageCreation("message_creation") } }
40
Kotlin
11
117
91b282c6d50aee58b27ad2676eaa77bee4d4036c
1,086
xef
Apache License 2.0
packages/library/src/commonMain/kotlin/io/realm/Realm.kt
john-reynan
354,320,897
true
{"Kotlin": 378513, "SWIG": 10202, "CMake": 2866, "Java": 974}
/* * Copyright 2020 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm import io.realm.internal.NotificationToken import io.realm.internal.RealmModelInternal import io.realm.internal.copyToRealm import io.realm.internal.unmanage import io.realm.interop.NativePointer import io.realm.interop.RealmInterop import kotlin.reflect.KClass // TODO API-PUBLIC Document platform specific internals (RealmInitilizer, etc.) class Realm { private var dbPointer: NativePointer? = null // TODO API-INTERNAL nullable to avoid "'lateinit' modifier is not allowed on properties of primitive types" private lateinit var realmConfiguration: RealmConfiguration companion object { fun open(realmConfiguration: RealmConfiguration): Realm { // TODO API-INTERNAL // IN Android use lazy property delegation init to load the shared library use the // function call (lazy init to do any preprocessing before starting Realm eg: log level etc) // or implement an init method which is a No-OP in iOS but in Android it load the shared library val realm = Realm() realm.realmConfiguration = realmConfiguration realm.dbPointer = RealmInterop.realm_open(realmConfiguration.nativeConfig) return realm } // FIXME API-MUTABLE-REALM This should actually only be possible on a mutable realm, i.e. inside // a transaction // FIXME EVALUATE Should this be on RealmModel instead? fun <T : RealmObject> delete(obj: T) { val internalObject = obj as RealmModelInternal internalObject.`$realm$ObjectPointer`?.let { RealmInterop.realm_object_delete(it) } ?: throw IllegalArgumentException("Cannot delete unmanaged object") internalObject.unmanage() } /** * Observe change. * * Triggers calls to [callback] when there are changes to [obj]. * * To receive asynchronous callbacks this must be called: * - Android: on a thread with a looper * - iOS/macOS: on the main thread (as we currently do not support opening Realms with * different schedulers similarly to * https://github.com/realm/realm-cocoa/blob/master/Realm/RLMRealm.mm#L424) * * Notes: * - Calls are triggered synchronously on a [beginTransaction] when the version is advanced. * - Ignoring the return value will eliminate the possibility to cancel the registration * and will leak the [callback] and potentially the internals related to the registration. */ // @CheckReturnValue Not available for Kotlin? fun <T : RealmObject> observe(obj: T, callback: Callback): Cancellable { val internalObject = obj as RealmModelInternal internalObject.`$realm$ObjectPointer`?.let { val internalCallback = object : io.realm.interop.Callback { override fun onChange(objectChanges: NativePointer) { // FIXME Need to expose change details to the user // https://github.com/realm/realm-kotlin/issues/115 callback.onChange() } } val token = RealmInterop.realm_object_add_notification_callback(it, internalCallback) return NotificationToken(internalCallback, token) } ?: throw IllegalArgumentException("Cannot register listeners on unmanaged object") } } fun beginTransaction() { RealmInterop.realm_begin_write(dbPointer!!) } fun commitTransaction() { RealmInterop.realm_commit(dbPointer!!) } fun cancelTransaction() { TODO() } fun <T : RealmObject> create(type: KClass<T>): T { return io.realm.internal.create(realmConfiguration.schema, dbPointer!!, type) } // Convenience inline method for the above to skip KClass argument inline fun <reified T : RealmObject> create(): T { return create(T::class) } /** * Creates a copy of an object in the Realm. * * This will create a copy of an object and all it's children. Any already managed objects will * not be copied, including the root `instance`. So invoking this with an already managed * object is a no-operation. * * @param instance The object to create a copy from. * @return The managed version of the `instance`. */ fun <T : RealmObject> copyToRealm(instance: T): T { return copyToRealm(realmConfiguration.schema, dbPointer!!, instance) } fun <T : RealmObject> objects(clazz: KClass<T>): RealmResults<T> { return RealmResults( dbPointer!!, @Suppress("SpreadOperator") // TODO PERFORMANCE Spread operator triggers detekt { RealmInterop.realm_query_parse(dbPointer!!, clazz.simpleName!!, "TRUEPREDICATE") }, clazz, realmConfiguration.schema ) } // FIXME Consider adding a delete-all along with query support // https://github.com/realm/realm-kotlin/issues/64 // fun <T : RealmModel> delete(clazz: KClass<T>) fun close() { dbPointer?.let { RealmInterop.realm_close(it) } dbPointer = null } }
0
null
0
0
d83c2cf91eb0f9a0a4136042913f06c7caae7218
5,877
realm-kotlin
DOC License
app/src/main/java/com/example/android/inventory/ui/ItemsRecyclerViewAdapter.kt
AAli9400
89,738,338
false
null
package com.example.android.inventory.ui import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.example.android.inventory.R import com.example.android.inventory.model.Item import kotlinx.android.synthetic.main.items_list_item.view.* class ItemsRecyclerViewAdapter( private var mItems: MutableList<Item>? = null, private val mListener: ListInteractionListener, private val mResources: RecyclerViewResources) : RecyclerView.Adapter<ItemsRecyclerViewAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.items_list_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = mItems?.get(position) var text: String? item?.let { holder.apply { it.picture?.let { picture -> //val pic = BitmapFactory.decodeByteArray(picture, 0, picture.size) mItemImage.setImageBitmap(picture) } mItemName.text = it.name text = when { !it.type.isNullOrBlank() -> mResources.getString(R.string.type) + it.type else -> mResources.getString(R.string.type_unknown) } mItemType.text = text text = when { !it.amount.isNullOrBlank() -> mResources.getString(R.string.amount) + it.amount else -> mResources.getString(R.string.amount_unknown) } mItemAmount.text = text text = when { !it.supplier.isNullOrBlank() -> mResources.getString(R.string.supplier) + it.type else -> mResources.getString(R.string.supplier_unknown) } mItemSupplier.text = text mView.setOnClickListener { _ -> mListener.onRecyclerViewItemClickListener(it) } } } } fun setItems(items: List<Item>?) { mItems = items?.toMutableList() notifyDataSetChanged() } fun getItem(position: Int): Item? { return mItems?.get(position) } fun removeItem(position: Int): Item? { mItems?.let { val itemRemoved = it.removeAt(position) notifyItemRemoved(position) return itemRemoved } return null } fun addItem(item: Item?, position: Int) { mItems?.let { mItems -> item?.let { item -> mItems.add(position, item) notifyItemInserted(position) } } } fun removeAll() { mItems?.let { it.clear() notifyDataSetChanged() } } override fun getItemCount(): Int { mItems?.let { return it.size } return 0 } inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) { val mItemImage: ImageView = mView.iv_item_image val mItemName: TextView = mView.tv_item_name val mItemSupplier: TextView = mView.tv_item_supplier val mItemAmount: TextView = mView.tv_item_amount val mItemType: TextView = mView.tv_type } interface ListInteractionListener { fun onRecyclerViewItemClickListener(item: Item) } interface RecyclerViewResources { fun getString(id: Int): String } }
0
Kotlin
0
1
97b811aa7140af03962d95b93144b7dafab45a67
3,736
Inventory
Apache License 2.0
app/src/main/java/ru/nbsp/pushka/util/AuthBackendUtils.kt
dimorinny
51,604,851
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 11, "Java": 14, "XML": 102, "Kotlin": 258}
package ru.nbsp.pushka.util import android.content.Context import ru.nbsp.pushka.R import javax.inject.Inject import javax.inject.Singleton /** * Created by Dimorinny on 31.05.16. */ @Singleton class AuthBackendUtils @Inject constructor(val context: Context) { companion object { private val PREFIX_MAP = mapOf( "vk" to R.string.vk, "google" to R.string.google ) } fun backendNameById(identity: String): String? { for ((prefix, name) in PREFIX_MAP) { if (identity.startsWith(prefix)) { return context.getString(name) } } return null } }
0
Kotlin
0
0
71ac416b33f628bbcec12fad4776f7abc242c882
671
pushka-android
MIT License
app/src/main/java/com/officehunter/ui/composables/SimpleStarRow.kt
SonOfGillas
792,829,985
false
{"Kotlin": 275316}
package com.officehunter.ui.composables import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.officehunter.R import com.officehunter.data.remote.firestore.entities.Rarity @Composable fun SimpleStarRow(rarity: Rarity){ val numberOfStars = rarity.ordinal+1 Row { repeat(numberOfStars){ Image( painter = painterResource(R.drawable.star), contentDescription = null, modifier = Modifier .width(14.dp) .height(14.dp), colorFilter = ColorFilter.tint( if (rarity==Rarity.UNDISCOVERED) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.primary ) ) } } }
0
Kotlin
0
0
6d259c1eac1c819b41237b3677c49a520d62a006
1,220
OfficeHunter
MIT License
parcelable-stream/src/main/java/com/zero/xera/parcelable/stream/UnstableApi.kt
0xera
746,013,123
false
{"Kotlin": 29394, "Java": 20130}
package com.zero.xera.parcelable.stream @RequiresOptIn(message = "This API is experimental and very unstable") @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) annotation class UnstableApi
0
Kotlin
0
1
22acfcef16584f290c288283ebedde06738ab507
238
parcelable-stream-slice
MIT License
app/src/main/java/com/flyjingfish/graphicsdrawable/Utils.kt
FlyJingFish
772,009,533
false
{"Kotlin": 35947, "Java": 7449}
package com.flyjingfish.graphicsdrawable import android.util.TypedValue val Int.dp get() = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), MyApplication.mInstance.resources.displayMetrics )
0
Kotlin
1
5
f4ead074b6704e20558fe7d8ee96bf0b8522936d
271
GraphicsDrawable
Apache License 2.0
app/src/main/java/website/lizihanglove/newbee/app/NewBeeApplication.kt
lizihanglove
139,587,744
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Markdown": 2, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 33, "Java": 3, "XML": 48}
package website.lizihanglove.newbee.app import android.app.Application import com.orhanobut.logger.AndroidLogAdapter import com.orhanobut.logger.Logger /** * @author lizihanglove * @email <EMAIL> * @date 2018-06-15 * @time 23:59 * @desc */ open class NewBeeApplication:Application(){ override fun onCreate() { super.onCreate() Logger.addLogAdapter(AndroidLogAdapter()) } }
0
Kotlin
1
4
d6be9b89db4278c9adbd9a617be3598c079ccd54
407
Gankotlin
Apache License 2.0
app/src/main/java/website/lizihanglove/newbee/app/NewBeeApplication.kt
lizihanglove
139,587,744
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Markdown": 2, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 33, "Java": 3, "XML": 48}
package website.lizihanglove.newbee.app import android.app.Application import com.orhanobut.logger.AndroidLogAdapter import com.orhanobut.logger.Logger /** * @author lizihanglove * @email <EMAIL> * @date 2018-06-15 * @time 23:59 * @desc */ open class NewBeeApplication:Application(){ override fun onCreate() { super.onCreate() Logger.addLogAdapter(AndroidLogAdapter()) } }
0
Kotlin
1
4
d6be9b89db4278c9adbd9a617be3598c079ccd54
407
Gankotlin
Apache License 2.0
mineinabyss-features/src/main/kotlin/com/mineinabyss/moderation/HelperFeature.kt
MineInAbyss
115,279,675
false
{"Kotlin": 354608}
package com.mineinabyss.moderation import com.mineinabyss.components.moderation.HelperInfo import com.mineinabyss.components.moderation.OldLocSerializer import com.mineinabyss.components.moderation.helperMode import com.mineinabyss.components.moderation.isInHelperMode import com.mineinabyss.components.playerData import com.mineinabyss.geary.papermc.access.toGeary import com.mineinabyss.helpers.luckPerms import com.mineinabyss.idofront.commands.extensions.actions.playerAction import com.mineinabyss.idofront.messaging.error import com.mineinabyss.idofront.messaging.success import com.mineinabyss.idofront.plugin.registerEvents import com.mineinabyss.mineinabyss.core.AbyssFeature import com.mineinabyss.mineinabyss.core.MineInAbyssPlugin import com.mineinabyss.mineinabyss.core.commands import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.bukkit.GameMode import org.bukkit.Material import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack @Serializable @SerialName("helper") class HelperFeature : AbyssFeature { override fun MineInAbyssPlugin.enableFeature() { registerEvents(HelperListener()) commands { mineinabyss { "helper" { playerAction { val player = sender as? Player ?: return@playerAction if (luckPerms.userManager.getUser(player.uniqueId)?.primaryGroup != "helper") { player.error("This command is only for helper-rank players!") } else if (!player.isInHelperMode) player.enterHelperMode() else player.exitHelperMode() } } } tabCompletion { when (args.size) { 1 -> listOf("helper").filter { it.startsWith(args[0]) } else -> null } } } } //TODO Toggle cosmetics? fun Player.enterHelperMode() { if (isInHelperMode) return toGeary().setPersisting(HelperInfo( OldLocSerializer(location.world.uid, location.x, location.y, location.z, location.yaw, location.pitch), gameMode, inventory.contents ?.map { it ?: ItemStack(Material.AIR) } ?: emptyList())) gameMode = GameMode.SPECTATOR inventory.clear() this.playerData.isAffectedByCurse = false success("Entering Helper-Mode") } fun Player.exitHelperMode() { if (!isInHelperMode) return gameMode = helperMode!!.oldGameMode inventory.clear() inventory.contents = helperMode!!.inventory.map { it }.toTypedArray() this.playerData.isAffectedByCurse = true teleport(helperMode!!.oldLocation.toLocation()) toGeary().remove<HelperInfo>() error("Exited Helper-Mode") } }
15
Kotlin
26
88
186de7605ab21d34a0f1178ad9eb6bff34583e59
2,911
MineInAbyss
MIT License
RickAndMorty/app/src/androidTest/java/com/example/rickandmorty/SettingsFragmentTests.kt
diable201
462,816,171
false
{"Kotlin": 72994}
package com.example.rickandmorty import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.example.rickandmorty.ui.settings.SettingsFragment import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class SettingsFragmentTests { private lateinit var stringToBetyped: String @Before fun initValidString() { stringToBetyped = "espresso" } @Test fun typeEditText_matchesSameValue() { launchFragmentInContainer<SettingsFragment>() onView(withId(R.id.editTextSettings)) .perform(typeText(stringToBetyped), closeSoftKeyboard()) onView(withId(R.id.editTextSettings)) .check(matches(withText("espresso"))) } @Test fun clickRadioButtonDark_radioButtonDarkIsChecked() { launchFragmentInContainer<SettingsFragment>() onView(withId(R.id.radio_dark)).perform(click()) //TODO: verify snackbar after clicking onView(withId(R.id.radio_dark)).check(matches(isDisplayed())) onView(withId(R.id.radio_dark)).check(matches(isChecked())) onView(withId(R.id.radio_light)).check(matches(isNotChecked())) } }
0
Kotlin
0
0
673cade0f8d35664c697c1b5baa1046df6a85a15
1,519
AndroidDevelopment
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Coin1.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup public val OutlineGroup.Coin1: ImageVector get() { if (_coin1 != null) { return _coin1!! } _coin1 = Builder(name = "Coin1", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 22.7499f) curveTo(8.0f, 22.7499f, 4.75f, 19.8799f, 4.75f, 16.3499f) verticalLineTo(12.6499f) curveTo(4.75f, 12.2399f, 5.09f, 11.8999f, 5.5f, 11.8999f) curveTo(5.91f, 11.8999f, 6.25f, 12.2399f, 6.25f, 12.6499f) curveTo(6.25f, 15.2699f, 8.72f, 17.2499f, 12.0f, 17.2499f) curveTo(15.28f, 17.2499f, 17.75f, 15.2699f, 17.75f, 12.6499f) curveTo(17.75f, 12.2399f, 18.09f, 11.8999f, 18.5f, 11.8999f) curveTo(18.91f, 11.8999f, 19.25f, 12.2399f, 19.25f, 12.6499f) verticalLineTo(16.3499f) curveTo(19.25f, 19.8799f, 16.0f, 22.7499f, 12.0f, 22.7499f) close() moveTo(6.25f, 16.4599f) curveTo(6.32f, 19.1099f, 8.87f, 21.2499f, 12.0f, 21.2499f) curveTo(15.13f, 21.2499f, 17.68f, 19.1099f, 17.75f, 16.4599f) curveTo(16.45f, 17.8699f, 14.39f, 18.7499f, 12.0f, 18.7499f) curveTo(9.61f, 18.7499f, 7.56f, 17.8699f, 6.25f, 16.4599f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 13.75f) curveTo(9.24f, 13.75f, 6.76f, 12.51f, 5.55f, 10.51f) curveTo(5.03f, 9.66f, 4.75f, 8.67f, 4.75f, 7.65f) curveTo(4.75f, 5.93f, 5.52f, 4.31f, 6.91f, 3.09f) curveTo(8.27f, 1.9f, 10.08f, 1.25f, 12.0f, 1.25f) curveTo(13.92f, 1.25f, 15.72f, 1.9f, 17.09f, 3.08f) curveTo(18.48f, 4.31f, 19.25f, 5.93f, 19.25f, 7.65f) curveTo(19.25f, 8.67f, 18.97f, 9.65f, 18.45f, 10.51f) curveTo(17.24f, 12.51f, 14.76f, 13.75f, 12.0f, 13.75f) close() moveTo(12.0f, 2.75f) curveTo(10.44f, 2.75f, 8.98f, 3.27f, 7.89f, 4.23f) curveTo(6.83f, 5.15f, 6.25f, 6.37f, 6.25f, 7.65f) curveTo(6.25f, 8.4f, 6.45f, 9.1f, 6.83f, 9.73f) curveTo(7.78f, 11.29f, 9.76f, 12.25f, 12.0f, 12.25f) curveTo(14.24f, 12.25f, 16.22f, 11.28f, 17.17f, 9.73f) curveTo(17.56f, 9.1f, 17.75f, 8.4f, 17.75f, 7.65f) curveTo(17.75f, 6.37f, 17.17f, 5.15f, 16.1f, 4.21f) curveTo(15.01f, 3.27f, 13.56f, 2.75f, 12.0f, 2.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 18.75f) curveTo(7.87f, 18.75f, 4.75f, 16.13f, 4.75f, 12.65f) verticalLineTo(7.65f) curveTo(4.75f, 4.12f, 8.0f, 1.25f, 12.0f, 1.25f) curveTo(13.92f, 1.25f, 15.72f, 1.9f, 17.09f, 3.08f) curveTo(18.48f, 4.31f, 19.25f, 5.93f, 19.25f, 7.65f) verticalLineTo(12.65f) curveTo(19.25f, 16.13f, 16.13f, 18.75f, 12.0f, 18.75f) close() moveTo(12.0f, 2.75f) curveTo(8.83f, 2.75f, 6.25f, 4.95f, 6.25f, 7.65f) verticalLineTo(12.65f) curveTo(6.25f, 15.27f, 8.72f, 17.25f, 12.0f, 17.25f) curveTo(15.28f, 17.25f, 17.75f, 15.27f, 17.75f, 12.65f) verticalLineTo(7.65f) curveTo(17.75f, 6.37f, 17.17f, 5.15f, 16.1f, 4.21f) curveTo(15.01f, 3.27f, 13.56f, 2.75f, 12.0f, 2.75f) close() } } .build() return _coin1!! } private var _coin1: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
5,141
VuesaxIcons
MIT License
app/src/main/java/com/example/android/marsphotos/ui/start/StartFragment.kt
vietcong00
510,071,138
false
{"Kotlin": 142265, "Java": 47905}
package com.example.android.marsphotos.ui.start import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.example.android.marsphotos.MainActivity import com.example.android.marsphotos.R import com.example.android.marsphotos.data.EventObserver import com.example.android.marsphotos.data.constant.POSITION_TYPE import com.example.android.marsphotos.databinding.FragmentStartBinding import com.example.android.marsphotos.util.SharedPreferencesUtil class StartFragment : Fragment() { private val viewModel by viewModels<StartViewModel>() private lateinit var viewDataBinding: FragmentStartBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewDataBinding = FragmentStartBinding.inflate(inflater, container, false).apply { viewmodel = viewModel } viewDataBinding.lifecycleOwner = this.viewLifecycleOwner setHasOptionsMenu(false) if (userIsAlreadyLoggedIn()) { viewModel.setupProfile() }else{ viewModel.goToLoginPressed() } return viewDataBinding.root } override fun onResume() { super.onResume() Handler(Looper.getMainLooper()).postDelayed({ if(userIsAlreadyLoggedIn()) { viewModel.goToLoginPressed() } }, 2000) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setupViewModelObservers() } private fun userIsAlreadyLoggedIn(): Boolean { return SharedPreferencesUtil.getUserID(requireContext()) != null } private fun setupViewModelObservers() { viewModel.loginEvent.observe(viewLifecycleOwner, EventObserver { navigateToLogin() }) viewModel.position.observe(requireActivity()) { if (userIsAlreadyLoggedIn()) { when (viewModel.position.value) { POSITION_TYPE.chef -> navigateDirectlyToFoodChef() POSITION_TYPE.waiter -> navigateDirectlyToFoodWaiter() POSITION_TYPE.table -> navigateDirectlyToMenu() } } } } private fun navigateDirectlyToMenu() { (activity as MainActivity).changeNavCustomer() findNavController().navigate(R.id.action_startFragment_to_startSelectFoodFragment) } private fun navigateDirectlyToFoodChef() { (activity as MainActivity).changeNavChef() findNavController().navigate(R.id.action_startFragment_to_navigation_food_chef) } private fun navigateDirectlyToFoodWaiter() { (activity as MainActivity).changeNavWaiter() findNavController().navigate(R.id.action_startFragment_to_navigation_food_waiter) } private fun navigateToLogin() { findNavController().navigate(R.id.action_startFragment_to_loginFragment) } }
0
Kotlin
0
0
b5f5fb61ed28009cc932dc2ffbeaf5b89dbae7a4
3,214
DATN-mobile-app
Apache License 2.0
src/main/kotlin/com/ort/lastwolf/LastwolfApplication.kt
h-orito
288,476,085
false
null
package com.ort.lastwolf import com.ort.dbflute.allcommon.DBFluteBeansJavaConfig import com.ort.lastwolf.fw.config.FirebaseConfig import com.ort.lastwolf.fw.config.LastwolfAppConfig import com.ort.lastwolf.fw.config.LastwolfWebMvcConfigurer import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.context.annotation.Import @SpringBootApplication @Import( DBFluteBeansJavaConfig::class, LastwolfAppConfig::class, LastwolfWebMvcConfigurer::class, FirebaseConfig::class ) class LastwolfApplication fun main(args: Array<String>) { runApplication<LastwolfApplication>(*args) }
7
Kotlin
0
0
0a02f0f62930a310380bf17de4d751319bc46beb
680
lastwolf-api
MIT License
app/src/main/java/com/devtoochi/blood_donation/ui/adapters/GenericAdapter.kt
Toochidennis
779,960,304
false
{"Kotlin": 261675}
package com.devtoochi.blood_donation.ui.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView /** * GenericAdapter for RecyclerView. * * @param itemList List of items to be displayed. * @param itemResLayout Layout resource for individual items. * @param bindItem Function to bind item data to the view. * @param onItemClick Function to handle item click events. */ class GenericAdapter<Model>( private val itemList: MutableList<Model>, private val itemResLayout: Int, private val bindItem: (binding: ViewDataBinding, model: Model) -> Unit, private val onLongClick: ((position: Int) -> Unit)? = null, private val onItemClick: (position: Int) -> Unit ) : RecyclerView.Adapter<GenericAdapter<Model>.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ViewDataBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), itemResLayout, parent, false ) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val model = itemList[position] bindItem(holder.binding, model) holder.itemView.setOnClickListener { onItemClick(position) } holder.itemView.setOnLongClickListener { onLongClick?.invoke(position) true } } override fun getItemCount() = itemList.size inner class ViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) }
0
Kotlin
0
1
f9041d4b83d95d051c5d892d453a991744cd25d3
1,709
Blood-Donation
MIT License
app/src/main/kotlin/be/zvz/covid/remaining/vaccine/Latitude.kt
woobinn
392,902,676
true
{"Gradle Kotlin DSL": 2, "Shell": 1, "YAML": 4, "Markdown": 1, "Git Attributes": 1, "Batchfile": 1, "Text": 1, "Ignore List": 2, "XML": 10, "INI": 1, "Kotlin": 5, "Java": 12}
package be.zvz.covid.remaining.vaccine data class Latitude( val x: Double, val y: Double )
0
null
0
0
96b3cce6c00acd0e28e8a8377dcffab193d37c3a
100
korea-covid-19-remaining-vaccine
Apache License 2.0
utbot-java-fuzzing/src/main/kotlin/org/utbot/fuzzing/spring/SavedEntity.kt
UnitTestBot
480,810,501
false
null
package org.utbot.fuzzing.spring import org.utbot.framework.plugin.api.SpringRepositoryId import org.utbot.framework.plugin.api.UtAssembleModel import org.utbot.framework.plugin.api.UtReferenceModel import org.utbot.framework.plugin.api.util.SpringModelUtils import org.utbot.fuzzer.FuzzedType import org.utbot.fuzzer.FuzzedValue import org.utbot.fuzzer.IdGenerator import org.utbot.fuzzer.fuzzed import org.utbot.fuzzing.FuzzedDescription import org.utbot.fuzzing.JavaValueProvider import org.utbot.fuzzing.Routine import org.utbot.fuzzing.Seed import org.utbot.fuzzing.providers.nullRoutine class SavedEntityProvider( private val idGenerator: IdGenerator<Int>, private val repositoryId: SpringRepositoryId ) : JavaValueProvider { override fun accept(type: FuzzedType): Boolean = type.classId == repositoryId.entityClassId override fun generate(description: FuzzedDescription, type: FuzzedType): Sequence<Seed<FuzzedType, FuzzedValue>> = sequenceOf( Seed.Recursive( construct = Routine.Create(listOf(type)) { values -> val entityValue = values.single() val entityModel = entityValue.model UtAssembleModel( id = idGenerator.createId(), classId = type.classId, modelName = "${repositoryId.repositoryBeanName}.save(${(entityModel as? UtReferenceModel)?.modelName ?: "..."})", instantiationCall = SpringModelUtils.createSaveCallModel( repositoryId = repositoryId, id = idGenerator.createId(), entityModel = entityModel ) ).fuzzed { summary = "%var% = ${repositoryId.repositoryBeanName}.save(${entityValue.summary})" } }, modify = emptySequence(), empty = nullRoutine(type.classId) ) ) }
352
Kotlin
26
85
8227e23a0924a519ce87c5d42b3491aa7db41d0c
2,034
UTBotJava
Apache License 2.0
composeApp/src/commonMain/kotlin/game/presentation/components/FrontCard.kt
ommagtibay
784,569,847
false
{"Kotlin": 43418, "Swift": 1213}
package game.presentation.components import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import memory.composeapp.generated.resources.Res import memory.composeapp.generated.resources.ic_logo import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import theme.AppColor @OptIn(ExperimentalResourceApi::class) @Composable fun FrontCard() { Box( modifier = Modifier .fillMaxSize() .background(AppColor.Snow) .padding(16.dp), contentAlignment = Alignment.Center, ) { Image( modifier = Modifier.fillMaxSize(), painter = painterResource(resource = Res.drawable.ic_logo), contentDescription = null, contentScale = ContentScale.Crop ) } }
0
Kotlin
0
0
956fc2ec68943e7f817c79bcc6738bfa13a0bdf8
1,205
Memory-Compose-Multiplatform
Apache License 2.0
app/src/main/java/com/rubens/conectamedicina/data/reviews/Review.kt
rubens23
771,260,917
false
{"Kotlin": 258586}
package com.rubens.conectamedicina.data.reviews import kotlinx.serialization.Serializable @Serializable data class Review( val userUsername: String, val doctorUsername: String, val rating: Int, val feedbackText: String, val name: String, val timestamp: String )
0
Kotlin
0
0
de8ab5ff6f54675081cd4eee8278140b005277c2
288
ConectaMedicina
Apache License 2.0
hexagon_starters/server.kts
dragneelfps
239,465,178
true
{"Kotlin": 414049, "HTML": 25432, "Scala": 3554, "JavaScript": 2701, "Groovy": 1860, "Dockerfile": 1775, "Shell": 864, "CSS": 704}
#!/bin/env kscript
0
null
0
0
cbe206b61e0344073cb96ff3f811a567206eec9c
20
hexagon
MIT License
src/main/kotlin/com/aswad/coroutines/CoroutinesApplication.kt
anasaswad
256,897,648
false
null
package com.aswad.coroutines import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration import org.springframework.boot.runApplication @SpringBootApplication(exclude = arrayOf(MongoReactiveDataAutoConfiguration::class)) class CoroutinesApplication fun main(args: Array<String>) { runApplication<CoroutinesApplication>(*args) }
0
Kotlin
0
0
bcf4411ad035a55ae152ecdf514c4619800e52b8
436
spring-kotlin
Apache License 2.0
serialization/src/main/kotlin/com/ing/zkflow/serialization/serializer/FixedLengthListSerializer.kt
ing-bank
550,239,957
false
{"Kotlin": 1610321, "Shell": 1609}
package com.ing.zkflow.serialization.serializer import com.ing.zkflow.serialization.FixedLengthKSerializerWithDefault import com.ing.zkflow.serialization.FixedLengthType import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder open class FixedLengthListSerializer<T>( maxSize: Int, valueSerializer: FixedLengthKSerializerWithDefault<T>, ) : FixedLengthKSerializerWithDefault<List<T>> { private val strategy = FixedLengthCollectionSerializer(maxSize, valueSerializer, FixedLengthType.LIST) override val descriptor = strategy.descriptor override val default: List<T> = emptyList() override fun deserialize(decoder: Decoder): List<T> { return strategy.deserialize(decoder) } override fun serialize(encoder: Encoder, value: List<T>) { return strategy.serialize(encoder, value) } }
0
Kotlin
4
9
f6e2524af124c1bdb2480f03bf907f6a44fa3c6c
869
zkflow
MIT License
lang/compiled/src/main/kotlin/com/yandex/yatagan/lang/compiled/CtNamedType.kt
yandex
570,094,802
false
{"Kotlin": 1455421}
/* * Copyright 2022 Yandex LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yandex.yatagan.lang.compiled /** * TODO: Merge this and all the naming logic into `:common` - no need to restrict this to "compiled" implementations. */ interface CtNamedType { /** * Class name. * @see CtTypeNameModel */ val nameModel: CtTypeNameModel }
11
Kotlin
10
231
d0d7b823711c7f5a48cfd76d673ad348407fd904
882
yatagan
Apache License 2.0
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/api/builder/component/LogAreaBuilderTest.kt
Hexworks
94,116,947
false
{"Kotlin": 1614685, "Shell": 64}
package org.hexworks.zircon.api.builder.component import org.hexworks.zircon.api.component.LogArea import org.junit.Before class LogAreaBuilderTest : JvmComponentBuilderTest<LogArea>() { override lateinit var target: LogAreaBuilder @Before override fun setUp() { target = LogAreaBuilder() } }
42
Kotlin
138
738
55a0ccc19a3f1b80aecd5f1fbe859db94ba9c0c6
322
zircon
Apache License 2.0
feature/city-list/src/jsMain/kotlin/com.krossovochkin.kweather.citylist.presentation.localization/LocalizationManagerImpl.kt
krossovochkin
266,317,132
false
null
package com.krossovochkin.kweather.citylist.presentation.localization import com.krossovochkin.i18n.LocalizationManager internal actual class LocalizationManagerImpl : LocalizationManager<LocalizedStringKey> { override fun getString(key: LocalizedStringKey): String { return map(key) } override fun getString(key: LocalizedStringKey, vararg params: Any): String { var string = map(key) params.forEach { param -> string = string.replaceFirst("%s", "$param") } return string } private fun map(key: LocalizedStringKey): String { return when (key) { LocalizedStringKey.CityList_CityNameHint -> "City Name" LocalizedStringKey.CityList_UseCurrentLocation -> "Current Location" } } }
0
Kotlin
2
37
727d74e19020f1be508af87ced18c53e5ee4fca2
798
KWeather
Apache License 2.0
presentation/src/main/java/com/tamimattafi/pizza/android/presentation/fragments/global/pizza/PizzaDiffCallBack.kt
tamimattafi
428,131,583
false
{"Kotlin": 96172}
package com.tamimattafi.pizza.android.presentation.fragments.global.pizza import com.tamimattafi.pizza.android.presentation.core.recycler.SimpleDiffUtilCallback import com.tamimattafi.pizza.domain.model.Pizza class PizzaDiffCallBack( oldData: List<Pizza>, newData: List<Pizza> ) : SimpleDiffUtilCallback<Pizza>( oldData, newData ) { override fun areItemIdentitiesTheSame(oldItem: Pizza, newItem: Pizza): Boolean = oldItem.id == newItem.id override fun areDisplayContentsTheSame(oldItem: Pizza, newItem: Pizza): Boolean = oldItem.name == newItem.name && oldItem.description == newItem.description && oldItem.price == newItem.price && oldItem.imageUrls.first() == newItem.imageUrls.first() }
0
Kotlin
1
0
b0732e71ca1aeb4b6934fa2ec512c61620adc5b9
781
i-pizza-android
Apache License 2.0
app/src/main/java/com/vpaliy/mediaplayer/domain/model/RequestError.kt
vpaliy
92,111,841
false
null
package com.vpaliy.mediaplayer.domain.model sealed class RequestError object Connection : RequestError() object FailedRequest : RequestError()
0
null
13
56
bedd632358e604063fd29f00c63d2ad7c3487767
143
android-music-app
Apache License 2.0
app/src/main/java/com/example/compose_weather_app/data/repository/WeatherScreenPreferencesRepositoryImpl.kt
Drakime
603,802,754
false
null
package com.example.compose_weather_app.data.repository import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.example.compose_weather_app.common.Constants.WEATHER_SCREEN_PREFERENCES_DATASTORE_NAME import com.example.compose_weather_app.domain.repository.WeatherScreenPreferencesRepository import kotlinx.coroutines.flow.first import javax.inject.Inject class WeatherScreenPreferencesRepositoryImpl @Inject constructor( private val dataStore: DataStore<Preferences> ) : WeatherScreenPreferencesRepository { override suspend fun putString(key: String, value: String) { val preferenceKey = stringPreferencesKey(key) dataStore.edit { it[preferenceKey] = value } } override suspend fun getString(key: String): String? { return try { val preferenceKey = stringPreferencesKey(key) val preference = dataStore.data.first() preference[preferenceKey] } catch (e:Exception) { e.printStackTrace() null } } }
0
Kotlin
0
0
b171e32f7841bd19a01591461d9bcff0b0bf33f4
1,293
Compose_Weather_App
The Unlicense
src/main/kotlin/link/kotlin/scripts/OkHttpExtensions.kt
milos85vasic
93,749,291
true
{"Kotlin": 2475700, "TypeScript": 9399, "HTML": 5694, "CSS": 5256, "JavaScript": 3963, "Shell": 591}
package link.kotlin.scripts import okhttp3.Call import okhttp3.Callback import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import java.io.IOException import java.util.concurrent.CompletableFuture import kotlin.coroutines.experimental.Continuation import kotlin.coroutines.experimental.suspendCoroutine class OkHttpException(val request: Request, val exception: Exception) : RuntimeException(exception) suspend fun Call.await(): Response = suspendCoroutine<Response> { cont: Continuation<Response> -> this.enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { cont.resume(response) } override fun onFailure(call: Call, exception: IOException) { cont.resumeWithException(OkHttpException(call.request(), exception)) } }) } fun Call.async(): CompletableFuture<Response> { val future = CompletableFuture<Response>() this.enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { future.complete(response) } override fun onFailure(call: Call, exception: IOException) { future.completeExceptionally(OkHttpException(call.request(), exception)) } }) return future } fun <T> okhttp(call: (OkHttpClient) -> T): T { val client = OkHttpClient() client.dispatcher().maxRequests = 200 client.dispatcher().maxRequestsPerHost = 100 try { return call(client) } finally { client.dispatcher().cancelAll() client.dispatcher().executorService().shutdown() } }
0
Kotlin
0
3
fb76a934c588c6a649f6e90531b64b14996eb785
1,640
awesome-kotlin
Creative Commons Zero v1.0 Universal
src/main/kotlin/Web3jFactory.kt
lyr408
588,592,076
false
null
import org.web3j.protocol.Web3j import org.web3j.protocol.http.HttpService object Web3jFactory { fun buildWeb3j(url: String) = Web3j.build(HttpService(url)) }
0
Kotlin
40
55
0fb728f59562d2b409e7976e80c39421fd7cc3f9
164
CryptocurrencyWallet
Apache License 2.0
app/src/main/java/com/haldny/dragonball/MainActivity.kt
haldny
771,170,616
false
{"Kotlin": 58917}
package com.haldny.dragonball import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.haldny.dragonball.design.theme.DragonBallComposeTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { DragonBallComposeTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainApp() } } } } } @Preview(showBackground = true) @Composable fun DefaultPreview() { DragonBallComposeTheme { MainApp() } }
0
Kotlin
0
0
360f823818d830a24fb1f76d6cc959530faece32
1,199
DragonBall-Compose
Apache License 2.0
backend/src/main/kotlin/com/tinder/dating/nosqlData/repo/ProfileRepository.kt
Sashimi4
527,875,352
false
null
package com.tinder.dating.nosqlData.repo import com.tinder.dating.nosqlData.domain.Profile import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.stereotype.Repository import java.util.* @Repository interface ProfileRepository: MongoRepository<Profile, UUID> { fun findByGenderAndGenderPreference(): List<Profile> fun findProfileByName(name: String): Profile }
7
Kotlin
0
1
5c4605d98cb3ce3522c8f07df271efee20d42ef3
412
M151
MIT License
src/main/kotlin/com/between_freedom_and_space/mono_backend/profiles/internal/icon/api/models/CreateProfileIconRequest.kt
Between-Freedom-and-Space
453,797,438
false
{"Kotlin": 614504, "HTML": 8733, "Dockerfile": 503, "Shell": 166}
package com.between_freedom_and_space.mono_backend.profiles.internal.icon.api.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import javax.validation.constraints.Min import javax.validation.constraints.NotBlank @Serializable data class CreateProfileIconRequest( @SerialName("icon_base64") @get:NotBlank val iconBase64: String, @SerialName("profile_id") @get:Min(1, message = "Profile id can't be less than 1") val profileId: Long, )
0
Kotlin
0
1
812d8257e455e7d5b1d0c703a66b55ed2e1dcd35
502
Mono-Backend
Apache License 2.0
app/src/main/java/com/kasuminotes/ui/app/equip/UniqueCraftList.kt
chilbi
399,723,451
false
null
package com.kasuminotes.ui.app.equip import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.kasuminotes.R import com.kasuminotes.data.UniqueCraft import com.kasuminotes.ui.components.BgBorderColumn import com.kasuminotes.ui.components.ColumnLabel import com.kasuminotes.utils.UrlUtil @Composable fun UniqueCraftList( craftList: List<UniqueCraft>, onEnhanceLevelChange: (Int) -> Unit, modifier: Modifier = Modifier ) { BgBorderColumn(modifier, 0.dp) { ColumnLabel(stringResource(R.string.synthetic_material), 8.dp) Column( Modifier .verticalScroll(rememberScrollState()) .padding(4.dp, 0.dp, 8.dp, 4.dp) ) { craftList.forEach { craftItem -> Row(verticalAlignment = Alignment.CenterVertically) { CraftItem( imageUrl = UrlUtil.getEquipIconUrl(craftItem.heartId), consumeSum = craftItem.heartSum, selected = false, enabled = false, onClick = {} ) Spacer(Modifier.width(8.dp)) CraftItem( imageUrl = UrlUtil.getItemIconUrl(craftItem.memoryId), consumeSum = craftItem.memorySum, selected = false, enabled = false, onClick = {} ) Spacer(Modifier.weight(1f)) Button(onClick = { onEnhanceLevelChange(craftItem.unlockLevel) }) { Text(text = craftItem.unlockLevel.toString()) } } } } } }
0
Kotlin
0
0
0339b1dc44a57d0b2ef18fdd9314a3b7c717fa62
2,336
KasumiNotes
Apache License 2.0
interne-eventer/src/main/kotlin/no/nav/paw/arbeidssokerregisteret/intern/v1/SituasjonMottatt.kt
navikt
698,089,423
false
{"Kotlin": 63804, "Dockerfile": 608}
package no.nav.paw.arbeidssokerregisteret.intern.v1 import no.nav.paw.arbeidssokerregisteret.intern.v1.vo.Metadata import no.nav.paw.arbeidssokerregisteret.intern.v1.vo.Situasjon import java.util.* data class SituasjonMottatt( override val hendelseId: UUID, override val identitetsnummer: String, val situasjon: Situasjon ): Hendelse { override val hendelseType: String = situasjonMottattHendelseType override val metadata: Metadata = situasjon.metadata }
0
Kotlin
0
0
eeaffb3262d05e2398c8fb8e64787ba7044408b5
477
paw-arbeidssokerregisteret-event-prosessor
MIT License
server/src/test/kotlin/ch/frequenzdieb/common/BaseHelper.kt
bendsoft
217,017,882
false
null
package ch.frequenzdieb.common import org.springframework.data.mongodb.core.MongoTemplate abstract class BaseHelper( protected val mongoTemplate: MongoTemplate, private val entityClass: Class<*> ) { init { Dsl.mongoTemplate = mongoTemplate } companion object Dsl { @DslMarker annotation class HelperDsl lateinit var mongoTemplate: MongoTemplate @HelperDsl fun <T : BaseEntity> T.insert(): T = mongoTemplate.insert(this) @HelperDsl fun <T : BaseEntity> List<T>.insert(): List<T> = this.map { it.insert() } } fun resetCollection() { mongoTemplate.dropCollection(entityClass) } private val charPool : List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9') fun createRandomString(stringLength: Int) = (1..stringLength) .map { kotlin.random.Random.nextInt(0, charPool.size) } .map(charPool::get) .joinToString("") }
0
Kotlin
0
0
ef31be5e5a46811be7bb745200431ef025013292
974
frequenzdieb-homepage
MIT License
kdenticon/src/main/kotlin/com/github/thibseisel/kdenticon/rendering/SvgPath.kt
thibseisel
109,754,408
false
null
/* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.thibseisel.kdenticon.rendering /** * Represents a SVG path element. * * This class can be used as a builder: you may call any `add*` method to add drawings to the SVG path in order, * then call [toString] to obtain it as a string that can be written to a SVG file. */ internal class SvgPath { private val pathBuilder = StringBuilder() /** * Adds a circle to this SVG path. * @param location * @param diameter * @param counterClockwise */ fun addCircle(location: PointF, diameter: Float, counterClockwise: Boolean) { // Circles are drawn using "arc-to" SVG instructions val sweepFlag = if (counterClockwise) "0" else "1" val radius = diameter / 2f pathBuilder.append("""M${location.x} ${location.y + radius} a$radius,$radius 0 1, $sweepFlag ${diameter},0 a$radius,$radius 0 1, $sweepFlag ${-diameter},0""".trimIndent()) } /** * Adds a polygon to this SVG path. * @param points the points this polygon consists of. */ fun addPolygon(points: Array<PointF>) { // Prevent failures if the polygon has no point if (points.isNotEmpty()) { // The first point of this path defined with an M command pathBuilder.append("M${points[0].x} ${points[0].y}") for (point in points) { // Draw segments using absolute Line-to commands pathBuilder.append("L${point.x} ${point.y}") } // Close the path with a Z command pathBuilder.append("Z") } } override fun toString(): String { return pathBuilder.toString() } }
1
Kotlin
0
2
52696593537f83ba3c853894d5d83af0e27a7fdb
2,312
Kdenticon
Apache License 2.0
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/coronatest/type/common/ResultScheduler.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.coronatest.type.common import androidx.work.WorkInfo import androidx.work.WorkManager import de.rki.coronawarnapp.util.coroutine.await import java.util.concurrent.TimeUnit open class ResultScheduler( private val workManager: WorkManager, ) { internal suspend fun isScheduled(workerName: String) = workManager.getWorkInfosForUniqueWork(workerName) .await() .any { it.isScheduled } internal val WorkInfo.isScheduled: Boolean get() = state == WorkInfo.State.RUNNING || state == WorkInfo.State.ENQUEUED companion object { /** * Kind initial delay in minutes for periodic work for accessibility reason * * @see TimeUnit.SECONDS */ internal const val TEST_RESULT_PERIODIC_INITIAL_DELAY = 10L } }
6
null
514
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
836
cwa-app-android
Apache License 2.0
app/src/main/java/ken/projects/imagegalleryapp/ui/theme/Color.kt
aakifnehal
680,914,711
false
null
package ken.projects.imagegalleryapp.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Purple = Color(0xFF2b2d61) val Cyan = Color(0xFF43cbff) val Teal200 = Color(0xFF03DAC5)
0
Kotlin
0
0
40572e968ee5df2b3719f4aa8e2ef4d861603634
283
FlickArt
MIT License
app/src/main/java/com/decimalab/todokotlin/fragments/list/ListFragment.kt
ShakilAhmedShaj
291,435,138
false
null
package com.decimalab.todokotlin.fragments.list import android.app.AlertDialog import android.os.Bundle import android.view.* import android.widget.SearchView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.decimalab.todokotlin.R import com.decimalab.todokotlin.data.models.ToDoData import com.decimalab.todokotlin.data.viewmodel.ToDoViewModel import com.decimalab.todokotlin.databinding.FragmentListBinding import com.decimalab.todokotlin.fragments.BaseViewModel import com.decimalab.todokotlin.fragments.list.adapter.ListAdapter import com.decimalab.todokotlin.utils.hideKeyboard import com.google.android.material.snackbar.Snackbar import jp.wasabeef.recyclerview.animators.SlideInUpAnimator class ListFragment : Fragment(), SearchView.OnQueryTextListener { private val mToDoViewModel: ToDoViewModel by viewModels() private val mBaseViewModel: BaseViewModel by viewModels() private var _binding: FragmentListBinding? = null private val binding get() = _binding!! private val adapter: ListAdapter by lazy { ListAdapter() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { //Data binding _binding = FragmentListBinding.inflate(inflater, container, false) binding.lifecycleOwner = this binding.mBaseViewModel = mBaseViewModel //Setup RecyclerView setupRecyclerView() mToDoViewModel.getAllData.observe(viewLifecycleOwner, Observer { data -> mBaseViewModel.checkIfDatabaseEmpty(data) adapter.setData(data) }) setHasOptionsMenu(true) // Hide soft keyboard hideKeyboard(requireActivity()) return binding.root } private fun setupRecyclerView() { val recyclerView = binding.recyclerView recyclerView.adapter = adapter recyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) recyclerView.itemAnimator = SlideInUpAnimator().apply { addDuration = 300 } swipeToDelete(recyclerView) } private fun swipeToDelete(recyclerView: RecyclerView) { val swipeToDeleteCallback = object : SwipeToDelete() { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val deletedItem = adapter.dataList[viewHolder.adapterPosition] // Delete Item mToDoViewModel.deleteItem(deletedItem) Toast.makeText( requireContext(), "Deleted", Toast.LENGTH_SHORT ).show() adapter.notifyItemRemoved(viewHolder.adapterPosition) // Restore Deleted Item restoreDeletedData(viewHolder.itemView, deletedItem) } } val itemTouchHelper = ItemTouchHelper(swipeToDeleteCallback) itemTouchHelper.attachToRecyclerView(recyclerView) } private fun restoreDeletedData(view: View, deletedItem: ToDoData) { val snackBar = Snackbar.make( view, "Deleted '${deletedItem.title}'", Snackbar.LENGTH_LONG ) snackBar.setAction("Undo") { mToDoViewModel.insertData(deletedItem) } snackBar.show() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.list_fragment_menu, menu) val search = menu.findItem(R.id.menu_search) val searchView = search.actionView as? SearchView searchView?.isSubmitButtonEnabled = true searchView?.setOnQueryTextListener(this) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_delete_all -> confirmRemoval() R.id.menu_priority_high -> mToDoViewModel.sortByHighPriority.observe( this, Observer { adapter.setData(it) }) R.id.menu_priority_low -> mToDoViewModel.sortByLowPriority.observe( this, Observer { adapter.setData(it) }) } return super.onOptionsItemSelected(item) } override fun onQueryTextSubmit(query: String?): Boolean { if (query != null) { searchThroughDatabase(query) } return true } override fun onQueryTextChange(query: String?): Boolean { if (query != null) { searchThroughDatabase(query) } return true } private fun searchThroughDatabase(query: String) { val searchQuery = "%$query%" mToDoViewModel.searchDatabase(searchQuery).observe(this, Observer { list -> list?.let { adapter.setData(it) } }) } private fun confirmRemoval() { val builder = AlertDialog.Builder(requireContext()) builder.setPositiveButton("Yes") { _, _ -> mToDoViewModel.deleteAll() Toast.makeText( requireContext(), "Successfully Removed Everything!", Toast.LENGTH_SHORT ).show() } builder.setNegativeButton("No") { _, _ -> } builder.setTitle("Delete everything?") builder.setMessage("Are you sure you want to remove everything?") builder.create().show() } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
3
5
d4888971b3d5f0ff510e36ab9195c24da2e49993
5,838
TodoKotlin
The Unlicense
plugins/markdown/core/src/org/intellij/plugins/markdown/model/psi/headers/MarkdownHeaderSymbol.kt
JetBrains
2,489,216
false
null
package org.intellij.plugins.markdown.model.psi.headers import com.intellij.openapi.util.NlsSafe import org.intellij.plugins.markdown.model.psi.MarkdownSymbolWithUsages internal interface MarkdownHeaderSymbol: MarkdownSymbolWithUsages { val text: @NlsSafe String val anchorText: @NlsSafe String }
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
303
intellij-community
Apache License 2.0
vire-engine/src/main/kotlin/net/voxelpi/vire/engine/kernel/generated/declaration/SettingDeclaration.kt
VoxelPi
700,036,011
false
{"Kotlin": 336452}
package net.voxelpi.vire.engine.kernel.generated.declaration @Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD) public annotation class SettingDeclaration( val name: String = "", )
2
Kotlin
0
0
425bd5d0c2fee1125f059b7a6308ab8d5409c7b7
194
Vire
MIT License
app/src/main/java/com/denicks21/onboarding/screens/OnboardingPage.kt
ndenicolais
611,802,325
false
null
package com.denicks21.onboarding.screens import android.annotation.SuppressLint import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.Image import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import com.denicks21.onboarding.navigation.NavScreens import com.denicks21.onboarding.navigation.OnboardingScreen import com.denicks21.onboarding.ui.components.FinishButton import com.denicks21.onboarding.ui.components.TopComponent import com.denicks21.onboarding.ui.theme.DarkGrey import com.denicks21.onboarding.ui.theme.LightYellow import com.denicks21.onboarding.viewmodels.HomeViewModel import com.google.accompanist.pager.* import kotlinx.coroutines.launch @SuppressLint("UnusedMaterialScaffoldPaddingParameter") @ExperimentalAnimationApi @ExperimentalPagerApi @Composable fun OnboardingPage( navController: NavHostController, welcomeViewModel: HomeViewModel = hiltViewModel(), ) { val pages = listOf( OnboardingScreen.FirstScreen, OnboardingScreen.SecondScreen, OnboardingScreen.ThirdScreen, OnboardingScreen.FourthScreen ) val pagerState = rememberPagerState() val scope = rememberCoroutineScope() Scaffold( topBar = { TopComponent( onBackClick = { if (pagerState.currentPage + 1 > 1) scope.launch { pagerState.scrollToPage(pagerState.currentPage - 1) } }, onSkipClick = { navController.navigate(NavScreens.HomePage.route) } ) }, bottomBar = { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { HorizontalPagerIndicator( pagerState = pagerState, activeColor = if (isSystemInDarkTheme()) LightYellow else DarkGrey, inactiveColor = if (isSystemInDarkTheme()) DarkGrey else LightYellow, indicatorWidth = 10.dp, indicatorHeight = 10.dp ) Spacer(modifier = Modifier.height(10.dp)) FinishButton( modifier = Modifier .height(60.dp) .width(350.dp) .padding(bottom = 10.dp), pagerState = pagerState ) { welcomeViewModel.saveOnBoardingState(completed = true) navController.popBackStack() navController.navigate(NavScreens.HomePage.route) } } }, backgroundColor = Color.White ) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(20.dp)) HorizontalPager( count = 4, state = pagerState, verticalAlignment = Alignment.CenterVertically ) { position -> PagerScreen(onBoardingScreen = pages[position]) } } } } @Composable fun PagerScreen(onBoardingScreen: OnboardingScreen) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(10.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = onBoardingScreen.title, modifier = Modifier.fillMaxWidth(), color = DarkGrey, fontSize = 50.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center ) Image( modifier = Modifier .width(400.dp) .height(400.dp), painter = painterResource(id = onBoardingScreen.image), contentDescription = "Pager image" ) Text( text = onBoardingScreen.description, modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp), color = DarkGrey, fontSize = 20.sp, fontWeight = FontWeight.Medium, textAlign = TextAlign.Center ) } }
0
Kotlin
0
0
0b40bf6c2a179f88056473f3d27df4676b037822
5,003
Onboarding
MIT License
src/main/kotlin/com/masahirosaito/spigot/homes/datas/PlayerData.kt
MasahiroSaito
81,658,813
false
null
package com.masahirosaito.spigot.homes.datas import com.masahirosaito.spigot.homes.exceptions.NoDefaultHomeException import com.masahirosaito.spigot.homes.exceptions.NoNamedHomeException import com.masahirosaito.spigot.homes.homedata.PlayerHome import com.masahirosaito.spigot.homes.nms.HomesEntity import org.bukkit.Chunk import org.bukkit.OfflinePlayer data class PlayerData( val offlinePlayer: OfflinePlayer, var defaultHome: HomesEntity? = null, val namedHomes: MutableList<HomesEntity> = mutableListOf() ) { fun tearDown() { defaultHome?.despawnEntities() namedHomes.forEach { it.despawnEntities() } } fun toPlayerHome(): PlayerHome = PlayerHome().apply { defaultHome?.let { defaultHomeData = it.toHomeData() } namedHomes.forEach { namedHomeData.add(it.toHomeData()) } } fun getHomesEntitiesIn(chunk: Chunk): List<HomesEntity> { return mutableListOf<HomesEntity>().apply { defaultHome?.let { if (it.inChunk(chunk)) add(it) } namedHomes.forEach { if (it.inChunk(chunk)) add(it) } } } fun load(): PlayerData = this.apply { defaultHome?.let { if (it.location.chunk.isLoaded) it.spawnEntities() } namedHomes.forEach { if (it.location.chunk.isLoaded) it.spawnEntities() } } fun hasNamedHome(homeName: String): Boolean { return namedHomes.any { it.homeName == homeName } } fun getNamedHome(homeName: String): HomesEntity { return namedHomes.find { it.homeName == homeName } ?: throw NoNamedHomeException(offlinePlayer, homeName) } fun removeDefaultHome() { if (defaultHome != null) { defaultHome!!.despawnEntities() defaultHome = null } else { throw NoDefaultHomeException(offlinePlayer) } } fun removeNamedHome(homeName: String) { if (hasNamedHome(homeName)) { getNamedHome(homeName).despawnEntities() namedHomes.removeIf { it.homeName == homeName } } else { throw NoNamedHomeException(offlinePlayer, homeName) } } }
12
Kotlin
0
1
f07ac116147877eec13821a1c750b3bd8f1dd725
2,154
Homes
Apache License 2.0
gradle/plugins/setup/src/main/kotlin/impl/Catalog.kt
fluxo-kt
566,869,438
false
{"Kotlin": 540610, "Shell": 968, "Dockerfile": 791}
package impl import org.gradle.api.Project import org.gradle.api.artifacts.ExternalModuleDependencyBundle import org.gradle.api.artifacts.MinimalExternalModuleDependency import org.gradle.api.artifacts.VersionCatalog import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.api.provider.Provider import org.gradle.kotlin.dsl.getByType import org.gradle.plugin.use.PluginDependency import kotlin.jvm.optionals.getOrNull internal val Project.catalogs: VersionCatalogsExtension get() = extensions.getByType(VersionCatalogsExtension::class) internal val Project.libsCatalog: VersionCatalog get() = catalogs.named("libs") internal fun VersionCatalog.onLibrary(alias: String, body: (Provider<MinimalExternalModuleDependency>) -> Unit): Boolean { val opt = findLibrary(alias) if (opt.isPresent) { body(opt.get()) return true } return false } internal fun VersionCatalog.d(alias: String): Provider<MinimalExternalModuleDependency> { return findLibrary(alias).get() } internal fun VersionCatalog.onBundle( alias: String, body: (Provider<ExternalModuleDependencyBundle>) -> Unit, ): Boolean { val opt = findBundle(alias) if (opt.isPresent) { body(opt.get()) return true } return false } internal fun VersionCatalog.b(alias: String): Provider<ExternalModuleDependencyBundle> { return findBundle(alias).get() } internal fun VersionCatalog.plugin(alias: String): Provider<PluginDependency> { return findPlugin(alias).get() } internal fun VersionCatalog.onPlugin(alias: String, body: (PluginDependency) -> Unit): Boolean { val opt = findPlugin(alias) if (opt.isPresent) { body(opt.get().get()) return true } return false } internal fun VersionCatalog.onVersion(alias: String, body: (String) -> Unit): Boolean { val opt = findVersion(alias) if (opt.isPresent) { body(opt.get().toString()) return true } return false } internal fun VersionCatalog.v(alias: String): String { return findVersion(alias).get().toString() } internal fun VersionCatalog.optionalVersion(alias: String): String? { return findVersion(alias).getOrNull()?.toString() }
9
Kotlin
1
28
aac0f6ba9118e9b3d20ec1cca934e230f3ec8066
2,224
fluxo
Apache License 2.0