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
app/src/main/java/com/example/flirtcompose/network/RequestApiService.kt
OverLordN7
612,099,774
false
null
package com.example.flirtcompose.network import com.example.flirtcompose.model.Request import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface RequestApiService { @GET("ByLiked") suspend fun getJournals( @Query("page") page:Int, ): Response<Request> }
0
Kotlin
0
1
ffc77ad182d26ab9bb51b482f6d371d228654637
307
FlirtCompose
The Unlicense
app/src/main/java/com/benli/kotlinweather/main/weather/model/WeatherModel.kt
beilly
98,971,871
false
null
package com.benli.kotlinweather.main.weather.model /** * Created by shibenli on 2017/8/14. */ data class WeatherModel( val lcation: String = "", val forecasts: List<Forecast> ) data class Forecast( val time: String = "", val iconText: String = "", val temperature: String = "" ) fun temperature(country: String, openWeatherMapDegrees: Double): String { val degrees: String if (country == "US") { degrees = kelvinToFahrenheit(openWeatherMapDegrees).toString() + "\uf045" } else { degrees = kelvinToCelsius(openWeatherMapDegrees).toString() + "\uf03c" } return degrees } fun kelvinToCelsius(degrees: Double): Long { return Math.round(degrees - 273.15) } fun kelvinToFahrenheit(degrees: Double): Long { return Math.round(degrees * 9 / 5 - 459.67) }
0
Kotlin
0
1
74ad306c941d49a22012d67aa6c05309a81c0452
837
KotlinWeather
Apache License 2.0
src/main/kotlin/com/github/sgdan/kiss/syntax/Function.kt
sgdan
164,282,700
false
null
package com.github.sgdan.kiss.syntax import com.github.sgdan.kiss.KissLanguage import com.github.sgdan.kiss.ast.FunctionNode class Function( val name: String, private val expression: Syntax ) : Syntax() { lateinit var node: FunctionNode override fun createNode(kl: KissLanguage) { node = FunctionNode(kl) expression.createNode(kl) } override fun resolve(functions: Map<String, Function>) { node.body = expression.node() expression.resolve(functions) } }
1
Kotlin
0
1
d8b52ab6bc4469f68ae599c1690ed929e0923989
528
kiss
MIT License
components-core/src/main/java/com/adyen/checkout/components/flow/FlowExtensions.kt
leandromagnabosco
533,836,687
false
null
/* * Copyright (c) 2022 Adyen N.V. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by josephj on 19/8/2022. */ package com.adyen.checkout.components.flow import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow /** * This method creates a shared flow that produces a single value at a time (buffer = 1), with priority to the latest * (BufferOverflow.DROP_OLDEST). * * Being a shared flow, the values emitted behave as events (as opposed to state) which means if an observer re-observes * the flow, they will NOT receive a value that they already collected earlier. * * Having replay = 1 ensures that an observer that started observing this flow after it has already emitted an event * will be able to collect it and will not miss out on any past events. */ @Suppress("FunctionName") fun <T> MutableSingleEventSharedFlow(): MutableSharedFlow<T> = MutableSharedFlow( replay = 1, extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST )
2
Kotlin
0
0
c154e989a08f1dc76cf90f6949878621cbbfa644
1,088
testsonarcloud
MIT License
app/src/main/java/com/bignerdranch/android/photogallery/api/GalleryItem.kt
JRSiwiecki
705,941,996
false
{"Kotlin": 21623}
package com.bignerdranch.android.photogallery.api import android.net.Uri import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class GalleryItem( val title: String, val id: String, @Json(name = "url_s") val url: String, val owner: String ) { val photoPageUri: Uri get() = Uri.parse("https://www.flickr.com/photos/") .buildUpon() .appendPath(owner) .appendPath(id) .build() }
0
Kotlin
0
0
85a43de40d5474535cc4cafd64e6e36e48c7e8f1
509
PhotoGallery
MIT License
jvm/src/test/kotlin/fr/xgouchet/elmyr/jvm/factories/LocalDateTimeForgeryFactoryTest.kt
xgouchet
92,030,208
false
{"Kotlin": 480997, "Java": 23870}
package fr.xgouchet.elmyr.jvm.factories import fr.xgouchet.elmyr.annotation.Forgery import fr.xgouchet.elmyr.junit5.ForgeConfiguration import fr.xgouchet.elmyr.junit5.ForgeExtension import fr.xgouchet.elmyr.jvm.JvmConfigurator import java.time.LocalDateTime import java.time.ZoneOffset import kotlin.math.abs import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(ForgeExtension::class) @ForgeConfiguration(JvmConfigurator::class) class LocalDateTimeForgeryFactoryTest { @Test fun `forge date within one year`(@Forgery fakeDate: LocalDateTime) { val now = LocalDateTime.now() val zoneOffset = ZoneOffset.UTC val diff = abs(fakeDate.toEpochSecond(zoneOffset) - now.toEpochSecond(zoneOffset)) assertThat(diff) .isLessThanOrEqualTo(ONE_YEAR_SEC) } @Test fun `forges different values`( @Forgery date1: LocalDateTime, @Forgery date2: LocalDateTime ) { assertThat(date1.compareTo(date2)).isNotEqualTo(0) } companion object { private const val ONE_YEAR_SEC: Long = 365L * 24L * 60L * 60L } }
6
Kotlin
3
83
0ab6c3a673fd8771e9fc02f0676a3a886992a1ef
1,199
Elmyr
MIT License
src/main/java/io/github/sergkhram/managers/idb/IdbKtManager.kt
SergKhram
499,425,493
false
{"Java": 259512, "Kotlin": 23424, "Shell": 1768, "Dockerfile": 1446, "JavaScript": 1438, "CSS": 273}
package io.github.sergkhram.managers.idb import io.github.sergkhram.data.entity.AppDescription import io.github.sergkhram.data.entity.Device import io.github.sergkhram.data.entity.DeviceDirectoryElement import io.github.sergkhram.data.entity.Host import io.github.sergkhram.data.enums.DeviceType import io.github.sergkhram.data.enums.IOSPackageType import io.github.sergkhram.data.enums.OsType import io.github.sergkhram.idbClient.IOSDebugBridgeClient import io.github.sergkhram.idbClient.entities.address.DomainSocketAddress import io.github.sergkhram.idbClient.entities.address.TcpAddress import io.github.sergkhram.idbClient.entities.requestsBody.files.ContainerKind import io.github.sergkhram.idbClient.entities.requestsBody.files.FileContainer import io.github.sergkhram.idbClient.entities.requestsBody.files.LsRequestBody import io.github.sergkhram.idbClient.entities.response.DescribeKtResponse import io.github.sergkhram.idbClient.requests.app.ListAppsRequest import io.github.sergkhram.idbClient.requests.files.LsRequest import io.github.sergkhram.idbClient.requests.files.PullRequest import io.github.sergkhram.idbClient.requests.media.ScreenshotRequest import io.github.sergkhram.idbClient.util.exportFile import io.github.sergkhram.managers.Manager import io.github.sergkhram.managers.Logger import io.github.sergkhram.utils.Const import kotlinx.coroutines.* import lombok.extern.slf4j.Slf4j import org.springframework.stereotype.Service import java.io.File import java.util.* import java.util.stream.Collectors import kotlin.collections.HashMap @Service @Slf4j open class IdbKtManager: Manager { val idb: IOSDebugBridgeClient = IOSDebugBridgeClient() companion object : Logger() override fun getListOfDevices(host: Host?): List<Device> { return runBlocking { val response = idb.getTargetsList() return@runBlocking if(host == null) convert(response, null) ?: emptyList() else convert( response.filter { if(it.address is TcpAddress) { (it.address as TcpAddress).host.contains(host.address) } else { (it.address as DomainSocketAddress).path.contains(host.address) } }, host ) ?: emptyList() } } override fun connectToHost(host: String?, port: Int?) { runBlocking { host?.let { withTimeoutOrNull(Const.TIMEOUT.toLong()) { val processUuid = UUID.randomUUID() log.info("[$processUuid] Connecting to host ${"$host:$port"} process started") idb.connectToCompanion( TcpAddress(host, port ?: 0) ) log.info("[$processUuid] Connecting to host ${"$host:$port"} process finished") } } } } override fun disconnectHost(host: String?, port: Int?) { if(host!=null && port!=null) { val processUuid = UUID.randomUUID() log.info("[$processUuid] Disconnecting host ${"$host:$port"} process started") idb.disconnectCompanion( TcpAddress(host, port) ) log.info("[$processUuid] Disconnecting host ${"$host:$port"} process finished") } } override fun getDevicesStates(): Map<String, String> { val devicesMap: HashMap<String, String> = HashMap() val devices = getListOfDevices(null) devicesMap.putAll(devices.map { Pair(it.serial, it.state) }) return devicesMap } override fun rebootDevice(device: Device?) { TODO("Not yet implemented") } override fun makeScreenshot(device: Device?, filePath: String): File { device?.let { runBlocking { idb.execute( ScreenshotRequest(), it.serial ).exportFile(filePath) } } return File(filePath) } override fun getAppsList(device: Device?): List<AppDescription> { return device?.let { runBlocking { idb.execute( ListAppsRequest(), it.serial ).appsList.map { AppDescription( it.bundleId, it.name, "", it.processState.name, it.processState.name.contains("Running") ) } } } ?: emptyList() } private fun convert(iosDevices: List<DescribeKtResponse>, host: Host?): List<Device>? { return iosDevices.parallelStream().map { val device = Device() device.serial = it.targetDescription.udid device.state = it.targetDescription.state device.isActive = it.targetDescription.state != "Shutdown" device.host = host device.osType = OsType.IOS device.name = it.targetDescription.name device.deviceType = DeviceType.valueOf(it.targetDescription.targetType.uppercase()) device.osVersion = it.targetDescription.osVersion device }.collect(Collectors.toList()) } open fun downloadFile( device: Device, deviceDirectoryElement: DeviceDirectoryElement, iosPackageType: IOSPackageType, destination: String ): File { val file = File(destination + File.separator + deviceDirectoryElement.name) return runBlocking { idb.execute( PullRequest( deviceDirectoryElement.path + "/" + deviceDirectoryElement.name, FileContainer( kind = ContainerKind.valueOf(iosPackageType.name) ) ), device.serial ).exportFile(file.absolutePath + ".gz") } } open fun downloadFolder( device: Device, deviceDirectoryElement: DeviceDirectoryElement, iosPackageType: IOSPackageType, destination: String ): File { val file = File(destination + File.separator + deviceDirectoryElement.name) return runBlocking { idb.execute( PullRequest( deviceDirectoryElement.path + "/" + deviceDirectoryElement.name, FileContainer( kind = ContainerKind.valueOf(iosPackageType.name) ) ), device.serial ).exportFile(file.absolutePath + ".gz") } } open fun getListFiles(device: Device, path: String, iosPackageType: IOSPackageType ): List<DeviceDirectoryElement> { return runBlocking { val response = idb.execute( LsRequest( LsRequestBody.SingleLsRequestBody( path, FileContainer(kind = ContainerKind.valueOf(iosPackageType.name)) ) ), device.serial ) response.filesList.map { file -> DeviceDirectoryElement().apply { name = file.path this.path = path } } } } }
1
null
1
1
470961d43892b8b4a04af6c41d77f94102388637
7,460
DeviceIO
Apache License 2.0
scuttlebutt-client-lib/src/main/kotlin/org/apache/tuweni/scuttlebutt/lib/RawRequestService.kt
Consensys
693,991,624
true
{"SVG": 2, "Java Properties": 2, "Markdown": 64, "Gradle": 64, "Shell": 3, "EditorConfig": 1, "YAML": 13760, "Git Attributes": 1, "Batchfile": 1, "Text": 33, "Ignore List": 2, "Git Config": 1, "Kotlin": 393, "TOML": 8, "Java": 443, "XML": 18, "JSON": 17343, "JavaScript": 4, "CSS": 1, "HTML": 8, "SQL": 5, "INI": 3, "ANTLR": 2, "Public Key": 1, "Dockerfile": 2}
// Copyright The Tuweni Authors // SPDX-License-Identifier: Apache-2.0 package org.apache.tuweni.scuttlebutt.lib import com.fasterxml.jackson.core.JsonProcessingException import org.apache.tuweni.scuttlebutt.rpc.RPCAsyncRequest import org.apache.tuweni.scuttlebutt.rpc.RPCResponse import org.apache.tuweni.scuttlebutt.rpc.RPCStreamRequest import org.apache.tuweni.scuttlebutt.rpc.mux.ConnectionClosedException import org.apache.tuweni.scuttlebutt.rpc.mux.Multiplexer import org.apache.tuweni.scuttlebutt.rpc.mux.ScuttlebuttStreamHandler import java.util.function.Function /** * Intended to make RPC requests which aren't supported by the higher level services possible. * * We cannot support every desired RPC request with higher level abstractions because it's possible to define custom * plugins with custom endpoints. */ class RawRequestService(private val multiplexer: Multiplexer) { @Throws(JsonProcessingException::class) suspend fun makeAsyncRequest(request: RPCAsyncRequest): RPCResponse { return multiplexer.makeAsyncRequest(request) } @Throws(JsonProcessingException::class, ConnectionClosedException::class) fun openStream(request: RPCStreamRequest, streamFactory: Function<Runnable, ScuttlebuttStreamHandler>) { multiplexer.openStream(request, streamFactory) } }
1
Java
2
0
d780a654afc90f5fd3c16540d592259487e0a190
1,303
tuweni
Apache License 2.0
agp-7.1.0-alpha01/tools/base/common/src/main/java/com/android/utils/concurrency/EvictingExecutorService.kt
jomof
502,039,754
true
{"Markdown": 63, "Java Properties": 56, "Shell": 31, "Batchfile": 12, "Proguard": 30, "CMake": 10, "Kotlin": 3443, "C++": 594, "Java": 4446, "HTML": 34, "Makefile": 14, "RenderScript": 22, "C": 30, "JavaScript": 2, "CSS": 3, "INI": 11, "Filterscript": 11, "Prolog": 1, "GLSL": 1, "Gradle Kotlin DSL": 5, "Python": 12, "Dockerfile": 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.android.utils.concurrency import com.google.common.collect.EvictingQueue import java.util.NoSuchElementException import java.util.Queue import java.util.concurrent.AbstractExecutorService import java.util.concurrent.ExecutorService import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * [ExecutorService] that only allows [maxQueueingTasks] tasks waiting to be executed. If the limit is * reached, the next task to arrive will preempt the first one in the queue. * The tasks are executed on the given [delegateExecutor]. * * This class is thread-safe */ class EvictingExecutor(private val delegateExecutor: ExecutorService, maxQueueingTasks: Int = 1) : AbstractExecutorService() { private val evictingQueueLock = ReentrantLock() private val evictingQueue: Queue<Runnable> = EvictingQueue.create<Runnable>(maxQueueingTasks) private fun queueProcessor() = delegateExecutor.execute inner@{ // For each offer call we always queue a remove so it will always be true that // (number of removes) >= (number of elements) val runnable = try { evictingQueueLock.withLock { evictingQueue.remove() } } catch (e: NoSuchElementException) { return@inner } runnable.run() } override fun isTerminated(): Boolean = delegateExecutor.isTerminated override fun execute(command: Runnable) { if (delegateExecutor.isTerminated) { return } evictingQueueLock.withLock { val before = evictingQueue.size evictingQueue.offer(command) if (before != evictingQueue.size) { queueProcessor() } } } override fun shutdown() { shutdownNow() } override fun shutdownNow(): MutableList<Runnable> { val pendingRunnables = mutableListOf<Runnable>() evictingQueueLock.withLock { evictingQueue.removeAll { pendingRunnables.add(it) } } return pendingRunnables.apply { addAll(delegateExecutor.shutdownNow()) } } override fun isShutdown(): Boolean = delegateExecutor.isShutdown override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = delegateExecutor.awaitTermination(timeout, unit) }
1
null
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
3,016
CppBuildCacheWorkInProgress
Apache License 2.0
backend-spring-kotlin/src/testIntegration/kotlin/lunchbox/util/ocr/NginxTest.kt
rori-dev
29,542,877
false
null
@file:Suppress("ktlint:standard:max-line-length") package lunchbox.util.ocr import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.bodyToMono import org.testcontainers.containers.BindMode import org.testcontainers.containers.NginxContainer import org.testcontainers.containers.wait.strategy.HttpWaitStrategy import org.testcontainers.junit.jupiter.Container import org.testcontainers.junit.jupiter.Testcontainers import java.io.File import java.nio.file.Paths import java.time.Duration /** * Der Test ist unsinnig. Er demonstriert nur die Funktionsweise von TestContainers' nginx Modul. */ @Testcontainers class NginxTest { companion object { // provide test resources in Docker-ed nginx (via TestContainers) @Container private val resourcesContainer = KtNginxContainer() .withFileSystemBind(Paths.get("src/test/resources").toString(), "/usr/share/nginx/html", BindMode.READ_ONLY) .waitingFor(HttpWaitStrategy()) private fun resourcesHost() = resourcesContainer.getBaseUrl("http", 80) } @Test fun `serve test resource files`() { val resourceFile = "menus/feldkueche/ocr/2016-10-10.jpg.txt" val httpResult = WebClient.create("${resourcesHost()}/$resourceFile") .get() .retrieve() .bodyToMono<String>() .block(Duration.ofSeconds(5)) ?: "" httpResult shouldBeEqualTo File("src/test/resources/$resourceFile").readText() } } // BUGFIX: Kotlin does not support SELF types // -> https://github.com/testcontainers/testcontainers-java/issues/1010 class KtNginxContainer : NginxContainer<KtNginxContainer>("nginx:alpine")
2
null
2
1
91fa2d558d56ee2b05bb3058c842f3656fa7fab3
1,763
lunchbox
MIT License
common/src/main/kotlin/combo/sat/constraints/Arithmetic.kt
rasros
148,620,275
false
null
package combo.sat.constraints import combo.model.IntVar import combo.sat.* import combo.sat.constraints.Relation.* import combo.util.* import kotlin.math.abs import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.min import kotlin.random.Random /** * Linear constraint encodes a linear sum [relation] with a [degree], e.g. 2*x2 - 3*x4 <= 2. * Some solvers cannot handle [Relation.NE] because it cannot be expressed as a linear relation. * Intermediate results are stored in a 32 bit integer so there is a real risk of integer overflow for large weights. */ class Linear(override val literals: IntHashMap, val weights: IntArray, val degree: Int, val relation: Relation) : PropositionalConstraint { override val priority: Int get() = 500 - literals.size val lowerBound = weights.sumBy { min(0, it) } val upperBound = weights.sumBy { max(0, it) } private val average = max(1, weights.sumBy { it.absoluteValue } / weights.size) init { assert(weights.size == literals.size) assert(literals.isNotEmpty()) } override operator fun not() = Linear(literals, weights, degree, !relation) override fun cacheUpdate(cacheResult: Int, newLit: Int) = cacheResult + if (newLit in literals) weights[literals[newLit]] else -weights[literals[!newLit]] override fun cache(instance: Instance): Int { var sum = 0 for (entry in literals.entryIterator()) { val lit = entry.key() val index = entry.value() if (instance.literal(lit.toIx()) == lit) sum += weights[index] } return sum } override fun violations(instance: Instance, cacheResult: Int): Int { val absoluteViolations = relation.violations(cacheResult, degree) val approximateViolations = absoluteViolations / average return if (approximateViolations == 0 && absoluteViolations != 0) 1 else approximateViolations.coerceAtMost(literals.size) } override fun unitPropagation(unit: Int): PropositionalConstraint { val ix1 = literals[unit, -1] val ix2 = literals[!unit, -1] return if (ix1 >= 0 || ix2 >= 0) { val litCopy = literals.copy().apply { if (ix1 >= 0) remove(unit) else remove(!unit) } val weightIx = if (ix1 >= 0) literals[unit] else literals[!unit] val d = degree - if (ix1 >= 0) weights[weightIx] else 0 val adjustedLower = lowerBound - min(0, weights[weightIx]) val adjustedUpper = upperBound - max(0, weights[weightIx]) return if (litCopy.size == 0) { assert(adjustedLower == 0) assert(adjustedUpper == 0) if (relation.violations(0, d) == 0) Tautology else Empty } else if (relation.isEmpty(adjustedLower, adjustedUpper, d)) Empty else if (relation.isTautology(adjustedLower, adjustedUpper, d)) Tautology else { val weightCopy = weights.removeAt(weightIx) for (lit in litCopy) { if (litCopy[lit] > weightIx) // This does not change hash position so is safe from concurrent modification litCopy[lit] = litCopy[lit] - 1 } return Linear(litCopy, weightCopy, d, relation) } } else this } /** * Unit literals for Arithmetic constraint is tricky because there can be free literals in a constraint containing * unit literals. For example if some weights are 0. Or -1x1 + 10x2 > 8, here x2=1 and x1 can be 0 or 1. * For this reason we skip unit literals for Arithmetic constraint. */ override fun unitLiterals() = throw UnsupportedOperationException() override fun isUnit() = false override fun coerce(instance: Instance, rng: Random) { val card = this var value = cache(instance) val perm = card.literals.permutation(rng) if (card.relation == LE || card.relation == LT || card.relation == EQ) { val d = if (card.relation == LT) card.degree - 1 else card.degree while (value > d && perm.hasNext()) { val lit = perm.nextInt() if (instance.literal(lit.toIx()) == lit) { instance.flip(lit.toIx()) value-- } } } if (card.relation == GE || card.relation == GT || card.relation == EQ) { val d = if (card.relation == GT) card.degree + 1 else card.degree while (value < d && perm.hasNext()) { val lit = perm.nextInt() if (instance.literal(lit.toIx()) != lit) { instance.flip(lit.toIx()) value++ } } } if (card.relation == NE && value == card.degree && perm.hasNext()) { instance.flip(perm.nextInt().toIx()) } } override fun toString() = literals.joinToString(", ", "Linear(", " ${relation.operator} $degree)") { "${weights[literals[it]]}x$it" } } /** * Cardinality constraint encodes a linear equality [relation] with a [degree]. * Some solvers cannot handle [Relation.NE] because it cannot be expressed as a linear relation. */ class Cardinality(override val literals: IntCollection, val degree: Int, val relation: Relation) : PropositionalConstraint { override val priority: Int get() = 400 - literals.size init { assert(degree >= 0) assert(literals.isNotEmpty()) } override operator fun not() = Cardinality(literals, degree, !relation) override fun violations(instance: Instance, cacheResult: Int) = relation.violations(cacheResult, degree).coerceAtMost(literals.size) override fun unitPropagation(unit: Int): PropositionalConstraint { val match = unit in literals return if (match || !unit in literals) { val copy = literals.mutableCopy(nullValue = 0).apply { if (match) remove(unit) else remove(!unit) } val d = degree - if (match) 1 else 0 return if (relation.isEmpty(0, copy.size, d)) Empty else if (relation.isTautology(0, copy.size, d)) Tautology else { val card = Cardinality(copy, d, relation) if (card.isUnit()) Conjunction(collectionOf(*card.unitLiterals())) else card } } else this } override fun isUnit() = relation.isUnit(0, literals.size, degree) override fun unitLiterals(): IntArray { assert(isUnit()) return when (relation) { GT -> literals.toArray() GE -> literals.toArray() LE -> literals.toArray().mapArray { !it } LT -> literals.toArray().mapArray { !it } NE -> throw IllegalArgumentException() EQ -> if (degree == 0) literals.toArray().mapArray { !it } else literals.toArray() } } override fun coerce(instance: Instance, rng: Random) { val card = this var value = cache(instance) val perm = card.literals.permutation(rng) if (card.relation == LE || card.relation == LT || card.relation == EQ) { val d = if (card.relation == LT) card.degree - 1 else card.degree while (value > d && perm.hasNext()) { val lit = perm.nextInt() if (instance.literal(lit.toIx()) == lit) { instance.flip(lit.toIx()) value-- } } } if (card.relation == GE || card.relation == GT || card.relation == EQ) { val d = if (card.relation == GT) card.degree + 1 else card.degree while (value < d && perm.hasNext()) { val lit = perm.nextInt() if (instance.literal(lit.toIx()) != lit) { instance.flip(lit.toIx()) value++ } } } if (card.relation == NE && value == card.degree && perm.hasNext()) { instance.flip(perm.nextInt().toIx()) } } override fun toString() = literals.joinToString(", ", "Cardinality(", " ${relation.operator} $degree)") { it.toString() } } class CardinalityVar(valueLiterals: IntCollection, val degreeVar: IntVar, val varIndex: Int, val parentLiteral: Int, val relation: Relation) : PropositionalConstraint { override val priority: Int get() = 400 - literals.size override val literals: IntUnionCollection init { assert(valueLiterals.isNotEmpty()) val l = varIndex.toLiteral(true) val degreeLiterals = IntRangeCollection(l, l + degreeVar.nbrValues - 1) literals = if (parentLiteral == 0) IntUnionCollection(valueLiterals, degreeLiterals) else IntUnionCollection(valueLiterals, IntUnionCollection(degreeLiterals, collectionOf(parentLiteral))) } private val baseCardinality = Cardinality(literals.a, 0, relation) override fun cacheUpdate(cacheResult: Int, newLit: Int) = cacheResult + when { newLit in literals.a -> 1 !newLit in literals.a -> -1 else -> 0 } override fun cache(instance: Instance) = baseCardinality.cache(instance) override operator fun not() = CardinalityVar(literals.a, degreeVar, varIndex, parentLiteral, !relation) // TODO unitPropagation by having a units as field override fun violations(instance: Instance, cacheResult: Int): Int { val degree = degreeVar.valueOf(instance, varIndex, parentLiteral) ?: return 0 return relation.violations(cacheResult, degree).coerceAtMost(literals.a.size) } override fun coerce(instance: Instance, rng: Random) { val degree = degreeVar.valueOf(instance, varIndex, parentLiteral) ?: return Cardinality(literals.a, degree, relation).coerce(instance, rng) } override fun toString() = literals.a.joinToString(", ", "CardinalityVar(", " ${relation.operator} $varIndex)") { it.toString() } } class LinearVar(valueLiterals: IntHashMap, val weights: IntArray, val degreeVar: IntVar, val varIndex: Int, val parentLiteral: Int, val relation: Relation) : PropositionalConstraint { override val priority: Int get() = 500 - literals.size override val literals: IntUnionCollection init { assert(valueLiterals.isNotEmpty()) val l = varIndex.toLiteral(true) val degreeLiterals = IntRangeCollection(l, l + degreeVar.nbrValues - 1) literals = if (parentLiteral == 0) IntUnionCollection(valueLiterals, degreeLiterals) else IntUnionCollection(valueLiterals, IntUnionCollection(degreeLiterals, collectionOf(parentLiteral))) } private val baseLinear = Linear(literals.a as IntHashMap, weights, 0, relation) override fun cacheUpdate(cacheResult: Int, newLit: Int) = cacheResult + when { newLit in literals.a -> 1 !newLit in literals.a -> -1 else -> 0 } override fun cache(instance: Instance) = baseLinear.cache(instance) override operator fun not() = LinearVar(literals.a as IntHashMap, weights, degreeVar, varIndex, parentLiteral, !relation) // TODO unitPropagation by having a units as field override fun violations(instance: Instance, cacheResult: Int): Int { val degree = degreeVar.valueOf(instance, varIndex, parentLiteral) ?: return 0 return relation.violations(cacheResult, degree).coerceAtMost(literals.a.size) } override fun coerce(instance: Instance, rng: Random) { val degree = degreeVar.valueOf(instance, varIndex, parentLiteral) ?: return Linear(literals.a as IntHashMap, weights, degree, relation).coerce(instance, rng) } override fun toString() = literals.a.joinToString(", ", "LinearVar(", " ${relation.operator} $varIndex)") { "${weights[(literals.a as IntHashMap)[it]]}x$it" } } enum class Relation(val operator: String) { GT(">") { override fun violations(value: Int, degree: Int) = max(0, 1 + degree - value) override fun isTautology(lowerBound: Int, upperBound: Int, degree: Int) = degree < lowerBound override fun isUnit(lowerBound: Int, upperBound: Int, degree: Int) = degree == upperBound - 1 }, GE(">=") { override fun violations(value: Int, degree: Int) = max(0, degree - value) override fun isTautology(lowerBound: Int, upperBound: Int, degree: Int) = degree <= lowerBound override fun isUnit(lowerBound: Int, upperBound: Int, degree: Int) = degree == upperBound }, LE("<=") { override fun violations(value: Int, degree: Int) = max(0, value - degree) override fun isTautology(lowerBound: Int, upperBound: Int, degree: Int) = degree >= upperBound override fun isUnit(lowerBound: Int, upperBound: Int, degree: Int) = degree == lowerBound }, LT("<") { override fun violations(value: Int, degree: Int) = max(0, 1 + value - degree) override fun isTautology(lowerBound: Int, upperBound: Int, degree: Int) = degree > upperBound override fun isUnit(lowerBound: Int, upperBound: Int, degree: Int) = degree == lowerBound + 1 }, NE("!=") { override fun violations(value: Int, degree: Int) = if (value == degree) 1 else 0 override fun isEmpty(lowerBound: Int, upperBound: Int, degree: Int) = (lowerBound == upperBound && lowerBound == degree) override fun isTautology(lowerBound: Int, upperBound: Int, degree: Int) = degree !in lowerBound..upperBound override fun isUnit(lowerBound: Int, upperBound: Int, degree: Int) = false }, EQ("=") { override fun violations(value: Int, degree: Int) = abs(value - degree) override fun isEmpty(lowerBound: Int, upperBound: Int, degree: Int) = degree !in lowerBound..upperBound override fun isTautology(lowerBound: Int, upperBound: Int, degree: Int) = (lowerBound == upperBound && lowerBound == degree) override fun isUnit(lowerBound: Int, upperBound: Int, degree: Int) = degree == lowerBound || degree == upperBound }; operator fun not(): Relation { return when (this) { GT -> LE GE -> LT LE -> GT LT -> GE NE -> EQ EQ -> NE } } abstract fun violations(value: Int, degree: Int): Int open fun isEmpty(lowerBound: Int, upperBound: Int, degree: Int) = violations(upperBound, degree) != 0 && violations(lowerBound, degree) != 0 abstract fun isTautology(lowerBound: Int, upperBound: Int, degree: Int): Boolean abstract fun isUnit(lowerBound: Int, upperBound: Int, degree: Int): Boolean }
0
Kotlin
1
2
4e133cbf332dc48ddd65eef2f8366241627c2365
14,679
combo
Apache License 2.0
app/src/main/java/com/wololo/hulkify/ui/splash/SplashActivity.kt
msayan
141,748,886
false
null
package com.wololo.hulkify.ui.splash import android.animation.Animator import android.animation.ValueAnimator import android.content.Intent import android.media.MediaPlayer import android.os.Bundle import android.os.Handler import android.os.Looper import android.support.annotation.RawRes import android.support.v7.app.AppCompatActivity import android.widget.FrameLayout import android.widget.ImageView import com.wololo.hulkify.R import com.wololo.hulkify.ui.main.MainActivity import com.wololo.hulkify.utils.extensions.show private const val DEFAULT_ANIM_DURATION = 1700L class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) val wololoImageView = findViewById<ImageView>(R.id.imageview_wololo) val hulkImageView = findViewById<ImageView>(R.id.imageview_hulk) startAlphaAnimation(wololoImageView, hulkImageView) startMoveAnimation(wololoImageView) playSound(R.raw.wololo) } private fun startMoveAnimation(wololoImageView: ImageView?) { val marginAnimator = ValueAnimator.ofInt(0, 170).apply { duration = DEFAULT_ANIM_DURATION addUpdateListener { animation -> val value = animation.animatedValue as Int wololoImageView?.layoutParams = (wololoImageView?.layoutParams as FrameLayout.LayoutParams).apply { setMargins(0, 0, 0, value) } wololoImageView?.requestLayout() } } marginAnimator.start() } private fun startAlphaAnimation(wololoImageView: ImageView?, hulkImageView: ImageView?) { val alphaAnimator = ValueAnimator.ofFloat(0f, 1f).apply { duration = DEFAULT_ANIM_DURATION addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) { } override fun onAnimationEnd(animation: Animator?) { playSound(R.raw.household038) hulkImageView?.show() Handler(Looper.getMainLooper()).postDelayed({ startActivity(Intent(this@SplashActivity, MainActivity::class.java)) finish() }, 700) } override fun onAnimationCancel(animation: Animator?) { } override fun onAnimationStart(animation: Animator?) { } }) addUpdateListener { animation -> val animatedValue = animation.animatedValue as Float wololoImageView?.alpha = animatedValue wololoImageView?.requestLayout() } } alphaAnimator.start() } private fun playSound(@RawRes resId: Int) { val player = MediaPlayer.create(this, resId) player.start() } }
1
null
1
5
6b174dae47682d714ca2e961c4602967cf0c659a
3,007
hulkify
Apache License 2.0
app/src/main/java/com/skydoves/waterdays/consts/LocalNames.kt
skydoves
100,711,724
false
null
/* * Copyright (C) 2016 skydoves * * 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.skydoves.waterdays.consts /** * Developed by skydoves on 2017-08-18. * Copyright (c) 2017 skydoves rights reserved. */ object LocalNames { fun getLocalName(index: Int): String { when (index) { 1 -> return "경기도" 2 -> return "강원도" 3 -> return "경상남도" 4 -> return "경상북도" 5 -> return "광주광역시" 6 -> return "대구광역시" 7 -> return "대전광역시" 8 -> return "부산광역시" 9 -> return "울산광역시" 10 -> return "인천광역시" 11 -> return "전라남도" 12 -> return "전라북도" 13 -> return "충청북도" 14 -> return "충청남도" 15 -> return "제주특별자치도" else -> return "서울특별시" } } }
1
Kotlin
23
75
0196d34d71e11d0466e8e08e5ceab788e9d7fbbb
1,238
WaterDrink
Apache License 2.0
app/src/main/java/com/disruption/cookcentral/models/search/SearchedRecipe.kt
Fbada006
255,243,946
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "YAML": 1, "JSON": 3, "Proguard": 1, "Java": 2, "XML": 48, "Kotlin": 42}
package com.disruption.cookcentral.models.search data class SearchedRecipe( var id: Int = 0, var title: String? = null, var readyInMinutes: Int = 0, var servings: Int = 0, var image: String? = null)
0
Kotlin
0
0
bba7c12f0a615b16a10fd2bffea5a92704474df1
241
Cook-Central
Apache License 2.0
app/src/main/java/org/fattili/luckymusic/ui/view/main/song/edit/SongsEditModelFactory.kt
dengzhenli
354,794,474
false
null
package org.fattili.luckymusic.ui.view.main.song.edit import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.fattili.luckymusic.data.SongRepository import org.fattili.luckymusic.data.SongsRepository /** * 2020/10/28 * @author dengzhenli * 歌单编辑 */ class SongsEditModelFactory(private val repository: SongsRepository ) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { return SongsEditViewModel(repository) as T } }
1
Kotlin
0
1
869d5714a1a9fa4c131da4e833dfcb0856bc3549
548
LuckyMusic
Apache License 2.0
plugins/editorconfig/src/org/editorconfig/language/psi/reference/EditorConfigDeclarationReference.kt
hieuprogrammer
284,920,751
true
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.psi.reference import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceBase import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement class EditorConfigDeclarationReference(node: EditorConfigDescribableElement) : PsiReferenceBase<EditorConfigDescribableElement>(node) { override fun resolve(): PsiElement? = myElement }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
534
intellij-community
Apache License 2.0
app/src/main/java/org/simple/clinic/newentry/PatientEntryUi.kt
simpledotorg
132,515,649
false
{"Kotlin": 6129044, "Shell": 1660, "HTML": 545}
package org.simple.clinic.newentry import org.simple.clinic.newentry.country.InputFields import org.simple.clinic.widgets.ageanddateofbirth.DateOfBirthAndAgeVisibility interface PatientEntryUi { fun setDateOfBirthAndAgeVisibility(visibility: DateOfBirthAndAgeVisibility) fun showIdentifierSection() fun hideIdentifierSection() fun nextButtonShowInProgress() fun enableNextButton() fun setColonyOrVillagesAutoComplete(colonyOrVillageList: List<String>) fun setupUi(inputFields: InputFields) }
13
Kotlin
73
236
ff699800fbe1bea2ed0492df484777e583c53714
508
simple-android
MIT License
implementation/src/main/kotlin/com/aoc/fuel/calculator/strategy/FuelCalculationStrategy.kt
TomPlum
227,887,094
false
null
package com.aoc.fuel.calculator.strategy import kotlin.math.floor abstract class FuelCalculationStrategy { /** * The strategy contract. * @param mass The mass of the module whose fuel requirements are being calculated. * @return The quantity of fuel required for the given module [mass]. */ abstract fun calculateRequirements(mass: Int): Int /** * Fuel required to launch a given module is based on its [mass]. * Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. * @return fuel quantity */ protected fun calculateModuleFuel(mass: Int) : Int = (floor(mass.toDouble() / 3) - 2).toInt() }
7
null
1
2
12d47cc9c50aeb9e20bcf110f53d097d8dc3762f
708
advent-of-code-2019
Apache License 2.0
gradle-plugin/src/main/kotlin/com/athaydes/wasm/WasmGradlePlugin.kt
andrewaylett
476,364,503
false
null
package com.athaydes.wasm import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaBasePlugin import org.gradle.api.tasks.SourceSetContainer import org.gradle.api.tasks.compile.AbstractCompile class WasmGradlePlugin : Plugin<Project> { override fun apply(project: Project) { project.pluginManager.apply(JavaBasePlugin::class.java) val sourceSetContainer = project.extensions.getByType(SourceSetContainer::class.java) sourceSetContainer.forEach { sourceSet -> val name = sourceSet.getCompileTaskName("wasm") val source = project.objects.sourceDirectorySet("wasm", "Web Assembly") source.srcDir("src/" + sourceSet.name + "/wasm") source.destinationDirectory.set(project.layout.buildDirectory.dir("classes/wasm/${sourceSet.name}")) val compileWasm = project.tasks.register(name, CompileWasmTask::class.java) { it.description = "Compiles the " + sourceSet.name + " WASM" it.destinationDirectory.set(source.destinationDirectory) it.source = source it.classpath = project.objects.fileCollection() } project.tasks.getByName(sourceSet.classesTaskName).dependsOn(name) source.compiledBy(compileWasm, AbstractCompile::getDestinationDirectory) sourceSet.extensions.add(source.name, source) project.dependencies.add(sourceSet.implementationConfigurationName, project.files(source.classesDirectory)) project.dependencies.add(sourceSet.compileOnlyConfigurationName, "eu.aylett.asmble:annotations") } } }
5
null
1
3
e6b0cb60033435d25aad1cef720a21d231703afe
1,703
asmble
MIT License
shared/src/commonMain/kotlin/ui/JobsScreen.kt
Pulkitjndl
723,968,507
false
{"Kotlin": 34088, "Swift": 650}
package ui import androidx.compose.runtime.Composable @Composable fun JobsScreen() { }
0
Kotlin
0
0
7ae80d7d5b3ef7bc080947f0c8047c293e174ff4
88
LearningApp
MIT License
src/main/kotlin/ru/krindra/vknorthtypes/newsfeed/NewsfeedList.kt
kravandir
745,597,090
false
{"Kotlin": 633233}
package ru.krindra.vknorthtypes.newsfeed import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class NewsfeedList ( @SerialName("title") val title: String, @SerialName("id") val id: Long, )
0
Kotlin
0
0
508d2d1d59c4606a99af60b924c6509cfec6ef6c
247
VkNorthTypes
MIT License
src/main/kotlin/xtex/minecraftServerPropsDumper/analyzer/Analyzer.kt
xtexChooser
586,400,650
false
null
package xtex.minecraftServerPropsDumper.analyzer import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import xtex.minecraftServerPropsDumper.mjapi.ensureServerJar import xtex.minecraftServerPropsDumper.mjapi.fetchGameVersion import xtex.minecraftServerPropsDumper.util.ensureFile import java.time.Instant import java.time.format.DateTimeFormatter suspend fun analyze(version: String): AnalyzeReport { val releaseTime = DateTimeFormatter.ISO_INSTANT.parse(fetchGameVersion(version).releaseTime, Instant::from).epochSecond try { val file = ensureServerJar(version) val (propClass, propCount) = file.findPropertiesClass() val strings = file.extractKeys(propClass).toSet() val keys = strings.matchKeys() return AnalyzeReport( version = version, releaseTime = releaseTime, propertiesClass = propClass, propertiesClassFingerprints = propCount, keys = keys.toSet(), ) } catch (e: Throwable) { return AnalyzeReport( version = version, releaseTime = releaseTime, error = if (e is IllegalStateException) e.message else e.stackTraceToString() ) } } val REPORT_SERIALIZER = Json { prettyPrint = true } suspend fun doReport(version: String) = ensureFile("$version-report.json") { it.writeText(REPORT_SERIALIZER.encodeToString(analyze(version))) }
0
Kotlin
0
0
70e9ab8b77e20ada3bbe109ea6b5533a10ef2562
1,456
minecraft-server-props-dumper
Apache License 2.0
src/main/kotlin/it/unibo/skpf/re/utils/RegressionUtils.kt
sabbatinif
418,445,072
true
null
package it.unibo.skpf.re.utils import it.unibo.skpf.re.Extractor import it.unibo.skpf.re.cart.CartPredictor import it.unibo.skpf.re.utils.RegressionUtils.createCART import it.unibo.skpf.re.utils.RegressionUtils.createGridEx import it.unibo.skpf.re.utils.RegressionUtils.createITER import it.unibo.skpf.re.utils.RegressionUtils.createSVR import it.unibo.tuprolog.core.format import it.unibo.tuprolog.theory.Theory import org.apache.commons.csv.CSVFormat import smile.base.mlp.Layer import smile.base.mlp.LayerBuilder import smile.base.mlp.OutputFunction import smile.data.DataFrame import smile.data.Tuple import smile.data.formula.Formula import smile.data.inputs import smile.data.inputsArray import smile.data.name import smile.data.outputs import smile.data.outputsArray import smile.data.randomSplit import smile.io.Read import smile.math.TimeFunction import smile.math.kernel.GaussianKernel import smile.regression.MLP import smile.regression.Regression import smile.regression.cart import smile.regression.rbfnet import smile.regression.svr import smile.validation.metric.MAD import smile.validation.metric.MSE import smile.validation.metric.R2 internal object MLPRegressorUtils { // mlp params private const val initLearningRate = 0.01 private const val decaySteps = 10000.0 private const val endLearningRate = 0.001 private const val epochs = 200 private const val layer1neurons = 35 private const val layer2neurons = 15 fun createMLP(x: Array<DoubleArray>, y: DoubleArray) = mlpRegressor( x, y, arrayOf( Layer.tanh(layer1neurons), Layer.tanh(layer2neurons), Layer.mse(1, OutputFunction.LINEAR) ), epochs, TimeFunction.linear(initLearningRate, decaySteps, endLearningRate) ) private fun mlpRegressor( x: Array<DoubleArray>, y: DoubleArray, builders: Array<LayerBuilder>, epochs: Int, learningRate: TimeFunction, momentum: TimeFunction = TimeFunction.constant(0.0), weightDecay: Double = 0.0, rho: Double = 0.0, epsilon: Double = 1E-7 ): MLP { val net = MLP(x[0].size, *builders) net.setLearningRate(learningRate) net.setMomentum(momentum) net.weightDecay = weightDecay net.setRMSProp(rho, epsilon) (1..epochs).forEach { _ -> net.update(x, y) } return net } } internal object RegressionUtils { // svr params private const val sigma = 0.06 private const val epsilon = 0.005 private const val C = 1.0 fun createSVR(train: DataFrame) = svr(train.inputsArray(), train.outputsArray(), GaussianKernel(sigma), epsilon, C) // rbf params const val k = 95 const val normalized = true fun createRBF(x: Array<DoubleArray>, y: DoubleArray) = rbfnet(x, y, k, normalized) // iter params const val minUpdate = 1.0 / 20 const val threshold = 0.19 fun createITER(model: Regression<DoubleArray>) = Extractor.iter(model, minUpdate = minUpdate, threshold = threshold) const val gridExThreshold = 0.05 const val steps = 2 fun createGridEx(model: Regression<DoubleArray>) = Extractor.gridex( model, steps = listOf(steps, steps), threshold = gridExThreshold, minExamples = 15 ) // cart params const val maxDepth = 3 const val maxNodes = 0 const val nodeSize = 5 fun createCART(train: DataFrame) = CartPredictor( cart( Formula.lhs(train.name()), train.inputs().merge(train.outputs()), maxDepth, maxNodes, nodeSize ) ) } fun printMetrics( actual: DoubleArray, expected: DoubleArray, printR2: Boolean = true, printMSE: Boolean = true, printMAD: Boolean = false ): Triple<Double, Double, Double> { val r2 = R2.of(expected, actual).round(2) val mse = MSE.of(expected, actual).round(2) val mad = MAD.of(expected, actual).round(2) if (printR2) println("Regressor R2 = $r2") if (printMSE) println("Regressor MSE = $mse") if (printMAD) println("Regressor MAD = $mad") return Triple(r2, mse, mad) } @Suppress("UNUSED_VARIABLE") fun regression(name: String, testSplit: Double) { println("*** $name ***") val dataset = Read.csv("datasets/$name", CSVFormat.DEFAULT.withHeader()) val (train, test) = dataset.randomSplit(testSplit) // val x = train.inputsArray() // val y = train.outputsArray() val svr = createSVR(train) // saveToFile("artiRBF95.txt", rbf) // saveToFile("artiTest50.txt", test) // saveToFile("artiTrain50.txt", train) printMetrics(svr.predict(test.inputsArray()), test.outputsArray()) val iter = createITER(svr) testRegressionExtractor("ITER", train, test, iter, svr, true, true) val gridex = createGridEx(svr) testRegressionExtractor("GridEx", train, test, gridex, svr, true, true) val cart = createCART(train) val cartEx = Extractor.cart(cart) testRegressionExtractor("CART", train, test, cartEx, true, true) } private fun test( name: String, test: DataFrame, printMetrics: Boolean, theory: Theory, predictions: Array<*> ) { println("\n################################") println("# $name extractor") println("################################\n") if (printMetrics) { val metrics = printMetrics( test.outputsArray(), predictions.map { it.toString().toDouble() }.toDoubleArray(), false, false, false ) println( theory.size.toString() + " rules with R2 = " + metrics.first + " and MSE = " + metrics.second + " w.r.t. the data" ).also { println() } } } fun testRegressionExtractor( name: String, train: DataFrame, test: DataFrame, extractor: Extractor<Tuple, CartPredictor>, printMetrics: Boolean = true, printRules: Boolean = false ) { val theory = extractor.extract(train) test(name, test, printMetrics, theory, extractor.predict(test)) if (printRules) theory.clauses.forEach { println(it.format(prettyRulesFormatter())) }.also { println() } } fun testRegressionExtractor( name: String, train: DataFrame, test: DataFrame, extractor: Extractor<*, *>, predictor: Regression<DoubleArray>, printMetrics: Boolean = true, printRules: Boolean = false ) { val theory = extractor.extract(train) test(name, test, printMetrics, theory, extractor.predict(test)) if (printMetrics) { val metricsFid = printMetrics( predictor.predict(test.inputsArray()), extractor.predict(test).map { it.toString().toDouble() }.toDoubleArray(), false, false, false ) println("R2 = ${metricsFid.first} and MSE = ${metricsFid.second} w.r.t. the black box") .also { println() } } if (printRules) theory.clauses.forEach { println(it.format(prettyRulesFormatter())) }.also { println() } }
1
Kotlin
2
0
f8f70a720dfa8222f2d40525872ca6ae84e85910
7,138
psyke-jvm
Apache License 2.0
src/main/kotlin/com/ioannuwu/inline/domain/MaxErrorsPerLine.kt
IoaNNUwU
594,100,636
false
null
package com.ioannuwu.inline.domain import com.ioannuwu.inline.data.DefaultSettings import com.ioannuwu.inline.data.MySettingsService import com.ioannuwu.inline.domain.settings.SettingsChangeEvent import com.ioannuwu.inline.domain.settings.SettingsChangeListener import com.ioannuwu.inline.domain.settings.SettingsChangeObservable interface MaxErrorsPerLine { val maxPerLine: Int object BySettings : MaxErrorsPerLine, SettingsChangeListener { init { MySettingsService.OBSERVABLE.subscribe(this, SettingsChangeObservable.Priority.DEFAULT) } private var _maxPerLine: Int = DefaultSettings.MAX_ERRORS_PER_LINE override val maxPerLine: Int get() = _maxPerLine override fun onSettingsChange(event: SettingsChangeEvent) { _maxPerLine = event.newSettingsState.maxErrorsPerLine } } }
0
Kotlin
0
6
daad0725a42495ee0c5b5733ed03e91fcb4ccbc0
880
InLine
MIT License
canvas2_lp/src/main/java/com/angcyo/canvas2/laser/pecker/dslitem/control/RendererFlatItem.kt
angcyo
229,037,684
false
{"Kotlin": 3482606, "JavaScript": 5542, "HTML": 1598}
package com.angcyo.canvas2.laser.pecker.dslitem.control import com.angcyo.canvas.render.renderer.CanvasGroupRenderer import com.angcyo.canvas2.laser.pecker.R import com.angcyo.canvas2.laser.pecker.dslitem.CanvasIconItem import com.angcyo.library.canvas.core.Reason import com.angcyo.library.component.Strategy /** * Canvas图层分布 * @author <a href="mailto:<EMAIL>">angcyo</a> * @since 2022/10/27 */ class RendererFlatItem : CanvasIconItem() { /**水平分布*/ var itemFlatType: Int = CanvasGroupRenderer.FLAT_TYPE_HORIZONTAL init { itemLayoutId = R.layout.item_canvas_icon_horizontal_layout itemClick = { itemRenderer?.let { if (it is CanvasGroupRenderer) { it.updateRendererFlat( itemFlatType, Reason.user, Strategy.normal, itemRenderDelegate ) } } } //点击后自动关闭pop //itemFlag = MenuPopupConfig.FLAG_ITEM_DISMISS } }
0
Kotlin
4
4
16490a3e212472aeaad38ba9b53db97b17ac328a
1,064
UICoreEx
MIT License
feature/setting/src/main/java/com/goms/setting/component/SelectThemeDropDown.kt
team-haribo
740,096,241
false
{"Kotlin": 566099}
package com.goms.setting.component import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.goms.design_system.component.dropdown.GomsDropdown import com.goms.design_system.theme.GomsTheme.colors import com.goms.design_system.theme.GomsTheme.typography import com.goms.design_system.theme.ThemeType import kotlinx.collections.immutable.toPersistentList @Composable internal fun SelectThemeDropDown( modifier: Modifier, onThemeSelect: (Int) -> Unit, themeState: String ) { val dropdownList = listOf("다크(기본)", "라이트", "시스템 테마 설정") var selectedIndex by remember { mutableIntStateOf(0) } selectedIndex = when(themeState) { ThemeType.DARK.value -> 0 ThemeType.LIGHT.value -> 1 ThemeType.SYSTEM.value -> 2 else -> 0 } Column( modifier = modifier.fillMaxWidth() ) { Text( text = "앱 테마 설정", style = typography.textMedium, color = colors.WHITE, fontWeight = FontWeight.SemiBold ) Spacer(modifier = Modifier.height(8.dp)) GomsDropdown( dropdownList = dropdownList.toPersistentList(), dropdownListSize = dropdownList.size, selectedIndex = selectedIndex, modifier = Modifier.padding(horizontal = 20.dp), backgroundColor = colors.G1, onClick = {}, onItemClick = { selectedIndex = it onThemeSelect(selectedIndex) } ) } }
2
Kotlin
0
7
d9e1aba763c8b3b1201a522a63ae7abba07be2cb
2,145
GOMS-Android-V2
MIT License
jasy/src/main/java/com/example/jasy/helpers/constants/DateFormatConstants.kt
vespinola
207,432,505
false
null
package com.example.jasy.helpers.constants class DateFormatConstants { companion object { val year = "yyyy" val default = "yyyy-MM-dd" val pretty = "LLLL dd, yyyy" } }
0
Kotlin
0
0
372259eb46475fa58267d1fca8088f3feacdf0ca
200
jasy-android
MIT License
src/test/kotlin/com/preslavrachev/kandas/DataFrameUTest.kt
preslavrachev
141,668,237
false
null
package com.preslavrachev.kandas import assertk.assertThat import assertk.assertions.containsOnly import assertk.assertions.isNotNull import org.junit.jupiter.api.Test internal class DataFrameUTest { @Test fun `ensure column names when providing a list of maps`() { val df = DataFrame(listOf( mapOf( "a" to 1, "b" to 2 ), mapOf( "c" to 3, "d" to 4 ) )) assertThat(df.columnNames) .isNotNull() .containsOnly("a", "b", "c", "d") } @Test fun `ensure that a single series contains the right items`() { val df = DataFrame(listOf( mapOf( "a" to 1, "b" to 2 ), mapOf( "c" to 3, "d" to 4 ) )) print(df["a"].toList()) assertThat(df["a"].toList()) .isNotNull() .containsOnly(1.0, Double.NaN) } }
1
Kotlin
0
3
0cd8df3abc89fdab87b5fbe823982b3a70d485af
1,157
kandas
MIT License
web/widgets/src/commonMain/kotlin/layouts/defaults/BoxDefault.kt
bvc3at
390,572,166
true
{"Kotlin": 928979, "Shell": 10292, "Dockerfile": 5716, "HTML": 2892, "PowerShell": 1708, "Groovy": 1415, "CSS": 1022, "JavaScript": 203}
package org.jetbrains.compose.common.foundation.layout import org.jetbrains.compose.common.ui.Modifier import androidx.compose.runtime.Composable @Composable fun Box( modifier: Modifier = Modifier.Companion, content: @Composable () -> Unit ) { BoxActual(modifier, content) }
0
null
0
1
2e571c8734c31426cc7cd6be3076ec39d638b4fc
285
compose-jb
Apache License 2.0
firebase-installations/src/androidMain/kotlin/suntrix/kmp/firebase/installations/FirebaseInstallations.kt
kotlin-multiplatform
542,823,504
false
{"Kotlin": 126662, "Makefile": 152}
package suntrix.kmp.firebase.installations import kotlinx.coroutines.tasks.await /** * Created by <NAME> on 25/09/2022 */ actual class FirebaseInstallations internal constructor(val nativeSdk: com.google.firebase.installations.FirebaseInstallations) { actual suspend fun delete() { nativeSdk.delete().await() } actual suspend fun getId(): String = nativeSdk.id.await() actual suspend fun getToken(forceRefresh: Boolean): String = nativeSdk.getToken(forceRefresh).await().token }
0
Kotlin
0
1
684e9142ce9fced949c1a9c539e8651aeb0a87da
517
firebase-kmp-sdks
MIT License
src/main/kotlin/network/cere/ddc/node/api/apps/Applications.kt
Cerebellum-Network
346,027,534
false
null
package network.cere.ddc.node.api.apps import network.cere.ddc.node.api.DdcNodeApiResponse interface Applications { fun create(request: CreateApplicationRequest) : DdcNodeApiResponse<Unit> fun get(appPubKey: String): DdcNodeApiResponse<Application> fun getTopology(appPubKey: String) : DdcNodeApiResponse<ApplicationTopology> }
0
Kotlin
1
0
06280470629e6851a6b7ca13a3813a707edf9ea4
344
ddc-node-api-kotlin
MIT License
app/src/main/java/com/lyc/gank/utils/SingleLiveEvent.kt
SirLYC
93,046,345
false
null
package com.lyc.gank.utils import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Observer import android.support.annotation.MainThread import java.util.concurrent.atomic.AtomicBoolean /** * Created by hgj on 20/12/2017. */ open class SingleLiveEvent<T> : MutableLiveData<T>() { private val pending = AtomicBoolean(false) @MainThread override fun setValue(value: T?) { pending.set(true) super.setValue(value) } override fun postValue(value: T) { pending.set(true) super.postValue(value) } @MainThread override fun observe(owner: LifecycleOwner, observer: Observer<T>) { super.observe(owner, Observer { if (pending.compareAndSet(true, false)) { observer.onChanged(it) } }) } @MainThread override fun observeForever(observer: Observer<T>) { super.observeForever { if (pending.compareAndSet(true, false)) { observer.onChanged(it) } } } }
1
Kotlin
0
6
f72e0079a84871da510012e8f4b8cb330f80d1a1
1,104
Android-Gank-Share
Apache License 2.0
src/main/kotlin/chatterbox/util/commands/DynamicCommandRegistry.kt
Plugineers
136,838,957
false
{"Kotlin": 14185}
package chatterbox.util.commands import chatterbox.logInfo import chatterbox.logSevere import chatterbox.logWarn import org.bukkit.Bukkit import org.bukkit.command.Command import org.bukkit.command.CommandMap import java.lang.reflect.Field val HELP_ARGS = arrayOf("help", "h", "?") class DynamicCommandRegistry(private val owningPlugin: String) { private val registeredCommands = mutableSetOf<DynamicPluginCommand>() private fun hasRegisteredCommand(dynamicCommand: DynamicCommand) = registeredCommands.any { it.name == dynamicCommand.aliases[0] } fun <T : DynamicPluginCommand> registerCommand(cmd: () -> T): DynamicCommandRegistry { val t = cmd() if (t::class.annotations.any { it is DynamicCommand }) { val registration: DynamicCommand = t::class.annotations.first { it is DynamicCommand } as DynamicCommand val registrationName = registration.aliases[0] if (hasRegisteredCommand(registration)) { logWarn("Attempted to doubly register command \"$registrationName\"") return this } t.owningPlugin = owningPlugin t.name = registrationName t.label = registrationName t.aliases = registration.aliases.copyOfRange(1, registration.aliases.size - 1).asList() t.argbounds = registration.bounds t.usage = registration.help t.playerOnly = registration.playerOnly if (t::class.annotations.any { it is Description }) { val desc: Description = t::class.annotations.first { it is Description } as Description t.description = desc.value } fun commandFromMap(commandMap: CommandMap, commandName: String): Command? = commandMap.getCommand(commandName) try { val commandMapField: Field = Bukkit.getServer().javaClass.getDeclaredField("commandMap") commandMapField.isAccessible = true val commandMap: CommandMap = commandMapField.get(Bukkit.getServer()) as CommandMap val cmdFromMap = commandFromMap(commandMap, registrationName) if (cmdFromMap != null) { logWarn("Did not register \"$registrationName\" due to already existing command") } else { logInfo("Successfully registered \"$registrationName\"") commandMap.register(t.label, t) registeredCommands.add(t) } } catch (ex: Exception) { ex.printStackTrace() return this } } else { logSevere("Invalid registration for command class encountered: \"${t::class.simpleName}\"") } return this } }
1
Kotlin
0
1
e5889e451c5922cdf511d5f2bb0af3f0c56b1393
2,855
Chatterbox
MIT License
src/main/java/com/github/moskvax/viewbinding/components/ViewBindingFragment.kt
moskvax
428,208,963
false
{"Kotlin": 2118}
package com.github.moskvax.viewbinding.components import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.fragment.app.Fragment import androidx.viewbinding.ViewBinding import kotlin.reflect.KClass abstract class ViewBindingFragment<T : ViewBinding> : Fragment() { protected abstract val viewBindingClass: KClass<T> private var _binding: T? = null protected val binding: T get() = _binding!! @CallSuper override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = viewBindingClass.inflate(inflater, container) .also { _binding = it } .root @CallSuper override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
a57c883a598a39592701c97fc86d61f5b17dc4c0
884
viewbinding-components
Apache License 2.0
src/main/java/com/github/moskvax/viewbinding/components/ViewBindingFragment.kt
moskvax
428,208,963
false
{"Kotlin": 2118}
package com.github.moskvax.viewbinding.components import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.fragment.app.Fragment import androidx.viewbinding.ViewBinding import kotlin.reflect.KClass abstract class ViewBindingFragment<T : ViewBinding> : Fragment() { protected abstract val viewBindingClass: KClass<T> private var _binding: T? = null protected val binding: T get() = _binding!! @CallSuper override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = viewBindingClass.inflate(inflater, container) .also { _binding = it } .root @CallSuper override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
a57c883a598a39592701c97fc86d61f5b17dc4c0
884
viewbinding-components
Apache License 2.0
src/main/kotlin/com/odim/simulator/tree/templates/redfish/embedded/FPGATemplate.kt
ODIM-Project
355,910,204
false
null
// Copyright (c) Intel Corporation // // 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.odim.simulator.tree.templates.redfish.embedded import com.odim.simulator.tree.EmbeddedObjectTemplate import com.odim.simulator.tree.RedfishVersion.V1_4_0 import com.odim.simulator.tree.ResourceTemplate import com.odim.simulator.tree.structure.EmbeddedObjectType.FPGA import com.odim.simulator.tree.structure.EmbeddedObjectType.FPGA_RECONFIGURATION_SLOT import com.odim.simulator.tree.structure.EmbeddedObjectType.PROCESSOR_INTERFACE import com.odim.simulator.tree.structure.Resource.Companion.embeddedArray import com.odim.simulator.tree.structure.Resource.Companion.embeddedObject /** * This is generated class. Please don't edit it's contents. */ @EmbeddedObjectTemplate(FPGA) open class FPGATemplate : ResourceTemplate() { init { version(V1_4_0, embeddedObject( "FpgaType" to "Integrated", "Model" to "", "FirmwareId" to "", "FirmwareManufacturer" to "", "FirmwareVersion" to "", "HostInterface" to embeddedObject(PROCESSOR_INTERFACE), "ExternalInterfaces" to embeddedArray(PROCESSOR_INTERFACE), "PCIeVirtualFunctions" to 0, "ProgrammableFromHost" to null, "ReconfigurationSlots" to embeddedArray(FPGA_RECONFIGURATION_SLOT), "Oem" to embeddedObject() )) } }
1
Kotlin
0
7
7e8a3030ca83c040678f8edf76def588b2b01cca
1,970
BMCSimulator
Apache License 2.0
src/commonMain/kotlin/io/violabs/ripley/domain/DefaultTaskGroup.kt
violabs
672,379,526
false
null
package io.violabs.ripley.domain class DefaultTaskGroup( override var normalizedTask: ITask? = null, override var targetedTask: IAcceptedTask? = null, override var taskOptions: Any? = null ) : ITaskGroup
0
Kotlin
0
1
bd6182281977a89c28454a46cc341fdd19c48723
216
ripley
Apache License 2.0
src/test/kotlin/asserts/strikt/StriktAssertsTest.kt
ov7a
277,275,871
false
null
package asserts.strikt import common.AssertsFullTest class StriktAssertsTest : AssertsFullTest(StriktAsserts())
0
Kotlin
1
6
b3a4ff794d755837fdf8177c7fe9b05b9ca1653b
113
kotlin-asserts-comparison
MIT License
app/src/main/java/dev/cdrck/mdgtictoe/themes/Color.kt
cedrick1445
748,069,467
false
{"Kotlin": 66457, "HTML": 11095, "CSS": 1471, "JavaScript": 425}
package dev.cdrck.mdgtictoe.themes import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFFA63A23) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFFFDAD3) val md_theme_light_onPrimaryContainer = Color(0xFF3D0600) val md_theme_light_secondary = Color(0xFF77574F) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFFFDAD3) val md_theme_light_onSecondaryContainer = Color(0xFF2C1510) val md_theme_light_tertiary = Color(0xFF6E5D2E) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFF8E0A6) val md_theme_light_onTertiaryContainer = Color(0xFF241A00) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFFFBFF) val md_theme_light_onBackground = Color(0xFF201A19) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF201A19) val md_theme_light_surfaceVariant = Color(0xFFF5DDD9) val md_theme_light_onSurfaceVariant = Color(0xFF534340) val md_theme_light_outline = Color(0xFF85736F) val md_theme_light_inverseOnSurface = Color(0xFFFBEEEB) val md_theme_light_inverseSurface = Color(0xFF362F2D) val md_theme_light_inversePrimary = Color(0xFFFFB4A4) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFFA63A23) val md_theme_light_outlineVariant = Color(0xFFD8C2BD) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFFFB4A4) val md_theme_dark_onPrimary = Color(0xFF630E00) val md_theme_dark_primaryContainer = Color(0xFF86220D) val md_theme_dark_onPrimaryContainer = Color(0xFFFFDAD3) val md_theme_dark_secondary = Color(0xFFE7BDB4) val md_theme_dark_onSecondary = Color(0xFF442A24) val md_theme_dark_secondaryContainer = Color(0xFF5D3F39) val md_theme_dark_onSecondaryContainer = Color(0xFFFFDAD3) val md_theme_dark_tertiary = Color(0xFFDBC58C) val md_theme_dark_onTertiary = Color(0xFF3C2F04) val md_theme_dark_tertiaryContainer = Color(0xFF544519) val md_theme_dark_onTertiaryContainer = Color(0xFFF8E0A6) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF201A19) val md_theme_dark_onBackground = Color(0xFFEDE0DD) val md_theme_dark_surface = Color(0xFF201A19) val md_theme_dark_onSurface = Color(0xFFEDE0DD) val md_theme_dark_surfaceVariant = Color(0xFF534340) val md_theme_dark_onSurfaceVariant = Color(0xFFD8C2BD) val md_theme_dark_outline = Color(0xFFA08C88) val md_theme_dark_inverseOnSurface = Color(0xFF201A19) val md_theme_dark_inverseSurface = Color(0xFFEDE0DD) val md_theme_dark_inversePrimary = Color(0xFFA63A23) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFFFB4A4) val md_theme_dark_outlineVariant = Color(0xFF534340) val md_theme_dark_scrim = Color(0xFF000000) val seed = Color(0xFFEF6F53) val light_flirt = Color(0xFFb4007e) val light_flirtContainer = Color(0xFFffd8e8) val light_onFlirt = Color(0xFFffffff) val light_onFlirtContainer = Color(0xFF3d0027) val dark_flirt = Color(0xFFffafd5) val dark_flirtContainer = Color(0xFF620042) val dark_onFlirt = Color(0xFF8a005f) val dark_onFlirtContainer = Color(0xFFffd8e8)
0
Kotlin
0
0
718ab193784a806a604796701d3844de9fcf2396
3,528
Zodiac_TicTacToe
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Tags.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.Tags: ImageVector get() { if (_tags != null) { return _tags!! } _tags = Builder(name = "Tags", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.707f, 9.293f) curveToRelative(0.391f, 0.391f, 0.391f, 1.024f, 0.0f, 1.414f) curveToRelative(-0.391f, 0.391f, -1.024f, 0.391f, -1.414f, 0.0f) curveToRelative(-0.391f, -0.391f, -0.391f, -1.024f, 0.0f, -1.414f) curveToRelative(0.391f, -0.391f, 1.024f, -0.391f, 1.414f, 0.0f) close() moveTo(22.18f, 12.924f) lineToRelative(-1.24f, 1.281f) curveToRelative(0.187f, 0.884f, -0.06f, 1.842f, -0.745f, 2.527f) lineToRelative(-6.244f, 6.449f) curveToRelative(-0.532f, 0.532f, -1.225f, 0.819f, -1.962f, 0.819f) reflectiveCurveToRelative(-1.43f, -0.287f, -1.95f, -0.808f) lineTo(1.025f, 14.18f) lineTo(2.034f, 5.057f) lineToRelative(9.137f, -1.25f) lineToRelative(8.663f, 8.663f) lineToRelative(0.92f, -0.95f) curveToRelative(0.308f, -0.307f, 0.308f, -0.788f, 0.012f, -1.084f) lineTo(12.435f, 2.107f) lineToRelative(-7.255f, 0.937f) lineToRelative(-0.256f, -1.983f) lineTo(13.153f, -0.002f) lineToRelative(9.026f, 9.026f) curveToRelative(1.075f, 1.075f, 1.075f, 2.825f, 0.0f, 3.901f) close() moveTo(18.781f, 14.245f) lineTo(10.458f, 5.924f) lineToRelative(-6.607f, 0.904f) lineToRelative(-0.731f, 6.617f) lineToRelative(8.333f, 8.333f) curveToRelative(0.287f, 0.287f, 0.785f, 0.287f, 1.072f, 0.0f) lineToRelative(6.244f, -6.449f) curveToRelative(0.308f, -0.307f, 0.308f, -0.788f, 0.012f, -1.084f) close() } } .build() return _tags!! } private var _tags: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,029
icons
MIT License
resources-generator/src/main/kotlin/dev/icerock/gradle/generator/js/JsImagesGenerator.kt
icerockdev
204,874,263
false
{"Kotlin": 343774, "Shell": 1130}
/* * Copyright 2022 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.gradle.generator.js import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeSpec import dev.icerock.gradle.generator.ImagesGenerator import dev.icerock.gradle.generator.NOPObjectBodyExtendable import dev.icerock.gradle.generator.ObjectBodyExtendable import dev.icerock.gradle.generator.jsJvmCommon.generateHighestQualityImageResources import org.gradle.api.file.FileTree import java.io.File class JsImagesGenerator( inputFileTree: FileTree ) : ImagesGenerator(inputFileTree), ObjectBodyExtendable by NOPObjectBodyExtendable() { override fun getClassModifiers(): Array<KModifier> = arrayOf(KModifier.ACTUAL) override fun getPropertyModifiers(): Array<KModifier> = arrayOf(KModifier.ACTUAL) override fun getPropertyInitializer(fileName: String): CodeBlock { val requireDeclaration = """require("$IMAGES_DIR/$fileName")""" return CodeBlock.of( "ImageResource(fileUrl = js(%S) as String, fileName = %S)", requireDeclaration, fileName ) } override fun beforeGenerateResources(objectBuilder: TypeSpec.Builder, keys: List<String>) { val languageKeysList = keys.joinToString { key -> key.substringBeforeLast(".").replace(".", "_") } objectBuilder.addFunction( FunSpec.builder("values") .addModifiers(KModifier.OVERRIDE) .addStatement("return listOf($languageKeysList)") .returns( ClassName("kotlin.collections", "List") .parameterizedBy(resourceClassName) ) .build() ) } override fun generateResources( resourcesGenerationDir: File, keyFileMap: Map<String, List<File>> ) { generateHighestQualityImageResources(resourcesGenerationDir, keyFileMap, IMAGES_DIR) } companion object { const val IMAGES_DIR = "images" } }
149
Kotlin
112
997
590fc8f2eacbe5aca4992df83aa7473bb3e28b62
2,281
moko-resources
Apache License 2.0
app/src/main/java/com/example/assignment_7/viewsHolders/BaseViewHolder.kt
SawThanDar18
209,331,092
false
null
package com.example.assignment_7.viewsHolders import android.view.View import androidx.recyclerview.widget.RecyclerView abstract class BaseViewHolder<T>(itemView: View): RecyclerView.ViewHolder(itemView) { var data: T? = null set(value) { field = value value?.let { bindData(value) } } abstract fun bindData(data: T) }
0
Kotlin
0
0
74a750de9e651919873268a59401c2bcd8e03622
399
Assignment_7
Apache License 2.0
app/src/androidTest/java/info/jukov/rijksmuseum/feature/art/collection/data/ArtCollectionRepositoryTestImpl.kt
jukov
722,639,886
false
{"Kotlin": 143624}
package info.jukov.rijksmuseum.feature.art.details.data import info.jukov.rijksmuseum.feature.art.collection.domain.ArtCollectionRepository import info.jukov.rijksmuseum.feature.art.collection.domain.model.ArtCollectionItem import io.reactivex.rxjava3.core.Single import javax.inject.Inject class ArtCollectionRepositoryTestImpl @Inject constructor() : ArtCollectionRepository { override fun get(page: Int): Single<List<ArtCollectionItem>> = Single.just( (((page - 1) * 5) until ((page - 1) * 5 + 5)).map { index -> ArtCollectionItem( id = index.toString(), title = index.toString(), longTitle = index.toString(), author = "author", imageUrl = null, imageAspectRatio = null ) } ) }
0
Kotlin
0
0
ffbada31bc49d8e02d3b2fe28b88f6650906c1dd
829
Rijksmuseum
The Unlicense
src/main/kotlin/org/jaqpot/api/service/qsartoolbox/QSARToolboxAPI.kt
ntua-unit-of-control-and-informatics
790,773,279
false
{"Kotlin": 206289, "FreeMarker": 3417, "PLpgSQL": 1407}
package org.jaqpot.api.service.qsartoolbox import io.github.oshai.kotlinlogging.KotlinLogging import org.jaqpot.api.service.qsartoolbox.config.QsartoolboxConfig import org.jaqpot.api.service.qsartoolbox.dto.QSARSearchSmilesResponse import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpMethod import org.springframework.stereotype.Component import org.springframework.web.client.RestTemplate @Component class QSARToolboxAPI(private val qsartoolboxConfig: QsartoolboxConfig) { companion object { private val logger = KotlinLogging.logger {} } fun searchSmiles(smiles: String): Array<QSARSearchSmilesResponse>? { val registerUnknown = true val ignoreStereo = false val url = "${qsartoolboxConfig.url}/api/v6/search/smiles/${registerUnknown}/${ignoreStereo}?smiles={smiles}" val restTemplate = RestTemplate() val response = restTemplate.getForEntity(url, Array<QSARSearchSmilesResponse>::class.java, smiles) return response.body } fun runQsarModel( chemId: String, qsarGuid: String ): Map<*, *>? { val url = "${qsartoolboxConfig.url}/api/v6/qsar/apply/${qsarGuid}/${chemId}" val restTemplate = RestTemplate() val response = restTemplate.getForEntity(url, Map::class.java) return response.body } fun runProfiler( chemId: String, profilerGuid: String ): List<String>? { val url = "${qsartoolboxConfig.url}/api/v6/profiling/${profilerGuid}/${chemId}" val restTemplate = RestTemplate() val response = restTemplate.exchange( url, HttpMethod.GET, null, object : ParameterizedTypeReference<List<String>>() {} ) return response.body } fun runCalculator( chemId: String, calculatorId: String ): Map<*, *>? { val url = "${qsartoolboxConfig.url}/api/v6/calculation/${calculatorId}/${chemId}" val restTemplate = RestTemplate() val response = restTemplate.getForEntity(url, Map::class.java) return response.body } }
1
Kotlin
0
0
810ba82016fae28a64e57f14d8df74a721678836
2,199
jaqpot-api
MIT License
app/src/main/kotlin/com/ceh9/portfolio/common/data/local/CommonData.kt
CeH9
202,865,791
false
null
package com.ceh9.portfolio.common.data.local /** * Created by CeH9 on 19.09.2019 */ object CommonData { const val DEBUG_START_DESTINATION_ENABLED: Boolean = false const val DEBUG_LET_EXCEPTIONS_THROW: Boolean = false }
0
Kotlin
0
0
d4efdcffbee64a02cdb82d73d4f707f322964c40
229
Portfolio
MIT License
roboquant-core/test/orders/CombinedOrderTest.kt
neurallayer
406,929,056
false
null
/* * Copyright 2021 Neural Layer * * 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 org.roboquant.orders import org.roboquant.TestData import java.time.Instant import org.junit.Test import org.roboquant.brokers.sim.Execution import kotlin.test.assertEquals internal class CombinedOrderTest { private class MyOrder(order: MarketOrder) : CombinedOrder(order) { override fun execute(price: Double, time: Instant): List<Execution> { return listOf() } } @Test fun test() { val child = TestData.euMarketOrder() val order = MyOrder(child) order.price = 100.0 assertEquals(100.0, child.price) assertEquals(child.getValue(), order.getValue()) } }
4
Kotlin
9
27
601f0b39950a53b32889d6c3688b2bcfecae9323
1,254
roboquant
Apache License 2.0
src/main/kotlin/Application.kt
paulmiddelkoop
347,105,584
false
null
package se.pamisoft.skola.avgifter import com.sksamuel.hoplite.ConfigLoader import se.pamisoft.skola.avgifter.calculation.CalculateFees import se.pamisoft.skola.avgifter.calculation.FamilyFee import se.pamisoft.skola.avgifter.fortnox.InvoiceInFortnox import se.pamisoft.skola.avgifter.fortnox.fortnoxModule import se.pamisoft.skola.avgifter.sheet.googleSheetsModule import se.pamisoft.skola.avgifter.sheet.output.FeeOutputSheet import toothpick.InjectConstructor import toothpick.ktp.KTP import toothpick.ktp.binding.module import toothpick.ktp.extension.getInstance import java.time.YearMonth.now @InjectConstructor class Application( private val calculateFees: CalculateFees, private val outputSheet: FeeOutputSheet, private val invoiceInFortnox: InvoiceInFortnox, private val reporting: Reporting, private val options: CommandLineOptions ) { fun run() { check(options.invoiceMonth <= now().plusMonths(1)) { "Cannot create invoices for more than one month in advance." } calculateFees(options.invoiceMonth, determinePreviousMonthFees()) .also { fees -> if (options.listEmails) { reporting.printEmails(fees) } else if (options.noNewIncomeSince != null) { reporting.printMissingIncomes(fees, options) } else { outputSheet.writeSheet(fees) invoiceInFortnox(options.invoiceMonth, fees) } } } private fun determinePreviousMonthFees(): Set<FamilyFee> { if (options.init) return emptySet() val previousInvoiceMonth = options.invoiceMonth.minusMonths(1) return outputSheet.ensureNotChanged(previousInvoiceMonth, calculateFees(previousInvoiceMonth, emptySet())) } companion object { fun create(options: CommandLineOptions): Application = with(loadConfig(options)) { KTP.openRootScope().installModules( commandLineOptionsModule(options), fortnoxModule(fortnox), googleSheetsModule(googleSheets) ) }.getInstance() private fun loadConfig(options: CommandLineOptions) = ConfigLoader().loadConfigOrThrow<ApplicationConfig>("/application-${if (options.testEnvironment) "test" else "production"}.yaml") private fun commandLineOptionsModule(options: CommandLineOptions) = module { bind(CommandLineOptions::class.java).toInstance(options) } } }
1
Kotlin
0
0
0ea54cf6bbac8541b02400ec3eadc092cf6f9c88
2,555
skola-avgifter
MIT License
app/src/main/kotlin/com/stepmate/app/ui/navigation/permission/PermissionRequester.kt
step-Mate
738,437,093
false
{"Kotlin": 732407}
package com.stepmate.app.ui.navigation.permission import android.Manifest import android.app.AlarmManager import android.content.Context import android.content.pm.PackageManager import android.os.Build import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat object PermissionRequester { @RequiresApi(Build.VERSION_CODES.TIRAMISU) fun checkNotification(context: Context): Boolean { val result = ContextCompat.checkSelfPermission( context, Manifest.permission.POST_NOTIFICATIONS ) return result == PackageManager.PERMISSION_GRANTED } fun checkActivityRecognition(context: Context): Boolean { val result = ContextCompat.checkSelfPermission( context, Manifest.permission.ACTIVITY_RECOGNITION ) return result == PackageManager.PERMISSION_GRANTED } @RequiresApi(Build.VERSION_CODES.S) fun checkExactAlarm(context: Context) : Boolean { val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager return alarmManager.canScheduleExactAlarms() } }
0
Kotlin
0
0
589774b58ae8529b486c3ec19e0e39db01e48dd6
1,149
Android
Apache License 2.0
app/src/main/java/com/chocolate/triviatitans/presentation/screens/quiz_screen/text_game/view_model/mapper/QuestionsMapper.kt
team-chocolate-cake
661,943,976
false
null
package com.chocolate.triviatitans.presentation.screens.quiz_screen.text_game.view_model.mapper import com.chocolate.triviatitans.domain.entities.TextChoiceEntity import com.chocolate.triviatitans.domain.mapper.Mapper import com.chocolate.triviatitans.presentation.screens.quiz_screen.base.QuestionUiState import javax.inject.Inject class QuestionsMapper @Inject constructor() : Mapper<TextChoiceEntity, QuestionUiState> { override fun map(input: TextChoiceEntity): QuestionUiState { return QuestionUiState( id = input.id, question = input.question, category = input.category, difficulty = input.difficulty, correctAnswer = input.correctAnswer, incorrectAnswers = input.incorrectAnswers ) } }
0
Kotlin
3
1
94e74e9943f25d94a64311d898baf4b07fabfc63
790
TriviaTitans
MIT License
kotlin-electron/src/jsMain/generated/electron/core/Product.kt
JetBrains
93,250,841
false
null
// Generated by Karakum - do not modify it manually! package electron.core external interface Product { // Docs: https://electronjs.org/docs/api/structures/product /** * 3 character code presenting a product's currency based on the ISO 4217 standard. */ var currencyCode: String /** * An array of discount offers */ var discounts: js.array.ReadonlyArray<ProductDiscount> /** * The total size of the content, in bytes. */ var downloadContentLengths: js.array.ReadonlyArray<Double> /** * A string that identifies the version of the content. */ var downloadContentVersion: String /** * The locale formatted price of the product. */ var formattedPrice: String /** * The object containing introductory price information for the product. available * for the product. */ var introductoryPrice: ProductDiscount? /** * A boolean value that indicates whether the App Store has downloadable content * for this product. `true` if at least one file has been associated with the * product. */ var isDownloadable: Boolean /** * A description of the product. */ var localizedDescription: String /** * The name of the product. */ var localizedTitle: String /** * The cost of the product in the local currency. */ var price: Double /** * The string that identifies the product to the Apple App Store. */ var productIdentifier: String /** * The identifier of the subscription group to which the subscription belongs. */ var subscriptionGroupIdentifier: String /** * The period details for products that are subscriptions. */ var subscriptionPeriod: ProductSubscriptionPeriod? }
40
null
174
1,347
997ed3902482883db4a9657585426f6ca167d556
1,822
kotlin-wrappers
Apache License 2.0
app/src/mvvmMaterial/java/xyz/thaihuynh/android/sample/arch/ui/notes/NotesFragment.kt
thaihuynhxyz
470,112,438
false
{"Kotlin": 59749}
package xyz.thaihuynh.android.sample.arch.ui.notes import android.content.res.Resources import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import xyz.thaihuynh.android.sample.arch.R import xyz.thaihuynh.android.sample.arch.databinding.NotesFragmentBinding import xyz.thaihuynh.android.sample.arch.model.Note import xyz.thaihuynh.android.sample.arch.ui.note.NoteFragment import xyz.thaihuynh.android.sample.arch.util.autoCleared /** * Represent for View */ @AndroidEntryPoint class NotesFragment : Fragment() { private lateinit var viewModel: NotesViewModel private lateinit var adapter: NotesAdapter private var binding by autoCleared<NotesFragmentBinding>() companion object { fun newInstance() = NotesFragment() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DataBindingUtil.inflate(inflater, R.layout.notes_fragment, container, false) return binding.root } // Setup views override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.lifecycleOwner = viewLifecycleOwner // Receive input from Controller binding.add.setOnClickListener { onAddClicked() } viewModel = ViewModelProvider(this)[NotesViewModel::class.java] initRecyclerView() } override fun onResume() { super.onResume() viewModel.start() } private fun initRecyclerView() { binding.notes.layoutManager = GridLayoutManager(context, 2) adapter = NotesAdapter( ::onNoteSelected, ) binding.notes.adapter = adapter val dividerItemDecoration = DividerItemDecoration(context, RecyclerView.VERTICAL) binding.notes.addItemDecoration(dividerItemDecoration) val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback( 0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ) = false override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) { //Remove swiped item from list and notify the RecyclerView val position = viewHolder.adapterPosition val note = adapter.currentList[position] onNoteItemDelete(note) } } val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback) itemTouchHelper.attachToRecyclerView(binding.notes) viewModel.notes.observe(viewLifecycleOwner) { adapter.submitList(it) } } private fun onAddClicked() { parentFragmentManager.beginTransaction() .replace(R.id.container, NoteFragment.newInstance()) .addToBackStack(null) .commit() } private fun onNoteSelected(note: Note) { parentFragmentManager.beginTransaction() .replace(R.id.container, NoteFragment.newInstance(note)) .addToBackStack(null) .commit() } private fun onNoteItemDelete(note: Note) = try { viewModel.deleteNote(note) } catch (e: Resources.NotFoundException) { Snackbar.make(requireView(), "204", Snackbar.LENGTH_SHORT).show() } }
0
Kotlin
0
1
58b23685e7b690bcb3a1ec9b97ffe6d151e70969
3,986
android-architecture-samples
Apache License 2.0
1905.Count Sub Islands.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
internal class Solution { private val dirs = intArrayOf(-1, 0, 1, 0, -1) private var grid1: Array<IntArray> private var grid2: Array<IntArray> private var m = 0 private var n = 0 fun countSubIslands(grid1: Array<IntArray>, grid2: Array<IntArray>): Int { m = grid1.size n = grid1[0].size this.grid1 = grid1 this.grid2 = grid2 var ans = 0 for (i in 0 until m) { for (j in 0 until n) { if (grid2[i][j] == 1) { ans += dfs(i, j) } } } return ans } private fun dfs(i: Int, j: Int): Int { var ok = grid1[i][j] grid2[i][j] = 0 for (k in 0..3) { val x = i + dirs[k] val y = j + dirs[k + 1] if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1) { ok = ok and dfs(x, y) } } return ok } }
0
Kotlin
0
0
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
825
kotlin-leetcode
MIT License
app/src/main/java/dev/jamescullimore/wifiwizard/WiFiWizardScreen.kt
LethalMaus
708,772,183
false
{"Kotlin": 30344}
package dev.jamescullimore.wifiwizard import android.content.Intent import android.provider.Settings import android.widget.Toast import androidx.annotation.StringRes import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import dev.jamescullimore.wifiwizard.ui.EnterPasswordScreen import dev.jamescullimore.wifiwizard.ui.WiFiListScreen enum class WiFiWizardScreen(@StringRes val title: Int, val route: String) { WiFiList(title = R.string.app_name, route = "WiFiList"), ConnectToWiFi(title = R.string.connect_to_wifi, route = "ConnectToWiFi/{ssid}"); companion object { fun getScreenByRoute(route: String): WiFiWizardScreen { return when (route) { WiFiList.route -> WiFiList ConnectToWiFi.name, ConnectToWiFi.route -> ConnectToWiFi else -> throw IllegalArgumentException("Unknown WiFiWizardScreen route: $route") } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun WiFiWizardAppBar( currentScreen: WiFiWizardScreen, canNavigateBack: Boolean, navigateUp: () -> Unit, modifier: Modifier = Modifier ) { TopAppBar( title = { Text(stringResource(currentScreen.title)) }, colors = TopAppBarDefaults.mediumTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer ), modifier = modifier, navigationIcon = { if (canNavigateBack) { IconButton(onClick = navigateUp) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = stringResource(R.string.back_button) ) } } } ) } @Composable fun WiFiWizardApp( navController: NavHostController = rememberNavController() ) { val backStackEntry by navController.currentBackStackEntryAsState() val currentScreen = WiFiWizardScreen.getScreenByRoute( backStackEntry?.destination?.route ?: WiFiWizardScreen.WiFiList.route ) val context = LocalContext.current fun openSettings() { try { context.startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) } catch (ex: RuntimeException) { Toast.makeText(context, R.string.cant_open_wifi_settings, Toast.LENGTH_SHORT).show() } } Scaffold( topBar = { WiFiWizardAppBar( currentScreen = currentScreen, canNavigateBack = navController.previousBackStackEntry != null, navigateUp = { navController.navigateUp() } ) } ) { innerPadding -> NavHost( navController = navController, startDestination = WiFiWizardScreen.WiFiList.name, modifier = Modifier.padding(innerPadding) ) { composable(route = WiFiWizardScreen.WiFiList.route) { WiFiListScreen( onWiFiClicked = { if (it.isNotEmpty()) { navController.navigate(WiFiWizardScreen.ConnectToWiFi.route.replace("{ssid}", it)) } }, onEnterManuallyClicked = { navController.navigate(WiFiWizardScreen.ConnectToWiFi.name) } ) } composable( route = WiFiWizardScreen.ConnectToWiFi.name, ) { EnterPasswordScreen( onSuccess = { navController.navigate(WiFiWizardScreen.WiFiList.route) }, onGoToSettings = { openSettings() } ) } composable( route = WiFiWizardScreen.ConnectToWiFi.route, arguments = listOf(navArgument("ssid") {type = NavType.StringType}) ) { EnterPasswordScreen( chosenSsid = it.arguments?.getString("ssid")!!, onSuccess = { navController.navigate(WiFiWizardScreen.WiFiList.route) }, onGoToSettings = { openSettings() } ) } } } }
0
Kotlin
0
0
6cdd14891401e8629fc6328e64d2641519c971a2
5,397
WiFiWizard
MIT License
src/main/kotlin/db/tables/GroupChatInviteMessages.kt
ertprs
330,072,795
true
{"Kotlin": 548594, "Dockerfile": 1135}
package com.neelkamath.omniChat.db.tables import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction /** @see [Messages] */ object GroupChatInviteMessages : Table() { override val tableName = "group_chat_invite_messages" private val messageId: Column<Int> = integer("message_id").uniqueIndex().references(Messages.id) private val groupChatId: Column<Int> = integer("group_chat_id").references(GroupChats.id) /** @see [Messages.createGroupChatInviteMessage] */ fun create(id: Int, groupChatId: Int): Unit = transaction { insert { it[this.messageId] = id it[this.groupChatId] = groupChatId } } /** Returns the ID of the invited chat. */ fun read(messageId: Int): Int = transaction { select { GroupChatInviteMessages.messageId eq messageId }.first()[groupChatId] } fun delete(idList: List<Int>): Unit = transaction { deleteWhere { messageId inList idList } } }
0
null
0
0
ce27f094c2d33967367be0c8d8e36c021272f77c
996
omni-chat
MIT License
platform/src/main/kotlin/researchstack/backend/application/service/mapper/InvestigatorStudyRelationMapper.kt
S-ResearchStack
520,365,362
false
{"Kotlin": 1297740, "Dockerfile": 202, "Shell": 59}
package researchstack.backend.application.service.mapper import org.mapstruct.Mapper import org.mapstruct.factory.Mappers import researchstack.backend.application.port.incoming.investigator.InviteInvestigatorCommand import researchstack.backend.domain.common.Email import researchstack.backend.domain.investigator.InvestigatorStudyRelation @Mapper abstract class InvestigatorStudyRelationMapper { abstract fun toDomain(command: InviteInvestigatorCommand): InvestigatorStudyRelation fun mapEmail(email: String): Email = Email(email) } private val converter = Mappers.getMapper(InvestigatorStudyRelationMapper::class.java) fun InviteInvestigatorCommand.toDomain(): InvestigatorStudyRelation = converter.toDomain(this)
1
Kotlin
9
29
edd76f219cdb10c8151b8ac14175b1e818a6036a
733
backend-system
Apache License 2.0
02-func-and-objects/app/src/main/java/com/example/funcandobjects/BankAccount.kt
omerfarukgulhan
855,786,708
false
{"Kotlin": 110308}
package com.example.funcandobjects class BankAccount(var accountNumber: String) { private var balance: Double = 0.0 init { printAccountDetails() } fun getBalance(): Double { return balance } fun printAccountDetails() { println("Account Number: ${getBalance()}") println("Current Balance: $$balance") } fun withdraw(amount: Double) { if (amount > 0) { if (amount <= balance) { balance -= amount println("withdrew: $$amount") } else { println("insufficient funds.") } } else { println("withdrawal amount must be positive.") } } fun deposit(amount: Double) { if (amount > 0) { balance += amount println("deposited: $$amount") } else { println("deposit amount must be positive.") } } }
0
Kotlin
0
0
a15360feabe764a68bcf7cb0d6489065b8df57d9
943
kotlin-workshops
MIT License
philarios-circleci/src/main/kotlin/io/philarios/circleci/Sugar.kt
taxpon
180,252,847
true
{"Kotlin": 666395, "Ruby": 7769, "Shell": 1002, "HTML": 398}
package io.philarios.circleci fun <C> JobBuilder<C>.run(body: RunBuilder<C>.() -> Unit) { step(RunStepSpec { run(body) }) } fun <C> JobBuilder<C>.run(command: String, body: RunBuilder<C>.() -> Unit = {}) { run { command(command) apply(body) } } fun <C> JobBuilder<C>.run(name: String, command: String, body: RunBuilder<C>.() -> Unit = {}) { run { name(name) command(command) apply(body) } } fun <C> JobBuilder<C>.runFromResource(name: String, resource: String, body: RunBuilder<C>.() -> Unit = {}) { run { name(name) command(readResource(resource)) apply(body) } } fun readResource(resource: String) = ClassLoader.getSystemResourceAsStream(resource).bufferedReader().readText() fun <C> JobBuilder<C>.checkout(body: CheckoutBuilder<C>.() -> Unit) { step(CheckoutStepSpec { checkout(body) }) } fun <C> JobBuilder<C>.checkout() { checkout { path(".") } } fun <C> JobBuilder<C>.setup_remote_docker(body: SetupRemoteDockerBuilder<C>.() -> Unit) { step(SetupRemoteDockerStepSpec { setup_remote_docker(body) }) } fun <C> JobBuilder<C>.save_cache(body: SaveCacheBuilder<C>.() -> Unit) { step(SaveCacheStepSpec { save_cache(body) }) } fun <C> JobBuilder<C>.restore_cache(body: RestoreCacheBuilder<C>.() -> Unit) { step(RestoreCacheStepSpec { restore_cache(body) }) } fun <C> JobBuilder<C>.deploy(body: RunBuilder<C>.() -> Unit) { step(DeployStepSpec { deploy(body) }) } fun <C> JobBuilder<C>.store_artifacts(body: StoreArtifactsBuilder<C>.() -> Unit) { step(StoreArtifactsStepSpec { store_artifacts(body) }) } fun <C> JobBuilder<C>.store_test_results(body: StoreTestResultsBuilder<C>.() -> Unit) { step(StoreTestResultsStepSpec { store_test_results(body) }) } fun <C> JobBuilder<C>.persist_to_workspace(body: PersistToWorkspaceBuilder<C>.() -> Unit) { step(PersistToWorkspaceStepSpec { persist_to_workspace(body) }) } fun <C> JobBuilder<C>.attach_workspace(body: AttachWorkspaceBuilder<C>.() -> Unit) { step(AttachWorkspaceStepSpec { attach_workspace(body) }) } fun <C> JobBuilder<C>.add_ssh_keys(body: AddSshKeysBuilder<C>.() -> Unit) { step(AddSshKeysStepSpec { add_ssh_keys(body) }) }
0
Kotlin
0
0
ea311f14fe3e62ea5f2b76f13bafe76ac5dfe073
2,375
philarios
MIT License
src/test/kotlin/days/aoc2021/Day24Test.kt
bjdupuis
435,570,912
false
{"Kotlin": 498025}
package days.aoc2021 import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert import org.junit.Test class Day24Test { private val day = Day24() @Test fun testPartOne() { val instructions1 = """ inp x mul x -1 """.trimIndent().lines() var alu = Day24.ALU(instructions1) MatcherAssert.assertThat(alu.processInstructionsWithInput("4").registers["x"], `is`(-4)) val instructions2 = """ inp z inp x mul z 3 eql z x """.trimIndent().lines() alu = Day24.ALU(instructions2) MatcherAssert.assertThat(alu.processInstructionsWithInput("39").registers["z"], `is`(1)) alu.reset() MatcherAssert.assertThat(alu.processInstructionsWithInput("37").registers["z"], `is`(0)) } }
0
Kotlin
0
1
8da2d31224769546a559280c47a13461a4f1e0a0
846
Advent-Of-Code
Creative Commons Zero v1.0 Universal
app/src/main/java/com/sqz/writingboard/glance/MainWidget.kt
Z-Siqi
685,058,978
false
{"Kotlin": 184638}
package com.sqz.writingboard.glance import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.ui.unit.dp import androidx.glance.GlanceId import androidx.glance.GlanceModifier import androidx.glance.GlanceTheme import androidx.glance.Image import androidx.glance.ImageProvider import androidx.glance.LocalContext import androidx.glance.LocalSize import androidx.glance.action.clickable import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.SizeMode import androidx.glance.appwidget.cornerRadius import androidx.glance.appwidget.lazy.LazyColumn import androidx.glance.appwidget.provideContent import androidx.glance.layout.Alignment import androidx.glance.layout.Box import androidx.glance.layout.Column import androidx.glance.layout.ContentScale import androidx.glance.layout.Spacer import androidx.glance.layout.fillMaxSize import androidx.glance.layout.padding import androidx.glance.layout.size import androidx.glance.text.FontFamily import androidx.glance.text.FontWeight import androidx.glance.text.Text import androidx.glance.text.TextStyle import com.sqz.writingboard.R class WritingBoardWidget : GlanceAppWidget() { override val sizeMode = SizeMode.Exact override suspend fun provideGlance(context: Context, id: GlanceId) { provideContent { Content() } } @Composable private fun Content(modifier: GlanceModifier = GlanceModifier) { val context = LocalContext.current val size = LocalSize.current val fontFamily = fontStyleData(context) Box( modifier = modifier, contentAlignment = Alignment.Center ) { WidgetBoard(size = size) LazyColumn( modifier = modifier.size(size.width - 12.dp, size.height - 8.dp) ) { item { Column { Text( text = savedText(context), style = TextStyle( color = GlanceTheme.colors.onSurfaceVariant, fontWeight = if (fontFamily != 1) { FontWeight.Bold } else { FontWeight.Medium }, fontFamily = when (fontFamily) { 0 -> FontFamily.Monospace 1 -> null 2 -> FontFamily.Serif 3 -> FontFamily.Cursive else -> null } ), modifier = modifier.fillMaxSize() ) Spacer(modifier = modifier.size(size.width, 45.dp)) } } } } Column( verticalAlignment = Alignment.Bottom, horizontalAlignment = Alignment.End, modifier = modifier.fillMaxSize().padding(8.dp) ) { Image( provider = ImageProvider(R.drawable.widget_button), contentDescription = LocalContext.current.getString(R.string.edit), modifier = modifier.size(45.dp).cornerRadius(12.dp) .clickable { openAppAction(context) }, contentScale = ContentScale.FillBounds ) } } }
0
Kotlin
1
9
477df96a7945b3a64f2e66b25c379f24a1c5e970
3,569
WritingBoard
MIT License
app/src/main/java/com/concordium/wallet/ui/transaction/sendfundsconfirmed/SendFundsConfirmedActivity.kt
Concordium
750,205,274
false
{"Kotlin": 1641344, "Java": 247867, "HTML": 31416, "CSS": 256}
package com.concordium.wallet.ui.transaction.sendfundsconfirmed import android.content.Intent import android.os.Bundle import android.view.View import androidx.lifecycle.ViewModelProvider import com.concordium.wallet.R import com.concordium.wallet.data.room.Recipient import com.concordium.wallet.data.room.Transfer import com.concordium.wallet.data.util.CurrencyUtil import com.concordium.wallet.databinding.ActivitySendFundsConfirmedBinding import com.concordium.wallet.ui.account.accountdetails.AccountDetailsActivity import com.concordium.wallet.ui.base.BaseActivity import com.concordium.wallet.util.CBORUtil class SendFundsConfirmedActivity : BaseActivity(R.layout.activity_send_funds_confirmed, R.string.send_funds_confirmed_title) { companion object { const val EXTRA_TRANSFER = "EXTRA_TRANSFER" const val EXTRA_RECIPIENT = "EXTRA_RECIPIENT" } private lateinit var viewModel: SendFundsConfirmedViewModel private val binding by lazy { ActivitySendFundsConfirmedBinding.bind(findViewById(R.id.root_layout)) } //region Lifecycle // ************************************************************ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val transfer = intent.extras!!.getSerializable(EXTRA_TRANSFER) as Transfer val recipient = intent.extras!!.getSerializable(EXTRA_RECIPIENT) as Recipient initializeViewModel() viewModel.initialize(transfer, recipient) initViews() closeBtn?.visibility = View.VISIBLE closeBtn?.setOnClickListener { gotoAccountDetails() } } override fun onBackPressed() { // Ignore back press } // endregion //region Initialize // ************************************************************ private fun initializeViewModel() { viewModel = ViewModelProvider( this, ViewModelProvider.AndroidViewModelFactory.getInstance(application) )[SendFundsConfirmedViewModel::class.java] } private fun initViews() { hideActionBarBack(false) binding.amountTextview.text = CurrencyUtil.formatGTU(viewModel.transfer.amount, withGStroke = true) binding.feeTextview.text = getString( R.string.send_funds_confirmed_fee_info, CurrencyUtil.formatGTU(viewModel.transfer.cost) ) if (viewModel.transfer.memo.isNullOrEmpty()) { binding.memoConfirmationTextview.visibility = View.GONE } else { binding.memoConfirmationTextview.visibility = View.VISIBLE binding.memoConfirmationTextview.text = getString( R.string.send_funds_confirmation_memo, viewModel.transfer.memo?.let { CBORUtil.decodeHexAndCBOR(it) } ?: "" ) } binding.confirmButton.setOnClickListener { gotoAccountDetails() } } //endregion //region Control/UI // ************************************************************ private fun gotoAccountDetails() { val intent = Intent(this, AccountDetailsActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } //endregion }
6
Kotlin
0
1
35ce1e40d756c9dabef4d72c2766a47c309f53ab
3,303
cryptox-android
Apache License 2.0
app/src/main/java/com/aemerse/quanage/activities/ProfileActivity.kt
akshaaatt
448,409,041
false
{"Kotlin": 140910, "Ruby": 465}
package com.aemerse.quanage.activities import android.app.Activity import android.content.Intent import android.graphics.drawable.Drawable import android.net.Uri import android.os.Bundle import android.view.View import android.view.View.GONE import androidx.appcompat.app.AppCompatActivity import com.aemerse.quanage.R import com.aemerse.quanage.databinding.ProfileActivityBinding import com.aemerse.quanage.utils.* import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.resource.bitmap.CenterCrop import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.firebase.ui.auth.AuthUI import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.UserProfileChangeRequest import com.google.firebase.storage.FirebaseStorage import id.zelory.compressor.Compressor import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.io.File class ProfileActivity : AppCompatActivity() { private lateinit var currentAuth: FirebaseUser private lateinit var binding: ProfileActivityBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up) binding = ProfileActivityBinding.inflate(layoutInflater) setContentView(binding.root) binding.bottomnavview.itemIconTintList = null binding.bottomnavview.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) currentAuth = FirebaseAuth.getInstance().currentUser!! binding.emailIdText.text = currentAuth.email binding.dobText.text = currentAuth.displayName if(currentAuth.phoneNumber.isNullOrEmpty()){ binding.phonell.visibility = GONE } else{ binding.phoneNumberText.text = currentAuth.phoneNumber } Glide.with(this).load(currentAuth.photoUrl) .transition(DrawableTransitionOptions.withCrossFade()) .apply(RequestOptions().transform(CenterCrop(), RoundedCorners(60))) .listener(object : RequestListener<Drawable?> { override fun onLoadFailed(e: GlideException?, model: Any, target: Target<Drawable?>, isFirstResource: Boolean): Boolean { binding.progressBar.visibility = GONE binding.faceRecognitionPic.visibility = View.VISIBLE return false } override fun onResourceReady(resource: Drawable?, model: Any, target: Target<Drawable?>, dataSource: DataSource, isFirstResource: Boolean): Boolean { binding.progressBar.visibility = GONE binding.faceRecognitionPic.visibility = View.VISIBLE return false } }).into(binding.faceRecognitionPic) binding.faceRecognitionPic.setOnClickListener { intent = Intent(applicationContext, SelectedImage::class.java) intent.putExtra("file", currentAuth.photoUrl) startActivity(intent) } binding.toolbar.setOnMenuItemClickListener { when(it.itemId){ R.id.signOut -> { GifDialog.Builder(this) .setTitle("Logout") .setMessage("Are you sure?") .setPositiveBtnText("Ok") .setPositiveBtnBackground("#22b573") .setNegativeBtnText("No") .setNegativeBtnBackground("#c1272d") .setGifResource(R.raw.cycling) .isCancellable(true) .OnPositiveClicked(object : GifDialog.GifDialogListener { override fun onClick() { AuthUI.getInstance() .signOut(this@ProfileActivity) .addOnCompleteListener { // user is now signed out startActivity(Intent(this@ProfileActivity, SplashActivity::class.java)) finish() } } }) .OnNegativeClicked(object : GifDialog.GifDialogListener { override fun onClick() {} }) .build() } R.id.update -> { if (!askForPermissions(this, permissionsToGive, permissionsRequest)) { val photoPickerIntent = Intent(Intent.ACTION_PICK) photoPickerIntent.type = "image/*" startActivityForResult(photoPickerIntent, 1) } } } false } binding.content.startRippleAnimation() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if(!askForPermissions(this, permissionsToGive, permissionsRequest)) { val photoPickerIntent = Intent(Intent.ACTION_PICK) photoPickerIntent.type = "image/*" startActivityForResult(photoPickerIntent, 1) } } private fun uploadFile(file: String) { GlobalScope.launch(Dispatchers.Default) { FirebaseStorage.getInstance().reference.child("Users") .child(FirebaseAuth.getInstance().currentUser!!.uid) .child("ProfilePic") .putFile(Uri.fromFile(Compressor.compress(applicationContext, File(file)))) .addOnSuccessListener { taskSnapshot -> taskSnapshot.metadata!!.reference!!.downloadUrl .addOnSuccessListener { uri: Uri -> val profileUpdates = UserProfileChangeRequest.Builder() .setPhotoUri(uri) .build() FirebaseAuth.getInstance().currentUser!!.updateProfile(profileUpdates).addOnSuccessListener { recreate() } } } } } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK && data != null) { when (requestCode) { 1 -> { uploadFile(getRealPathFromURI(data.data!!, this)!!) } } } } override fun onStart() { super.onStart() overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up) } private var mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { menuItem -> when (menuItem.itemId) { R.id.home -> { intent = Intent(applicationContext, MainActivity::class.java) startActivity(intent) } R.id.chat -> { intent = Intent(applicationContext, ChatsDM::class.java) startActivity(intent) } } false } }
0
Kotlin
0
0
cbe86a2ef172fcf38a3c5f17b29dd8256d0bddfd
7,797
Quanage-Android
Apache License 2.0
app/src/main/java/io/github/jingtuo/android/aa/ui/widget/AppList.kt
jingtuo
551,964,282
false
{"Kotlin": 69008}
package io.github.jingtuo.android.aa.ui.widget import android.content.pm.PackageInfo import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Clear import androidx.compose.material.icons.filled.Search import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import io.github.jingtuo.android.aa.ext.label import io.github.jingtuo.android.aa.ext.signInfo import io.github.jingtuo.android.aa.ui.model.AppListViewModel @Composable fun AppList(vm: AppListViewModel = viewModel(), onClickLog: () -> Unit, onClickItem: (pkgName: String) -> Unit) { Scaffold( topBar = { HomeTopAppBar(onClickLog) } ) { innerPadding -> Surface( modifier = Modifier.padding(innerPadding) ) { Column(modifier = Modifier.padding(top = 10.dp)) { var searchText by remember { mutableStateOf("") } val curPackages = vm.curPackages().observeAsState(emptyList<PackageInfo>()) Surface( modifier = Modifier .padding(horizontal = 16.dp) .fillMaxWidth() ) { OutlinedTextField( value = searchText, onValueChange = { searchText = it vm.search(it) }, leadingIcon = { Icon( imageVector = Icons.Default.Search, contentDescription = "搜索" ) }, trailingIcon = { if (searchText.isNotEmpty()) { Icon( imageVector = Icons.Default.Clear, contentDescription = "清除", modifier = Modifier .size(16.dp) .clickable { searchText = "" } ) } }, maxLines = 1, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Search ) ) } LazyColumn { items(curPackages.value) { it -> AppRow(it, onClickItem) Divider() } } } } } } @Composable fun AppRow(packageInfo: PackageInfo, onClickItem: (pkgName: String) -> Unit) { val context = LocalContext.current val labelWidth = 70.dp val dividerHeight = 6.dp Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 10.dp) .clickable { onClickItem(packageInfo.packageName) } ) { Row( modifier = Modifier.fillMaxWidth() ) { Text( text = "应用名: ", color = MaterialTheme.colors.onBackground, modifier = Modifier.width(labelWidth) ) Text( text = packageInfo.label(context.packageManager), color = MaterialTheme.colors.onBackground, modifier = Modifier.fillMaxWidth() ) } Divider( modifier = Modifier .fillMaxWidth() .height(dividerHeight), color = Color.Transparent ) Row( modifier = Modifier.fillMaxWidth() ) { Text( text = "包名: ", color = MaterialTheme.colors.onBackground, modifier = Modifier.width(labelWidth) ) Text( text = packageInfo.packageName, color = MaterialTheme.colors.onBackground, modifier = Modifier.fillMaxWidth() ) } Divider( modifier = Modifier .fillMaxWidth() .height(dividerHeight), color = Color.Transparent ) Row( modifier = Modifier.fillMaxWidth() ) { Text( text = "MD5: ", color = MaterialTheme.colors.onBackground, modifier = Modifier.width(labelWidth) ) Text( text = packageInfo.signInfo("MD5", true), color = MaterialTheme.colors.onBackground, modifier = Modifier.fillMaxWidth() ) } } }
0
Kotlin
0
2
02de06746966207bba02fc4b5ba716e5f17303c0
5,451
app-analysis
Apache License 2.0
SpaceSoccerr/app/src/main/java/aula5/example/spacesoccer/views/TermosECondicoes.kt
macyuri94
257,707,367
false
null
package aula5.example.spacesoccer.views import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import aula5.example.spacesoccer.R class TermosECondicoes : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.termos_e_condicoes) } }
0
Kotlin
0
1
e9f3d461cffe60934ca2980c2d46b5186bae2067
356
space_soccer
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/R.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.R: ImageVector get() { if (_r != null) { return _r!! } _r = Builder(name = "R", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.657f, 14.294f) curveTo(24.829f, 10.966f, 22.51f, 0.038f, 14.5f, 0.0f) horizontalLineTo(7.5f) curveTo(4.467f, 0.0f, 2.0f, 2.468f, 2.0f, 5.5f) verticalLineTo(22.5f) curveToRelative(0.034f, 1.972f, 2.967f, 1.971f, 3.0f, 0.0f) verticalLineToRelative(-7.5f) horizontalLineTo(14.5f) curveToRelative(0.038f, 0.0f, 0.076f, -0.005f, 0.114f, -0.006f) lineToRelative(4.575f, 8.234f) curveToRelative(0.405f, 0.731f, 1.33f, 0.981f, 2.04f, 0.583f) curveToRelative(0.725f, -0.402f, 0.985f, -1.315f, 0.583f, -2.04f) lineToRelative(-4.154f, -7.478f) close() moveTo(5.0f, 5.5f) curveToRelative(0.0f, -1.379f, 1.122f, -2.5f, 2.5f, -2.5f) horizontalLineToRelative(7.0f) curveToRelative(5.935f, 0.156f, 5.931f, 8.846f, 0.0f, 9.0f) horizontalLineTo(5.0f) verticalLineTo(5.5f) close() } } .build() return _r!! } private var _r: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,263
icons
MIT License
app/src/main/java/com/manu/pokedoke/network/IPokemonService.kt
ManaswiniKundeti
274,271,534
false
null
package com.manu.pokedoke.network import com.manu.pokedoke.model.PokemonInfo import com.manu.pokedoke.model.PokemonResponse import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query fun createPokemonService() : IPokemonService { val okHttpClient = OkHttpClient .Builder() .build() val retrofit = Retrofit.Builder() .client(okHttpClient) .baseUrl("https://pokeapi.co/api/v2/") .addConverterFactory(MoshiConverterFactory.create()) .build() return retrofit.create(IPokemonService::class.java) } interface IPokemonService { @GET("pokemon") fun fetchPokemonList( @Query("limit") limit: Int = 20, @Query("offset") offset: Int = 0 ): Call<PokemonResponse> @GET("pokemon/{name}") fun fetchPokemonDetails( @Path("name") name : String) : Call<PokemonInfo> }
1
Kotlin
5
5
04f7a7a29f072235204073394dea118b36bb3a01
1,021
Pokedoke
Apache License 2.0
app/src/main/java/com/patrykkosieradzki/androidmviexample/ui/composables/LifecycleUtils.kt
k0siara
374,188,998
false
null
package com.patrykkosieradzki.androidmviexample.ui.composables import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.collectAsState import androidx.compose.runtime.remember import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.flowWithLifecycle import kotlinx.coroutines.flow.StateFlow @Composable fun <T> lifecycleAwareState( lifecycleOwner: LifecycleOwner, stateFlow: StateFlow<T>, initialState: T ): State<T> { val lifecycleAwareStateFlow = remember(stateFlow, lifecycleOwner) { stateFlow.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED) } return lifecycleAwareStateFlow.collectAsState(initialState) }
0
Kotlin
3
58
5039dc84d560bd7ccdd43895108d3cde15df699f
766
AndroidMVIExample
Apache License 2.0
app/src/main/java/com/afra/cheforia/ui/HomeScreen.kt
afradigm
853,749,359
false
{"Kotlin": 50350}
package com.afra.cheforia.ui import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text 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.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.afra.cheforia.R import com.afra.cheforia.model.Recipe import com.afra.cheforia.ui.components.ErrorScreen import com.afra.cheforia.ui.components.LoadingScreen import com.afra.cheforia.ui.components.RecipeCard import com.afra.cheforia.ui.theme.CheforiaTheme import org.jetbrains.annotations.Debug @Composable fun HomeScreen( recipeUiState: RecipeUiState, retryAction: () -> Unit, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp) ) { when (recipeUiState) { is RecipeUiState.Loading -> LoadingScreen(modifier = modifier.fillMaxSize()) is RecipeUiState.Success -> PhotosGridScreen( recipes = recipeUiState.recipes, modifier = modifier.fillMaxSize(), contentPadding = contentPadding ) is RecipeUiState.Error -> ErrorScreen(retryAction, modifier = modifier.fillMaxSize()) } } @Composable fun PhotosGridScreen( recipes: List<Recipe>, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp) ) { LazyVerticalGrid( columns = GridCells.Fixed(2), modifier = modifier.padding(horizontal = 4.dp), contentPadding = contentPadding ) { items(items = recipes, key = { recipe -> recipe.id }) { recipe -> RecipeCard( recipe = recipe, isFavorite = false, //TODO add favorite logic onFavoriteClick = {}, onCardClick = {}, ) } } } @Preview(showBackground = true) @Composable fun LoadingScreenPreview() { CheforiaTheme { LoadingScreen() } } @Preview(showBackground = true) @Composable fun ErrorScreenPreview() { CheforiaTheme { ErrorScreen({}) } }
1
Kotlin
0
1
0e583ca99c9df4af703c8ddb27ca28e34cc03057
3,149
cheforia-android-app
Apache License 2.0
app/src/main/java/tf/samir/borrowtee/viewbase/RecyclerViewBindings.kt
samirtf
298,431,857
false
null
package tf.samir.borrowtee.viewbase import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView @BindingAdapter("items") fun setRecyclerViewItems( recyclerView: RecyclerView, items: List<RecyclerItem>? ) { var adapter = (recyclerView.adapter as? RecyclerViewAdapter) if (adapter == null) { adapter = RecyclerViewAdapter() recyclerView.adapter = adapter } adapter.submitList(items.orEmpty()) }
3
Kotlin
0
0
feb4cd97c194701505eaed98b811498a59a8e5da
467
borrowtee
MIT License
codebase/android/core/data/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/data/usecase/transactionfor/GetAllTransactionForValuesUseCase.kt
Abhimanyu14
429,663,688
false
{"Kotlin": 1459939, "Dart": 102426}
package com.makeappssimple.abhimanyu.financemanager.android.core.data.usecase.transactionfor import com.makeappssimple.abhimanyu.financemanager.android.core.data.repository.transactionfor.TransactionForRepository import com.makeappssimple.abhimanyu.financemanager.android.core.model.TransactionFor interface GetAllTransactionForValuesUseCase { suspend operator fun invoke(): List<TransactionFor> } class GetAllTransactionForValuesUseCaseImpl( private val transactionForRepository: TransactionForRepository, ) : GetAllTransactionForValuesUseCase { override suspend operator fun invoke(): List<TransactionFor> { return transactionForRepository.getAllTransactionForValues() } }
11
Kotlin
0
1
433728cb7a9003e38ea9f579d561e4e27b47ef76
702
finance-manager
Apache License 2.0
Plantilla/app/src/main/java/com/example/codigocolores/ui/AuthActivity.kt
jjmorleo
343,568,652
false
null
package com.example.codigocolores.ui import android.app.ActivityOptions import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.core.widget.addTextChangedListener import com.example.codigocolores.ColorActivity import com.example.codigocolores.R import com.example.codigocolores.databinding.ActivityAuthBinding import com.example.codigocolores.ui.A.AActivity import com.google.android.material.textfield.TextInputEditText import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class AuthActivity : AppCompatActivity() { private lateinit var binding: ActivityAuthBinding private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.Base_MyTheme) super.onCreate(savedInstanceState) auth = Firebase.auth binding = ActivityAuthBinding.inflate(layoutInflater) val view = binding.root setContentView(view) binding.mainIniciarSeccion.setOnClickListener { val editPassword = binding.mainTiePassword val password = editPassword.text if(password.isNullOrBlank()) { binding.mainIntroducirPassword.error = "¡La contraseña no puede estar vacia!" return@setOnClickListener } val intent = Intent(this, AActivity ::class.java) startActivity(intent) } binding.mainTiePassword.addTextChangedListener { val size = it!!.length if (size<5){ binding.mainIntroducirPassword.error = "Cracteres $size/5" }else{ binding.mainIntroducirPassword.error = "" } } binding.mainTiePassword.setOnClickListener { val textInputEditText = it as TextInputEditText //Casteo //Recuperamos el texto del editext lo convertimos a string y de este string comprobamos su longitud val size = textInputEditText.text.toString().length if (size<5) { binding.mainIntroducirPassword.error = "Cracteres $size/5" }else{ binding.mainIntroducirPassword.error = "" } } binding.mainRegistrate.setOnClickListener { val intent = Intent (this, RegistroActivity::class.java) startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this).toBundle()) } binding.mainTiePassword.setOnFocusChangeListener { _, hasFocus -> if (hasFocus) { binding.mainIntroducirPassword.error = "" } } } }
0
Kotlin
0
0
e0f95b0b7c2c1aa244f867d453735b51fea249e3
2,719
Codigo-Colores
MIT License
Dialogue/src/main/kotlin/Statistics.kt
AdorableParker
519,499,809
false
null
package org.nymph import net.mamoe.mirai.console.command.CommandManager import net.mamoe.mirai.console.command.MemberCommandSenderOnMessage import net.mamoe.mirai.console.command.SimpleCommand object Statistics : SimpleCommand( Dialogue, "Statistics", "统计", description = "统计问答数据" ) { override val usage: String = "${CommandManager.commandPrefix}统计 [关键词]\t#$description" @Handler suspend fun MemberCommandSenderOnMessage.main(key: String) { if (group.botMuteRemaining > 0) return val result = // Dialogue.SQLiteLink.executeDQLorDCL<CorpusData> { "SELECT * FROM Corpus WHERE answer GLOB '*$key*' OR question GLOB '*$key*';" } Dialogue.SQLiteLink.safeExecuteDQLorDCL<CorpusData>( "SELECT * FROM Corpus WHERE answer GLOB '*?*' OR question GLOB '*?*';", key, key ) result.error?.let { error -> sendMessage(error) return } (if (result.data.isEmpty()) "统计查询失败" else { val cSpecial = result.data.count { it.fromGroup == group.id } val cAvailable = result.data.count { it.fromGroup == 0L } + cSpecial "目前数据库含关键词[$key]的教学数据共计${result.data.size}条\n其中本群可读教学数据${cAvailable}条\n本群专属教学数据${cSpecial}条\n占本群可读的${ "%.2f".format( cSpecial.toDouble() / cAvailable * 100 ) }%,占数据库总量的${"%.2f".format(cSpecial.toDouble() / result.data.size * 100)}%" }).let { sendMessage(it) } } @Handler suspend fun MemberCommandSenderOnMessage.main() { if (group.botMuteRemaining > 0) return val result = Dialogue.SQLiteLink.executeDQLorDCL<CorpusData> { "SELECT * FROM Corpus;" } result.error?.let { error -> sendMessage(error) return } (if (result.data.isEmpty()) "统计查询失败" else { val cSpecial = result.data.count { it.fromGroup == group.id } val cAvailable = result.data.count { it.fromGroup == 0L } + cSpecial "目前数据库教学数据共计${result.data.size}条\n本群可读教学数据${cAvailable}条\n其中本群专属教学数据${cSpecial}条\n占本群可读的${ "%.2f".format( cSpecial.toDouble() / cAvailable * 100 ) }%,占数据库总量的${"%.2f".format(cSpecial.toDouble() / result.data.size * 100)}%" }).let { sendMessage(it) } } }
0
Kotlin
0
0
34ca0d5d5ab303b4d30bbd9415e1d17f2849bab7
2,413
MiraiConsolePlugins
Apache License 2.0
connectors/aws/lambda/src/main/kotlin/io/river/connector/aws/lambda/LambdaExt.kt
River-Kt
539,201,163
false
null
package io.river.connector.aws.lambda import io.river.core.mapParallel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.future.await import software.amazon.awssdk.core.SdkBytes import software.amazon.awssdk.services.lambda.LambdaAsyncClient import software.amazon.awssdk.services.lambda.model.InvocationType import software.amazon.awssdk.services.lambda.model.InvokeResponse import software.amazon.awssdk.services.lambda.model.LogType fun LambdaAsyncClient.invokeFlow( functionName: String, upstream: Flow<String>, invocationType: InvocationType = InvocationType.REQUEST_RESPONSE, logType: LogType? = null, qualifier: String? = null, clientContext: String? = null, parallelism: Int = 1 ): Flow<InvokeResponse> = upstream .mapParallel(parallelism) { content -> invoke { builder -> builder .functionName(functionName) .invocationType(invocationType) .logType(logType) .qualifier(qualifier) .clientContext(clientContext) .payload(SdkBytes.fromUtf8String(content)) }.await() }
11
Kotlin
1
7
0d31565394650e8fca318fd103e6009db6c3e93f
1,196
river
MIT License
next/kmp/window/src/commonMain/kotlin/org/dweb_browser/sys/window/core/modal/WindowModalState.kt
BioforestChain
594,577,896
false
{"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818}
package org.dweb_browser.sys.window.core.modal import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import org.dweb_browser.core.module.MicroModule import org.dweb_browser.core.std.dns.nativeFetch import org.dweb_browser.helper.Debugger import org.dweb_browser.helper.randomUUID import org.dweb_browser.helper.trueAlso import org.dweb_browser.pure.http.PureClientRequest import org.dweb_browser.pure.http.PureMethod import org.dweb_browser.sys.window.core.WindowController import org.dweb_browser.sys.window.core.constant.LowLevelWindowAPI import org.dweb_browser.sys.window.core.windowAdapterManager val debugModal = Debugger("modal") @OptIn(LowLevelWindowAPI::class) @Serializable sealed class ModalState() { val modalId = randomUUID() abstract val callbackUrl: String? /** * 关闭提示 * 如果非空,那么在用户尝试主动关闭模态窗口的时候,会弹出报警提示 */ var closeTip: String? = null /** * 是否只展示一次,之后自动销毁 */ val once = false @Transient protected val isOpenState = mutableStateOf(false) /** * 是否开启 */ var isOpen: Boolean = false private set val isClose get() = !isOpen var sessionId: Int = 1 private set @LowLevelWindowAPI open fun open() { this.sessionId += 1; this.isOpen = true this.isOpenState.value = true } suspend fun safeOpen(): Boolean { if (this._isDestroyed || this.isOpen) { return false } open() parent.updateOpeningModal() return true } @LowLevelWindowAPI open fun close() { this.isOpen = false this.isOpenState.value = false this.showCloseTip.value = "" } @OptIn(LowLevelWindowAPI::class) suspend fun safeClose(mm: MicroModule.Runtime) = this.isOpen.trueAlso { close(); /// 更新渲染中的modal parent.updateOpeningModal() // 发送 close 的信号 sendCallback(mm, CloseModalCallback(sessionId)) // 如果是一次性显示的,那么直接关闭它 if (once) { mm.scopeLaunch(cancelable = false) { safeDestroy(mm) } } } @Transient private var _isDestroyed = false @Transient internal val afterDestroy = CompletableDeferred<Unit>() suspend fun safeDestroy(mm: MicroModule.Runtime): Boolean { if (this._isDestroyed) { return false } this._isDestroyed = true afterDestroy.complete(Unit) /// 从parent中移除 parent.state.modals -= modalId /// 更新渲染中的modal parent.updateOpeningModal() /// 移除渲染器 windowAdapterManager.renderProviders.remove(renderId) /// 触发回调 sendCallback(mm, DestroyModalCallback(sessionId)) return true } @Transient internal val showCloseTip = mutableStateOf("") internal val isShowCloseTip get() = showCloseTip.value.isNotEmpty() @Composable abstract fun Render() var renderId: String = "" private set @Transient internal lateinit var parent: WindowController internal fun initParent(win: WindowController) { parent = win win.state.modals += modalId to this renderId = win.id + "/" + modalId /// 主窗口关闭的时候,它也要跟着被销毁 val mm = win.state.constants.microModule.value ?: throw Error("fail to get window's microModule") win.onClose { safeDestroy(mm) } } fun sendCallback(mm: MicroModule.Runtime, callbackData: ModalCallback) = callbackUrl?.also { url -> mm.scopeLaunch(cancelable = true) { mm.nativeFetch( PureClientRequest.fromJson( url, PureMethod.POST, body = callbackData ) ) } } /** * 关闭modal指令的发送器 */ @Transient internal val dismissFlow = MutableSharedFlow<Boolean>() @Composable protected fun TryShowCloseTip(onConfirmToClose: () -> Unit) { if (isShowCloseTip) { RenderCloseTipImpl(onConfirmToClose) } } private fun resetState() { close() } init { // 强制重制状态,确保反序列化出来的对象能正确工作 resetState() } } @Serializable sealed class ModalCallback { abstract val sessionId: Int } @Serializable @SerialName("open") data class OpenModalCallback(override val sessionId: Int) : ModalCallback(); @Serializable @SerialName("close") data class CloseModalCallback(override val sessionId: Int) : ModalCallback(); @Serializable @SerialName("close-alert") data class CloseAlertModalCallback(override val sessionId: Int, val confirm: Boolean) : ModalCallback(); @Serializable @SerialName("destroy") data class DestroyModalCallback(override val sessionId: Int) : ModalCallback(); enum class WindowModalState { INIT, OPENING, OPEN, CLOSING, CLOSE, DESTROYING, DESTROY, }
66
Kotlin
5
20
6db1137257e38400c87279f4ccf46511752cd45a
4,701
dweb_browser
MIT License
app/src/main/java/com/lyricgan/winky/hello/MainActivity.kt
LyricGan
429,727,070
false
null
package com.lyricgan.winky.hello import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<TextView>(R.id.tv_content).text = stringFromJNI() } private external fun stringFromJNI(): String? companion object { init { System.loadLibrary("hello-jni") } } }
0
Kotlin
0
0
b082a898d6a6afc39fce2b4c607294d5023fa5c4
557
Winky
Apache License 2.0
src/main/kotlin/org/carPooling/cars/domain/CarValidator.kt
ortzit
588,298,236
false
null
package org.carPooling.cars.domain import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service class CarValidator { private val logger: Logger = LoggerFactory.getLogger(this::class.java) fun check(cars: Collection<Car>) { cars.checkDuplicatedId() cars.forEach { checkSeatCount(it) } } private fun Collection<Car>.checkDuplicatedId() { this.distinctBy { it.id }.takeIf { carsWithUniqueIds -> carsWithUniqueIds.size != this.size }?.let { logger.info("Tried to load cars with duplicated ids") throw DuplicatedCarIdException("Duplicated 'id' field values found") } } private fun checkSeatCount(car: Car) { car.takeIf { it.seats < MIN_CAR_SEATS || it.seats > MAX_CAR_SEATS }?.let { invalidCar -> logger.info("Tried to add ${invalidCar.id} car with invalid seats count [${invalidCar.seats}]") throw InvalidNumberOfSeatsException( "[${car.id}] car seats value [${car.seats}] should be between $MIN_CAR_SEATS and $MAX_CAR_SEATS" ) } } companion object { private const val MIN_CAR_SEATS: Short = 4 private const val MAX_CAR_SEATS: Short = 6 } }
0
Kotlin
0
0
a39c6ad957e366480e19adef9a6089e1300535d1
1,267
car-pooling
MIT License
core/src/main/kotlin/ch/ergon/dope/resolvable/fromable/Bucket.kt
ergon
745,483,606
false
{"Kotlin": 252052}
package ch.ergon.dope.resolvable.fromable import ch.ergon.dope.resolvable.expression.AsteriskExpression sealed class Bucket(open val name: String) : Fromable { override fun toQueryString(): String = name } open class UnaliasedBucket(name: String) : Bucket(name) { fun alias(alias: String) = AliasedBucket(name, alias) } class AliasedBucket(name: String, val alias: String) : Bucket(name) { override fun toQueryString(): String = "$name AS $alias" } fun Bucket.asterisk() = AsteriskExpression(this)
2
Kotlin
0
3
e5cd66e4001b5d84a0812c7a604bc4c2a1bc9436
515
dope-query-builder
MIT License
core/src/commonMain/kotlin/com/sjaindl/s11/core/firestore/user/UserRepository.kt
sjaindl
833,289,183
false
{"Kotlin": 342674, "Ruby": 7377, "Swift": 1695, "HTML": 1023, "CSS": 306}
package com.sjaindl.s11.core.firestore.user import com.sjaindl.s11.core.firestore.user.model.User import dev.gitlive.firebase.Firebase import dev.gitlive.firebase.auth.FirebaseUser import dev.gitlive.firebase.auth.auth import dev.gitlive.firebase.storage.File import kotlinx.coroutines.flow.Flow import org.koin.core.component.KoinComponent interface UserRepository { suspend fun getUsers(): List<User> fun getUsersFlow(): Flow<List<User>> suspend fun getCurrentUser(): User? suspend fun getCurrentUserFlow(): Flow<User?> suspend fun createUser(user: FirebaseUser) suspend fun setUserName(uid: String, newName: String) suspend fun setUserPhotoRef(uid: String, file: File) suspend fun deleteUserPhotoRef(uid: String) suspend fun setFormation(uid: String, formationId: String) } internal class UserRepositoryImpl( private val userDataSource: UserDataSource, ): UserRepository, KoinComponent { private val auth by lazy { Firebase.auth } override suspend fun getUsers(): List<User> { return userDataSource.getUsers() } override fun getUsersFlow(): Flow<List<User>> { return userDataSource.getUsersFlow() } override suspend fun getCurrentUser() = auth.currentUser?.uid?.let { userDataSource.getUser(uid = it) } override suspend fun getCurrentUserFlow(): Flow<User?> { return userDataSource.getUserFlow() } override suspend fun createUser(user: FirebaseUser) { userDataSource.createUser(user = user) } override suspend fun setUserName(uid: String, newName: String) { userDataSource.setUserName(uid = uid, newName = newName) } override suspend fun setUserPhotoRef(uid: String, file: File) { userDataSource.setUserPhotoRef(uid = uid, file = file) } override suspend fun deleteUserPhotoRef(uid: String) { userDataSource.deleteUserPhotoRef(uid = uid) } override suspend fun setFormation(uid: String, formationId: String) { userDataSource.setFormation(uid = uid, formationId = formationId) } }
0
Kotlin
0
0
b06e955e5d8ed3d3a62274952d8187055864af6b
2,095
StartingEleven
MIT License
src/main/kotlin/me/katsumag/aspigotframework/worldbuilder/factories/SuperflatWorldFactory.kt
katsumag
281,989,662
false
null
package me.katsumag.aspigotframework.worldbuilder.factories import me.katsumag.aspigotframework.worldbuilder.generators.SuperflatWorldGenerator import me.katsumag.aspigotframework.worldbuilder.options.LayerOptions import org.bukkit.World import org.bukkit.WorldCreator class SuperflatWorldFactory(private val options: LayerOptions<SuperflatWorldGenerator>) { fun generate(name: String): World? { val creator = WorldCreator(name) creator.generator(SuperflatWorldGenerator(options)) return creator.createWorld() } }
0
Kotlin
0
0
c0580e5f70ea45690479a3b3868c2fda15a4f695
549
ASpigotFramework
MIT License
src/main/kotlin/com/example/DogResponse.kt
gledsonvsantos
759,418,822
false
{"Kotlin": 5216}
package com.example import io.micronaut.serde.annotation.Serdeable @Serdeable.Serializable @Serdeable.Deserializable data class DogResponse( val message: String, val status: String )
0
Kotlin
0
0
06a240e9224a48118b5a91fbb05ceb36582876d7
192
KotlinHttpClientsExploration
Apache License 2.0
src/me/anno/extensions/events/EventHandler.kt
AntonioNoack
456,513,348
false
null
package me.anno.extensions.events annotation class EventHandler(val priority: Int = 0)
0
Kotlin
1
9
b2532f7d40527eb2c9e24e3659dd904aa725a1aa
87
RemsEngine
Apache License 2.0
chapter_two/app/src/main/java/com/madona/chapter_two/app_one/SportsScoreApp.kt
PacktPublishing
797,780,112
false
{"Kotlin": 37589}
package com.madona.chapter_two.app_one import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun SportsScoreScreen() { val homeTeamScore = remember { mutableIntStateOf(0) } val awayTeamScore = remember { mutableIntStateOf(0) } LaunchedEffect(homeTeamScore.intValue) { // Perform some action when the home team score changes println("Home team score changed to ${homeTeamScore.intValue}") } LaunchedEffect(awayTeamScore.intValue) { // Perform some action when the away team score changes println("Away team score changed to ${awayTeamScore.intValue}") } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(text = "Home Team: ${homeTeamScore.intValue}") Button(onClick = { homeTeamScore.intValue++ }) { Text("Increment Home Team Score") } Spacer(modifier = Modifier.height(16.dp)) Text(text = "Away Team: ${awayTeamScore.intValue}") Button(onClick = { awayTeamScore.intValue++ }) { Text("Increment Away Team Score") } } } @Composable fun SportsApp() { val homeTeamScore = remember { mutableIntStateOf(0) } val awayTeamScore = remember { mutableIntStateOf(0) } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { ScoreDisplay(homeTeamScore.intValue, awayTeamScore.intValue) ScoreButtons( onIncrementHome = { homeTeamScore.intValue++ }, onIncrementAway = { awayTeamScore.intValue++ } ) } } @Composable fun ScoreDisplay(homeScore: Int, awayScore: Int) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text(text = "Home Team: $homeScore") Spacer(modifier = Modifier.height(16.dp)) Text(text = "Away Team: $awayScore") } } @Composable fun ScoreButtons(onIncrementHome: () -> Unit, onIncrementAway: () -> Unit) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Button(onClick = onIncrementHome) { Text("Increment Home Team Score") } Spacer(modifier = Modifier.height(16.dp)) Button(onClick = onIncrementAway) { Text("Increment Away Team Score") } } } @Preview(showBackground = true) @Composable fun ShowSportApp() { SportsScoreScreen() }
0
Kotlin
0
0
0d16dd5b35723301b3fdab214be42b1263c7cdf1
3,153
Modern-Android-15-Development-Cookbook-2nd-Edition
MIT License
core1/src/main/kotlin/coroutines/Future.kt
pull-vert
209,649,296
false
null
package coroutines import java.util.concurrent.Future /** * Cancels a specified [future] when this job is cancelled. * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created). * ``` * invokeOnCancellation { future.cancel(false) } * ``` */ public fun CancellableContinuation<*>.cancelFutureOnCancellation(future: Future<*>) = invokeOnCancellation(handler = CancelFutureOnCancel(future)) private class CancelFutureOnCancel(private val future: Future<*>) : CancelHandler() { override fun invoke(cause: Throwable?) { // Don't interrupt when cancelling future on completion, because no one is going to reset this // interruption flag and it will cause spurious failures elsewhere future.cancel(false) } override fun toString() = "CancelFutureOnCancel[$future]" }
0
Kotlin
0
0
2bf6a041b34a31765ecfbc6f925831f4d9351e07
869
kotlin-play
Apache License 2.0
shared/src/commonMain/kotlin/me/saket/press/shared/preferences/sync/stats/SyncStatsForNerdsPresenter.kt
saket
201,701,386
false
null
package me.saket.press.shared.preferences.sync.stats import com.badoo.reaktive.observable.ObservableWrapper import com.badoo.reaktive.observable.combineLatest import com.badoo.reaktive.observable.distinctUntilChanged import com.badoo.reaktive.observable.flatMap import com.badoo.reaktive.observable.startWithValue import com.badoo.reaktive.observable.switchMap import com.badoo.reaktive.observable.wrap import com.badoo.reaktive.single.Single import com.badoo.reaktive.single.asObservable import com.badoo.reaktive.single.observeOn import com.badoo.reaktive.single.singleFromFunction import com.badoo.reaktive.single.subscribeOn import me.saket.press.shared.localization.Strings import me.saket.press.shared.rx.Schedulers import me.saket.press.shared.syncer.Syncer import me.saket.press.shared.syncer.git.File import me.saket.press.shared.syncer.git.FileBasedSyncLogger import me.saket.press.shared.syncer.git.children import me.saket.press.shared.syncer.git.existsOrNull import me.saket.press.shared.ui.Presenter import me.saket.press.shared.util.format class SyncStatsForNerdsPresenter( private val syncer: Syncer, private val strings: Strings, private val schedulers: Schedulers, ) : Presenter<Nothing, SyncStatsForNerdsUiModel>() { override fun defaultUiModel(): SyncStatsForNerdsUiModel { return SyncStatsForNerdsUiModel( gitDirectorySize = strings.sync.nerd_stats_git_size.format("..."), logs = "" ) } override fun models(): ObservableWrapper<SyncStatsForNerdsUiModel> { return syncer.status() .switchMap { val formattedSize = syncer.directory.formatSize() .subscribeOn(schedulers.computation) .asObservable() .startWithValue(strings.sync.nerd_stats_git_size.format("...")) val logs = readSyncLogs() .subscribeOn(schedulers.io) .asObservable() .startWithValue("") combineLatest(formattedSize, logs, ::SyncStatsForNerdsUiModel) } .distinctUntilChanged() .wrap() } private fun File.formatSize(): Single<String> { return singleFromFunction { val bytes = try { children(recursively = true).map { it.sizeInBytes() }.sum() } catch (e: Throwable) { e.printStackTrace() null } strings.sync.nerd_stats_git_size.format( if (bytes != null) { val kb = bytes / 1024 val mb = kb / 1024 val gb = mb / 1024 when { mb < 1 -> "~$kb KB" gb < 1 -> "~$mb MB" else -> "~$gb GB" } } else { strings.sync.nerd_stats_git_size_unavailable } ) } } private fun readSyncLogs(): Single<String> { return singleFromFunction { FileBasedSyncLogger(syncer.directory).file .existsOrNull() ?.read() ?: strings.sync.nerd_stats_emptystate } } }
13
null
110
1,849
5f64350ec51402f3e6aeff145cbc35438780a03c
2,893
press
Apache License 2.0
library/src/main/java/org/dbtools/android/commons/ui/compose/image/ImageScrim.kt
jeffdcamp
521,116,574
false
{"Kotlin": 226673}
@file:Suppress("unused") package org.dbtools.android.commons.ui.compose.image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @Composable fun ImageScrim( modifier: Modifier = Modifier, alpha: Float = 0.15f ) { Box( modifier = modifier .fillMaxSize() .background(Color.Black.copy(alpha = alpha)) ) } @Composable fun BoxScope.ImageScrimTopDown( modifier: Modifier = Modifier, alpha: Float = 0.15f, height: Dp = 100.dp ) { Box( modifier = modifier .height(height) .fillMaxWidth() .align(Alignment.TopCenter) .background(brush = Brush.verticalGradient(colors = listOf(Color.Black.copy(alpha = alpha), Color.Transparent))) ) } @Composable fun BoxScope.ImageScrimBottomUp( modifier: Modifier = Modifier, alpha: Float = 0.15f, height: Dp = 100.dp ) { Box( modifier = modifier .height(height) .fillMaxWidth() .align(Alignment.BottomCenter) .background(brush = Brush.verticalGradient(colors = listOf(Color.Transparent, Color.Black.copy(alpha = alpha)))) ) } @Composable fun BoxScope.ImageScrimStartEnd( modifier: Modifier = Modifier, alpha: Float = 0.15f, width: Dp = 100.dp ) { Box( modifier = modifier .width(width) .fillMaxHeight() .align(Alignment.CenterStart) .background(brush = Brush.horizontalGradient(colors = listOf(Color.Black.copy(alpha = alpha), Color.Transparent))) ) } @Composable fun BoxScope.ImageScrimEndStart( modifier: Modifier = Modifier, alpha: Float = 0.15f, width: Dp = 100.dp ) { Box( modifier = modifier .width(width) .fillMaxHeight() .align(Alignment.CenterEnd) .background(brush = Brush.horizontalGradient(colors = listOf(Color.Transparent, Color.Black.copy(alpha = alpha)))) ) }
0
Kotlin
0
3
a725c575ec5ca9cf4323ddef8504236d54248c49
2,584
android-commons-ui
Apache License 2.0
ledger/storage/src/main/kotlin/org/knowledger/ledger/storage/results/IntoResult.kt
andrediogo92
122,662,386
false
{"Kotlin": 795385, "Rust": 9666, "Python": 228}
package org.knowledger.ledger.storage.results import org.knowledger.ledger.database.results.DataFailure import org.knowledger.ledger.database.results.QueryFailure import org.knowledger.ledger.results.propagate //--------------------------------------- //Into Ledger Result //--------------------------------------- fun LoadFailure.intoLedger(): LedgerFailure = when (this) { is LoadFailure.UnknownFailure -> LedgerFailure.UnknownFailure(failable.cause, failable.exception) is LoadFailure.NonExistentData -> LedgerFailure.NonExistentData(failable.cause) is LoadFailure.UnrecognizedDataType, is LoadFailure.DuplicatedTransaction, -> failable.propagate(LedgerFailure::Propagated) is LoadFailure.Propagated -> LedgerFailure.Propagated( "LoadFailure -> ${failable.pointOfFailure}", failable.inner ) } fun QueryFailure.intoLedger(): LedgerFailure = when (this) { is QueryFailure.UnknownFailure -> LedgerFailure.UnknownFailure(failable.cause, failable.exception) is QueryFailure.NonExistentData -> LedgerFailure.NonExistentData(failable.cause) is QueryFailure.Propagated -> LedgerFailure.Propagated( "QueryFailure -> ${failable.pointOfFailure}", failable ) } //----------------------------------------- // Into Load Result //----------------------------------------- fun DataFailure.intoLoad(): LoadFailure = when (this) { is DataFailure.UnknownFailure -> LoadFailure.UnknownFailure(failable.cause, failable.exception) is DataFailure.NonExistentData -> LoadFailure.NonExistentData(failable.cause) is DataFailure.UnrecognizedDataType, is DataFailure.UnrecognizedUnit, is DataFailure.UnexpectedClass, is DataFailure.NoUpdateNeeded, is DataFailure.NonRegisteredSchema, -> failable.propagate(LoadFailure::Propagated) is DataFailure.Propagated -> LoadFailure.Propagated( "DataFailure -> ${failable.pointOfFailure}", failable ) } fun LedgerFailure.intoLoad(): LoadFailure = when (this) { is LedgerFailure.UnknownFailure -> LoadFailure.UnknownFailure(failable.cause, failable.exception) is LedgerFailure.NonExistentData -> LoadFailure.NonExistentData(failable.cause) is LedgerFailure.NoKnownStorageAdapter -> failable.propagate(LoadFailure::Propagated) is LedgerFailure.Propagated -> LoadFailure.Propagated( "LedgerFailure -> ${failable.pointOfFailure}", failable ) } fun QueryFailure.intoLoad(): LoadFailure = when (this) { is QueryFailure.UnknownFailure -> LoadFailure.UnknownFailure(failable.cause, failable.exception) is QueryFailure.NonExistentData -> LoadFailure.NonExistentData(failable.cause) is QueryFailure.Propagated -> LoadFailure.Propagated( "QueryFailure -> ${failable.pointOfFailure}", failable ) } //------------------------------------- // Into Query Result //------------------------------------- fun LoadFailure.intoQuery(): QueryFailure = when (this) { is LoadFailure.UnknownFailure -> QueryFailure.UnknownFailure(failable.cause, failable.exception) is LoadFailure.NonExistentData -> QueryFailure.NonExistentData(failable.cause) is LoadFailure.UnrecognizedDataType, is LoadFailure.DuplicatedTransaction, -> failable.propagate(QueryFailure::Propagated) is LoadFailure.Propagated -> QueryFailure.Propagated( "LoadFailure -> ${failable.pointOfFailure}", failable ) } fun LedgerFailure.intoQuery(): QueryFailure = when (this) { is LedgerFailure.UnknownFailure -> QueryFailure.UnknownFailure(failable.cause, failable.exception) is LedgerFailure.NonExistentData -> QueryFailure.NonExistentData(failable.cause) is LedgerFailure.NoKnownStorageAdapter -> failable.propagate(QueryFailure::Propagated) is LedgerFailure.Propagated -> QueryFailure.Propagated( "LedgerResult -> ${failable.pointOfFailure}", failable ) } //--------------------------------------- // Into Data Result //--------------------------------------- fun QueryFailure.intoData(): DataFailure = when (this) { is QueryFailure.UnknownFailure -> DataFailure.UnknownFailure(failable.cause, failable.exception) is QueryFailure.NonExistentData -> DataFailure.NonExistentData(failable.cause) is QueryFailure.Propagated -> DataFailure.Propagated( "UnknownFailure -> ${failable.pointOfFailure}", failable ) }
0
Kotlin
1
3
0e5121243b9faf101b6d2ccf5bce60a657a31b4e
5,011
KnowLedger
MIT License
src/main/kotlin/org/example/detekt/util/Graph.kt
23522046
614,245,919
false
{"Kotlin": 245020, "Shell": 738}
package org.example.detekt.util import kotlin.collections.ArrayList //class to store edges of the weighted graph internal class Edge(var src: Int, var dest: Int, var weight: Int) // Graph class internal class Graph(edges: List<Edge>) { // node of adjacency list internal class Node(var value: Int, var weight: Int) // define adjacency list var adj_list = ArrayList<ArrayList<Node>>() //Graph Constructor init { // adjacency list memory allocation for (i in edges.indices) adj_list.add(i, ArrayList<Node>()) // add edges to the graph for (e in edges) { // allocate new node in adjacency List from src to dest adj_list[e.src].add(Node(e.dest, e.weight)) } } companion object { // print adjacency list for the graph fun printGraph(graph: Graph) { var srcVertex = 0 val listSize = graph.adj_list.size println("The contents of the graph:") while (srcVertex < listSize) { //traverse through the adjacency list and print the edges for (edge in graph.adj_list[srcVertex]) { print( "Vertex:" + srcVertex + " ==> " + edge.value + " (" + edge.weight + ")\t" ) } println() srcVertex++ } } } }
5
Kotlin
0
1
c253009ea715dfbd7c73d42647562e25184a0530
1,450
Detekt-Custom
Apache License 2.0
app/src/main/java/com/example/sneakersnap/AddNewSneaker.kt
codebyLFN
655,790,055
false
null
package com.example.sneakersnap import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Spinner import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.storage.FirebaseStorage import java.io.ByteArrayOutputStream class AddNewSneaker : AppCompatActivity() { private val PICK_IMAGE_REQUEST = 1 private val CAMERA_REQUEST_CODE = 2 private lateinit var addImageButton: Button private lateinit var imageView: ImageView private lateinit var addSneaker: Button private lateinit var sneakerName: EditText private lateinit var sneakerPrice: EditText private lateinit var sneakerSize: EditText private lateinit var sneakerBrand: Spinner private lateinit var cancelSneaker: Button private lateinit var cameraButton: Button private lateinit var firebaseAuth: FirebaseAuth private lateinit var firestore: FirebaseFirestore private lateinit var storage: FirebaseStorage private lateinit var user: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_new_sneaker) sneakerName = findViewById(R.id.etSneakerName) sneakerPrice = findViewById(R.id.etSneakerPrice) sneakerSize = findViewById(R.id.etSneakerSize) sneakerBrand = findViewById(R.id.spinnerSneakerBrand) addSneaker = findViewById(R.id.btnAddSneaker) cancelSneaker = findViewById(R.id.btnCancel) addImageButton = findViewById(R.id.btnAddImage) cameraButton = findViewById(R.id.btnCamera) imageView = findViewById(R.id.imageView) firebaseAuth = FirebaseAuth.getInstance() firestore = FirebaseFirestore.getInstance() storage = FirebaseStorage.getInstance() user = firebaseAuth.currentUser?.uid.toString() addImageButton.setOnClickListener { val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "image/*" } startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST) } cameraButton.setOnClickListener { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { openCamera() } else { ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA), CAMERA_REQUEST_CODE) } } addSneaker.setOnClickListener { val sneakerName = sneakerName.text.toString() val sneakerPrice = sneakerPrice.text.toString() val sneakerSize = sneakerSize.text.toString() val sneakerBrand = sneakerBrand.selectedItem.toString() if (imageView.tag != null) { val imageUri = Uri.parse(imageView.tag.toString()) val compressedImage = compressImage(MediaStore.Images.Media.getBitmap(this.contentResolver, imageUri)) if (compressedImage != null) { uploadImage(compressedImage) { imageUrl -> val sneakerImage = imageUrl ?: "" val sneaker = hashMapOf( "name" to sneakerName, "price" to sneakerPrice, "size" to sneakerSize, "brand" to sneakerBrand, "image" to sneakerImage, "user" to user ) firestore.collection("sneakers") .add(sneaker) .addOnSuccessListener { finish() } .addOnFailureListener { // handle error finish() } } } else { // Failed to compress image // Handle the error finish() } } else { // No image selected // Show an error message or handle it according to your app's requirements Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).show() finish() } } cancelSneaker.setOnClickListener { startActivity(Intent(this, SneakerCollection::class.java)) finish() } } // Camera private fun openCamera() { val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data?.data != null) { val imageUri = data.data imageView.setImageURI(imageUri) imageView.tag = imageUri.toString() } else if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK && data?.extras != null) { val imageBitmap = data.extras?.get("data") as Bitmap imageView.setImageBitmap(imageBitmap) val imageUri = getImageUriFromBitmap(imageBitmap) imageView.tag = imageUri.toString() } } private fun getImageUriFromBitmap(bitmap: Bitmap): Uri { val imagePath = MediaStore.Images.Media.insertImage(contentResolver, bitmap, "title", null) return Uri.parse(imagePath) } private fun compressImage(bitmap: Bitmap): Bitmap? { val maxHeight = 1280.0f val maxWidth = 1280.0f val scale = when { bitmap.width > bitmap.height -> maxHeight / bitmap.height else -> maxWidth / bitmap.width } val scaledWidth = (bitmap.width * scale).toInt() val scaledHeight = (bitmap.height * scale).toInt() return Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true) } private fun uploadImage(bitmap: Bitmap, onComplete: (String?) -> Unit) { val storageRef = storage.reference val imagesRef = storageRef.child("sneaker_images").child(user).child("${System.currentTimeMillis()}.jpg") val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos) val data = baos.toByteArray() val uploadTask = imagesRef.putBytes(data) uploadTask.addOnSuccessListener { imagesRef.downloadUrl.addOnSuccessListener { uri -> onComplete(uri.toString()) }.addOnFailureListener { exception -> onComplete(null) // Handle any errors Toast.makeText(this, exception.message, Toast.LENGTH_SHORT).show() } }.addOnFailureListener { exception -> onComplete(null) // Handle any errors } } }
0
Kotlin
1
2
7e15c32ea9b1877bbd7a77651d06b6b454fdeed0
7,560
SneakerSnap
MIT License
src/main/java/de/tum/www1/orion/build/instructor/OrionRunConfigurationProvider.kt
MDK5
344,242,897
true
{"Kotlin": 133045, "Java": 11785}
package de.tum.www1.orion.build.instructor import com.intellij.execution.RunnerAndConfigurationSettings interface OrionRunConfigurationProvider { fun provideBuildAndTestRunConfiguration(): RunnerAndConfigurationSettings }
0
Kotlin
0
0
190135cf809227301a8b33826af236d33f49ce89
227
Orion
MIT License
old-app-kotlin/src/main/java/tech/thdev/kotlin_udemy_sample/data/FlickrPhoto.kt
becooni
133,846,675
true
{"Kotlin": 125549, "Java": 48845}
package tech.thdev.kotlin_udemy_sample.data /** * Created by tae-hwan on 11/13/16. */ data class FlickrPhoto(val id: String, val secret: String, val server: String, val farm: Int, val dateuploaded: String, val owner: FlickrOwner, val title: FlickrContent, val description: FlickrContent, val dates: FlickrDates, val comments: FlickrContent, val views: String, val urls: FlickrUrls, val media: String) { /** * API : <a href="https://www.flickr.com/services/api/misc.urls.html">Photo source url</a> * https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg */ fun getImageUrl() = "https://farm$farm.staticflickr.com/$server/${id}_$secret.jpg" }
0
Kotlin
0
1
6d4964e1f6e70162b33a8d76023f1bd7557c2dfd
971
Kotlin-Udemy-Sample
Apache License 2.0
android/src/main/java/com/vydia/RNUploader/GlobalRequestObserverDelegate.kt
sedeepaksharma
461,828,271
true
{"Objective-C": 30466, "JavaScript": 21623, "Kotlin": 20756, "Java": 7754, "Starlark": 1934, "Shell": 1600, "Ruby": 1116, "Swift": 161, "C": 104}
package com.vydia.RNUploader import android.content.Context import android.util.Log import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.WritableMap import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter import net.gotev.uploadservice.data.UploadInfo import net.gotev.uploadservice.network.ServerResponse import net.gotev.uploadservice.observer.request.RequestObserverDelegate class GlobalRequestObserverDelegate(reactContext: ReactApplicationContext) : RequestObserverDelegate { private class ProgressEvent(var time: Long, var progress: Int) { } private val TAG = "UploadReceiver" private var reactContext: ReactApplicationContext = reactContext private val lastProgressEventRecords: HashMap<String, ProgressEvent> = HashMap() override fun onCompleted(context: Context, uploadInfo: UploadInfo) { } override fun onCompletedWhileNotObserving() { } override fun onError(context: Context, uploadInfo: UploadInfo, exception: Throwable) { val params = Arguments.createMap() params.putString("id", uploadInfo.uploadId) // Make sure we do not try to call getMessage() on a null object if (exception != null) { params.putString("error", exception.message) } else { params.putString("error", "Unknown exception") } resetLastProgressEventRecord(uploadInfo.uploadId); sendEvent("error", params, context) } override fun onProgress(context: Context, uploadInfo: UploadInfo) { val params = Arguments.createMap() params.putString("id", uploadInfo.uploadId) params.putInt("progress", uploadInfo.progressPercent) //0-100 if (canDispatchProgressEvent(uploadInfo.uploadId, uploadInfo.progressPercent)) { sendEvent("progress", params, context) } } override fun onSuccess(context: Context, uploadInfo: UploadInfo, serverResponse: ServerResponse) { val headers = Arguments.createMap() for ((key, value) in serverResponse.headers) { headers.putString(key, value) } val params = Arguments.createMap() params.putString("id", uploadInfo.uploadId) params.putInt("responseCode", serverResponse.code) params.putString("responseBody", serverResponse.bodyString) params.putMap("responseHeaders", headers) resetLastProgressEventRecord(uploadInfo.uploadId); sendEvent("completed", params, context) } /** * Sends an event to the JS module. */ private fun sendEvent(eventName: String, params: WritableMap?, context: Context) { reactContext?.getJSModule(RCTDeviceEventEmitter::class.java)?.emit("RNFileUploader-$eventName", params) ?: Log.e(TAG, "sendEvent() failed due reactContext == null!") } /** * dispatch progress event on progress changes and only after 1 second to last event */ private fun canDispatchProgressEvent(uploadId: String, progressPer: Int): Boolean { var progress = 1; if (progressPer > 1) { progress = progressPer; } val lastEventRecord = lastProgressEventRecords[uploadId]; var lastProgress: Int = 0; var lastTime: Long = 0; if (lastEventRecord != null) { lastProgress = lastEventRecord.progress; lastTime = lastEventRecord.time; } val currentTime = System.currentTimeMillis() if (lastEventRecord == null || lastProgress > progress || (lastProgress <= progress - 1 && currentTime - lastTime > 1 * 1000)) { lastProgressEventRecords[uploadId] = ProgressEvent(currentTime, progress); return true; } return false; } /** * reset upload progress event record */ private fun resetLastProgressEventRecord(uploadId: String) { lastProgressEventRecords.remove(uploadId); } }
0
Objective-C
0
2
8edfce2787ddbdc7e5cfd3ba1a36fa665f243eec
3,759
react-native-background-upload
MIT License
app/src/main/java/com/elementary/tasks/core/appwidgets/buttons/CombinedButtonsWidget.kt
naz013
165,067,747
false
{"Kotlin": 2615719, "HTML": 20926}
package com.elementary.tasks.core.appwidgets.buttons import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.widget.RemoteViews import com.elementary.tasks.R import com.elementary.tasks.birthdays.create.AddBirthdayActivity import com.elementary.tasks.core.appwidgets.WidgetUtils import com.elementary.tasks.notes.create.CreateNoteActivity import com.elementary.tasks.reminder.create.CreateReminderActivity class CombinedButtonsWidget : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { super.onUpdate(context, appWidgetManager, appWidgetIds) for (widgetId in appWidgetIds) { updateWidget(context, appWidgetManager, CombinedWidgetPrefsProvider(context, widgetId)) } } companion object { fun updateWidget( context: Context, appWidgetManager: AppWidgetManager, prefsProvider: CombinedWidgetPrefsProvider ) { val color = prefsProvider.getWidgetBackground() val rv = RemoteViews(context.packageName, R.layout.widget_combined_buttons) rv.setInt(android.R.id.background, "setBackgroundResource", WidgetUtils.newWidgetBg(color)) if (WidgetUtils.isDarkBg(color)) { WidgetUtils.initButton( context = context, rv = rv, iconId = R.drawable.ic_twotone_alarm_24px, color = R.color.pureWhite, viewId = R.id.btn_add_reminder, cls = CreateReminderActivity::class.java ) WidgetUtils.initButton( context = context, rv = rv, iconId = R.drawable.ic_twotone_note_24px, color = R.color.pureWhite, viewId = R.id.btn_add_note, cls = CreateNoteActivity::class.java ) WidgetUtils.initButton( context = context, rv = rv, iconId = R.drawable.ic_twotone_cake_24px, color = R.color.pureWhite, viewId = R.id.btn_add_birthday, cls = AddBirthdayActivity::class.java ) WidgetUtils.initButton( context = context, rv = rv, iconId = R.drawable.ic_twotone_mic_black_24px, color = R.color.pureWhite, viewId = R.id.btn_voice, cls = VoiceWidgetDialog::class.java ) } else { WidgetUtils.initButton( context = context, rv = rv, iconId = R.drawable.ic_twotone_alarm_24px, color = R.color.pureBlack, viewId = R.id.btn_add_reminder, cls = CreateReminderActivity::class.java ) WidgetUtils.initButton( context = context, rv = rv, iconId = R.drawable.ic_twotone_note_24px, color = R.color.pureBlack, viewId = R.id.btn_add_note, cls = CreateNoteActivity::class.java ) WidgetUtils.initButton( context = context, rv = rv, iconId = R.drawable.ic_twotone_cake_24px, color = R.color.pureBlack, viewId = R.id.btn_add_birthday, cls = AddBirthdayActivity::class.java ) WidgetUtils.initButton( context = context, rv = rv, iconId = R.drawable.ic_twotone_mic_black_24px, color = R.color.pureBlack, viewId = R.id.btn_voice, cls = VoiceWidgetDialog::class.java ) } appWidgetManager.updateAppWidget(prefsProvider.widgetId, rv) } } }
0
Kotlin
2
4
3334dc71c3451e90e675ffe1300fc1c0cac30046
3,547
reminder-kotlin
Apache License 2.0
basic-project/app/src/main/java/com/synerise/integration/app/di/DataModule.kt
Synerise
848,174,151
false
{"Kotlin": 490674}
package com.synerise.integration.app.di import android.content.Context import com.synerise.integration.app.product.storage.ProductDao import com.synerise.integration.app.product.storage.ProductDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DataModule { @Provides @Singleton fun provideDatabase(@ApplicationContext context: Context): ProductDatabase = ProductDatabase.create(context) @Provides fun provideDao(database: ProductDatabase): ProductDao { return database.productDao() } }
0
Kotlin
0
0
76bb2dd6190ff91be3734fd0961b1cf72282f007
749
android-codelabs
Apache License 2.0
playground/sandbox-compose/src/main/kotlin/com/sdds/playground/sandbox/switch/SandboxSwitch.kt
salute-developers
765,665,583
false
{"Kotlin": 1702334}
package com.sdds.playground.sandbox.switch import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.sdds.compose.uikit.Switch import com.sdds.playground.sandbox.SandboxTheme import com.sdds.playground.sandbox.tokens.compose.SddsServTheme @Composable internal fun SandboxSwitch( active: Boolean, modifier: Modifier = Modifier, onActiveChanged: ((Boolean) -> Unit)? = null, label: String? = null, description: String? = null, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, ) { Switch( active = active, modifier = modifier, onActiveChanged = onActiveChanged, label = label, description = description, labelColor = SddsServTheme.colors.textDefaultPrimary, descriptionColor = SddsServTheme.colors.textDefaultSecondary, labelTextStyle = SddsServTheme.typography.bodyMNormal, descriptionTextStyle = SddsServTheme.typography.bodySNormal, thumbColor = SddsServTheme.colors.surfaceOnDarkSolidDefault, activeTrackColor = SddsServTheme.colors.surfaceDefaultPositive, inactiveTrackColor = SddsServTheme.colors.surfaceDefaultTransparentTertiary, enabled = enabled, interactionSource = interactionSource, ) } @Composable @Preview internal fun SandboxSwitchPreviewOn() { SandboxTheme { SandboxSwitch( active = true, label = "Label", description = "Description", enabled = true, ) } } @Composable @Preview internal fun SandboxSwitchPreviewOff() { SandboxTheme { SandboxSwitch( active = false, label = "Label", description = "Description", enabled = false, ) } } @Composable @Preview internal fun SandboxSwitchPreviewOnDisabled() { SandboxTheme { SandboxSwitch( active = true, label = "Label", description = "Description", enabled = false, ) } }
2
Kotlin
0
1
f48c90444d32f4c25e25d87570daba44f6312f35
2,259
plasma-android
MIT License
app/src/main/java/com/odogwudev/user_authentication_compose_ktor_mongodb/data/repository/RepositoryImpl.kt
odogwudev
487,690,001
false
{"Kotlin": 62241}
package com.odogwudev.user_authentication_compose_ktor_mongodb.data.repository import com.odogwudev.user_authentication_compose_ktor_mongodb.data.remote.KtorApi import com.odogwudev.user_authentication_compose_ktor_mongodb.domain.model.ApiRequest import com.odogwudev.user_authentication_compose_ktor_mongodb.domain.model.ApiResponse import com.odogwudev.user_authentication_compose_ktor_mongodb.domain.model.UserUpdate import com.odogwudev.user_authentication_compose_ktor_mongodb.domain.repository.DataStoreOperation import com.odogwudev.user_authentication_compose_ktor_mongodb.domain.repository.Repository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class RepositoryImpl @Inject constructor( private val dataStoreOperations: DataStoreOperation, private val ktorApi: KtorApi ) : Repository { override suspend fun saveSignedInState(signedIn: Boolean) { dataStoreOperations.saveSignedInState(signedIn = signedIn) } override fun readSignedInState(): Flow<Boolean> { return dataStoreOperations.readSignedInState() } override suspend fun verifyTokenOnBackend(request: ApiRequest): ApiResponse { return try { ktorApi.verifyTokenOnBackend(request = request) } catch (e: Exception) { ApiResponse(success = false, error = e) } } override suspend fun getUserInfo(): ApiResponse { return try { ktorApi.getUserInfo() } catch (e: Exception) { ApiResponse(success = false, error = e) } } override suspend fun updateUser(userUpdate: UserUpdate): ApiResponse { return try { ktorApi.updateUser(userUpdate = userUpdate) } catch (e: Exception) { ApiResponse(success = false, error = e) } } override suspend fun deleteUser(): ApiResponse { return try { ktorApi.deleteUser() } catch (e: Exception) { ApiResponse(success = false, error = e) } } override suspend fun clearSession(): ApiResponse { return try { ktorApi.clearSession() } catch (e: Exception) { ApiResponse(success = false, error = e) } } }
0
Kotlin
1
3
a8b1ee274e43460ddccf7df49c894096ec72a257
2,231
user_authentication_compose_ktor_mongodb
MIT License
android_coverage_plugin/coverage-library/src/main/java/com/duqian/coverage_library/JacocoCallback.kt
duqian291902259
404,950,295
false
{"Ignore List": 10, "Text": 4, "Markdown": 5, "HTML": 40, "JavaScript": 11, "CSS": 2, "Shell": 13, "Batchfile": 1, "YAML": 4, "Maven POM": 1, "Dockerfile": 5, "JSON": 2, "Makefile": 1, "JSON with Comments": 1, "Vue": 6, "Java": 32, "Kotlin": 23, "Gradle": 10, "Java Properties": 5, "INI": 3, "Proguard": 3, "XML": 21, "Groovy": 9}
package com.duqian.coverage_library import java.io.File /** * Description:回调 * @author n20241 Created by 杜小菜 on 2022/1/21 - 10:01 . * E-mail: duqian2010@gmail.com */ interface JacocoCallback { fun onEcDumped(ecPath: String?) fun onEcUploaded(isSingleFile: Boolean, ecFile: File) fun onIgnored(failedMsg: String?) fun onLog(TAG: String?, msg: String?) }
2
Java
2
7
7044411b2f3216e40e77d0eb91a47aaa327362e4
374
android_coverage_jacoco
Apache License 2.0
app/src/main/java/com/kennyc/sleeptimer/main/MainActivity.kt
Kennyc1012
134,072,353
false
{"Kotlin": 28951}
package com.kennyc.sleeptimer.main import android.os.Bundle import android.preference.PreferenceManager import android.text.format.DateUtils import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.android.material.tabs.TabLayout import com.kennyc.sleeptimer.R import com.kennyc.sleeptimer.SleepTimerViewModelFactory import com.kennyc.sleeptimer.TimerService import com.kennyc.sleeptimer.options.OptionsFragment import com.kennyc.sleeptimer.timer.TimerFragment import kotlinx.android.synthetic.main.activity_main.* import timber.log.Timber class MainActivity : AppCompatActivity() { companion object { const val TAG = "MainActivity" const val ACTION_START_TIME = "$TAG.ACTION.START_TIMER" const val TAB_POSITION_TIMER = 0 const val TAB_POSITION_OPTIONS = 1 } private lateinit var viewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val factory = SleepTimerViewModelFactory(PreferenceManager.getDefaultSharedPreferences(applicationContext)) viewModel = ViewModelProviders.of(this, factory).get(MainViewModel::class.java) viewModel.currentTabPosition.observe(this, Observer { tab -> tab?.let { onTabChanged(it) } }) viewModel.fromAppShortcut.observe(this, Observer { result -> result?.let { onAppShortcut(it) } }) viewModel.checkForAppShortcut(intent) } private fun onTabChanged(position: Int) { Timber.v("onTabChanged: $position") when (position) { TAB_POSITION_TIMER -> { supportFragmentManager.beginTransaction() .replace(R.id.mainContent, TimerFragment()) .commit() } TAB_POSITION_OPTIONS -> { supportFragmentManager.beginTransaction() .replace(R.id.mainContent, OptionsFragment()) .commit() } else -> throw IllegalArgumentException("Unable to handle menu item with id $position") } } private fun onAppShortcut(fromShortcut: Boolean) { Timber.v("onAppShortcut: $fromShortcut") when (fromShortcut) { true -> { val lastTime = viewModel.getLastSavedTimer() val duration = lastTime * DateUtils.MINUTE_IN_MILLIS startService(TimerService.createIntent(applicationContext, duration)) finish() } else -> { setContentView(R.layout.activity_main) mainTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabReselected(tab: TabLayout.Tab) { // Ignore } override fun onTabUnselected(tab: TabLayout.Tab) { // Ignore } override fun onTabSelected(tab: TabLayout.Tab) { viewModel.onTabSelected(tab.position) } }) if (viewModel.currentTabPosition.value == null) { viewModel.currentTabPosition.value = TAB_POSITION_TIMER } } } } }
0
Kotlin
0
1
67bff9d23aeb0b8ace1fbb99c71c2644664678bf
3,376
Sleep-Timer
Apache License 2.0
app/src/main/java/ir/roohi/farshid/reminderpro/views/adapter/MapStyleAdapter.kt
FarshidRoohi
156,371,913
false
null
package ir.roohi.farshid.reminderpro.views.adapter import android.annotation.SuppressLint import android.graphics.Color import android.os.Handler import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.databinding.ViewDataBinding import ir.farshid_roohi.customadapterrecycleview.AdapterRecyclerView import ir.farshid_roohi.customadapterrecycleview.viewHolder.ItemViewHolder import ir.roohi.farshid.reminderpro.R import ir.roohi.farshid.reminderpro.Storage import ir.roohi.farshid.reminderpro.databinding.ItemMapStyleBinding import ir.roohi.farshid.reminderpro.keys.MAP_STYLE_URL import ir.roohi.farshid.reminderpro.model.MapStyle /** * Created by <NAME>. * ReminderPro | Copyrights 1/18/19. */ class MapStyleAdapter : AdapterRecyclerView<MapStyle>() { override fun getItemLayout(viewType: Int): Int { return R.layout.item_map_style } @SuppressLint("WrongConstant") override fun onBindView( viewDataBinding: ViewDataBinding, viewHolder:ItemViewHolder, position: Int, viewType: Int, element: MapStyle ) { val binding = viewDataBinding as ItemMapStyleBinding binding.txtTitle.text = element.title binding.imgMap.setImageResource(element.icon) binding.layoutRoot.setBackgroundColor(Color.TRANSPARENT) binding.txtTitle.setTextColor(getContextCompatColor(R.color.color_subtitle)) if (binding.root.context.resources.configuration.layoutDirection == 0) { binding.layoutRoot.layoutDirection = ViewCompat.LAYOUT_DIRECTION_LTR } else { binding.layoutRoot.layoutDirection = ViewCompat.LAYOUT_DIRECTION_RTL } if (element.status!!) { binding.layoutRoot.setBackgroundColor(getContextCompatColor(R.color.colorAccent)) binding.txtTitle.setTextColor(Color.WHITE) } binding.layoutRoot.setOnClickListener { items!!.forEach { item -> item.status = false } items!![viewHolder.adapterPosition].status = true binding.layoutRoot.setBackgroundColor(getContextCompatColor(R.color.colorAccent)) binding.txtTitle.setTextColor(Color.WHITE) Handler().post { notifyDataSetChanged() } Storage(viewDataBinding.root.context).put( String::class.java, MAP_STYLE_URL, items!![viewHolder.adapterPosition].url!! ) } } private fun getContextCompatColor(color: Int): Int { return ContextCompat.getColor(context!!, color) } }
9
Kotlin
8
32
ca8057f117442ae1ff292179723d0f779efbde7a
2,645
ReminderPro
Apache License 2.0
common/src/main/java/io/github/pelmenstar1/digiDict/common/GetLazyValue.kt
pelmenstar1
512,710,767
false
null
package io.github.pelmenstar1.digiDict.common /** * If [currentValue] is null, * then calls [create] lambda and the returned value of [create] is passed to [set] lambda * which should set argument [T] to some member in a class. * If [currentValue] isn't null, returns [currentValue] * * In other words, this just a convenience method for such code: * ``` * class SomeClass { * private var value: SomeType? = null * * fun useValue() { * var tempValue = value * * if(tempValue == null) { * tempValue = createValue() * value = tempValue * } * } * } * ``` * * This can be rewritten to: * class SomeClass { * private var value: SomeType? = null * * fun useValue() { * val tempValue = getLazyValue( * value, * { createValue() }, * { value = it } * ) * } * } * */ inline fun <T : Any> getLazyValue(currentValue: T?, create: () -> T, set: (T) -> Unit): T { currentValue?.let { return it } val newValue = create() set(newValue) return newValue }
6
Kotlin
0
3
76a8229099c3775bb36fff5cedb15b5bf54945df
1,114
DigiDictionary
MIT License
app/src/main/java/com/example/amoledwallpaper/wallpaperFirebase/Model/CategoryModel.kt
manojkp08
658,883,465
false
null
package com.example.amoledwallpaper.wallpaperFirebase.Model data class CategoryModel( val id: String = "", val link: String = "", val name: String = "" ){ }
0
Kotlin
0
0
f19c4eda5b381e6a5459eb29cac218222fd6dda5
171
Titan_Wallpapres
MIT License
cottontaildb-core/src/main/kotlin/org/vitrivr/cottontail/core/values/generators/ShortVectorValueGenerator.kt
vitrivr
160,775,368
false
{"Kotlin": 2769415, "TypeScript": 98011, "Java": 97672, "HTML": 38965, "ANTLR": 23679, "CSS": 8582, "SCSS": 1690, "JavaScript": 1441, "Dockerfile": 548}
package org.vitrivr.cottontail.core.values.generators import org.vitrivr.cottontail.core.types.VectorValue import org.vitrivr.cottontail.core.values.IntVectorValue import org.vitrivr.cottontail.core.values.ShortVectorValue import java.util.* import java.util.random.RandomGenerator /** * A [VectorValueGenerator] for [ShortVectorValue]s. * * @author <NAME> * @version 1.0.0 */ object ShortVectorValueGenerator: VectorValueGenerator<ShortVectorValue> { /** * Generates a [ShortVectorValue] of the given size initialized with random numbers. * * @param size Size of the new [ShortVectorValue] * @param rnd A [SplittableRandom] to generate the random numbers. * @return [ShortVectorValue] */ override fun random(size: Int, rnd: RandomGenerator) = ShortVectorValue(ShortArray(size) { rnd.nextInt().toShort() }) /** * Generates a [ShortVectorValue] of the given size initialized with ones. * * @param size Size of the new [ShortVectorValue] * @return [ShortVectorValue] */ override fun one(size: Int) = ShortVectorValue(ShortArray(size) { (1).toShort() }) /** * Generates a [IntVectorValue] of the given size initialized with zeros. * * @param size Size of the new [ShortVectorValue] * @return [ShortVectorValue] */ override fun zero(size: Int) = ShortVectorValue(ShortArray(size)) /** * Generates a [ShortVectorValue] given [Array] of [Number]s * * @param values List of [Number]s to generate the [VectorValue] for. * @return [ShortVectorValue] */ override fun with(values: Array<Number>) = ShortVectorValue(values) }
24
Kotlin
20
38
bc4d0aa435aac78628fa7771dbf8333f1fe5a971
1,660
cottontaildb
MIT License