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
kcrud-server/src/main/kotlin/kcrud/server/domain/contact/repository/IContactRepository.kt
perracodex
682,128,013
false
{"Kotlin": 476627, "CSS": 4664, "JavaScript": 3652, "HTML": 590}
/* * Copyright (c) 2024-Present <NAME>. All rights reserved. * This work is licensed under the terms of the MIT license. * For a copy, see <https://opensource.org/licenses/MIT> */ package kcrud.domain.contact.repository import kcrud.base.data.pagination.Page import kcrud.base.data.pagination.Pageable import kcrud.domain.contact.entities.ContactEntity import kcrud.domain.contact.entities.ContactRequest import kcrud.domain.employee.entities.EmployeeRequest import java.util.* interface IContactRepository { /** * Finds a contact by its id. * * @param contactId The id of the contact to be retrieved. * @return The contact if it exists, null otherwise. */ suspend fun findById(contactId: UUID): ContactEntity? /** * Finds a contact by the id of its employee. * * @param employeeId The id of the employee whose contact is to be retrieved. * @return The contact of the employee if it exists, null otherwise. */ suspend fun findByEmployeeId(employeeId: UUID): ContactEntity? /** * Retrieves all contacts. * @param pageable The pagination options to be applied. * If not provided, a single page with the result will be returned. * @return List of all contacts entities. */ suspend fun findAll(pageable: Pageable? = null): Page<ContactEntity> /** * Sets the contact of an employee, either by creating it, updating it * or deleting it, accordingly to the [employeeRequest]. * * @param employeeId The id of the employee to set the contact for. * @param employeeRequest The details of the employee to be processed. * @return The id of the contact if it was created or updated, null if it was deleted. */ suspend fun syncWithEmployee(employeeId: UUID, employeeRequest: EmployeeRequest): UUID? /** * Creates a new contact for an employee. * * @param employeeId The id of the employee to create the contact for. * @param contactRequest The details of the contact to be created. * @return The id of the created contact. */ suspend fun create(employeeId: UUID, contactRequest: ContactRequest): UUID /** * Updates the contact of an employee. * * @param contactId The id of the contact to be updated. * @param contactRequest The new details for the contact. * @return The number of rows updated. */ suspend fun update(employeeId: UUID, contactId: UUID, contactRequest: ContactRequest): Int /** * Deletes the contact of an employee. * * @param contactId The id of the contact to be deleted. * @return The number of rows deleted. */ suspend fun delete(contactId: UUID): Int /** * Deletes the contact of an employee. * * @param employeeId The id of the employee whose contact is to be deleted. * @return The number of rows deleted. */ suspend fun deleteByEmployeeId(employeeId: UUID): Int /** * Retrieves the total count of contacts. * * @param employeeId The ID of the employee to count its contacts, or null to count all contacts. * * @return The total count of contacts. */ suspend fun count(employeeId: UUID? = null): Int }
0
Kotlin
0
1
982ebb53ff47c6b46bbcf60fa0a901a02a2a675f
3,264
Kcrud
MIT License
capture/android/PressurePulsationsRecorder/src/main/java/com/avyss/ppr/acquisition/PressureCollectingListener.kt
avyss
165,913,335
false
null
package com.avyss.ppr.acquisition import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import com.avyss.ppr.data.NamedExportableData import com.avyss.ppr.data.NamedExportableValuesLine import com.avyss.ppr.data.RateAccommodatingSampleCollector class PressureCollectingListener( private val samplesPerSecond: Float, maxRecordingLengthSec: Int, recStartTimeNanos: Long ) : SensorEventListener { var dataCount: Int = 0 private val sampleCollector = RateAccommodatingSampleCollector( samplesPerSecond, maxRecordingLengthSec, recStartTimeNanos, 1 ) companion object { val SAMPLES_COLUMNS_NAMES = arrayOf("time [sec]", "pressure [hPa]") val SAMPLING_RATE_COLUMNS_NAMES = arrayOf("sampling_rate [Hz]") } override fun onSensorChanged(event: SensorEvent) { if (event.sensor.type != Sensor.TYPE_PRESSURE) { return } var pressureValue = event.values[0] // filter out unreasonable values of atmospheric pressure if (pressureValue.isInfinite() || pressureValue.isNaN() || (pressureValue <= 0)) { return } dataCount++ sampleCollector.onSampleAcquired(event.timestamp, pressureValue) } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {} fun exportablePressureSamples(): NamedExportableData { return sampleCollector.getExportable().withNames(SAMPLES_COLUMNS_NAMES) } fun exportableFs(): NamedExportableData { return NamedExportableValuesLine( SAMPLING_RATE_COLUMNS_NAMES, floatArrayOf(samplesPerSecond) ) } }
3
Kotlin
0
0
d6482b25c272a50ded476422185a0b7158a8224c
1,722
car-noise-pulsations
MIT License
src/main/kotlin/com/terraformation/backend/search/table/NurserySpeciesProjectsTable.kt
terraware
323,722,525
false
null
package com.terraformation.backend.search.table import com.terraformation.backend.auth.currentUser import com.terraformation.backend.db.default_schema.OrganizationId import com.terraformation.backend.db.default_schema.tables.references.ORGANIZATIONS import com.terraformation.backend.db.default_schema.tables.references.PROJECTS import com.terraformation.backend.db.default_schema.tables.references.SPECIES import com.terraformation.backend.db.nursery.tables.references.SPECIES_PROJECTS import com.terraformation.backend.search.SearchTable import com.terraformation.backend.search.SublistField import com.terraformation.backend.search.field.SearchField import org.jooq.Condition import org.jooq.OrderField import org.jooq.Record import org.jooq.TableField class NurserySpeciesProjectsTable(private val tables: SearchTables) : SearchTable() { override val primaryKey: TableField<out Record, out Any?> get() = SPECIES_PROJECTS.NURSERY_SPECIES_PROJECT_ID override val defaultOrderFields: List<OrderField<*>> get() = listOf(SPECIES_PROJECTS.SPECIES_ID, SPECIES_PROJECTS.PROJECT_ID) override val sublists: List<SublistField> by lazy { with(tables) { listOf( projects.asSingleValueSublist("project", SPECIES_PROJECTS.PROJECT_ID.eq(PROJECTS.ID)), species.asSingleValueSublist("species", SPECIES_PROJECTS.SPECIES_ID.eq(SPECIES.ID)), organizations.asSingleValueSublist( "organization", SPECIES_PROJECTS.ORGANIZATION_ID.eq(ORGANIZATIONS.ID)), ) } } override val fields: List<SearchField> = emptyList() override fun conditionForVisibility(): Condition { return SPECIES_PROJECTS.ORGANIZATION_ID.`in`(currentUser().organizationRoles.keys) } override fun conditionForOrganization(organizationId: OrganizationId): Condition { return SPECIES_PROJECTS.ORGANIZATION_ID.eq(organizationId) } }
6
null
1
9
b22d00af6b23775bee0852717b95ee743ae77f46
1,879
terraware-server
Apache License 2.0
app/src/main/java/io/github/hunachi/appointment/ui/profile/ProfileFragment.kt
Hunachi
257,057,650
false
null
package io.github.hunachi.appointment.ui.profile import androidx.lifecycle.ViewModelProviders import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import io.github.hunachi.appointment.MyPreference import io.github.hunachi.appointment.R import io.github.hunachi.appointment.data.User import kotlinx.android.synthetic.main.profile_fragment.* class ProfileFragment : Fragment() { private lateinit var preference: MyPreference private lateinit var viewModel: ProfileViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.profile_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(this).get(ProfileViewModel::class.java) preference = MyPreference(activity?.application!!) val user = preference.user() name.setText(user.name) student_number.setText(user.number) department.setText(user.department) address_mail.setText(user.mail) activity?.title = "Profile" } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) btn_submit.setOnClickListener { User( name = name.text.toString(), number = student_number.text.toString(), department = department.text.toString(), mail = address_mail.text.toString() ).let { preference.saveUser(it) } } } }
0
Kotlin
0
0
070523db7d34ce0065d03096819502c69c948a3b
1,873
Appointment
MIT License
shared/src/commonMain/kotlin/ru/blays/ficbook/reader/shared/data/repo/declaration/ICommentsRepo.kt
B1ays
710,470,973
false
{"Kotlin": 1547861}
package ru.blays.ficbook.reader.shared.data.repo.declaration import ru.blays.ficbook.api.dataModels.ListResult import ru.blays.ficbook.api.result.ApiResult import ru.blays.ficbook.reader.shared.data.dto.CommentModelStable interface ICommentsRepo { suspend fun getForPart(partID: String, page: Int): ApiResult<ListResult<CommentModelStable>> suspend fun getAll(href: String, page: Int): ApiResult<ListResult<CommentModelStable>> suspend fun postComment(partID: String, text: String, followType: Int): ApiResult<Boolean> suspend fun delete(commentID: String): ApiResult<Boolean> suspend fun like(commentID: String, like: Boolean): ApiResult<Boolean> }
0
Kotlin
2
15
929543039e0211289ef9a0ed75592ecb6b7d98f8
671
ficbook-reader
MIT License
app/src/main/java/com/stefan/universe/ui/main/data/model/User.kt
stefan12an
783,755,453
false
{"Kotlin": 73012}
package com.stefan.universe.ui.main.data.model interface User { val uid: String val email: String val displayName: String val photoUri: String val emailVerified: Boolean } data class FirebaseUserModel( override val uid: String = "", override val email: String = "", override val displayName: String = "", override val photoUri: String = "", override val emailVerified: Boolean = false ) : User
0
Kotlin
0
0
044c20e8e5e942367da933e4dee774a4a416d729
435
universe
Apache License 2.0
distributed-systems/consistent-hashing/src/Storage.kt
Lascor22
331,294,681
false
{"Java": 1706475, "HTML": 436528, "CSS": 371563, "C++": 342426, "Jupyter Notebook": 274491, "Kotlin": 248153, "Haskell": 189045, "Shell": 186916, "JavaScript": 159132, "Vue": 45665, "Python": 25957, "PLpgSQL": 23402, "Clojure": 11410, "Batchfile": 9677, "FreeMarker": 7201, "Yacc": 7148, "ANTLR": 6303, "Scala": 3020, "Lex": 1136, "Makefile": 473, "Grammatical Framework": 113}
class Storage { private val arr = ArrayList<Entry>(0) fun addToStorage(hash: Int, shard: Shard) { arr.add(Entry(hash, shard)) arr.sortBy { entry -> entry.hash } } fun isEmpty(): Boolean { return arr.isEmpty() } fun findAllHashes(shard: Shard): List<Int> { return arr.filter { entry -> entry.shard == shard } .map { entry -> entry.hash } } fun remove(shard: Shard) { arr.filter { entry -> entry.shard == shard } .forEach { entry -> arr.remove(entry) } } fun searchShard(hash: Int): Shard { return upperBound(hash).shard } fun searchAddBounds(hash: Int): Pair<Shard, HashRange> { val right = upperBound(hash) val left = lowerBound(hash) return Pair(right.shard, HashRange(left.hash + 1, hash)) } fun searchRemoveBounds(hash: Int, shard: Shard): Pair<Shard, HashRange> { var right = upperBound(hash + 1) while (right.shard == shard) { right = upperBound(right.hash + 1) } var left = lowerBound(hash) while (left.shard == shard) { left = lowerBound(left.hash) } return Pair(right.shard, HashRange(left.hash + 1, hash)) } private fun upperBound(hash: Int): Entry { val right = generalBinary(hash).second if (right == arr.size) { return upperBound(Int.MIN_VALUE) } return arr[right] } private fun lowerBound(hash: Int): Entry { val left = generalBinary(hash).first if (left == -1) { return lowerBound(Int.MAX_VALUE) } return arr[left] } private fun generalBinary(hash: Int): Pair<Int, Int> { var left = -1 var right = arr.size while (left < right - 1) { val mid = (right + left) / 2 if (arr[mid].hash < hash) { left = mid } else { right = mid } } return Pair(left, right) } } data class Entry(val hash: Int, val shard: Shard)
1
null
1
1
c41dfeb404ce995abdeb18fc93502027e54239ee
2,101
ITMO-university
MIT License
app/src/main/java/com/holiday/data/local/type_converters/ArrayListConverter.kt
kelvinkioko
595,959,798
false
null
package com.holiday.data.local.type_converters import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.lang.reflect.Type class ArrayListConverter { @TypeConverter fun fromStringArrayList(value: List<String>? = null): String { value?.let { return Gson().toJson(value) } ?: run { return "" } } @TypeConverter fun toStringArrayList(value: String): List<String> { return try { val listType: Type = object : TypeToken<List<String>>() {}.type Gson().fromJson(value, listType) } catch (e: Exception) { arrayListOf() } } }
0
Kotlin
0
0
183d6e084e1803f8ea818697885fa0c51027aa2d
710
Public-Holiday
Apache License 2.0
android/src/main/java/com/reactnativepedometer/StepCounterRecord.kt
rlmma
295,883,375
false
null
package com.mareksaktor.reactnativestepcounteriosandroid import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.util.Log import android.os.SystemClock import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReactContext import com.facebook.react.bridge.WritableMap import com.facebook.react.modules.core.DeviceEventManagerModule import com.facebook.react.bridge.ReactApplicationContext import android.content.Context class StepCounterRecord(reactContext: ReactApplicationContext) : SensorEventListener { private var mSensorManager: SensorManager = reactContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager private lateinit var mStepCounter:Sensor private var lastUpdate:Long = 0 private var i = 0 private var delay:Int = 0 private var reactContext:ReactContext = reactContext fun start(delay: Int): Int { this.delay = delay mStepCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) mSensorManager.registerListener(this, mStepCounter, SensorManager.SENSOR_DELAY_FASTEST) return 1 } fun stop() { mSensorManager.unregisterListener(this) } private fun sendEvent(eventName:String, params:WritableMap?) { try { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) .emit(eventName, params) } catch (e:RuntimeException) { Log.e("ERROR", "java.lang.RuntimeException: Trying to invoke JS before CatalystInstance has been set!") } } override fun onSensorChanged(sensorEvent: SensorEvent) { val mySensor = sensorEvent.sensor val map = Arguments.createMap() if (mySensor.type === Sensor.TYPE_STEP_COUNTER) { val curTime = System.currentTimeMillis() i++ if ((curTime - lastUpdate) > delay) { i = 0 val curSteps = sensorEvent.values[0].toDouble() val bootTime = curTime - SystemClock.elapsedRealtime() if (curSteps != null) { map.putDouble("steps", curSteps) map.putDouble("bootTimeMs", bootTime.toDouble()) } sendEvent("StepCounter", map) lastUpdate = curTime } } } override fun onAccuracyChanged(sensor:Sensor, accuracy:Int) {} }
2
null
4
5
26365482ade68319a1b75be5ffe9c059fd6c2d0a
2,327
react-native-pedometer
MIT License
platform/vcs-impl/src/com/intellij/openapi/diff/impl/combined/search/CombinedEditorSearchSessionListener.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.diff.impl.combined.search import com.intellij.openapi.editor.Editor import java.util.* /** * A listener for events related to [CombinedEditorSearchSession] (session with multiple editor session aggregated) */ interface CombinedEditorSearchSessionListener : EventListener { /** * Callback when during next/previous invocation the current [editor] changed. * Implementors may want to scroll to such [editor]. * * @param forward search direction * @param editor the editor where the search is performed */ fun onSearch(forward: Boolean, editor: Editor) /** * Notify that the status text is changed. Found [matches] within [files]. * * @param matches the number of matches found * @param files the number of files processed */ fun statusTextChanged(matches: Int, files: Int) }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
970
intellij-community
Apache License 2.0
feature/main/src/main/java/com/t8rin/imagetoolboxlite/feature/main/presentation/components/PickFontFamilySheet.kt
T8RIN
767,600,774
false
null
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (Malik Mukhametzyanov) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package com.t8rin.imagetoolboxlite.feature.main.presentation.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells import androidx.compose.foundation.lazy.staggeredgrid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.FontDownload import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.t8rin.imagetoolboxlite.core.resources.R import com.t8rin.imagetoolboxlite.core.settings.presentation.UiFontFam import com.t8rin.imagetoolboxlite.core.ui.widget.buttons.EnhancedButton import com.t8rin.imagetoolboxlite.core.ui.widget.other.FontSelectionItem import com.t8rin.imagetoolboxlite.core.ui.widget.sheets.SimpleSheet import com.t8rin.imagetoolboxlite.core.ui.widget.text.AutoSizeText import com.t8rin.imagetoolboxlite.core.ui.widget.text.TitleItem @Composable fun PickFontFamilySheet( visible: MutableState<Boolean>, onFontSelected: (UiFontFam) -> Unit ) { SimpleSheet( visible = visible, sheetContent = { LazyVerticalStaggeredGrid( columns = StaggeredGridCells.Adaptive(250.dp), contentPadding = PaddingValues(16.dp), verticalItemSpacing = 8.dp, horizontalArrangement = Arrangement.spacedBy( alignment = Alignment.CenterHorizontally, space = 8.dp ) ) { items(UiFontFam.entries) { font -> FontSelectionItem( font = font, onClick = { onFontSelected(font) } ) } } }, confirmButton = { EnhancedButton( onClick = { visible.value = false } ) { AutoSizeText(stringResource(R.string.close)) } }, title = { TitleItem( icon = Icons.Rounded.FontDownload, text = stringResource(R.string.font), ) } ) }
5
null
90
8
f8fe322c2bde32544e207b49a01cfeac92c187ce
3,155
ImageToolboxLite
Apache License 2.0
src/main/kotlin/cn/enaium/jimmer/gradle/SettingPlugin.kt
Enaium
762,181,289
false
{"Kotlin": 97918}
/* * Copyright 2024 Enaium * * 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 cn.enaium.jimmer.gradle import cn.enaium.jimmer.gradle.extension.SettingExtension import cn.enaium.jimmer.gradle.utility.lib import org.gradle.api.Plugin import org.gradle.api.initialization.Settings /** * @author Enaium */ class SettingPlugin : Plugin<Settings> { override fun apply(target: Settings) { val extension = target.extensions.create("jimmer", SettingExtension::class.java) target.dependencyResolutionManagement.versionCatalogs.apply { register("jimmer_catalog") { it.plugin("jimmer", "cn.enaium.jimmer.gradle").version { // Nothing } it.plugin("ksp", "com.google.devtools.ksp").version { // Nothing } it.lib("apt", "apt").version(extension.version.get()) it.lib("bom", "bom").version(extension.version.get()) it.lib("client", "client").version(extension.version.get()) it.lib("coreKotlin", "core-kotlin").version(extension.version.get()) it.lib("core", "core").version(extension.version.get()) it.lib("dtoCompiler", "dto-compiler").version(extension.version.get()) it.lib("ksp", "ksp").version(extension.version.get()) it.lib("mapstructApt", "mapstruct-apt").version(extension.version.get()) it.lib("springBootStarter", "spring-boot-starter").version(extension.version.get()) it.lib("sqlKotlin", "sql-kotlin").version(extension.version.get()) it.lib("sql", "sql").version(extension.version.get()) } } } }
0
Kotlin
0
7
fcb967934dc9c6d848afc74ab00aab424fbe8466
2,256
jimmer-gradle
Apache License 2.0
src/main/kotlin/no/nav/familie/ks/sak/kjerne/behandling/domene/BehandlingRepository.kt
navikt
533,308,075
false
null
package no.nav.familie.ks.sak.kjerne.behandling.domene import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import java.math.BigInteger interface BehandlingRepository : JpaRepository<Behandling, Long> { @Query(value = "SELECT b FROM Behandling b WHERE b.id = :behandlingId") fun hentBehandling(behandlingId: Long): Behandling @Query( "SELECT b FROM Behandling b JOIN b.fagsak f WHERE f.arkivert = false AND b.id=:behandlingId AND b.aktiv = true " ) fun hentAktivBehandling(behandlingId: Long): Behandling @Query(value = "SELECT b FROM Behandling b JOIN b.fagsak f WHERE f.id = :fagsakId AND f.arkivert = false") fun finnBehandlinger(fagsakId: Long): List<Behandling> @Query( "SELECT b FROM Behandling b JOIN b.fagsak f WHERE f.id = :fagsakId AND f.arkivert = false " + "AND b.aktiv = true " ) fun findByFagsakAndAktiv(fagsakId: Long): Behandling? @Query( "SELECT b FROM Behandling b JOIN b.fagsak f WHERE f.id = :fagsakId AND f.arkivert = false AND " + "b.aktiv = true AND b.status <> 'AVSLUTTET'" ) fun findByFagsakAndAktivAndOpen(fagsakId: Long): Behandling? @Query( """SELECT b FROM Behandling b INNER JOIN TilkjentYtelse ty on b.id = ty.behandling.id WHERE b.fagsak.id = :fagsakId AND ty.utbetalingsoppdrag IS NOT NULL""" ) fun finnIverksatteBehandlinger(fagsakId: Long): List<Behandling> @Query( """ select b from Behandling b where b.fagsak.id = :fagsakId and b.status = 'IVERKSETTER_VEDTAK' """ ) fun finnBehandlingerSomHolderPåÅIverksettes(fagsakId: Long): List<Behandling> @Query( """select b from Behandling b inner join BehandlingStegTilstand bst on b.id = bst.behandling.id where b.fagsak.id = :fagsakId AND bst.behandlingSteg = 'BESLUTTE_VEDTAK' AND bst.behandlingStegStatus IN (no.nav.familie.ks.sak.kjerne.behandling.steg.BehandlingStegStatus.KLAR, no.nav.familie.ks.sak.kjerne.behandling.steg.BehandlingStegStatus.VENTER)""" ) fun finnBehandlingerSendtTilGodkjenning(fagsakId: Long): List<Behandling> @Query("SELECT b FROM Behandling b JOIN b.fagsak f WHERE f.id = :fagsakId AND b.status = 'AVSLUTTET' AND f.arkivert = false") fun finnByFagsakAndAvsluttet(fagsakId: Long): List<Behandling> @Query( value = """WITH sisteiverksattebehandlingfraløpendefagsak AS ( SELECT f.id AS fagsakid, MAX(b.opprettet_tid) AS opprettet_tid FROM behandling b INNER JOIN fagsak f ON f.id = b.fk_fagsak_id INNER JOIN tilkjent_ytelse ty ON b.id = ty.fk_behandling_id WHERE f.status = 'LØPENDE' AND ty.utbetalingsoppdrag IS NOT NULL AND f.arkivert = false GROUP BY fagsakid) SELECT b.id FROM sisteiverksattebehandlingfraløpendefagsak silp JOIN behandling b ON b.fk_fagsak_id = silp.fagsakid WHERE b.opprettet_tid = silp.opprettet_tid""", countQuery = """WITH sisteiverksattebehandlingfraløpendefagsak AS ( SELECT f.id AS fagsakid, MAX(b.opprettet_tid) AS opprettet_tid FROM behandling b INNER JOIN fagsak f ON f.id = b.fk_fagsak_id INNER JOIN tilkjent_ytelse ty ON b.id = ty.fk_behandling_id WHERE f.status = 'LØPENDE' AND ty.utbetalingsoppdrag IS NOT NULL AND f.arkivert = false GROUP BY fagsakid) SELECT count(b.id) FROM sisteiverksattebehandlingfraløpendefagsak silp JOIN behandling b ON b.fk_fagsak_id = silp.fagsakid WHERE b.opprettet_tid = silp.opprettet_tid""", nativeQuery = true ) fun finnSisteIverksatteBehandlingFraLøpendeFagsaker(page: Pageable): Page<BigInteger> @Query( """ SELECT new kotlin.Pair(b.id, p.fødselsnummer) from Behandling b INNER JOIN Fagsak f ON f.id = b.fagsak.id INNER JOIN Aktør a on f.aktør.aktørId = a.aktørId INNER JOIN Personident p on p.aktør.aktørId = a.aktørId where b.id in (:behandlingIder) AND p.aktiv=true AND f.status = 'LØPENDE' """ ) fun finnAktivtFødselsnummerForBehandlinger(behandlingIder: List<Long>): List<Pair<Long, String>> }
5
null
1
2
d7a12df78b63280c202bbe4915ba6bd20efe4285
4,960
familie-ks-sak
MIT License
src/main/kotlin/com/writerai/plugins/Routing.kt
Vaibhav2002
512,184,098
false
{"Kotlin": 44267}
package com.writerai.plugins import com.writerai.routes.projectRoutes import com.writerai.routes.userRoutes import io.ktor.server.application.* import io.ktor.server.routing.* fun Application.configureRouting() { routing { route("/api") { userRoutes() projectRoutes() } } }
0
Kotlin
13
33
f77f0747f2846127dc6e413b9f32ccdabce91320
324
WriterAI-Backend
MIT License
beam-daemon/src/main/kotlin/dev/d1s/beam/daemon/database/SpaceRepository.kt
d1snin
632,895,652
false
{"Kotlin": 584093, "Shell": 2444, "JavaScript": 2406}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.d1s.beam.daemon.database import dev.d1s.beam.commons.SpaceSlug import dev.d1s.beam.daemon.entity.SpaceEntity import dev.d1s.exkt.ktorm.ExportedSequence import dev.d1s.exkt.ktorm.export import dispatch.core.withIO import org.koin.core.component.KoinComponent import org.koin.core.component.inject import org.ktorm.database.Database import org.ktorm.dsl.desc import org.ktorm.dsl.eq import org.ktorm.entity.add import org.ktorm.entity.find import java.util.* interface SpaceRepository { suspend fun addSpace(space: SpaceEntity): Result<SpaceEntity> suspend fun findSpaceById(id: UUID): Result<SpaceEntity> suspend fun findSpaceBySlug(slug: SpaceSlug): Result<SpaceEntity> suspend fun findAllSpaces(limit: Int, offset: Int): Result<ExportedSequence<SpaceEntity>> suspend fun updateSpace(space: SpaceEntity): Result<SpaceEntity> suspend fun removeSpace(space: SpaceEntity): Result<Unit> } class DefaultSpaceRepository : SpaceRepository, KoinComponent { private val database by inject<Database>() override suspend fun addSpace(space: SpaceEntity): Result<SpaceEntity> = withIO { runCatching { space.apply { setId() setCreatedAt() setUpdatedAt() database.spaces.add(space) } } } override suspend fun findSpaceById(id: UUID): Result<SpaceEntity> = withIO { runCatching { database.spaces.find { it.id eq id } ?: error("Space not found by ID $id") } } override suspend fun findSpaceBySlug(slug: SpaceSlug): Result<SpaceEntity> = withIO { runCatching { database.spaces.find { it.slug eq slug } ?: error("Space not found by slug $slug") } } override suspend fun findAllSpaces(limit: Int, offset: Int): Result<ExportedSequence<SpaceEntity>> = withIO { runCatching { database.spaces.export(limit, offset, sort = { it.createdAt.desc() }) } } override suspend fun updateSpace(space: SpaceEntity): Result<SpaceEntity> = withIO { runCatching { space.apply { setUpdatedAt() flushChanges() } } } override suspend fun removeSpace(space: SpaceEntity): Result<Unit> = withIO { runCatching { space.delete() Unit } } }
5
Kotlin
0
5
09d83345080089b50a4ef868dd63a17d66430a2b
3,241
beam
Apache License 2.0
theodolite/src/test/kotlin/theodolite/TestBenchmark.kt
cau-se
265,538,393
false
null
package theodolite import theodolite.benchmark.Benchmark import theodolite.benchmark.BenchmarkDeployment import theodolite.util.ConfigurationOverride import theodolite.util.LoadDimension import theodolite.util.Resource class TestBenchmark : Benchmark { override fun setupInfrastructure() { } override fun teardownInfrastructure() { } override fun buildDeployment( load: LoadDimension, res: Resource, configurationOverrides: List<ConfigurationOverride?>, loadGenerationDelay: Long, afterTeardownDelay: Long ): BenchmarkDeployment { return TestBenchmarkDeployment() } }
0
Java
7
20
a83a9f8bb1f31e5c5e3e0c9ca1e2a366c01df3e5
649
theodolite
Apache License 2.0
core/src/main/kotlin/com/labijie/infra/impl/DebugIdGenerator.kt
hongque-pro
307,931,824
false
{"Kotlin": 143121}
package com.labijie.infra.impl import com.labijie.infra.IIdGenerator import com.labijie.infra.utils.logger import java.util.concurrent.atomic.AtomicLong /** * Created with IntelliJ IDEA. * @author <NAME> * @date 2018-08-12 */ class DebugIdGenerator : IIdGenerator { val seed = AtomicLong(System.currentTimeMillis()) @Volatile private var logged = false override fun newId(): Long { if(logged && logger.isWarnEnabled) { logged = true this.logger.warn("DebugIdGenerator for unit testing only, do not use in a production environment.") } return seed.incrementAndGet() } }
0
Kotlin
0
3
d486e2d186a1074473e874e3882b478a42239b64
644
infra-commons
Apache License 2.0
PhoneApp/Conduit/app/src/main/java/ca/uwaterloo/fydp/conduit/LogDumpActivity.kt
davanB
137,275,499
false
{"Java": 416953, "Kotlin": 62980, "Objective-C": 15920, "C++": 10948, "C": 7438, "CMake": 1822, "Shell": 345, "Makefile": 67}
package ca.uwaterloo.fydp.conduit import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader class LogDumpActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_log_dump) try { val process = Runtime.getRuntime().exec("logcat -d") val bufferedReader = BufferedReader( InputStreamReader(process.inputStream)) val log = StringBuilder() var line:String? = "" while (line != null) { log.append(line).append('\n') line = bufferedReader.readLine() } val tv = findViewById<TextView>(R.id.logdumpview) tv.text = log.toString() } catch (e: IOException) { // Handle Exception } } }
1
null
1
1
1c134edb3281418c9fd33cd5bc35111fcbcddc93
1,020
Conduit
Apache License 2.0
src/main/kotlin/com/zqlite/android/dclib/sevice/DiyCodeService.kt
ZhangQinglian
99,917,239
false
null
/* * Copyright 2017 zhangqinglian * * 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.zqlite.android.dclib.sevice import com.zqlite.android.dclib.entiry.* import io.reactivex.Observable import okhttp3.* import okhttp3.internal.platform.Platform import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.* /** * Created by scott on 2017/8/10. */ internal interface DiyCodeService { interface Callback { fun getToken(): String? } @FormUrlEncoded @POST() fun login(@Url url: String, @Field(DiyCodeContract.kGrantType) grantType: String, @Field(DiyCodeContract.kUserName) userName: String, @Field(DiyCodeContract.kPassword) password: String, @Field(DiyCodeContract.kClientId) clientId: String, @Field(DiyCodeContract.kClientSecret) clientSecret: String): Observable<Token> @GET(DiyCodeContract.kTopic) fun getTopic(@Query(DiyCodeContract.TopicParams.type) type: String, @Query(DiyCodeContract.TopicParams.nodeId) nodeId: Int, @Query(DiyCodeContract.TopicParams.offset) offset: Int = 0, @Query(DiyCodeContract.TopicParams.limit) limit: Int = 20): Observable<List<Topic>> @GET(DiyCodeContract.kTopic) fun getTopic(@Query(DiyCodeContract.TopicParams.offset) offset: Int = 0, @Query(DiyCodeContract.TopicParams.limit) limit: Int = 20): Observable<List<Topic>> @POST(DiyCodeContract.kFollowTopic) fun followTopic(@Path("id") topicId: Int): Observable<ResponseBody> @POST(DiyCodeContract.kUnFollowTopic) fun unfollowTopic(@Path("id") topicId: Int): Observable<ResponseBody> @POST(DiyCodeContract.kFavorite) fun favoriteTopic(@Path("id") id: Int): Observable<ResponseBody> @POST(DiyCodeContract.kunFavorite) fun unfavoriteTopic(@Path("id") id: Int): Observable<ResponseBody> @GET(DiyCodeContract.kNodes) fun getNodes(): Observable<MutableList<Node>> @GET(DiyCodeContract.kTopicDetail) fun getTopicDetail(@Path("id") topicId: Int): Observable<TopicDetail> @GET(DiyCodeContract.kTopicReplies) fun getTopicReplies(@Path("id") topicId: Int): Observable<List<TopicReply>> @GET(DiyCodeContract.kUserDetails) fun getUserDetail(@Path("login") loginName: String): Observable<UserDetail> @GET(DiyCodeContract.kMe) fun getMe(): Observable<UserDetail> @POST(DiyCodeContract.kLikes) @FormUrlEncoded fun like(@Field("obj_id") id: Int, @Field("obj_type") type: String): Observable<ResponseBody> @FormUrlEncoded @HTTP(method = "DELETE", path = DiyCodeContract.kLikes, hasBody = true) fun unlike(@Field("obj_id") id: Int, @Field("obj_type") type: String): Observable<ResponseBody> @POST(DiyCodeContract.kFollowUser) fun followUser(@Path("login") loginName: String): Observable<ResponseBody> @POST(DiyCodeContract.kunFollowUser) fun unfollowUser(@Path("login") loginName: String): Observable<ResponseBody> @GET(DiyCodeContract.kFollowing) fun getFollowing(@Path("login") loginName: String, @Query(DiyCodeContract.TopicParams.offset) offset: Int = 0, @Query(DiyCodeContract.TopicParams.limit) limit: Int = 20): Observable<List<User>> @GET(DiyCodeContract.kFollowers) fun getFollowers(@Path("login") loginName: String, @Query(DiyCodeContract.TopicParams.offset) offset: Int = 0, @Query(DiyCodeContract.TopicParams.limit) limit: Int = 20): Observable<List<User>> @POST(DiyCodeContract.kReplyTopic) @FormUrlEncoded fun replyTopic(@Path("id") id: Int, @Field("body") body: String): Observable<ResponseBody> @Multipart @POST(DiyCodeContract.kUploadImage) fun uploadPhoto(@Part partList: List<MultipartBody.Part>): Observable<ResponseBody> @GET(DiyCodeContract.kUserTopics) fun getUserTopics(@Path("login") loginName: String, @Query(DiyCodeContract.TopicParams.offset) offset: Int = 0, @Query(DiyCodeContract.TopicParams.limit) limit: Int = 20): Observable<List<Topic>> @GET(DiyCodeContract.kUserFavoriteTopics) fun getUserFavoriteTopics(@Path("login") loginName: String, @Query(DiyCodeContract.TopicParams.offset) offset: Int = 0, @Query(DiyCodeContract.TopicParams.limit) limit: Int = 20): Observable<List<Topic>> @POST(DiyCodeContract.kDevice) @FormUrlEncoded fun updateDevice(@Field("platform") flatform :String = "android",@Field("token") token:String):Observable<ResponseBody> @GET(DiyCodeContract.kNotification) fun getNotification(@Query("offset") offset:Int = 0,@Query("limit") limit: Int = 20):Observable<List<Notification>> @POST(DiyCodeContract.kNotificaiontReaded) @FormUrlEncoded fun readNotification(@Field("ids[]") ids:List<Int>):Observable<ResponseBody> @FormUrlEncoded @HTTP(method = "DELETE", path = DiyCodeContract.kDevice, hasBody = true) fun deleteDevice(@Field("platform") platform:String = "android",@Field("token") token: String):Observable<ResponseBody> companion object Factory { var mCallback: Callback? = null fun create(callback: Callback): DiyCodeService { mCallback = callback var interceptor: Interceptor = object : Interceptor { override fun intercept(chain: Interceptor.Chain?): Response { var originRequest = chain!!.request() if (originRequest.url().toString().contains(DiyCodeContract.kOAuthUrl)) { return chain.proceed(originRequest) } if (originRequest.headers()["Authorization"] != null) { return chain.proceed(originRequest) } if (mCallback!!.getToken() == null || mCallback!!.getToken()?.length == 0) { return chain.proceed(originRequest) } var newRequest = originRequest. newBuilder(). addHeader("Authorization", "Bearer " + mCallback!!.getToken()). build() return chain.proceed(newRequest) } } var okHttpClient: OkHttpClient = OkHttpClient.Builder().addInterceptor(interceptor).build() val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(DiyCodeContract.kDiyCodeApi) .client(okHttpClient) .build() return retrofit.create(DiyCodeService::class.java) } } }
1
null
1
1
3f82c591da930bbe77b1d00eca846315d51584d2
7,509
dclib
Apache License 2.0
src/main/kotlin/eZmaxApi/models/EzmaxinvoicingsummaryexternalResponseCompound.kt
eZmaxinc
271,950,932
false
{"Kotlin": 6909939}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * A Ezmaxinvoicingsummaryexternal Object * * @param fkiBillingentityexternalID The unique ID of the Billingentityexternal * @param sBillingentityexternalDescription The description of the Billingentityexternal * @param sEzmaxinvoicingsummaryexternalDescription The description of the Ezmaxinvoicingsummaryexternal * @param pkiEzmaxinvoicingsummaryexternalID The unique ID of the Ezmaxinvoicingsummaryexternal * @param fkiEzmaxinvoicingID The unique ID of the Ezmaxinvoicing */ data class EzmaxinvoicingsummaryexternalMinusResponse ( /* The unique ID of the Billingentityexternal */ @Json(name = "fkiBillingentityexternalID") val fkiBillingentityexternalID: kotlin.Int, /* The description of the Billingentityexternal */ @Json(name = "sBillingentityexternalDescription") val sBillingentityexternalDescription: kotlin.String, /* The description of the Ezmaxinvoicingsummaryexternal */ @Json(name = "sEzmaxinvoicingsummaryexternalDescription") val sEzmaxinvoicingsummaryexternalDescription: kotlin.String, /* The unique ID of the Ezmaxinvoicingsummaryexternal */ @Json(name = "pkiEzmaxinvoicingsummaryexternalID") val pkiEzmaxinvoicingsummaryexternalID: kotlin.Int? = null, /* The unique ID of the Ezmaxinvoicing */ @Json(name = "fkiEzmaxinvoicingID") val fkiEzmaxinvoicingID: kotlin.Int? = null )
0
Kotlin
0
0
961c97a9f13f3df7986ea7ba55052874183047ab
1,742
eZmax-SDK-kotlin
MIT License
packages/expo-image/android/src/main/java/expo/modules/image/thumbhash/ThumbhashDecoder.kt
betomoedano
462,599,485
false
null
package expo.modules.image.thumbhash import android.graphics.Bitmap import android.graphics.Color // ThumbHash Java implementation (converted to kotlin) thanks to @evanw https://github.com/evanw/thumbhash object ThumbhashDecoder { /** * Encodes an RGBA image to a ThumbHash. RGB should not be premultiplied by A. * * @param w The width of the input image. Must be ≤100px. * @param h The height of the input image. Must be ≤100px. * @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements. * @return The ThumbHash as a byte array. */ fun rgbaToThumbHash(w: Int, h: Int, rgba: ByteArray): ByteArray { // Encoding an image larger than 100x100 is slow with no benefit require(!(w > 100 || h > 100)) { w.toString() + "x" + h + " doesn't fit in 100x100" } // Determine the average color var avg_r = 0f var avg_g = 0f var avg_b = 0f var avg_a = 0f var i = 0 var j = 0 while (i < w * h) { val alpha = (rgba[j + 3].toInt() and 255) / 255.0f avg_r += alpha / 255.0f * (rgba[j].toInt() and 255) avg_g += alpha / 255.0f * (rgba[j + 1].toInt() and 255) avg_b += alpha / 255.0f * (rgba[j + 2].toInt() and 255) avg_a += alpha i++ j += 4 } if (avg_a > 0) { avg_r /= avg_a avg_g /= avg_a avg_b /= avg_a } val hasAlpha = avg_a < w * h val l_limit = if (hasAlpha) 5 else 7 // Use fewer luminance bits if there's alpha val lx = Math.max(1, Math.round((l_limit * w).toFloat() / Math.max(w, h).toFloat())) val ly = Math.max(1, Math.round((l_limit * h).toFloat() / Math.max(w, h).toFloat())) val l = FloatArray(w * h) // luminance val p = FloatArray(w * h) // yellow - blue val q = FloatArray(w * h) // red - green val a = FloatArray(w * h) // alpha // Convert the image from RGBA to LPQA (composite atop the average color) i = 0 j = 0 while (i < w * h) { val alpha = (rgba[j + 3].toInt() and 255) / 255.0f val r = avg_r * (1.0f - alpha) + alpha / 255.0f * (rgba[j].toInt() and 255) val g = avg_g * (1.0f - alpha) + alpha / 255.0f * (rgba[j + 1].toInt() and 255) val b = avg_b * (1.0f - alpha) + alpha / 255.0f * (rgba[j + 2].toInt() and 255) l[i] = (r + g + b) / 3.0f p[i] = (r + g) / 2.0f - b q[i] = r - g a[i] = alpha i++ j += 4 } // Encode using the DCT into DC (constant) and normalized AC (varying) terms val l_channel = Channel(Math.max(3, lx), Math.max(3, ly)).encode(w, h, l) val p_channel = Channel(3, 3).encode(w, h, p) val q_channel = Channel(3, 3).encode(w, h, q) val a_channel = if (hasAlpha) Channel(5, 5).encode(w, h, a) else null // Write the constants val isLandscape = w > h val header24 = ( Math.round(63.0f * l_channel.dc) or (Math.round(31.5f + 31.5f * p_channel.dc) shl 6) or (Math.round(31.5f + 31.5f * q_channel.dc) shl 12) or (Math.round(31.0f * l_channel.scale) shl 18) or if (hasAlpha) 1 shl 23 else 0 ) val header16 = ( (if (isLandscape) ly else lx) or (Math.round(63.0f * p_channel.scale) shl 3) or (Math.round(63.0f * q_channel.scale) shl 9) or if (isLandscape) 1 shl 15 else 0 ) val ac_start = if (hasAlpha) 6 else 5 val ac_count = ( l_channel.ac.size + p_channel.ac.size + q_channel.ac.size + if (hasAlpha) a_channel!!.ac.size else 0 ) val hash = ByteArray(ac_start + (ac_count + 1) / 2) hash[0] = header24.toByte() hash[1] = (header24 shr 8).toByte() hash[2] = (header24 shr 16).toByte() hash[3] = header16.toByte() hash[4] = (header16 shr 8).toByte() if (hasAlpha) hash[5] = ( Math.round(15.0f * a_channel!!.dc) or (Math.round(15.0f * a_channel.scale) shl 4) ).toByte() // Write the varying factors var ac_index = 0 ac_index = l_channel.writeTo(hash, ac_start, ac_index) ac_index = p_channel.writeTo(hash, ac_start, ac_index) ac_index = q_channel.writeTo(hash, ac_start, ac_index) if (hasAlpha) a_channel!!.writeTo(hash, ac_start, ac_index) return hash } /** * Decodes a ThumbHash to an RGBA image. RGB is not be premultiplied by A. * * @param hash The bytes of the ThumbHash. * @return The width, height, and pixels of the rendered placeholder image. */ fun thumbHashToRGBA(hash: ByteArray): Image { // Read the constants val header24 = hash[0].toInt() and 255 or (hash[1].toInt() and 255 shl 8) or (hash[2].toInt() and 255 shl 16) val header16 = hash[3].toInt() and 255 or (hash[4].toInt() and 255 shl 8) val l_dc = (header24 and 63).toFloat() / 63.0f val p_dc = (header24 shr 6 and 63).toFloat() / 31.5f - 1.0f val q_dc = (header24 shr 12 and 63).toFloat() / 31.5f - 1.0f val l_scale = (header24 shr 18 and 31).toFloat() / 31.0f val hasAlpha = header24 shr 23 != 0 val p_scale = (header16 shr 3 and 63).toFloat() / 63.0f val q_scale = (header16 shr 9 and 63).toFloat() / 63.0f val isLandscape = header16 shr 15 != 0 val lx = Math.max(3, if (isLandscape) if (hasAlpha) 5 else 7 else header16 and 7) val ly = Math.max(3, if (isLandscape) header16 and 7 else if (hasAlpha) 5 else 7) val a_dc = if (hasAlpha) (hash[5].toInt() and 15).toFloat() / 15.0f else 1.0f val a_scale = (hash[5].toInt() shr 4 and 15).toFloat() / 15.0f // Read the varying factors (boost saturation by 1.25x to compensate for quantization) val ac_start = if (hasAlpha) 6 else 5 var ac_index = 0 val l_channel = Channel(lx, ly) val p_channel = Channel(3, 3) val q_channel = Channel(3, 3) var a_channel: Channel? = null ac_index = l_channel.decode(hash, ac_start, ac_index, l_scale) ac_index = p_channel.decode(hash, ac_start, ac_index, p_scale * 1.25f) ac_index = q_channel.decode(hash, ac_start, ac_index, q_scale * 1.25f) if (hasAlpha) { a_channel = Channel(5, 5) a_channel.decode(hash, ac_start, ac_index, a_scale) } val l_ac = l_channel.ac val p_ac = p_channel.ac val q_ac = q_channel.ac val a_ac = if (hasAlpha) a_channel!!.ac else null // Decode using the DCT into RGB val ratio = thumbHashToApproximateAspectRatio(hash) val w = Math.round(if (ratio > 1.0f) 32.0f else 32.0f * ratio) val h = Math.round(if (ratio > 1.0f) 32.0f / ratio else 32.0f) val rgba = ByteArray(w * h * 4) val cx_stop = Math.max(lx, if (hasAlpha) 5 else 3) val cy_stop = Math.max(ly, if (hasAlpha) 5 else 3) val fx = FloatArray(cx_stop) val fy = FloatArray(cy_stop) var y = 0 var i = 0 while (y < h) { var x = 0 while (x < w) { var l = l_dc var p = p_dc var q = q_dc var a = a_dc // Precompute the coefficients for (cx in 0 until cx_stop) fx[cx] = Math.cos(Math.PI / w * (x + 0.5f) * cx).toFloat() for (cy in 0 until cy_stop) fy[cy] = Math.cos(Math.PI / h * (y + 0.5f) * cy).toFloat() // Decode L run { var cy = 0 var j = 0 while (cy < ly) { val fy2 = fy[cy] * 2.0f var cx = if (cy > 0) 0 else 1 while (cx * ly < lx * (ly - cy)) { l += l_ac[j] * fx[cx] * fy2 cx++ j++ } cy++ } } // Decode P and Q var cy = 0 var j = 0 while (cy < 3) { val fy2 = fy[cy] * 2.0f var cx = if (cy > 0) 0 else 1 while (cx < 3 - cy) { val f = fx[cx] * fy2 p += p_ac[j] * f q += q_ac[j] * f cx++ j++ } cy++ } // Decode A if (hasAlpha) { var cy = 0 var j = 0 while (cy < 5) { val fy2 = fy[cy] * 2.0f var cx = if (cy > 0) 0 else 1 while (cx < 5 - cy) { a += a_ac!![j] * fx[cx] * fy2 cx++ j++ } cy++ } } // Convert to RGB val b = l - 2.0f / 3.0f * p val r = (3.0f * l - b + q) / 2.0f val g = r - q rgba[i] = Math.max(0, Math.round(255.0f * Math.min(1f, r))).toByte() rgba[i + 1] = Math.max(0, Math.round(255.0f * Math.min(1f, g))).toByte() rgba[i + 2] = Math.max(0, Math.round(255.0f * Math.min(1f, b))).toByte() rgba[i + 3] = Math.max(0, Math.round(255.0f * Math.min(1f, a))).toByte() x++ i += 4 } y++ } return Image(w, h, rgba) } /** * Converts a ThumbHash into a Bitmap image */ fun thumbHashToBitmap(hash: ByteArray): Bitmap { val thumbhashImage = thumbHashToRGBA(hash) // TODO: @behenate it should be possible to replace all of the code below with // with BitmapFactory.decodeByteArray but it always returns null when using thumbhashImage.rgba val imageArray = IntArray(thumbhashImage.width * thumbhashImage.height) val thumbhashImageInt = thumbhashImage.rgba.map { it.toUByte().toInt() } for (i in thumbhashImageInt.indices step 4) { imageArray[i / 4] = Color.argb( thumbhashImageInt[i + 3], thumbhashImageInt[i], thumbhashImageInt[i + 1], thumbhashImageInt[i + 2] ) } return Bitmap.createBitmap(imageArray, thumbhashImage.width, thumbhashImage.height, Bitmap.Config.ARGB_8888) } /** * Extracts the average color from a ThumbHash. RGB is not be premultiplied by A. * * @param hash The bytes of the ThumbHash. * @return The RGBA values for the average color. Each value ranges from 0 to 1. */ fun thumbHashToAverageRGBA(hash: ByteArray): RGBA { val header = hash[0].toInt() and 255 or (hash[1].toInt() and 255 shl 8) or (hash[2].toInt() and 255 shl 16) val l = (header and 63).toFloat() / 63.0f val p = (header shr 6 and 63).toFloat() / 31.5f - 1.0f val q = (header shr 12 and 63).toFloat() / 31.5f - 1.0f val hasAlpha = header shr 23 != 0 val a = if (hasAlpha) (hash[5].toInt() and 15).toFloat() / 15.0f else 1.0f val b = l - 2.0f / 3.0f * p val r = (3.0f * l - b + q) / 2.0f val g = r - q return RGBA( Math.max(0f, Math.min(1f, r)), Math.max(0f, Math.min(1f, g)), Math.max(0f, Math.min(1f, b)), a ) } /** * Extracts the approximate aspect ratio of the original image. * * @param hash The bytes of the ThumbHash. * @return The approximate aspect ratio (i.e. width / height). */ fun thumbHashToApproximateAspectRatio(hash: ByteArray): Float { val header = hash[3] val hasAlpha = hash[2].toInt() and 0x80 != 0 val isLandscape = hash[4].toInt() and 0x80 != 0 val lx = if (isLandscape) if (hasAlpha) 5 else 7 else header.toInt() and 7 val ly = if (isLandscape) header.toInt() and 7 else if (hasAlpha) 5 else 7 return lx.toFloat() / ly.toFloat() } class Image(var width: Int, var height: Int, var rgba: ByteArray) class RGBA(var r: Float, var g: Float, var b: Float, var a: Float) private class Channel internal constructor(var nx: Int, var ny: Int) { var dc = 0f var ac: FloatArray var scale = 0f init { var n = 0 for (cy in 0 until ny) { var cx = if (cy > 0) 0 else 1 while (cx * ny < nx * (ny - cy)) { n++ cx++ } } ac = FloatArray(n) } fun encode(w: Int, h: Int, channel: FloatArray): Channel { var n = 0 val fx = FloatArray(w) for (cy in 0 until ny) { var cx = 0 while (cx * ny < nx * (ny - cy)) { var f = 0f for (x in 0 until w) fx[x] = Math.cos(Math.PI / w * cx * (x + 0.5f)).toFloat() for (y in 0 until h) { val fy = Math.cos(Math.PI / h * cy * (y + 0.5f)).toFloat() for (x in 0 until w) f += channel[x + y * w] * fx[x] * fy } f /= (w * h).toFloat() if (cx > 0 || cy > 0) { ac[n++] = f scale = Math.max(scale, Math.abs(f)) } else { dc = f } cx++ } } if (scale > 0) for (i in ac.indices) ac[i] = 0.5f + 0.5f / scale * ac[i] return this } fun decode(hash: ByteArray, start: Int, index: Int, scale: Float): Int { var index = index for (i in ac.indices) { val data = hash[start + (index shr 1)].toInt() shr (index and 1 shl 2) ac[i] = ((data and 15).toFloat() / 7.5f - 1.0f) * scale index++ } return index } fun writeTo(hash: ByteArray, start: Int, index: Int): Int { var index = index for (v in ac) { hash[start + (index shr 1)] = (hash[start + (index shr 1)].toInt() or (Math.round(15.0f * v) shl (index and 1 shl 2))).toByte() index++ } return index } } }
668
null
5226
4
52d6405570a39a87149648d045d91098374f4423
12,916
expo
MIT License
common/src/commonMain/kotlin/io/github/irack/stonemanager/interface/ui/style/AdvancedTextShape.kt
IRACK000
723,712,145
false
{"Kotlin": 136170, "Swift": 540}
package io.github.irack.stonemanager.`interface`.ui.style import androidx.compose.animation.core.* import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.SubcomposeLayout import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay /** * @see <a href="https://www.appsloveworld.com/kotlin/100/6/marquee-text-effect-in-jetpack-compose">Marquee Text Effect</a> */ @Composable fun MarqueeText( text: String, modifier: Modifier = Modifier, textModifier: Modifier = Modifier, gradientEdgeColor: Color = Color.White, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontStyle: FontStyle? = null, fontWeight: FontWeight? = null, fontFamily: FontFamily? = null, letterSpacing: TextUnit = TextUnit.Unspecified, textDecoration: TextDecoration? = null, textAlign: TextAlign? = null, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current, ) { val createText = @Composable { localModifier: Modifier -> Text( text, textAlign = textAlign, modifier = localModifier, color = color, fontSize = fontSize, fontStyle = fontStyle, fontWeight = fontWeight, fontFamily = fontFamily, letterSpacing = letterSpacing, textDecoration = textDecoration, lineHeight = lineHeight, overflow = overflow, softWrap = softWrap, maxLines = 1, onTextLayout = onTextLayout, style = style, ) } var offset by remember { mutableStateOf(0) } val textLayoutInfoState = remember { mutableStateOf<TextLayoutInfo?>(null) } LaunchedEffect(textLayoutInfoState.value) { val textLayoutInfo = textLayoutInfoState.value ?: return@LaunchedEffect if (textLayoutInfo.textWidth <= textLayoutInfo.containerWidth) return@LaunchedEffect val nonZeroContainerWidth = if (textLayoutInfo.containerWidth < 1) 1 else textLayoutInfo.containerWidth val duration = 5500 * textLayoutInfo.textWidth / nonZeroContainerWidth val delay = 1000L do { val animation = TargetBasedAnimation( animationSpec = infiniteRepeatable( animation = tween( durationMillis = duration, delayMillis = 1000, easing = LinearEasing, ), repeatMode = RepeatMode.Restart ), typeConverter = Int.VectorConverter, initialValue = 0, targetValue = -textLayoutInfo.textWidth ) val startTime = withFrameNanos { it } do { val playTime = withFrameNanos { it } - startTime offset = (animation.getValueFromNanos(playTime)) } while (!animation.isFinishedFromNanos(playTime)) delay(delay) } while (true) } SubcomposeLayout( modifier = modifier.clipToBounds() ) { constraints -> val infiniteWidthConstraints = constraints.copy(maxWidth = Int.MAX_VALUE) var mainText = subcompose(MarqueeLayers.MainText) { createText(textModifier) }.first().measure(infiniteWidthConstraints) var gradient: Placeable? = null var secondPlaceableWithOffset: Pair<Placeable, Int>? = null if (mainText.width <= constraints.maxWidth) { mainText = subcompose(MarqueeLayers.SecondaryText) { createText(textModifier.fillMaxWidth()) }.first().measure(constraints) textLayoutInfoState.value = null } else { val spacing = constraints.maxWidth * 2 / 3 textLayoutInfoState.value = TextLayoutInfo( textWidth = mainText.width + spacing, containerWidth = constraints.maxWidth ) val secondTextOffset = mainText.width + offset + spacing val secondTextSpace = constraints.maxWidth - secondTextOffset if (secondTextSpace > 0) { secondPlaceableWithOffset = subcompose(MarqueeLayers.SecondaryText) { createText(textModifier) }.first().measure(infiniteWidthConstraints) to secondTextOffset } gradient = subcompose(MarqueeLayers.EdgesGradient) { Row { GradientEdge(gradientEdgeColor, Color.Transparent) Spacer(Modifier.weight(1f)) GradientEdge(Color.Transparent, gradientEdgeColor) } }.first().measure(constraints.copy(maxHeight = mainText.height)) } layout( width = constraints.maxWidth, height = mainText.height ) { mainText.place(offset, 0) secondPlaceableWithOffset?.let { it.first.place(it.second, 0) } gradient?.place(0, 0) } } } @Composable private fun GradientEdge( startColor: Color, endColor: Color, ) { Box( modifier = Modifier .width(10.dp) .fillMaxHeight() .background( brush = Brush.horizontalGradient( 0f to startColor, 1f to endColor, ) ) ) } private enum class MarqueeLayers { MainText, SecondaryText, EdgesGradient } private data class TextLayoutInfo(val textWidth: Int, val containerWidth: Int) /** * @see <a href="https://stackoverflow.com/questions/63971569/androidautosizetexttype-in-jetpack-compose">AutoSizeText</a> */ @Composable fun AutoSizeTextWithResizer( text: String, modifier: Modifier = Modifier, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontStyle: FontStyle? = null, fontWeight: FontWeight? = null, fontFamily: FontFamily? = null, letterSpacing: TextUnit = TextUnit.Unspecified, textDecoration: TextDecoration? = null, textAlign: TextAlign? = null, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = 1, minLines: Int = 1, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current, resizer: MutableState<Float> = remember { mutableStateOf(1f) } ) { Text( text, modifier, color, fontSize = fontSize * resizer.value, fontStyle, fontWeight, fontFamily, letterSpacing, textDecoration, textAlign, lineHeight, overflow, softWrap, maxLines, minLines, onTextLayout = { if (it.hasVisualOverflow) { resizer.value *= 0.99f } onTextLayout(it) }, style ) } /** * @see <a href="https://stackoverflow.com/questions/63971569/androidautosizetexttype-in-jetpack-compose">AutoSizeText</a> */ @Composable fun ConstraintAutoSizeText( text: String, modifier: Modifier = Modifier, color: Color = Color.Unspecified, fontStyle: FontStyle? = null, fontWeight: FontWeight? = null, fontFamily: FontFamily? = null, letterSpacing: TextUnit = TextUnit.Unspecified, textDecoration: TextDecoration? = null, textAlign: TextAlign? = null, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, maxLines: Int = 1, minLines: Int = 1, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current ) { var scaledTextStyle by remember { mutableStateOf(style) } val localDensity = LocalDensity.current Text( text = text, color = color, maxLines = maxLines, minLines = minLines, fontStyle = fontStyle, fontWeight = fontWeight, fontFamily = fontFamily, letterSpacing = letterSpacing, textDecoration = textDecoration, textAlign = textAlign, lineHeight = lineHeight, overflow = overflow, softWrap = false, style = scaledTextStyle, onTextLayout = { result -> val scaleByHeight = result.layoutInput.constraints.maxHeight / 2 val scaleByWidth = result.layoutInput.constraints.maxWidth / result.layoutInput.text.length scaledTextStyle = scaledTextStyle.copy( fontSize = with(localDensity) { if (scaleByHeight < scaleByWidth) scaleByHeight.toSp() else scaleByWidth.toSp() } ) onTextLayout(result) }, modifier = modifier.drawWithContent { drawContent() } ) } /** * @see <a href="https://stackoverflow.com/questions/63971569/androidautosizetexttype-in-jetpack-compose">AutoSizeText</a> */ @Composable fun AutoSizeText( text: String, modifier: Modifier = Modifier, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontStyle: FontStyle? = null, fontWeight: FontWeight? = null, fontFamily: FontFamily? = null, letterSpacing: TextUnit = TextUnit.Unspecified, textDecoration: TextDecoration? = null, textAlign: TextAlign? = null, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = 1, minLines: Int = 1, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current ) { val resizer = remember { mutableStateOf(1f) } val stableFlag = mutableStateOf(false) Text( text, modifier, color, fontSize = fontSize * resizer.value, fontStyle, fontWeight, fontFamily, letterSpacing, textDecoration, textAlign, lineHeight, overflow, softWrap, maxLines, minLines, onTextLayout = { if (stableFlag.value) { resizer.value = 1f stableFlag.value = false } if (it.hasVisualOverflow) { resizer.value -= 0.01f } else { stableFlag.value = true } onTextLayout(it) }, style ) }
0
Kotlin
0
0
8e86910e7f2121b99639ab190be36458f7de8b83
11,386
StoneManager
MIT License
shared/src/iosMain/kotlin/com/mindinventory/kmm/shared/cache/DatabaseDriverFactory.kt
Mindinventory
309,282,828
false
null
package com.mindinventory.kmm.shared.cache import com.squareup.sqldelight.db.SqlDriver import com.squareup.sqldelight.drivers.native.NativeSqliteDriver // here we are providing SqlDriver of iOS - a native implementation actual class DatabaseDriverFactory { actual fun createDriver(): SqlDriver { return NativeSqliteDriver(AppDatabase.Schema, "employee.db") } }
0
Kotlin
4
21
fd4e175b62404b92f825f9ef2ff07540dcffd58a
378
Kotlin-multiplatform-sample
MIT License
app/src/main/java/io/stanwood/mhwdb/glide/GlideAppFactory.kt
stanwood
156,602,065
false
null
package io.stanwood.mhwdb.glide import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment interface GlideAppFactory { fun get(): GlideRequests } class GlideAppFragmentFactory(private val fragment: Fragment) : GlideAppFactory { override fun get() = GlideApp.with(fragment) } class GlideAppActivityFactory(private val activity: AppCompatActivity) : GlideAppFactory { override fun get() = GlideApp.with(activity) }
1
Kotlin
1
4
586d82d6f742a1c90626e98b148318e7c37d6817
455
framework-arch-android
MIT License
src/main/kotlin/org/vitrivr/cottontail/execution/operators/sources/EntityScanOperator.kt
mittulmandhan
356,384,694
true
{"Kotlin": 1692179, "Dockerfile": 478}
package org.vitrivr.cottontail.execution.operators.sources import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import org.vitrivr.cottontail.database.column.ColumnDef import org.vitrivr.cottontail.database.entity.Entity import org.vitrivr.cottontail.database.entity.EntityTx import org.vitrivr.cottontail.database.queries.GroupId import org.vitrivr.cottontail.execution.TransactionContext import org.vitrivr.cottontail.execution.operators.basics.Operator import org.vitrivr.cottontail.model.basics.Record /** * An [AbstractEntityOperator] that scans an [Entity] and streams all [Record]s found within. * * @author <NAME> * @version 1.2.0 */ class EntityScanOperator(groupId: GroupId, entity: Entity, columns: Array<ColumnDef<*>>, private val range: LongRange) : AbstractEntityOperator(groupId, entity, columns) { /** * Converts this [EntityScanOperator] to a [Flow] and returns it. * * @param context The [TransactionContext] used for execution * @return [Flow] representing this [EntityScanOperator] * @throws IllegalStateException If this [Operator.status] is not [OperatorStatus.OPEN] */ override fun toFlow(context: TransactionContext): Flow<Record> { val tx = context.getTx(this.entity) as EntityTx return flow { for (record in tx.scan([email protected], [email protected])) { emit(record) } } } }
0
null
0
0
ac203a7ef25a9e331024878029d8b39ee4edda14
1,461
cottontaildb
MIT License
src/main/kotlin/fe/kartifice/virtualpack/KArtificeResourcePackContainer1.kt
natanfudge
217,017,390
false
null
package fe.kartifice.virtualpack import net.fabricmc.api.EnvType import net.fabricmc.api.Environment import net.minecraft.client.resource.ClientResourcePackProfile import net.minecraft.resource.ResourcePackProfile import java.util.function.Supplier /** A wrapper around [ClientResourcePackProfile] exposing optionality/visibility. * @see ClientResourcePackBuilder.setOptional * * @see ClientResourcePackBuilder.setVisible */ @Environment(EnvType.CLIENT) class KArtificeResourcePackContainer(val isOptional: Boolean, val isVisible: Boolean, wrapping: ResourcePackProfile) : ClientResourcePackProfile( wrapping.name, !isOptional, Supplier { wrapping.createResourcePack() }, wrapping.displayName, wrapping.description, wrapping.compatibility, wrapping.initialPosition, wrapping.isPinned, null ) { /** @return Whether this pack is optional. */ /** @return Whether this pack is visible. */ }
0
Kotlin
0
0
0f9e392bcf2cc0df628cf6d22786759be256284b
983
Fabricated-Energistics
MIT License
app/src/main/java/com/concordium/wallet/ui/passphrase/setup/PassPhraseBaseFragment.kt
Concordium
358,250,608
false
null
package com.concordium.wallet.ui.passphrase.setup import android.content.Context import androidx.fragment.app.Fragment import com.concordium.wallet.ui.passphrase.setup.PassPhraseViewModel.Companion.PASS_PHRASE_DATA abstract class PassPhraseBaseFragment : Fragment() { protected lateinit var viewModel: PassPhraseViewModel override fun onAttach(context: Context) { super.onAttach(context) arguments?.getSerializable(PASS_PHRASE_DATA)?.let { viewModel = it as PassPhraseViewModel } } }
10
Kotlin
3
9
9d744fa7fd08980a2f0ec24aaaa363e8564b812b
535
concordium-reference-wallet-android
Apache License 2.0
src/main/kotlin/no/nav/familie/klage/behandling/OpprettRevurderingService.kt
navikt
524,953,794
false
null
package no.nav.familie.klage.behandling import no.nav.familie.klage.behandling.OpprettRevurderingUtil.skalOppretteRevurderingAutomatisk import no.nav.familie.klage.integrasjoner.FagsystemVedtakService import no.nav.familie.kontrakter.felles.klage.KanOppretteRevurderingResponse import org.springframework.stereotype.Service import java.util.UUID @Service class OpprettRevurderingService( private val behandlingService: BehandlingService, private val fagsystemVedtakService: FagsystemVedtakService, ) { fun kanOppretteRevurdering(behandlingId: UUID): KanOppretteRevurderingResponse { val behandling = behandlingService.hentBehandling(behandlingId) return if (skalOppretteRevurderingAutomatisk(behandling.påklagetVedtak)) { fagsystemVedtakService.kanOppretteRevurdering(behandlingId) } else { KanOppretteRevurderingResponse(false, null) } } }
1
Kotlin
0
2
79b9d38a55dab2679aa2c4b6047be57f16462e1e
916
familie-klage
MIT License
solar/src/main/java/com/chiksmedina/solar/outline/arrowsaction/UndoLeft.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.outline.arrowsaction import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd 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 com.chiksmedina.solar.outline.ArrowsActionGroup val ArrowsActionGroup.UndoLeft: ImageVector get() { if (_undoLeft != null) { return _undoLeft!! } _undoLeft = Builder( name = "UndoLeft", defaultWidth = 24.0.dp, defaultHeight = 24.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 = EvenOdd ) { moveTo(7.5303f, 3.4697f) curveTo(7.8232f, 3.7626f, 7.8232f, 4.2374f, 7.5303f, 4.5303f) lineTo(5.8107f, 6.25f) lineTo(15.0358f, 6.25f) curveTo(15.94f, 6.25f, 16.6693f, 6.25f, 17.2576f, 6.3033f) curveTo(17.864f, 6.3583f, 18.3938f, 6.4746f, 18.875f, 6.7524f) curveTo(19.4451f, 7.0815f, 19.9185f, 7.5549f, 20.2476f, 8.125f) curveTo(20.5254f, 8.6062f, 20.6417f, 9.136f, 20.6967f, 9.7424f) curveTo(20.75f, 10.3307f, 20.75f, 11.06f, 20.75f, 11.9643f) verticalLineTo(12.0358f) curveTo(20.75f, 12.94f, 20.75f, 13.6693f, 20.6967f, 14.2576f) curveTo(20.6418f, 14.8639f, 20.5255f, 15.3937f, 20.2476f, 15.875f) curveTo(19.9185f, 16.4451f, 19.4451f, 16.9185f, 18.875f, 17.2476f) curveTo(18.3938f, 17.5254f, 17.864f, 17.6417f, 17.2576f, 17.6967f) curveTo(16.6693f, 17.75f, 15.94f, 17.75f, 15.0358f, 17.75f) horizontalLineTo(8.0f) curveTo(7.5858f, 17.75f, 7.25f, 17.4142f, 7.25f, 17.0f) curveTo(7.25f, 16.5858f, 7.5858f, 16.25f, 8.0f, 16.25f) horizontalLineTo(15.0f) curveTo(15.9484f, 16.25f, 16.6096f, 16.2493f, 17.1222f, 16.2028f) curveTo(17.6245f, 16.1573f, 17.9101f, 16.0726f, 18.125f, 15.9486f) curveTo(18.4671f, 15.7511f, 18.7511f, 15.467f, 18.9486f, 15.125f) curveTo(19.0726f, 14.9101f, 19.1573f, 14.6245f, 19.2028f, 14.1222f) curveTo(19.2493f, 13.6096f, 19.25f, 12.9484f, 19.25f, 12.0f) curveTo(19.25f, 11.0516f, 19.2493f, 10.3904f, 19.2028f, 9.8778f) curveTo(19.1573f, 9.3755f, 19.0726f, 9.0899f, 18.9486f, 8.875f) curveTo(18.7511f, 8.533f, 18.467f, 8.2489f, 18.125f, 8.0514f) curveTo(17.9101f, 7.9274f, 17.6245f, 7.8427f, 17.1222f, 7.7972f) curveTo(16.6096f, 7.7507f, 15.9484f, 7.75f, 15.0f, 7.75f) horizontalLineTo(5.8107f) lineTo(7.5303f, 9.4697f) curveTo(7.8232f, 9.7626f, 7.8232f, 10.2374f, 7.5303f, 10.5303f) curveTo(7.2374f, 10.8232f, 6.7626f, 10.8232f, 6.4697f, 10.5303f) lineTo(3.4697f, 7.5303f) curveTo(3.1768f, 7.2374f, 3.1768f, 6.7626f, 3.4697f, 6.4697f) lineTo(6.4697f, 3.4697f) curveTo(6.7626f, 3.1768f, 7.2374f, 3.1768f, 7.5303f, 3.4697f) close() } } .build() return _undoLeft!! } private var _undoLeft: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
3,841
SolarIconSetAndroid
MIT License
components/flow/flow-service/src/main/kotlin/net/corda/flow/pipeline/factory/impl/FlowMessageFactoryImpl.kt
corda
346,070,752
false
null
package net.corda.flow.pipeline.factory.impl import net.corda.data.ExceptionEnvelope import net.corda.data.flow.output.FlowStates import net.corda.data.flow.output.FlowStatus import net.corda.flow.pipeline.factory.FlowMessageFactory import net.corda.flow.state.FlowCheckpoint import org.osgi.service.component.annotations.Activate import org.osgi.service.component.annotations.Component import java.time.Instant @Component(service = [FlowMessageFactory::class]) @Suppress("Unused") class FlowMessageFactoryImpl(private val currentTimeProvider: () -> Instant) : FlowMessageFactory { @Activate constructor() : this(Instant::now) override fun createFlowCompleteStatusMessage(checkpoint: FlowCheckpoint, flowResult: String?): FlowStatus { return getCommonFlowStatus(checkpoint).apply { flowStatus = FlowStates.COMPLETED result = flowResult } } override fun createFlowStartedStatusMessage(checkpoint: FlowCheckpoint): FlowStatus { return getCommonFlowStatus(checkpoint).apply { flowStatus = FlowStates.RUNNING } } override fun createFlowRetryingStatusMessage(checkpoint: FlowCheckpoint): FlowStatus { return getCommonFlowStatus(checkpoint).apply { flowStatus = FlowStates.RETRYING } } override fun createFlowFailedStatusMessage(checkpoint: FlowCheckpoint, errorType: String, message: String): FlowStatus { return getCommonFlowStatus(checkpoint).apply { flowStatus = FlowStates.FAILED error = ExceptionEnvelope(errorType, message) } } override fun createFlowKilledStatusMessage(checkpoint: FlowCheckpoint, message: String?): FlowStatus { return getCommonFlowStatus(checkpoint).apply { flowStatus = FlowStates.KILLED message?.let { processingTerminatedReason = it } } } private fun getCommonFlowStatus(checkpoint: FlowCheckpoint): FlowStatus { val startContext = checkpoint.flowStartContext return FlowStatus().apply { key = startContext.statusKey initiatorType = startContext.initiatorType flowId = checkpoint.flowId flowClassName = startContext.flowClassName createdTimestamp = startContext.createdTimestamp lastUpdateTimestamp = currentTimeProvider() } } }
96
null
27
69
d478e119ab288af663910f9a2df42a7a7b9f5bce
2,389
corda-runtime-os
Apache License 2.0
app/src/main/java/com/example/root/kotlin_eyepetizer/mvp/presenter/RankPresenter.kt
jiwenjie
156,038,520
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Kotlin": 123, "XML": 91, "Java": 17}
package com.example.root.kotlin_eyepetizer.mvp.presenter import com.example.baselibrary.baseutils.ExceptionHandle import com.example.root.kotlin_eyepetizer.basic.base.BasePresenter import com.example.root.kotlin_eyepetizer.mvp.contract.RankContract import com.example.root.kotlin_eyepetizer.mvp.model.RankModel /** * author:Jiwenjie * email:<EMAIL> * time:2018/11/21 * desc: 获取排行榜数据的 Presenter * version:1.0 */ class RankPresenter : BasePresenter<RankContract.View>(), RankContract.Presenter { private val rankModel by lazy { RankModel() } /** * 请求排行榜数据 */ override fun requestRankList(apiUrl: String) { checkViewAttached() mRootView?.showLoading() val disposable = rankModel.requestRankList(apiUrl) .subscribe({ issue -> mRootView?.apply { dismissLoading() setRankList(issue.itemList) } }, { throwable -> mRootView?.apply { //处理异常 showError( ExceptionHandle.handleException(throwable), ExceptionHandle.errorCode) } }) addSubscription(disposable) } }
1
null
1
1
104af621e315bc5588f97206ca04438a082875b9
1,251
Kotlin_Eyepetizer
Apache License 2.0
runtime/runtime-core/common/src/aws/smithy/kotlin/runtime/util/JMESPath.kt
smithy-lang
294,823,838
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.smithy.kotlin.runtime.util import aws.smithy.kotlin.runtime.InternalApi @InternalApi public fun Short.toNumber(): Short = this @InternalApi public fun Int.toNumber(): Int = this @InternalApi public fun Long.toNumber(): Long = this @InternalApi public fun Float.toNumber(): Float = this @InternalApi public fun Double.toNumber(): Double = this @InternalApi public fun String.toNumber(): Double? = this.toDoubleOrNull() @InternalApi public fun Any.toNumber(): Nothing? = null /** * Evaluates the "truthiness" of a value based on * [JMESPath definitions](https://jmespath.org/specification.html#or-expressions). */ @InternalApi public fun truthiness(value: Any?): Boolean = when (value) { is Boolean -> value is Collection<*> -> value.isNotEmpty() is Map<*, *> -> value.isNotEmpty() is String -> value.isNotEmpty() null -> false else -> true } @InternalApi @JvmName("noOpUnnestedCollection") public inline fun <reified T> Collection<T>.flattenIfPossible(): Collection<T> = this @InternalApi @JvmName("flattenNestedCollection") public inline fun <reified T> Collection<Collection<T>>.flattenIfPossible(): Collection<T> = flatten() /** * Determines the length of a collection. This is a synonym for [Collection.size]. */ @InternalApi public val <T> Collection<T>.length: Int get() = size
36
null
26
82
ad18e2fb043f665df9add82083c17877a23f8610
1,457
smithy-kotlin
Apache License 2.0
feature/src/main/kotlin/de/scout/fireplace/feature/models/Expose.kt
Scout24
96,885,938
false
null
package de.scout.fireplace.feature.models import android.support.annotation.Keep import android.view.View import java.lang.StringBuilder @Keep data class Expose( val id: String, val pictures: List<Picture>, val address: Address, val isProject: Boolean, val isPrivate: Boolean, val listingType: ListingType, val published: String, val isNewObject: Boolean, val attributes: List<Attribute>, val realtor: Realtor ) { fun getPictureFor(view: View): String { if (pictures.isEmpty()) { throw IndexOutOfBoundsException("No pictures available") } return pictures[0].getUrl(view.width, view.height) } @Keep data class Picture(private val urlScaleAndCrop: String, val type: String?) { fun getUrl(width: Int, height: Int): String { return StringBuilder(urlScaleAndCrop) .replace("%WIDTH%", width.toString()) .replace("%HEIGHT%", height.toString()) .toString() } private fun StringBuilder.replace(from: String, to: String): StringBuilder { return replace(indexOf(from), indexOf(from) + from.length, to) } } @Keep data class Address(val distance: String, val line: String) @Keep data class Attribute(val label: String, val value: String) { override fun toString(): String { return value } } @Keep data class Realtor(val logoUrlScale: String, val showcasePlacementColor: String?) @Keep enum class ListingType { S, M, L, XL } }
0
Kotlin
0
0
9c4532cf447d6df5a55c42628ce9dd85e7068e76
1,482
is24-fireplace-android
Apache License 2.0
src/main/kotlin/com/github/imeszaros/buxfer/BuxferException.kt
imeszaros
144,388,890
false
null
package com.github.imeszaros.buxfer class BuxferException(message: String, val type: String? = null) : RuntimeException(message)
0
Kotlin
0
0
7c913d9dd9dc4221b4e48863395fedbb23836020
129
buxfer-api
Apache License 2.0
kalexa-model/src/main/kotlin/com/hp/kalexa/model/services/proactiveevents/RelationshipToInvite.kt
HPInc
164,478,295
false
null
/* * Copyright 2018 HP Development Company, L.P. * SPDX-License-Identifier: MIT */ package com.hp.kalexa.model.services.proactiveevents import com.fasterxml.jackson.annotation.JsonCreator enum class RelationshipToInvite { FRIEND, CONTACT; companion object { @JsonCreator fun fromValue(text: String): RelationshipToInvite? { for (value in values()) { if (value.name == text) { return value } } return null } } }
0
Kotlin
1
17
e6674eeb24c255aef1859a62a65b805effdc9676
543
kalexa-sdk
MIT License
features/finances/impl/src/main/kotlin/br/com/mob1st/features/finances/impl/ui/category/detail/CategoryDetailConsumables.kt
mob1st
526,655,668
false
{"Kotlin": 674473, "Shell": 1558}
package br.com.mob1st.features.finances.impl.ui.category.detail import androidx.compose.runtime.Immutable import arrow.optics.optics import br.com.mob1st.core.design.atoms.properties.texts.LocalizedText import br.com.mob1st.core.design.organisms.snack.SnackbarState import br.com.mob1st.core.kotlinx.checks.checkIs import br.com.mob1st.core.kotlinx.structures.IndexSelectableState import br.com.mob1st.core.kotlinx.structures.MultiIndexSelectableState import br.com.mob1st.core.kotlinx.structures.Uri import br.com.mob1st.features.finances.impl.domain.entities.Recurrences import br.com.mob1st.features.finances.impl.domain.entities.selectMonthsIndexes import br.com.mob1st.features.finances.impl.domain.values.DayOfMonth import br.com.mob1st.features.finances.impl.ui.category.components.dialog.CategoryNameDialogState import br.com.mob1st.features.finances.impl.ui.category.components.dialog.name import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList import kotlinx.datetime.Month /** * Consumables for the category detail screen. * @property dialog The dialog to be shown. * @property snackbarState The snackbar to be shown. * @property isSubmitted Indicates if the form was submitted or not. */ @Immutable @optics data class CategoryDetailConsumables( val dialog: Dialog? = null, val snackbarState: SnackbarState? = null, val isSubmitted: Boolean = false, ) { /** * The possible dialogs that can be consumed in the category detail screen. */ sealed interface Dialog /** * Show the proper [Dialog] for the given [recurrences]. * @param recurrences The recurrences to be shown. * @return A new [CategoryDetailConsumables] with the dialog set. */ fun showRecurrencesDialog(recurrences: Recurrences): CategoryDetailConsumables { val dialog = when (recurrences) { is Recurrences.Fixed -> EditRecurrencesDialog.Fixed( selected = DayOfMonth.allDays.indexOf(recurrences.day), ) is Recurrences.Seasonal -> EditRecurrencesDialog.Seasonal( selected = recurrences.selectMonthsIndexes().toImmutableList(), ) Recurrences.Variable -> VariableNotAllowEditionDialog } return copy(dialog = dialog) } /** * Shows the undo dialog to ensure that the user wants to undo the changes made. * @return A new [CategoryDetailConsumables] with the dialog set. */ fun showIconPickerDialog(selected: Uri): CategoryDetailConsumables { return copy( dialog = IconPickerDialog(selected), ) } /** * Opens a dialog to allow the user to type a new name for the category. * @param initialName The initial name to be shown in the dialog. * @return A new [CategoryDetailConsumables] with the dialog set. */ fun showEnterCategoryNameDialog(initialName: String): CategoryDetailConsumables { return copy(dialog = EditCategoryNameDialog(initialName)) } /** * Sets the name of the category in the dialog. * @param name The new name to be set. * @return A new [CategoryDetailConsumables] with the dialog set. * @throws IllegalStateException If the dialog is not a [EditCategoryNameDialog]. */ fun setName( name: String, ): CategoryDetailConsumables { val dialog = checkIs<EditCategoryNameDialog>(dialog) return CategoryDetailConsumables.dialog.set( this, EditCategoryNameDialog.state.name.set(dialog, name), ) } /** * For [optics] generation. */ companion object } /** * Allows the user to type a new name for the category * @property state The current state of the dialog. */ @optics @Immutable data class EditCategoryNameDialog( val state: CategoryNameDialogState = CategoryNameDialogState(), ) : CategoryDetailConsumables.Dialog { val name = state.name constructor(name: String) : this(CategoryNameDialogState(name)) /** * for [optics] generation */ companion object } /** * Allows the user to set a new recurrence date for the category. * @property recurrences The recurrences that can be set as the new category recurrences. */ @Immutable sealed interface EditRecurrencesDialog : CategoryDetailConsumables.Dialog { @Immutable data class Fixed( override val selected: Int, ) : EditRecurrencesDialog, IndexSelectableState<LocalizedText> { override val options = DayOfMonth.allDays.map { LocalizedText(it.toString()) }.toImmutableList() } @Immutable data class Seasonal( override val selected: ImmutableList<Int>, ) : EditRecurrencesDialog, MultiIndexSelectableState<LocalizedText> { override val options = Month.entries.map { // TODO write MonthLocalizedText LocalizedText(it.name.lowercase()) }.toImmutableList() } } /** * The dialog to show the user that the variable recurrences cannot be edited. */ data object VariableNotAllowEditionDialog : CategoryDetailConsumables.Dialog @Immutable internal data class IconPickerDialog( val selected: Uri, val query: String = "", val listOfIcons: ImmutableList<Uri> = persistentListOf(), ) : CategoryDetailConsumables.Dialog
11
Kotlin
0
3
6860644926fbc9f8fb686d6b14d9ef0545c139c0
5,406
bet-app-android
Apache License 2.0
app/src/main/java/com/google/norinori6791/cycledo/MainActivity.kt
norinori777
208,719,519
false
null
package com.google.norinori6791.cycledo import android.os.Bundle import com.google.android.material.snackbar.Snackbar import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.FragmentManager import androidx.lifecycle.ViewModelProviders import com.google.norinori6791.cycledo.databinding.ActivityMainBinding import com.google.norinori6791.cycledo.ui.edit.EditFragment import com.google.norinori6791.cycledo.ui.edit.EditViewModel class MainActivity : AppCompatActivity() { private lateinit var mainViewModel: MainViewModel private lateinit var addViewModel: EditViewModel private lateinit var dataBinging: ActivityMainBinding private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java) addViewModel = ViewModelProviders.of(this).get(EditViewModel::class.java) dataBinging = DataBindingUtil.setContentView(this, R.layout.activity_main) val navController = findNavController(R.id.nav_host_fragment) setSupportActionBar(dataBinging.includeMain.toolbar) dataBinging.includeMain.fab.setOnClickListener { view -> navController.navigate(R.id.nav_edit) } // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_list, R.id.nav_edit, R.id.nav_label, R.id.nav_label_edit ), dataBinging.drawerLayout ) setupActionBarWithNavController(navController, appBarConfiguration) dataBinging.navView.setupWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
6
Kotlin
0
0
64d33c5d84b39b4065b4034e45b33bace2eb3b5a
2,351
CycleDo
Apache License 2.0
BineClient/App/BineClient/app/src/main/java/com/microsoft/mobile/polymer/mishtu/utils/NotificationActionHandler.kt
microsoft
563,698,948
false
{"Kotlin": 1296950, "Java": 406327, "Gherkin": 3712, "Shell": 1179}
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. package com.microsoft.mobile.polymer.mishtu.utils import android.app.Activity import android.app.NotificationManager import android.content.Context import android.content.Intent import android.os.Handler import android.os.Looper import android.util.Log import androidx.fragment.app.FragmentManager import com.microsoft.mobile.polymer.mishtu.telemetry.AnalyticsLogger import com.microsoft.mobile.polymer.mishtu.ui.activity.MainActivity import com.microsoft.mobile.polymer.mishtu.ui.activity.SubscriptionActivity import com.microsoft.mobile.polymer.mishtu.ui.fragment.sheet.BottomSheetOrderComplete class NotificationActionHandler (private val activity: Activity, private val fragmentManager: FragmentManager?) { fun onWatchContentClicked() { val activity: MainActivity = activity as MainActivity activity.startService(/*BNConstants.Service.ENTERTAINMENT*/) } fun onRenewPackClicked() { fragmentManager?.let { AppUtils.startOrderFlow(it, activity as Context,null) } } fun viewOffersClicked() { } fun viewSubscriptionClicked() { val subscriptionActivity = Intent(activity, SubscriptionActivity::class.java) activity.startActivity(subscriptionActivity) } fun handleNotification(type: String, notificationId: Int, dataId: String?) { AnalyticsLogger.getInstance().logNotificationClicked(type) val notificationManager = activity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(notificationId) if (type == BNConstants.NotificationType.NewContentArrived.name) { Handler(Looper.getMainLooper()).postDelayed({ val activity: MainActivity = activity as MainActivity activity.startFilmsTab() }, 1000) } if (type == BNConstants.NotificationType.NewOffer.name) { Handler(Looper.getMainLooper()).postDelayed({ val activity: MainActivity = activity as MainActivity activity.startService(/*BNConstants.Service.OFFERS*/) }, 1000) } if (type == BNConstants.NotificationType.OrderComplete.name) { Log.d("NoAction", dataId.toString()+"_"+notificationId) fragmentManager?.let { val bottomSheet = BottomSheetOrderComplete(dataId) bottomSheet.show(it,bottomSheet.tag) } } if (type == BNConstants.NotificationType.UserDataExportComplete.name) { Handler(Looper.getMainLooper()).postDelayed({ val activity: MainActivity = activity as MainActivity activity.exportData() }, 500) } if (type == BNConstants.NotificationType.Downloads.name) { Handler(Looper.getMainLooper()).postDelayed({ val activity: MainActivity = activity as MainActivity activity.selectTab(activity.downloadTabIndex) }, 500) } } }
0
Kotlin
3
1
fd6d91ba7e2efa1edd1d2fd43e30ee5b27a5a290
3,098
digital-content-distribution-toolkit-client
MIT License
app/src/test/java/io/jobtools/android/HangulJosaTest.kt
jobtools
228,480,468
false
null
package com.sirjuseyo import com.sirjuseyo.lib.exceptions.HangulJosaException import com.sirjuseyo.lib.hangul.concatJosa import org.junit.Assert.assertEquals import org.junit.Test class HangulJosaTest { @Test(expected = HangulJosaException::class) fun josaExceptionOnNoHangul() { "ABC".concatJosa("을") } @Test fun josa사람을() { assertEquals("사람을", "사람".concatJosa("을")) assertEquals("사람을", "사람".concatJosa("를")) } @Test fun josa동기화를() { assertEquals("동기화를", "동기화".concatJosa("을")) assertEquals("동기화를", "동기화".concatJosa("를")) } @Test fun josa사람이() { assertEquals("사람이", "사람".concatJosa("이")) assertEquals("사람이", "사람".concatJosa("가")) } @Test fun josa동기화가() { assertEquals("동기화가", "동기화".concatJosa("이")) assertEquals("동기화가", "동기화".concatJosa("가")) } @Test fun josa사람은() { assertEquals("사람은", "사람".concatJosa("은")) assertEquals("사람은", "사람".concatJosa("는")) } @Test fun josa동기화는() { assertEquals("동기화는", "동기화".concatJosa("은")) assertEquals("동기화는", "동기화".concatJosa("는")) } @Test fun josa사람과() { assertEquals("사람과", "사람".concatJosa("과")) assertEquals("사람과", "사람".concatJosa("와")) } @Test fun josa동기화와() { assertEquals("동기화와", "동기화".concatJosa("과")) assertEquals("동기화와", "동기화".concatJosa("와")) } @Test fun josa사람으로() { assertEquals("사람으로", "사람".concatJosa("으로")) assertEquals("사람으로", "사람".concatJosa("로")) } @Test fun josa동기화로() { assertEquals("동기화로", "동기화".concatJosa("으로")) assertEquals("동기화로", "동기화".concatJosa("로")) } @Test fun josa사람아() { assertEquals("사람아", "사람".concatJosa("아")) assertEquals("사람아", "사람".concatJosa("야")) } @Test fun josa동기화야() { assertEquals("동기화야", "동기화".concatJosa("아")) assertEquals("동기화야", "동기화".concatJosa("야")) } @Test fun josa사람이랑() { assertEquals("사람이랑", "사람".concatJosa("이랑")) assertEquals("사람이랑", "사람".concatJosa("랑")) } @Test fun josa동기화랑() { assertEquals("동기화랑", "동기화".concatJosa("이랑")) assertEquals("동기화랑", "동기화".concatJosa("랑")) } }
1
null
1
1
9e15b0710f0c2c86ad9fed2d7818065f88770d04
2,292
android
MIT License
src/main/kotlin/com/p4ddy/paddycrm/plugins/gui/compose/contact/ContactListView.kt
Mueller-Patrick
441,986,437
false
{"Kotlin": 136386}
package com.p4ddy.paddycrm.plugins.gui.compose.contact import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.p4ddy.paddycrm.application.contact.ContactApplicationService import com.p4ddy.paddycrm.domain.contact.ContactRepo import com.p4ddy.paddycrm.plugins.gui.compose.layout.ControlButtonSection import com.p4ddy.paddycrm.plugins.gui.compose.layout.ScrollView import com.p4ddy.paddycrm.plugins.gui.compose.navigation.NavController import com.p4ddy.paddycrm.plugins.gui.compose.navigation.Screen import com.p4ddy.paddycrm.plugins.persistence.exposed.contact.ContactExposedRepo @Composable fun ContactListView( navController: NavController ) { val contactRepo: ContactRepo = ContactExposedRepo() val contactService = ContactApplicationService(contactRepo) ControlButtonSection { Button(onClick = { navController.navigate(Screen.ContactCreateView.name) }) { Text("New") } } ScrollView("All Contacts") { Column( modifier = Modifier.fillMaxSize(1F) ) { for (contact in contactService.findAllContacts()) { Button( onClick = { navController.navigate(Screen.ContactDetailView.name, contact.contactId) }, modifier = Modifier.padding(vertical = 5.dp).width(300.dp) ) { ContactCompactView(contact) } } } } }
0
Kotlin
0
1
0233f023d9763c293f457a176fe84f87cea16b60
1,624
Paddy-CRM
MIT License
src/main/kotlin/cn/har01d/notebook/vo/NotebookVo.kt
power721
455,496,984
false
{"Vue": 164653, "Kotlin": 149601, "TypeScript": 45280, "HTML": 39446, "JavaScript": 21584, "CSS": 5882, "Shell": 1465}
package cn.har01d.notebook.vo import cn.har01d.notebook.core.Access import cn.har01d.notebook.entity.Notebook import cn.har01d.notebook.util.IdUtils import cn.har01d.notebook.util.IdUtils.NOTEBOOK_OFFSET import java.time.Instant data class NotebookVo( val id: String, val name: String, val slug: String?, val description: String, val owner: UserVo2, val access: Access, val createdTime: Instant, val updatedTime: Instant? ) data class NotebookVo2( val id: String, val name: String, val slug: String?, val access: Access, ) fun Notebook.toVo() = NotebookVo(IdUtils.encode(id!! + NOTEBOOK_OFFSET), name, slug, description, owner.toVo2(), access, createdTime, updatedTime) fun Notebook.toVo2() = NotebookVo2(IdUtils.encode(id!! + NOTEBOOK_OFFSET), name, slug, access)
0
Vue
0
0
e8abef8d38b3a98b7bb47988f5f97038878bfc97
865
notebook
MIT License
app/src/main/java/com/example/housemaster/SignUpSuccessFragment.kt
PubuduGunasekara
704,944,238
false
{"Kotlin": 195506, "Java": 347}
package com.example.housemaster import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.housemaster.databinding.FragmentSignupSuccessBinding import com.google.android.material.bottomnavigation.BottomNavigationView class SignUpSuccessFragment : Fragment(R.layout.fragment_signup_success) { private lateinit var signUpSuccessBinding: FragmentSignupSuccessBinding override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) signUpSuccessBinding = FragmentSignupSuccessBinding.bind(view) //this is just to hide ActionBar from the fragment (activity as AppCompatActivity?)!!.supportActionBar!!.hide() //this is just to hide BottomNavBar from the fragment val view = requireActivity().findViewById<BottomNavigationView>(R.id.bottom_nav) view.visibility = View.GONE //sign in button action, sign up success screen to sign in screen signUpSuccessBinding.btnDone.setOnClickListener { val action = SignUpSuccessFragmentDirections.actionSignUpSuccessFragmentToSignInFragment() findNavController().navigate(action) } } }
0
Kotlin
0
0
cefcaca13c038be96f6fad0195c48d8885648936
1,357
HouseMaster
MIT License
src/main/kotlin/com/dkorobtsov/veriff/website/test/urlcheck/SSLSocketFactoryProvider.kt
dkorobtsov
202,503,293
false
{"Kotlin": 53525, "JavaScript": 4750, "Shell": 410}
package com.dkorobtsov.veriff.website.test.urlcheck import java.security.KeyManagementException import java.security.cert.CertificateException import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager @Suppress("EmptyFunctionBlock", "TooGenericExceptionThrown") class SSLSocketFactoryProvider { fun allTrustingSSLSocketFactory(): SSLSocketFactory { val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager { @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { } @Throws(CertificateException::class) override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { } override fun getAcceptedIssuers(): Array<X509Certificate> { return arrayOf() } }) try { val sslContext = SSLContext.getInstance("TLS") sslContext.init(null, trustAllCerts, java.security.SecureRandom()) return sslContext.socketFactory } catch (e: Exception) { when (e) { is RuntimeException, is KeyManagementException -> { throw RuntimeException("Failed to create a SSL socket factory", e) } else -> throw e } } } }
0
Kotlin
0
1
f4767ed769e04dfee07c90747a4de9a383e8163f
1,499
veriff-website-test
MIT License
src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/websocket/page/GithubStatusPageBuild.kt
TencentBlueKing
189,153,491
false
{"Kotlin": 30176725, "Vue": 6739254, "JavaScript": 1256623, "Go": 616850, "Lua": 567159, "TypeScript": 461781, "SCSS": 365654, "Shell": 157561, "Java": 153049, "CSS": 106299, "HTML": 96201, "Python": 39238, "Less": 24714, "Makefile": 10630, "Smarty": 10297, "Dockerfile": 5097, "Batchfile": 4908, "PowerShell": 1626, "VBScript": 189}
package com.tencent.devops.process.websocket.page import com.tencent.devops.common.websocket.pojo.BuildPageInfo class GithubStatusPageBuild : StatusPageBuild() { override fun extStatusPage(buildPageInfo: BuildPageInfo): String? { return "/pipeline/${buildPageInfo.projectId}" } }
719
Kotlin
498
2,382
dd483c38bdbe5c17fa0e5e5bc3390cd1cd40757c
298
bk-ci
MIT License
projects/core/src/main/kotlin/site/siredvin/peripheralworks/computercraft/peripherals/RealityForgerPeripheral.kt
SirEdvin
489,471,520
false
null
package site.siredvin.peripheralworks.computercraft.peripherals import dan200.computercraft.api.lua.IArguments import dan200.computercraft.api.lua.LuaException import dan200.computercraft.api.lua.LuaFunction import dan200.computercraft.api.lua.MethodResult import net.minecraft.core.BlockPos import net.minecraft.resources.ResourceLocation import net.minecraft.world.level.block.state.BlockState import net.minecraft.world.level.block.state.properties.BooleanProperty import net.minecraft.world.level.block.state.properties.EnumProperty import net.minecraft.world.level.block.state.properties.IntegerProperty import net.minecraft.world.level.block.state.properties.Property import site.siredvin.peripheralium.computercraft.peripheral.OwnedPeripheral import site.siredvin.peripheralium.computercraft.peripheral.owner.BlockEntityPeripheralOwner import site.siredvin.peripheralium.util.radiusCorrect import site.siredvin.peripheralium.util.representation.LuaInterpretation import site.siredvin.peripheralium.util.representation.LuaRepresentation import site.siredvin.peripheralium.util.world.ScanUtils import site.siredvin.peripheralium.xplat.XplatRegistries import site.siredvin.peripheralworks.common.block.FlexibleRealityAnchor import site.siredvin.peripheralworks.common.blockentity.FlexibleRealityAnchorBlockEntity import site.siredvin.peripheralworks.common.blockentity.RealityForgerBlockEntity import site.siredvin.peripheralworks.common.configuration.PeripheralWorksConfig import site.siredvin.peripheralworks.tags.BlockTags import java.util.* class RealityForgerPeripheral( blockEntity: RealityForgerBlockEntity, ) : OwnedPeripheral<BlockEntityPeripheralOwner<RealityForgerBlockEntity>>(TYPE, BlockEntityPeripheralOwner(blockEntity)) { companion object { const val TYPE = "reality_forger" private val FLAG_MAPPING = mapOf( "playerPassable" to FlexibleRealityAnchor.PLAYER_PASSABLE, "lightPassable" to FlexibleRealityAnchor.LIGHT_PASSABLE, "skyLightPassable" to FlexibleRealityAnchor.SKY_LIGHT_PASSABLE, "invisible" to FlexibleRealityAnchor.INVISIBLE, ) } override val isEnabled: Boolean get() = PeripheralWorksConfig.enableRealityForger private val interactionRadius: Int get() = PeripheralWorksConfig.realityForgerMaxRange override val peripheralConfiguration: MutableMap<String, Any> get() { val data = super.peripheralConfiguration data["interactionRadius"] = interactionRadius return data } // Please, don't blame me for this untyped garbage code // If you can handle it better, you're welcome @Throws(LuaException::class) private fun applyBlockAttrs(state: BlockState, blockAttrs: Map<*, *>): BlockState { var changeableState: BlockState = state blockAttrs.forEach { attr -> val property = state.properties.find { it.name.equals(attr.key) } ?: throw LuaException(String.format("Unknown property name %s", attr.key)) when (property) { is EnumProperty -> { val value = attr.value.toString().lowercase() val targetValue = property.getPossibleValues().find { it.toString().lowercase() == value } ?: throw LuaException( java.lang.String.format( "Incorrect value %s, only %s is allowed", attr.key, property.getPossibleValues().joinToString(", "), ), ) // AAAAAAAAAAAAAAAAAA // WHAT THE HELL IS THIS CASTING // YOU TELL ME val trickedProperty = property as Property<Comparable<Any>> changeableState = changeableState.setValue(trickedProperty, targetValue as Comparable<Any>) } is BooleanProperty -> { if (attr.value !is Boolean) { throw LuaException(String.format("Incorrect value %s, should be boolean", attr.key)) } changeableState = changeableState.setValue(property, attr.value as Boolean) } is IntegerProperty -> { if (attr.value !is Number) { throw LuaException(String.format("Incorrect value %s, should be boolean", attr.key)) } changeableState = changeableState.setValue(property, (attr.value as Number).toInt()) } } } return changeableState } @Throws(LuaException::class) private fun findBlock(table: Map<*, *>): BlockState? { if (table.containsKey("block")) { val blockID = table["block"].toString() val block = XplatRegistries.BLOCKS.get(ResourceLocation(blockID)) if (block == net.minecraft.world.level.block.Blocks.AIR) { throw LuaException(String.format("Cannot find block %s", table["block"])) } if (block.defaultBlockState().`is`(BlockTags.REALITY_FORGER_FORBIDDEN)) { throw LuaException("You cannot use this block, is blocklisted") } var targetState = block.defaultBlockState() if (table.containsKey("attrs")) { val blockAttrs = table["attrs"] as? Map<*, *> ?: throw LuaException("attrs should be a table") targetState = applyBlockAttrs(targetState, blockAttrs) } return targetState } return null } private fun forgeRealityTileEntity( realityMirror: FlexibleRealityAnchorBlockEntity, targetState: BlockState?, appearanceTable: Map<*, *>, ) { appearanceTable.forEach { if (it.value is Boolean) { val targetProperty = FLAG_MAPPING[it.key.toString()] if (targetProperty != null) { realityMirror.setBooleanStateValue(targetProperty, it.value as Boolean) } } else if (it.key == "lightLevel" && it.value is Number) { realityMirror.lightLevel = (it.value as Number).toInt() } } if (targetState != null) { realityMirror.setMimic(targetState) } else { realityMirror.pushInternalDataChangeToClient() } } @LuaFunction(mainThread = true) fun detectAnchors(): List<Map<String, Any>> { val data = mutableListOf<Map<String, Any>>() ScanUtils.traverseBlocks(level!!, pos, interactionRadius, { blockState, pos -> val blockEntity = level!!.getBlockEntity(pos) if (blockEntity is FlexibleRealityAnchorBlockEntity) { data.add(LuaRepresentation.forBlockPos(pos, this.peripheralOwner.facing, this.pos)) } }) return data } @LuaFunction(mainThread = true) @Throws(LuaException::class) fun forgeRealityPieces(arguments: IArguments): MethodResult { val poses: MutableList<BlockPos> = mutableListOf() for (value in arguments.getTable(0).values) { if (value !is Map<*, *>) throw LuaException("First argument should be list of block positions") poses.add(LuaInterpretation.asBlockPos(peripheralOwner.pos, value, peripheralOwner.facing)) } val entities: MutableList<FlexibleRealityAnchorBlockEntity> = ArrayList<FlexibleRealityAnchorBlockEntity>() for (pos in poses) { if (radiusCorrect(pos, peripheralOwner.pos, interactionRadius)) { return MethodResult.of(null, "One of blocks are too far away") } val entity = level!!.getBlockEntity(pos) as? FlexibleRealityAnchorBlockEntity ?: return MethodResult.of( false, "One of provided coordinate are not correct", ) entities.add(entity) } val table = arguments.getTable(1) val targetState = findBlock(table) entities.forEach { forgeRealityTileEntity( it, targetState, table, ) } return MethodResult.of(true) } @LuaFunction(mainThread = true) @Throws(LuaException::class) fun forgeReality(arguments: IArguments): MethodResult { val table = arguments.getTable(0) val targetState = findBlock(table) if (level == null) { return MethodResult.of(null, "Level is not loaded, what?") } ScanUtils.traverseBlocks(level!!, pos, interactionRadius, { blockState, blockPos -> val blockEntity = level!!.getBlockEntity(blockPos) if (blockEntity is FlexibleRealityAnchorBlockEntity) { forgeRealityTileEntity(blockEntity, targetState, table) } }) return MethodResult.of(true) } }
3
Kotlin
2
6
4261ad04499375f16704c8df3f3faeb0e314ac54
9,099
UnlimitedPeripheralWorks
MIT License
app/src/main/java/com/jarvislin/drugstores/base/App.kt
jarvislin
238,508,346
false
null
package com.jarvislin.drugstores.base import android.annotation.SuppressLint import android.app.Application import com.facebook.stetho.Stetho import com.jarvislin.drugstores.BuildConfig import com.jarvislin.drugstores.module.* import com.orhanobut.logger.AndroidLogAdapter import com.orhanobut.logger.Logger import com.orhanobut.logger.PrettyFormatStrategy import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.plugins.RxJavaPlugins import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin import timber.log.Timber class App : Application() { companion object { @SuppressLint("StaticFieldLeak") private var instance: App? = null fun instance() = instance!! private const val APP_NAME = "Drugstores" } private val compositeDisposable = CompositeDisposable() override fun onCreate() { super.onCreate() instance = this // koin startKoin { androidContext(this@App) modules( listOf( adapterModule, localModule, remoteModule, repositoryModule, useCaseModule, viewModelModule, databaseModule ) ) } if (BuildConfig.DEBUG) { initLogger() Stetho.initializeWithDefaults(this) } RxJavaPlugins.setErrorHandler { Timber.e(it) } } private fun initLogger() { val formatStrategy = PrettyFormatStrategy.newBuilder() .tag(APP_NAME) .showThreadInfo(false) .build() Logger.addLogAdapter(AndroidLogAdapter(formatStrategy)) Timber.plant(DebugTree()) } fun addDisposable(disposable: Disposable) { compositeDisposable.add(disposable) } } class DebugTree : Timber.DebugTree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { Logger.log(priority, tag, message, t) } override fun formatMessage(message: String, args: Array<out Any>): String { return super.formatMessage(message.replace("%", "%%"), args) } }
1
Kotlin
10
39
0f45d84d524fed54af0e3f7efb9925b8773eb004
2,284
drugstores
Apache License 1.1
app/src/debug/java/com/burrowsapps/gif/search/DebugApplication.kt
jaredsburrows
61,517,561
false
null
package com.burrowsapps.gif.search import android.os.StrictMode import timber.log.Timber import timber.log.Timber.DebugTree class DebugApplication : MainApplication() { override fun onCreate() { super.onCreate() Timber.plant(DebugTree()) StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() // TODO: .penaltyDeath(), okhttp Cache .build(), ) StrictMode.setVmPolicy( StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog() // TODO: .penaltyDeath(), search bar .build(), ) } }
7
null
50
406
b1795fbbc0bc40f3ad06b06504733778b0755731
620
android-gif-search
Apache License 2.0
app/src/main/java/sk/devprog/firmy/data/model/company/CompanyDeposit.kt
yuraj11
637,130,066
false
null
package sk.devprog.firmy.data.model.company import kotlinx.serialization.Contextual import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import sk.devprog.firmy.data.model.TimeRangeData import java.time.LocalDate @Serializable data class CompanyDeposit( @SerialName("validFrom") @Contextual override val validFrom: LocalDate, @SerialName("validTo") @Contextual override val validTo: LocalDate? = null, @SerialName("personName") val personName: CompanyPersonName? = null, @SerialName("fullName") val fullName: String? = null, @SerialName("type") val type: String? = null, @SerialName("amount") val amount: Double, @SerialName("currency") val currency: CompanyCodeValue, ): TimeRangeData
0
Kotlin
0
1
bd10f991ae17fdc1830b7dd79bdda177ff880527
787
firmy
Apache License 2.0
helper/src/main/java/me/hgj/mvvmhelper/widget/state/BaseErrorCallback.kt
hegaojian
318,128,798
false
null
package me.hgj.mvvmhelper.widget.state import com.kingja.loadsir.callback.Callback import me.hgj.mvvmhelper.R /** * 作者 : hegaojian * 时间 : 2021/6/8 * 描述 : */ class BaseErrorCallback : Callback() { override fun onCreateView(): Int { return R.layout.layout_error } }
3
Kotlin
38
256
4adb416e908db6342c5f58c24d9dd7c75e69edaa
287
MvvmHelper
Apache License 2.0
app/src/test/java/io/github/drumber/kitsune/domain/mapper/ImageMapperTest.kt
Drumber
406,471,554
false
{"Kotlin": 797542, "Ruby": 2045}
package io.github.drumber.kitsune.domain.mapper import io.github.drumber.kitsune.domain.model.database.DBDimension import io.github.drumber.kitsune.domain.model.database.DBDimensions import io.github.drumber.kitsune.domain.model.database.DBImage import io.github.drumber.kitsune.domain.model.database.DBImageMeta import io.github.drumber.kitsune.domain.model.infrastructure.algolia.search.AlgoliaDimension import io.github.drumber.kitsune.domain.model.infrastructure.algolia.search.AlgoliaDimensions import io.github.drumber.kitsune.domain.model.infrastructure.algolia.search.AlgoliaImage import io.github.drumber.kitsune.domain.model.infrastructure.algolia.search.AlgoliaImageMeta import io.github.drumber.kitsune.domain.model.infrastructure.image.Dimension import io.github.drumber.kitsune.domain.model.infrastructure.image.Dimensions import io.github.drumber.kitsune.domain.model.infrastructure.image.Image import io.github.drumber.kitsune.domain.model.infrastructure.image.ImageMeta import net.datafaker.Faker import org.assertj.core.api.Assertions.assertThat import org.junit.Test class ImageMapperTest { private val faker = Faker() @Test fun shouldMapImageToDBImage() { // given val image = Image( tiny = faker.internet().image(), small = faker.internet().image(), medium = faker.internet().image(), large = faker.internet().image(), original = faker.internet().image(), meta = ImageMeta( Dimensions( tiny = Dimension(faker.number().positive(), faker.number().positive()), small = Dimension(faker.number().positive(), faker.number().positive()), medium = Dimension(faker.number().positive(), faker.number().positive()), large = Dimension(faker.number().positive(), faker.number().positive()) ) ) ) // when val dbImage = image.toDBImage() // then assertThat(dbImage).usingRecursiveComparison().isEqualTo(image) } @Test fun shouldMapDBImageToImage() { // given val dbImage = DBImage( tiny = faker.internet().image(), small = faker.internet().image(), medium = faker.internet().image(), large = faker.internet().image(), original = faker.internet().image(), meta = DBImageMeta( DBDimensions( tiny = DBDimension(faker.number().positive(), faker.number().positive()), small = DBDimension(faker.number().positive(), faker.number().positive()), medium = DBDimension(faker.number().positive(), faker.number().positive()), large = DBDimension(faker.number().positive(), faker.number().positive()) ) ) ) // when val image = dbImage.toImage() // then assertThat(image).usingRecursiveComparison().isEqualTo(dbImage) } @Test fun shouldMapAlgoliaImageToImage() { // given val algoliaImage = AlgoliaImage( tiny = faker.internet().image(), small = faker.internet().image(), medium = faker.internet().image(), large = faker.internet().image(), original = faker.internet().image(), meta = AlgoliaImageMeta( AlgoliaDimensions( tiny = AlgoliaDimension(faker.number().positive(), faker.number().positive()), small = AlgoliaDimension(faker.number().positive(), faker.number().positive()), medium = AlgoliaDimension(faker.number().positive(), faker.number().positive()), large = AlgoliaDimension(faker.number().positive(), faker.number().positive()) ) ) ) // when val image = algoliaImage.toImage() // then assertThat(image).usingRecursiveComparison().isEqualTo(algoliaImage) } }
5
Kotlin
4
61
6ab88cfacd8ee4daad23edbe4a134ab1f2b1f62c
4,071
Kitsune
Apache License 2.0
src/lib/kotlin/slatekit-server/src/main/kotlin/slatekit/server/ktor/KtorResponse.kt
cybernetics
365,666,746
true
{"Kotlin": 2327187, "Shell": 14381, "Java": 14284, "Swift": 1555}
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: <NAME> * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.server.ktor import io.ktor.application.ApplicationCall import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.response.header import io.ktor.response.respondBytes import io.ktor.response.respondText import slatekit.serialization.responses.ResponseEncoder import slatekit.common.types.Content import slatekit.common.types.Doc import slatekit.common.requests.Response import slatekit.serialization.Serialization import slatekit.results.* import slatekit.server.ServerSettings import slatekit.server.common.ResponseHandler class KtorResponse(val settings:ServerSettings) : ResponseHandler { /** * Returns the value of the result as an html(string) */ override suspend fun result(call: ApplicationCall, result: Response<Any?>): Any { return when(result.success) { false -> { when(result.err){ is ExceptionErr -> error(call, result, (result.err as ExceptionErr).err) else -> json(call, result) } } true -> { when (result.value) { is Content -> content(call, result, result.value as Content) is Doc -> file(call, result, result.value as Doc) else -> json(call, result) } } } } /** * Returns the value of the resulut as JSON. */ override suspend fun json(call: ApplicationCall, result: Response<Any?>) { val rawJson = Serialization.json(true).serialize(result) val json = when(settings.formatJson) { false -> rawJson true -> org.json.JSONObject(rawJson).toString(4) } val contentType = io.ktor.http.ContentType.Application.Json // "application/json" val statusCode = toHttpStatus(result) call.respondText(json, contentType, statusCode) } /** * Explicitly supplied content * Return the value of the result as a content with type */ override suspend fun content(call: ApplicationCall, result: Response<Any?>, content: Content?) { val text = content?.text ?: "" val contentType = content?.let { ContentType.parse(it.tpe.http) } ?: io.ktor.http.ContentType.Text.Plain val statusCode = toHttpStatus(result) call.respondText(text, contentType, statusCode) } /** * Returns the value of the result as a file document */ override suspend fun file(call: ApplicationCall, result: Response<Any?>, doc: Doc) { val bytes = doc.content.toByteArray() val statusCode = toHttpStatus(result) // Make files downloadable call.response.header("Content-Disposition", "attachment; filename=" + doc.name) call.respondBytes(bytes, ContentType.parse(doc.tpe.http), statusCode) } override fun toHttpStatus(response:Response<Any?>): HttpStatusCode { val http = Codes.toHttp(Passed.Succeeded(response.name, response.code, response.desc ?: "")) return HttpStatusCode(http.first, http.second.desc) } private suspend fun error(call: ApplicationCall, result: Response<Any?>, err: Err){ val json = ResponseEncoder.response(err, result) val text = json.toJSONString() val contentType = io.ktor.http.ContentType.Application.Json // "application/json" val statusCode = toHttpStatus(result) call.respondText(text, contentType, statusCode) } }
0
null
0
0
b3770d512a72aa9351d16aba4addab41bd961872
3,832
slatekit
Apache License 2.0
compiler/testData/diagnostics/testsWithStdLib/contracts/controlflow/initialization/unknown/unknownInvocations.kt
JetBrains
3,432,266
false
null
// FIR_IDENTICAL // !LANGUAGE: +AllowContractsForCustomFunctions +UseCallsInPlaceEffect // !OPT_IN: kotlin.contracts.ExperimentalContracts // !DIAGNOSTICS: -INVISIBLE_REFERENCE -INVISIBLE_MEMBER import kotlin.contracts.* fun <T> inPlace(block: () -> T): T { contract { callsInPlace(block) } return block() } fun reassignmentAndNoInitializaiton() { val x: Int inPlace { <!VAL_REASSIGNMENT!>x<!> = 42 } <!UNINITIALIZED_VARIABLE!>x<!>.inc() }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
474
kotlin
Apache License 2.0
DocumentScanner/src/main/java/com/zynksoftware/documentscanner/common/extensions/ViewExtensions.kt
zynkware
302,617,942
false
null
/** Copyright 2020 ZynkSoftware SRL Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.zynksoftware.documentscanner.common.extensions import android.view.View internal fun View.hide() { visibility = View.GONE } internal fun View.show() { visibility = View.VISIBLE }
6
null
49
99
f6e20370deb5ad30aa5742cf8e9f4838926067d3
1,318
Document-Scanning-Android-SDK
The Unlicense
dist/src/main/kotlin/kr/toxicity/hud/manager/CompatibilityManager.kt
toxicity188
766,189,896
false
{"Kotlin": 93642, "Java": 11489}
package kr.toxicity.hud.manager import kr.toxicity.hud.api.update.UpdateEvent import kr.toxicity.hud.compatibility.mmocore.MMOCoreCompatibility import kr.toxicity.hud.compatibility.mythicmobs.MythicMobsCompatibility import kr.toxicity.hud.compatibility.worldguard.WorldGuardCompatibility import kr.toxicity.hud.resource.GlobalResource import kr.toxicity.hud.util.PLUGIN import org.bukkit.Bukkit import java.util.function.Function object CompatibilityManager: BetterHudManager { private val compatibilities = mapOf( "MMOCore" to { MMOCoreCompatibility() }, "MythicMobs" to { MythicMobsCompatibility() }, "WorldGuard" to { WorldGuardCompatibility() } ) override fun start() { compatibilities.forEach { if (Bukkit.getPluginManager().isPluginEnabled(it.key)) { runCatching { val obj = it.value() val namespace = it.key.lowercase() obj.listeners.forEach { entry -> PLUGIN.listenerManager.addListener("${namespace}_${entry.key}") { c -> val reason = entry.value(c) Function { u: UpdateEvent -> reason.invoke(u) } } } obj.numbers.forEach { entry -> PLUGIN.placeholderManager.numberContainer.addPlaceholder("${namespace}_${entry.key}", entry.value) } obj.strings.forEach { entry -> PLUGIN.placeholderManager.stringContainer.addPlaceholder("${namespace}_${entry.key}", entry.value) } obj.booleans.forEach { entry -> PLUGIN.placeholderManager.booleanContainer.addPlaceholder("${namespace}_${entry.key}", entry.value) } } } } } override fun reload(resource: GlobalResource) { } override fun end() { } }
0
Kotlin
1
1
e93de74cd747e4e39711a4355c4332cae6f7bc15
2,121
BetterHud
MIT License
CoronaKorea/app/src/main/java/com/mtjin/coronakorea/data/city/source/local/CityDao.kt
mtjin
259,939,061
false
null
package com.mtjin.coronakorea.data.city.source.local import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.mtjin.coronakorea.data.city.Korea @Dao interface CityDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertKorea(korea: Korea) @Query("SELECT * FROM korea LIMIT 1") fun getKorea(): Korea? }
0
Kotlin
0
2
53797f9b4451b2b66716db86595213b6b11b3bbb
403
CoronaKoreaReleaseVersion
MIT License
src/main/kotlin/no/nav/syfo/aktivitetskravvurdering/kafka/KafkaAktivitetskravVurderingTask.kt
navikt
189,998,720
false
{"Kotlin": 553842, "Dockerfile": 226}
package no.nav.syfo.aktivitetskravvurdering.kafka import no.nav.syfo.application.ApplicationState import no.nav.syfo.application.database.database import no.nav.syfo.application.kafka.KafkaEnvironment import no.nav.syfo.application.kafka.kafkaAivenConsumerConfig import no.nav.syfo.kafka.launchKafkaTask import no.nav.syfo.util.configuredJacksonMapper import org.apache.kafka.clients.consumer.ConsumerConfig import org.apache.kafka.common.serialization.Deserializer import java.util.* const val AKTIVITETSKRAV_VURDERING_TOPIC = "teamsykefravr.aktivitetskrav-vurdering" fun launchKafkaTaskAktivitetskravVurdering( applicationState: ApplicationState, kafkaEnvironment: KafkaEnvironment, ) { val kafkaAktivitetskravVurderingConsumer = KafkaAktivitetskravVurderingConsumer( database = database, ) val consumerProperties = Properties().apply { putAll(kafkaAivenConsumerConfig(kafkaEnvironment = kafkaEnvironment)) this[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = KafkaAktivitetskravVurderingDeserializer::class.java } launchKafkaTask( applicationState = applicationState, topic = AKTIVITETSKRAV_VURDERING_TOPIC, consumerProperties = consumerProperties, kafkaConsumerService = kafkaAktivitetskravVurderingConsumer, ) } class KafkaAktivitetskravVurderingDeserializer : Deserializer<KafkaAktivitetskravVurdering> { private val mapper = configuredJacksonMapper() override fun deserialize(topic: String, data: ByteArray): KafkaAktivitetskravVurdering = mapper.readValue(data, KafkaAktivitetskravVurdering::class.java) }
2
Kotlin
0
0
cfae083829f37d443d2afc23abd47fa5b0f94c5e
1,625
syfooversiktsrv
MIT License
android/src/main/java/com/stripeterminalreactnative/ReactNativeConstants.kt
stripe
433,542,525
false
{"TypeScript": 347217, "Kotlin": 105150, "Swift": 80482, "Java": 25595, "JavaScript": 21806, "Objective-C++": 9457, "Objective-C": 8093, "C++": 6971, "Ruby": 5656, "Shell": 3053, "Starlark": 1962, "Makefile": 1528, "C": 103}
package com.stripeterminalreactnative enum class ReactNativeConstants(val listenerName: String) { CHANGE_CONNECTION_STATUS("didChangeConnectionStatus"), CHANGE_PAYMENT_STATUS("didChangePaymentStatus"), FETCH_TOKEN_PROVIDER("onFetchTokenProviderListener"), FINISH_DISCOVERING_READERS("didFinishDiscoveringReaders"), FINISH_INSTALLING_UPDATE("didFinishInstallingUpdate"), REQUEST_READER_DISPLAY_MESSAGE("didRequestReaderDisplayMessage"), REQUEST_READER_INPUT("didRequestReaderInput"), REPORT_AVAILABLE_UPDATE("didReportAvailableUpdate"), REPORT_UNEXPECTED_READER_DISCONNECT("didReportUnexpectedReaderDisconnect"), REPORT_UPDATE_PROGRESS("didReportReaderSoftwareUpdateProgress"), START_INSTALLING_UPDATE("didStartInstallingUpdate"), UPDATE_DISCOVERED_READERS("didUpdateDiscoveredReaders"), START_READER_RECONNECT("didStartReaderReconnect"), READER_RECONNECT_SUCCEED("didSucceedReaderReconnect"), READER_RECONNECT_FAIL("didFailReaderReconnect"), }
25
TypeScript
38
70
1836ae2290413378105df64aa5ef64444a77468f
1,005
stripe-terminal-react-native
MIT License
src/app/io/portsIn/TerminalPort.kt
JBJamesBrownJB
200,662,229
false
null
package io.portsIn import application.addToDo import io.portsOut.EmailAdapter import io.portsOut.TerminalAdapter import java.time.Instant import java.time.ZoneOffset fun main(args: Array<String>) { println("Adding todo -> ${args.joinToString(" ")}") addToDo(args.joinToString(" "), Instant.now().atZone(ZoneOffset.UTC), listOf(TerminalAdapter(),EmailAdapter())) }
1
Kotlin
0
0
0bde5dd0b592552de0a872fd2ba3fdb80a587f33
390
remto
MIT License
modules/onboarding/src/main/kotlin/edu/stanford/spezi/module/onboarding/onboarding/OnboardingUiState.kt
StanfordSpezi
787,513,636
false
{"Kotlin": 333238, "Ruby": 1659, "Shell": 212}
package edu.stanford.spezi.module.onboarding.onboarding /** * A sealed class representing the actions that can be performed on the onboarding screen. */ sealed class Action { data class UpdateArea(val areas: List<Area>) : Action() data object ContinueButtonAction : Action() } /** * The UI state for the onboarding screen. */ data class OnboardingUiState( val areas: List<Area> = emptyList(), val title: String = "Title", val subtitle: String = "Subtitle", val error: String? = null, )
20
Kotlin
1
7
b77e6eacbcb464bf454f3f566642d4f3c6e0b3d3
517
SpeziKt
MIT License
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt
maheshwari-e
347,487,780
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsControllerCompat import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.androiddevchallenge.ui.theme.MyTheme class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window,false) ViewCompat.setOnApplyWindowInsetsListener(window.decorView.rootView) { _, insets -> insets } setContent { MyTheme { WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightStatusBars = !isSystemInDarkTheme() MyApp() } } } } // Start building your app here! @Composable fun MyApp() { Surface(color = MaterialTheme.colors.background) { val navController = rememberNavController() NavHost(navController = navController, startDestination = "Welcome"){ composable("Welcome"){ Welcome(navController)} composable("Login"){ Login(navController)} composable("Home"){ Home()} } } } @Preview("Light Theme", widthDp = 360, heightDp = 640) @Composable fun LightPreview() { MyTheme { MyApp() } } @Preview("Dark Theme", widthDp = 360, heightDp = 640) @Composable fun DarkPreview() { MyTheme(darkTheme = true) { MyApp() } }
0
Kotlin
0
0
0330c9386a57a419d4f2a87e95758cbd859ffeda
2,558
week3-jetpack-compose-challenge-d3
Apache License 2.0
app/src/main/java/com/example/digionebank/Pessoa.kt
dantas-barreto
344,179,815
false
null
package com.example.digionebank abstract class Pessoa ( val nome: String, val cpf: String ) {}
0
Kotlin
0
0
007250a688a1765eb25d428d36d30d448d5f04b6
103
Digione-Bank
MIT License
app/src/main/java/com/zaurh/polskismak/presentation/state/QuoteState.kt
zaurh
774,811,841
false
{"Kotlin": 104427}
package com.zaurh.polskismak.presentation.state import com.zaurh.polskismak.data.remote.dto.Quotes data class QuoteState( val result: Quotes? = null, val error: String = "", val isLoading: Boolean = false )
0
Kotlin
0
1
b16f11ec09e78220342c3c4532efa8e0e62b24f5
221
PolskiSmak
The Unlicense
kzen-auto-common/src/commonMain/kotlin/tech/kzen/auto/common/objects/document/feature/FeatureDocument.kt
alexoooo
131,353,826
false
{"Kotlin": 1948872, "Java": 163744, "CSS": 5632, "JavaScript": 203}
package tech.kzen.auto.common.objects.document.feature import tech.kzen.auto.common.objects.document.DocumentArchetype import tech.kzen.lib.common.model.document.DocumentPath import tech.kzen.lib.common.model.location.ObjectLocation import tech.kzen.lib.common.model.obj.ObjectName import tech.kzen.lib.common.model.obj.ObjectNesting import tech.kzen.lib.common.model.obj.ObjectPath import tech.kzen.lib.common.model.structure.notation.DocumentNotation import tech.kzen.lib.common.reflect.Reflect import tech.kzen.lib.common.service.notation.NotationConventions // see: https://en.wikipedia.org/wiki/Feature_(computer_vision) @Reflect class FeatureDocument( val objectLocation: ObjectLocation, val documentNotation: DocumentNotation ): DocumentArchetype() { //----------------------------------------------------------------------------------------------------------------- companion object { private val featureJvmPath = DocumentPath.parse("auto-jvm/feature/feature-jvm.yaml") val screenshotTakerLocation = ObjectLocation( featureJvmPath, ObjectPath(ObjectName("ScreenshotTaker"), ObjectNesting.root)) val screenshotCropperLocation = ObjectLocation( featureJvmPath, ObjectPath(ObjectName("ScreenshotCropper"), ObjectNesting.root)) val cropTopParam = "y" val cropLeftParam = "x" val cropWidthParam = "width" val cropHeightParam = "height" val archetypeObjectName = ObjectName("Feature") fun isFeature(documentNotation: DocumentNotation): Boolean { val mainObjectNotation = documentNotation.objects.notations[NotationConventions.mainObjectPath] ?: return false val mainObjectIs = mainObjectNotation.get(NotationConventions.isAttributeName)?.asString() ?: return false return mainObjectIs == archetypeObjectName.value } } }
1
Kotlin
1
1
ffdd5bb5dcc541b884d887a01d7dbbf1d506b610
2,004
kzen-auto
MIT License
presentation/settings/src/commonMain/kotlin/com/thomaskioko/tvmaniac/presentation/settings/SettingsActions.kt
thomaskioko
361,393,353
false
{"Kotlin": 605171, "Swift": 88232}
package com.thomaskioko.tvmaniac.presentation.settings import com.thomaskioko.tvmaniac.datastore.api.Theme sealed class SettingsActions data class ThemeSelected( val theme: Theme, ) : SettingsActions() object ChangeThemeClicked : SettingsActions() object DimissThemeClicked : SettingsActions() object ShowTraktDialog : SettingsActions() object DismissTraktDialog : SettingsActions() object TraktLogoutClicked : SettingsActions() object TraktLoginClicked : SettingsActions()
9
Kotlin
16
135
c77cb4961234b7ae7ae254becbcca8485062e74a
481
tv-maniac
Apache License 2.0
app/src/main/java/com/techpaliyal/androidkotlinmvvm/ui/view_model/MultiSelectListingActivityViewModel.kt
yogeshpaliyal
232,743,178
false
null
package com.techpaliyal.androidkotlinmvvm.ui.view_model import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.techpaliyal.androidkotlinmvvm.model.MultiSelectModel /** * @author <NAME> * <EMAIL> * https://techpaliyal.com * https://yogeshpaliyal.com * Created Date : 9 January 2020 */ class MultiSelectListingActivityViewModel : ViewModel(){ val data = MutableLiveData<ArrayList<MultiSelectModel>>(ArrayList<MultiSelectModel>()) fun fetchData(){ if (data.value.isNullOrEmpty()) { val tempArr = ArrayList<MultiSelectModel>() tempArr.add(MultiSelectModel(name = "Apple", isChecked = true)) tempArr.add(MultiSelectModel(name = "Banana", isChecked = false)) tempArr.add(MultiSelectModel(name = "Cherry", isChecked = false)) tempArr.add(MultiSelectModel(name = "Mango", isChecked = false)) tempArr.add(MultiSelectModel(name = "Orange", isChecked = false)) tempArr.add(MultiSelectModel(name = "Pineapple", isChecked = false)) tempArr.add(MultiSelectModel(name = "Watermelon", isChecked = false)) data.value = tempArr } } fun logData(){ /* data.value?.forEach { Log.d("Testing","Name ${it.name} value => ${it.isChecked}") }*/ } }
11
Kotlin
4
17
df69d49d769ccf8e25b54a57f4fe7e3af032cb8f
1,341
Android-Universal-Recycler-View-Adapter
MIT License
telegram-bot/src/commonMain/kotlin/eu/vendeli/tgbot/api/message/ForwardMessage.kt
vendelieu
496,567,172
false
null
@file:Suppress("MatchingDeclarationName") package eu.vendeli.tgbot.api.message import eu.vendeli.tgbot.interfaces.Action import eu.vendeli.tgbot.interfaces.features.OptionsFeature import eu.vendeli.tgbot.types.Message import eu.vendeli.tgbot.types.User import eu.vendeli.tgbot.types.chat.Chat import eu.vendeli.tgbot.types.internal.Identifier import eu.vendeli.tgbot.types.internal.TgMethod import eu.vendeli.tgbot.types.internal.options.ForwardMessageOptions import eu.vendeli.tgbot.utils.encodeWith import eu.vendeli.tgbot.utils.getReturnType import eu.vendeli.tgbot.utils.serde.DynamicLookupSerializer import eu.vendeli.tgbot.utils.toJsonElement class ForwardMessageAction(fromChatId: Identifier, messageId: Long) : Action<Message>(), OptionsFeature<ForwardMessageAction, ForwardMessageOptions> { override val method = TgMethod("forwardMessage") override val returnType = getReturnType() override val options = ForwardMessageOptions() init { parameters["from_chat_id"] = fromChatId.encodeWith(DynamicLookupSerializer) parameters["message_id"] = messageId.toJsonElement() } } /** * Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned. * * [Api reference](https://core.telegram.org/bots/api#forwardmessage) * @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername) * @param messageThreadId Unique identifier for the target message thread (topic) of the forum; for forum supergroups only * @param fromChatId Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) * @param disableNotification Sends the message silently. Users will receive a notification with no sound. * @param protectContent Protects the contents of the forwarded message from forwarding and saving * @param messageId Message identifier in the chat specified in from_chat_id * @returns [Message] */ @Suppress("NOTHING_TO_INLINE") inline fun forwardMessage(fromChatId: Identifier, messageId: Long) = ForwardMessageAction(fromChatId, messageId) @Suppress("NOTHING_TO_INLINE") inline fun forwardMessage(fromChatId: Long, messageId: Long) = forwardMessage(Identifier.from(fromChatId), messageId) @Suppress("NOTHING_TO_INLINE") inline fun forwardMessage(fromChatId: String, messageId: Long) = forwardMessage(Identifier.from(fromChatId), messageId) @Suppress("NOTHING_TO_INLINE") inline fun forwardMessage(fromChatId: User, messageId: Long) = forwardMessage(Identifier.from(fromChatId), messageId) @Suppress("NOTHING_TO_INLINE") inline fun forwardMessage(fromChatId: Chat, messageId: Long) = forwardMessage(Identifier.from(fromChatId.id), messageId)
6
null
9
165
c1ddf4a42c577410af31249dc650858320668263
2,815
telegram-bot
Apache License 2.0
library/src/main/java/renetik/android/core/lang/CSTitleValue.kt
renetik
506,035,450
false
{"Kotlin": 168027}
package renetik.android.core.lang import renetik.android.core.lang.value.CSValue data class CSTitleValue( override val title: String, override val value: Int ) : CSHasTitle, CSValue<Int>
0
Kotlin
1
1
33e3b0827c4428329a3fca07c7970b38376462b5
192
renetik-android-core
MIT License
kotlin_arch/src/main/java/com/czq/kotlin_arch/common/util/AssetUtil.kt
manondidi
154,757,414
false
null
package com.czq.kotlin_arch.common.util import android.content.Context import java.io.BufferedReader import java.io.IOException import java.io.InputStream import java.io.InputStreamReader class AssetUtil { companion object { fun getStringFromFile(context: Context, fileName: String): String? { val content = StringBuilder() var bufferedReader: BufferedReader? = null var inputStream: InputStream? = null val assetManager = context.getAssets() try { inputStream = assetManager.open(fileName) bufferedReader = BufferedReader(InputStreamReader(inputStream)) var line: String while (true) { line = bufferedReader.readLine() ?: break content.append(line) } bufferedReader!!.close() inputStream!!.close() return content.toString() } catch (e: IOException) { e.printStackTrace() } finally { try { if (bufferedReader != null) { bufferedReader!!.close() } if (inputStream != null) { inputStream!!.close() } } catch (e: IOException) { e.printStackTrace() } } return null } } }
2
null
24
206
70182365c6c1755f6a73b0cdc6403b34bd4841ec
1,449
kotlinArch
MIT License
ktask-server/src/main/kotlin/ktask/server/entity/notification/request/EmailRequest.kt
perracodex
810,476,641
false
{"Kotlin": 271635, "JavaScript": 11106, "HTML": 8779, "CSS": 4693, "Dockerfile": 3125}
/* * Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license. */ package ktask.notification.entity.message.request import kotlinx.serialization.Serializable import ktask.base.errors.SystemError import ktask.base.persistence.serializers.SUUID import ktask.base.persistence.validators.IValidator import ktask.base.persistence.validators.impl.EmailValidator import ktask.base.scheduler.service.schedule.Schedule import ktask.notification.consumer.message.task.EmailConsumer import ktask.notification.entity.message.IMessageRequest import ktask.notification.entity.message.Recipient /** * Represents a request to send an Email notification task. * * @property id The unique identifier of the task request. * @property description Optional description of the task. * @property schedule Optional [Schedule] for the task. * @property recipients List of target recipients. * @property template The template to be used for the notification. * @property fields Optional fields to be included in the template. * @property cc List of recipients to be copied on the notification. * @property subject The subject or title of the notification. */ @Serializable data class EmailRequest( override val id: SUUID, override val description: String? = null, override val schedule: Schedule? = null, override val recipients: List<Recipient>, override val template: String, override val fields: Map<String, String>? = null, val cc: List<String> = emptyList(), val subject: String, ) : IMessageRequest { init { verify() } override fun toMap(recipient: Recipient): MutableMap<String, Any?> { return super.toMap(recipient = recipient).apply { this[EmailConsumer.Property.CC.key] = cc this[EmailConsumer.Property.SUBJECT.key] = subject } } companion object { /** * Verifies the recipients of the request. * * @param request The [EmailRequest] instance to be verified. */ fun verifyRecipients(request: EmailRequest) { // This verification of recipients must be done within the scope of a route endpoint, // and not in the request dataclass init block, which is actually called before // the dataclass reaches the route endpoint scope. // This way we can raise a custom error response, as opposed to a generic // 400 Bad Request, which would be raised if the validation was done in the init block. request.recipients.forEach { recipient -> val result: IValidator.Result = EmailValidator.validate(value = recipient.target) if (result is IValidator.Result.Failure) { SystemError.InvalidEmailFormat(id = request.id, email = recipient.target).raise() } } } } }
0
Kotlin
0
1
d6ca6244e5a979cc2d5302237c3d555b2177aef2
2,900
ktask
MIT License
app/src/main/java/com/davion/github/paging/UserRepository.kt
dragonddavion
291,616,804
false
null
package com.davion.github.paging import android.util.Log import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.davion.github.paging.network.GithubApiService import com.davion.github.paging.model.Repo import com.davion.github.paging.model.User import com.davion.github.paging.ui.repo.RepoPagingSource import kotlinx.coroutines.flow.Flow import retrofit2.HttpException import java.io.IOException import javax.inject.Inject private const val NETWORK_PAGE_SIZE = 50 class UserRepository @Inject constructor(private val retrofitService: GithubApiService) { var since: Int = 0 var page: Int = 1 suspend fun getUsers(): List<User> { try { val response = retrofitService.getUsersAsync(since, NETWORK_PAGE_SIZE).await() return if (response.isSuccessful) { Log.d("Davion1", "since: $since, size: $NETWORK_PAGE_SIZE") if (response.body() != null) { since = response.body()!![NETWORK_PAGE_SIZE - 1].id response.body()!! } else { listOf() } } else { Log.d("Davion2", "since: $since, size: $NETWORK_PAGE_SIZE") listOf() } } catch (exception: IOException) { Log.d("Davion3", "${exception.message}") return listOf() } catch (exception: HttpException) { Log.d("Davion4", exception.message()) return listOf() } } fun getRepos() : Flow<PagingData<Repo>> { return Pager( config = PagingConfig( pageSize = NETWORK_PAGE_SIZE, enablePlaceholders = false ), pagingSourceFactory = { RepoPagingSource(service = retrofitService) } ).flow } }
0
Kotlin
0
0
f7ffe65edbbc7ab76b8995c98ab01c08f93dcb87
1,897
github-paging
Apache License 2.0
2023/SNMPTools/Snmp4jUtils_KtJvm/src/test/kotlin/SerializerTest.kt
kyoya-p
253,926,918
false
null
import jp.wjg.shokkaa.snmp4jutils.jsonSnmp4j import jp.wjg.shokkaa.snmp4jutils.yamlSnmp4j import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import org.junit.jupiter.api.Test import org.snmp4j.smi.* import java.net.InetAddress class SerializerTest { val mibs = listOf( VariableBinding(OID("1.3.5.0"), OID("1.3.5.1")), VariableBinding(OID("1.3.5.1"), Integer32(12345)), VariableBinding(OID("1.3.5.2"), OctetString("ABC-123#!$ ")), VariableBinding(OID("1.3.5.2.0"), OctetString("")), VariableBinding(OID("1.3.5.3"), Gauge32(12345L)), VariableBinding(OID("1.3.5.4"), Counter32(12345L)), VariableBinding(OID("1.3.5.5"), Counter64(12345L)), VariableBinding(OID("1.3.5.6"), Null()), VariableBinding(OID("1.3.5.7"), TimeTicks(12345L)), VariableBinding(OID("1.3.5.8"), Opaque(ByteArray(5) { it.toByte() })), VariableBinding(OID("1.3.5.8.0"), Opaque(ByteArray(0) { it.toByte() })), VariableBinding(OID("1.3.5.9"), IpAddress(InetAddress.getByAddress(ByteArray(4) { it.toByte() }))), ) val mibsJson = """[ "1.3.5.0 6 1.3.5.1", "1.3.5.1 2 12345", "1.3.5.2 4 ABC-123#!${'$'} ", "1.3.5.2.0 4 ", "1.3.5.3 66 12345", "1.3.5.4 65 12345", "1.3.5.5 70 12345", "1.3.5.6 5 ", "1.3.5.7 67 12345", "1.3.5.8 68 :00:01:02:03:04", "1.3.5.8.0 68 ", "1.3.5.9 64 0.1.2.3" ]""" val mibsYaml = """- "1.3.5.0 6 1.3.5.1" - "1.3.5.1 2 12345" - "1.3.5.2 4 ABC-123#!${'$'} " - "1.3.5.2.0 4 " - "1.3.5.3 66 12345" - "1.3.5.4 65 12345" - "1.3.5.5 70 12345" - "1.3.5.6 5 " - "1.3.5.7 67 12345" - "1.3.5.8 68 :00:01:02:03:04" - "1.3.5.8.0 68 " - "1.3.5.9 64 0.1.2.3"""" @Test fun serialiser_json() { val j = jsonSnmp4j.encodeToString(mibs) println(j) assert(j == mibsJson) } @Test fun deserialiser_json() { val m: List<VariableBinding> = jsonSnmp4j.decodeFromString(mibsJson) mibs.zip(m).forEach { (a, b) -> println("$a{${a.variable.syntaxString}} : $b{${b.variable.syntaxString}}") assert(a == b) } assert(mibs == m) } @Test fun serialiser_yaml() { val y = yamlSnmp4j.encodeToString(mibs) println(y) assert(y == mibsYaml) } @Test fun deserialiser_yaml() { val m: List<VariableBinding> = yamlSnmp4j.decodeFromString(mibsYaml) mibs.zip(m).forEach { (a, b) -> println("$a{${a.variable.syntaxString}} : $b{${b.variable.syntaxString}}") assert(a == b) } assert(mibs == m) } }
16
null
1
2
5565de461ab064580f5087d055d72a5aeda9da7b
2,646
samples
Apache License 2.0
src/client/kotlin/org/teamvoided/grappled/entities/GrapplingHookHeadEntityRenderer.kt
theendercore
814,108,674
false
{"Kotlin": 26641, "Java": 544}
package org.teamvoided.grappled.entities import com.mojang.blaze3d.vertex.VertexConsumer import net.minecraft.client.MinecraftClient import net.minecraft.client.network.ClientPlayerEntity import net.minecraft.client.render.Frustum import net.minecraft.client.render.OverlayTexture import net.minecraft.client.render.RenderLayer import net.minecraft.client.render.VertexConsumerProvider import net.minecraft.client.render.entity.EntityRenderer import net.minecraft.client.render.entity.EntityRendererFactory import net.minecraft.client.render.model.json.ModelTransformationMode import net.minecraft.client.util.math.MatrixStack import net.minecraft.client.world.ClientWorld import net.minecraft.entity.Entity import net.minecraft.item.Items import net.minecraft.text.Text import net.minecraft.util.Identifier import net.minecraft.util.math.Axis import net.minecraft.util.math.MathHelper.lerp import net.minecraft.util.math.Vec3d import org.teamvoided.grappled.util.GapRenderLayers import kotlin.math.acos import kotlin.math.atan2 class GrapplingHookHeadEntityRenderer(ctx: EntityRendererFactory.Context) : EntityRenderer<GrapplingHookHeadEntity>(ctx) { override fun render( entity: GrapplingHookHeadEntity, yaw: Float, tDelta: Float, matrices: MatrixStack, vertexConsumers: VertexConsumerProvider, entityLight: Int ) { super.render(entity, yaw, tDelta, matrices, vertexConsumers, 0xffffff) val world = entity.world val owner = (world as ClientWorld).entities.firstOrNull { it.uuid == entity.getOwner() } MinecraftClient.getInstance().itemRenderer.renderItem( Items.BREEZE_ROD.defaultStack, ModelTransformationMode.GROUND, entityLight, OverlayTexture.DEFAULT_UV, matrices, vertexConsumers, entity.world, 0 ) if (owner != null) { if (owner is ClientPlayerEntity) owner.sendMessage(Text.of("$entityLight | $entityLight"), true) matrices.push() matrices.translate(0.21, 0.35, 0.015) val hookPos = fromLerpedPosition(entity, 1.0, tDelta.toDouble()) val ownerPos = Vec3d( lerp(tDelta.toDouble(), owner.lastRenderX, owner.x), lerp(tDelta.toDouble(), owner.lastRenderY, owner.y) + 1.6, lerp(tDelta.toDouble(), owner.lastRenderZ, owner.z) ) fromLerpedPosition(owner, 1.6, tDelta.toDouble()) val subtracted = ownerPos.subtract(hookPos) val length = subtracted.length().toFloat() val normalized = subtracted.normalize() val o = atan2(normalized.z, normalized.x).toFloat() matrices.rotate(Axis.Y_POSITIVE.rotationDegrees((1.5707964F - o) * 57.295776F)) matrices.rotate(Axis.X_POSITIVE.rotationDegrees(acos(normalized.y).toFloat() * 57.295776F)) val vertexConsumer = vertexConsumers.getBuffer(GapRenderLayers.getGrapplingHookLayer(CHAIN_TEXTURE)) val entry = matrices.peek() vertexConsumer.vertex(entry, 0.093f, 0.0f, 0f, entityLight, 0.0f, 0f) vertexConsumer.vertex(entry, 0.093f, length, 0f, entityLight, 0.0f, length) vertexConsumer.vertex(entry, -0.093f, length, 0f, entityLight, 0.187f, length) vertexConsumer.vertex(entry, -0.093f, 0.0f, 0f, entityLight, 0.187f, 0f) vertexConsumer.vertex(entry, 0.0f, 0.0f, -0.093f, entityLight, 0.187f, 0f) vertexConsumer.vertex(entry, 0.0f, length, -0.093f, entityLight, 0.187f, length) vertexConsumer.vertex(entry, 0f, length, 0.093f, entityLight, 0.375f, length) vertexConsumer.vertex(entry, 0f, 0.0f, 0.093f, entityLight, 0.375f, 0f) matrices.pop() } } fun fromLerpedPosition(entity: Entity, yOffset: Double, delta: Double): Vec3d { return Vec3d( lerp(delta, entity.lastRenderX, entity.x), lerp(delta, entity.lastRenderY, entity.y) + yOffset, lerp(delta, entity.lastRenderZ, entity.z) ) } private fun VertexConsumer.vertex( entry: MatrixStack.Entry, x: Float, y: Float, z: Float, light: Int, u: Float, v: Float ) { this.method_56824(entry, x, y, z) .method_1336(255, 255, 255, 255) .method_22913(u, v) .method_22922(OverlayTexture.DEFAULT_UV) .method_60803(light) .method_60831(entry, 1.0f, 1.0f, 1.0f) } override fun getTexture(entity: GrapplingHookHeadEntity): Identifier? = null override fun shouldRender(e: GrapplingHookHeadEntity, f: Frustum, x: Double, y: Double, z: Double): Boolean = true companion object { val CHAIN_TEXTURE: Identifier = Identifier.ofDefault("textures/block/chain.png") fun map(value: Float): Int = (value * 0xffffff / 1.0).toInt() } }
0
Kotlin
0
0
e271f7c991c03411a27b0557d4056b200232112f
4,886
Grappled
MIT License
medalseats-core/adapters/http/common/src/main/kotlin/com/medalseats/adapter/http/common/response/MonetaryAmountResponse.kt
MedalSeats
783,322,804
false
{"Kotlin": 61788, "Shell": 303}
package com.medalseats.adapter.http.common.response import kotlinx.serialization.Serializable @Serializable data class MonetaryAmountResponse( val value: Double, val currency: String )
3
Kotlin
0
1
259353c1d6f7edf0dd1d34c81d87988aba3a0511
195
medalseats-backend
MIT License
devp2p-eth/src/integrationTest/kotlin/org/apache/tuweni/devp2p/eth/ConnectToAnotherNodeTest.kt
apache
178,461,625
false
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.tuweni.devp2p.eth import io.vertx.core.Vertx import kotlinx.coroutines.runBlocking import org.apache.lucene.index.IndexWriter import org.apache.tuweni.concurrent.AsyncCompletion import org.apache.tuweni.concurrent.coroutines.await import org.apache.tuweni.crypto.SECP256K1 import org.apache.tuweni.eth.genesis.GenesisFile import org.apache.tuweni.eth.repository.BlockchainIndex import org.apache.tuweni.eth.repository.BlockchainRepository import org.apache.tuweni.eth.repository.MemoryTransactionPool import org.apache.tuweni.junit.BouncyCastleExtension import org.apache.tuweni.junit.LuceneIndexWriter import org.apache.tuweni.junit.LuceneIndexWriterExtension import org.apache.tuweni.junit.VertxExtension import org.apache.tuweni.junit.VertxInstance import org.apache.tuweni.kv.MapKeyValueStore import org.apache.tuweni.rlpx.vertx.VertxRLPxService import org.apache.tuweni.units.bigints.UInt256 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import java.net.InetSocketAddress @ExtendWith(LuceneIndexWriterExtension::class, VertxExtension::class, BouncyCastleExtension::class) class ConnectToAnotherNodeTest { /** * To run this test, run an Ethereum mainnet node at home and point this test to it. * */ @Disabled @Test fun testCollectHeaders(@LuceneIndexWriter writer: IndexWriter, @VertxInstance vertx: Vertx) = runBlocking { val contents = ConnectToAnotherNodeTest::class.java.getResourceAsStream("/mainnet.json").readAllBytes() val genesisFile = GenesisFile.read(contents) val genesisBlock = genesisFile.toBlock() val repository = BlockchainRepository.init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), genesisBlock ) val service = VertxRLPxService( vertx, 30304, "127.0.0.1", 30304, SECP256K1.KeyPair.random(), listOf( EthSubprotocol( repository = repository, blockchainInfo = SimpleBlockchainInformation( UInt256.valueOf(genesisFile.chainId.toLong()), genesisBlock.header.difficulty, genesisBlock.header.hash, UInt256.valueOf(42L), genesisBlock.header.hash, genesisFile.forks ), pendingTransactionsPool = MemoryTransactionPool() ) ), "Tuweni Experiment 0.1" ) service.start().await() service.connectTo( SECP256K1.PublicKey.fromHexString( "<KEY>" + "<KEY>" ), InetSocketAddress("192.168.88.46", 30303) ).await() // val client = service.getClient(EthSubprotocol.ETH62) as EthRequestsManager // client.requestBlockHeaders(genesisBlock.header.hash, 100, 0, false).await() // // val header = repository.findBlockByHashOrNumber(UInt256.valueOf(99L).toBytes()) // Assertions.assertFalse(header.isEmpty()) // // val header3 = repository.findBlockByHashOrNumber(UInt256.valueOf(101L).toBytes()) // Assertions.assertTrue(header3.isEmpty()) // val header2 = repository.findBlockByHashOrNumber(UInt256.valueOf(100L).toBytes()) // Assertions.assertTrue(header2.isEmpty()) Thread.sleep(100000) service.stop().await() } @Disabled("flaky") @Test fun twoServers(@LuceneIndexWriter writer: IndexWriter, @VertxInstance vertx: Vertx) = runBlocking { val contents = EthHandlerTest::class.java.getResourceAsStream("/mainnet.json").readAllBytes() val genesisBlock = GenesisFile.read(contents).toBlock() val repository = BlockchainRepository.init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), genesisBlock ) val service = VertxRLPxService( vertx, 0, "127.0.0.1", 0, SECP256K1.KeyPair.random(), listOf( EthSubprotocol( repository = repository, blockchainInfo = SimpleBlockchainInformation( UInt256.ZERO, genesisBlock.header.difficulty, genesisBlock.header.hash, UInt256.valueOf(42L), genesisBlock.header.hash, emptyList() ), pendingTransactionsPool = MemoryTransactionPool() ) ), "Tuweni Experiment 0.1" ) val repository2 = BlockchainRepository.init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), genesisBlock ) val service2kp = SECP256K1.KeyPair.random() val service2 = VertxRLPxService( vertx, 0, "127.0.0.1", 0, service2kp, listOf( EthSubprotocol( repository = repository2, blockchainInfo = SimpleBlockchainInformation( UInt256.ZERO, genesisBlock.header.difficulty, genesisBlock.header.hash, UInt256.valueOf(42L), genesisBlock.header.hash, emptyList() ), pendingTransactionsPool = MemoryTransactionPool() ) ), "Tuweni Experiment 0.1" ) val result = AsyncCompletion.allOf(service.start(), service2.start()).then { service.connectTo(service2kp.publicKey(), InetSocketAddress("127.0.0.1", service2.actualPort())) } result.await() Assertions.assertNotNull(result.get()) AsyncCompletion.allOf(service.stop(), service2.stop()).await() } }
6
null
78
171
0852e0b01ad126b47edae51b26e808cb73e294b1
6,467
incubator-tuweni
Apache License 2.0
app/src/main/java/br/com/movieapp/movie_popular_feature/di/MoviePopularFeatureModule.kt
NicholasOliveira
772,579,579
false
{"Kotlin": 116427}
package br.com.movieapp.movie_popular_feature.di import br.com.movieapp.core.data.remote.MovieService import br.com.movieapp.movie_popular_feature.data.repository.MoviePopularRepositoryImpl import br.com.movieapp.movie_popular_feature.data.source.MoviePopularRemoteDataSourceImpl import br.com.movieapp.movie_popular_feature.domain.repository.MoviePopularRepository import br.com.movieapp.movie_popular_feature.domain.source.MoviePopularRemoteDataSource import br.com.movieapp.movie_popular_feature.domain.usecase.GetPopularMoviesUseCase import br.com.movieapp.movie_popular_feature.domain.usecase.GetPopularMoviesUseCaseImpl import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object MoviePopularFeatureModule { @Provides @Singleton fun provideMoviesPopularDataSource(service: MovieService): MoviePopularRemoteDataSource { return MoviePopularRemoteDataSourceImpl(movieService = service) } @Provides @Singleton fun provideMoviesPopularRepository(remoteDataSource: MoviePopularRemoteDataSource): MoviePopularRepository { return MoviePopularRepositoryImpl(remoteDataSource = remoteDataSource) } @Provides @Singleton fun provideGetMoviesPopularUseCase(moviePopularRepository: MoviePopularRepository) : GetPopularMoviesUseCase { return GetPopularMoviesUseCaseImpl(repository = moviePopularRepository) } }
0
Kotlin
0
1
81dc803726b64d732e4b504315cd27fdc25ccc63
1,526
movie-app
MIT License
src/main/kotlin/org/kowboy/command/CompositeCommandExecutor.kt
cpmcdaniel
109,547,667
false
null
package org.kowboy.command import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.command.TabCompleter import org.kowboy.util.ChatUtils.sendError import org.kowboy.util.ChatUtils.sendHelp import org.kowboy.util.TabCompletionUtils.partialMatch import java.util.* import java.util.stream.Collectors /** * An abstract command executor that provides the basis for a heirarchy/tree of subcommands. * * Example: * * /spit light-level apothem 8 * * In the above example, the command executor for "spit" would be a composite which may contain * additional subcommands beyond "light-level". The command executor for "light-level" may in turn be a composite * with subcommands "on", "off", and "apothem". * * Composite commands also provide a default "help" subcommand in order to provide usage summary, since capturing * an entire tree of subcommands in the usage text of the top-level command could scroll off the screen entirely. Such * top-level composite commands should only document their first level of subcommands in their usage text. * * Note: only the top-level composite executor should be registered with the plugin. * * Whenever [CommandExecutor.onCommand] is called and the first argument is equal to one of the subcommand names, * that subcommand's `onCommand` method is called with the args array shifted by one. Thus, subcommand * executors can safely assume they are called with only the args that come after the subcommand name in the original * args array. * * @author Craig McDaniel * @since 1.0 */ abstract class CompositeCommandExecutor protected constructor(private val commandName: String, private val description: String) : CommandExecutor, TabCompleter { private val subCommands: MutableMap<String, CommandExecutor> = LinkedHashMap() private val subCompleters: MutableMap<String, TabCompleter> = LinkedHashMap() /** * @param commandName Name for this subcommand. * @param ce Executor for this subcommand. * @param tc Tab completer for this subcommand. */ protected fun addSubCommand(commandName: String, ce: CommandExecutor, tc: TabCompleter? = null) { subCommands[commandName.toLowerCase()] = ce if (tc != null) subCompleters[commandName.toLowerCase()] = tc } /** * Adds a composite subcommand, thus creating a command tree. * * @param commandName Name for this subcommand. * @param cce Both the command executor and tab completer for this subcommand. */ protected fun addSubCommand(commandName: String, cce: CompositeCommandExecutor) { addSubCommand(commandName, cce, cce) } override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { // Composite commands must have at least one argument - the subcommand name. if (args.isEmpty()) { sendError(sender, "Missing sub-command") help(sender, false) return true } // Get the subcommand executor val subCommand = subCommands[args[0]] if (subCommand == null) { if (!"help".equals(args[0], ignoreCase = true)) { sendError(sender, "Unrecognized sub-command: " + args[0]) help(sender, false) } else { help(sender, true) } return true } // Delegate command processing to the subcommand executor. // Shifts args by 1. return subCommand.onCommand(sender, command, label, args.copyOfRange(1, args.size)) } private fun help(sender: CommandSender?, withDescription: Boolean) { if (withDescription) { sendHelp(sender!!, "Description: $description") } // This prints all subcommand names on the same line. It may be preferable to split them one-per line // at some point. sendHelp(sender!!, "Usage: " + commandName + " <" + subCommands.keys.stream().collect(Collectors.joining(", ")) + ">") } override fun onTabComplete(sender: CommandSender, command: Command, alias: String, args: Array<String>): List<String>? { if (args.isNotEmpty()) { val sub = subCompleters[args[0].toLowerCase()] return if (sub != null) { // Delegate tab completion to the subcommand tab completer. // Shifts args by 1. sub.onTabComplete(sender, command, alias, args.copyOfRange(1, args.size)) } else { subCommands.keys.stream() .filter(partialMatch(args)) .collect(Collectors.toList()) } } return emptyList() } }
1
null
1
4
571aab50aa3af9e21f37f4ff2d3340a73241f7d1
4,805
spittoon
Apache License 2.0
common/presentation/src/main/java/currencyconverter/common/presentation/ui/custom/FontCache.kt
ShabanKamell
235,781,240
false
null
package tracker.common.presentation.custom import android.annotation.SuppressLint import android.content.Context import android.graphics.Typeface import android.util.Log import androidx.core.content.res.ResourcesCompat import tracker.common.presentation.R import java.util.* object FontCache { @SuppressLint("UseSparseArrays") private val fontCache = HashMap<Int, Typeface>() interface Font { companion object { val DEFAULT = R.font.droid_sans_arabic } } fun defaultTypeface(context: Context): Typeface? { return typeface(Font.DEFAULT, context) } private fun typeface(fontRes: Int, context: Context): Typeface? { var typeface = fontCache[fontRes] if (typeface == null) { try { typeface = ResourcesCompat.getFont(context, R.font.droid_sans_arabic) } catch (e: Exception) { Log.e("font", "not applied") return null } fontCache[fontRes] = typeface!! } return typeface } }
1
null
3
9
40cd5f4eae27217f7f36ed24f24e9d9bb94b4bfa
1,074
CurrencyConverter
Apache License 2.0
jetpack-bindings-sample/src/main/kotlin/com/github/vmironov/jetpack/sample/SampleFragment.kt
nsk-mironov
43,271,057
false
null
package com.github.vmironov.jetpack.sample import android.app.Fragment import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.util.TypedValue import android.view.* import com.github.vmironov.jetpack.preferences.bindOptionalPreference import com.github.vmironov.jetpack.resources.bindResource import kotlinx.android.synthetic.main.fragment_sample.* class SampleFragment : Fragment() { private var firstNameValue by bindOptionalPreference<String>() private var lastNameValue by bindOptionalPreference<String>() private val firstNameLabel by bindResource<String>(R.string.first_name_label) private val firstNameHint by bindResource<String>(R.string.first_name_hint) private val lastNameLabel by bindResource<String>(R.string.last_name_label) private val lastNameHint by bindResource<String>(R.string.last_name_hint) private val paddingTiny by bindResource<Int>(R.dimen.padding_tiny) private val paddingSmall by bindResource<Int>(R.dimen.padding_small) private val paddingLarge by bindResource<Int>(R.dimen.padding_large) private val colorPrimary by bindResource<Int>(R.color.primary) private val colorBackground by bindResource<Int>(R.color.color_background) private val colorText by bindResource<Int>(R.color.color_text) private val colorHint by bindResource<Int>(R.color.color_hint) private val fontSmall by bindResource<Float>(R.dimen.font_small) private val fontNormal by bindResource<Float>(R.dimen.font_normal) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_sample, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.background = ColorDrawable(colorBackground) view.setPadding(paddingLarge, paddingLarge, paddingLarge, paddingLarge) first_name_label.text = firstNameLabel first_name_label.setPadding(paddingSmall, paddingTiny, paddingSmall, paddingTiny) first_name_label.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSmall) first_name_label.setTextColor(colorPrimary) last_name_label.text = lastNameLabel last_name_label.setPadding(paddingSmall, paddingTiny, paddingSmall, paddingTiny) last_name_label.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSmall) last_name_label.setTextColor(colorPrimary) first_name_input.hint = firstNameHint first_name_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontNormal) first_name_input.setHintTextColor(colorHint) first_name_input.setText(firstNameValue.orEmpty()) first_name_input.setTextColor(colorText) last_name_input.hint = lastNameHint last_name_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontNormal) last_name_input.setTextColor(colorText) last_name_input.setText(lastNameValue.orEmpty()) last_name_input.setHintTextColor(colorHint) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.menu_sample, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_done -> { firstNameValue = first_name_input.text?.toString() lastNameValue = last_name_input.text?.toString() } } return super.onOptionsItemSelected(item) } }
1
Kotlin
9
187
cad048de889991ffe90a8f11610823124812beb2
3,546
kotlin-jetpack
Apache License 2.0
src/main/java/com/github/udioshi85/tooly/extentions/PackageManager.kt
UdiOshi85
184,197,361
false
null
package com.github.udioshi85.tooly.extentions import android.content.Context import android.content.pm.PackageManager import java.util.concurrent.TimeUnit fun PackageManager.installTimeInDays(context: Context): Long = TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - getPackageInfo(context.packageName, 0).firstInstallTime)
1
Kotlin
1
6
23f96994a07f62a97873f25c88ea1555f8e4e0e6
335
Tooly
Apache License 2.0
app/src/main/java/com/mystic/koffee/petreport/features/reportsScreen/adapter/ReportsScreenViewHolder.kt
jaumpelicon
559,013,090
false
{"Kotlin": 71610}
package com.mystic.koffee.petreport.features.reportsScreen.adapter import android.content.Context import android.content.res.ColorStateList import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.mystic.koffee.petreport.R import com.mystic.koffee.petreport.databinding.ReportItemCardBinding import com.mystic.koffee.petreport.features.reportsScreen.models.ReportsModel class ReportsScreenViewHolder( private val binding: ReportItemCardBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind( report: ReportsModel, itemClickCallback: (report: ReportsModel) -> Unit, context: Context ) { with(binding) { titleReportCardTextView.text = report.title binding.seeDetailImageView.setOnClickListener { itemClickCallback(report) } val colorSelectedInt: Int = context.getColor(R.color.itemSelected) val cslSelected = ColorStateList.valueOf(colorSelectedInt) val colorBackgroundInt: Int = context.getColor(R.color.primaryBackGroundColor) val cslBackground = ColorStateList.valueOf(colorBackgroundInt) if (report.selected) { itemReportCardView.backgroundTintList = cslSelected } else { itemReportCardView.backgroundTintList = cslBackground } } } companion object { fun inflate(parent: ViewGroup) = ReportsScreenViewHolder( ReportItemCardBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } }
0
Kotlin
0
0
ee888f2cf57e83c855420458db7081e23e9a6f51
1,698
pet-report
MIT License
src/main/kotlin/no/nav/syfo/sykmelding/kafka/SykmeldingStatusKafkaProducer.kt
navikt
464,849,616
false
{"Kotlin": 301480, "TypeScript": 89496, "CSS": 3260, "HTML": 352, "JavaScript": 347, "Dockerfile": 278}
package no.nav.syfo.sykmelding.kafka import java.time.OffsetDateTime import java.time.ZoneOffset import no.nav.syfo.kafka.aiven.KafkaUtils import no.nav.syfo.kafka.toProducerConfig import no.nav.syfo.model.sykmeldingstatus.KafkaMetadataDTO import no.nav.syfo.model.sykmeldingstatus.SykmeldingStatusKafkaEventDTO import no.nav.syfo.model.sykmeldingstatus.SykmeldingStatusKafkaMessageDTO import no.nav.syfo.utils.JacksonKafkaSerializer import no.nav.syfo.utils.logger import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.clients.producer.ProducerRecord import org.apache.kafka.common.serialization.StringSerializer interface SykmeldingStatusKafkaProducer { fun send(sykmeldingStatusKafkaEventDTO: SykmeldingStatusKafkaEventDTO, fnr: String) } class SykmeldingStatusKafkaProducerProduction( private val statusTopic: String, ) : SykmeldingStatusKafkaProducer { private val kafkaProducer = KafkaProducer<String, SykmeldingStatusKafkaMessageDTO>( KafkaUtils.getAivenKafkaConfig("sykmelding-status-producer") .toProducerConfig( groupId = "mock-sykmelding-status-producer", valueSerializer = JacksonKafkaSerializer::class, keySerializer = StringSerializer::class, ), ) override fun send(sykmeldingStatusKafkaEventDTO: SykmeldingStatusKafkaEventDTO, fnr: String) { logger.info( "Skriver slettet-status for sykmelding med id ${sykmeldingStatusKafkaEventDTO.sykmeldingId}" ) val metadataDTO = KafkaMetadataDTO( sykmeldingId = sykmeldingStatusKafkaEventDTO.sykmeldingId, timestamp = OffsetDateTime.now( ZoneOffset.UTC, ), fnr = fnr, source = "teamsykmelding-mock-backend", ) val sykmeldingStatusKafkaMessageDTO = SykmeldingStatusKafkaMessageDTO(metadataDTO, sykmeldingStatusKafkaEventDTO) try { kafkaProducer .send( ProducerRecord( statusTopic, sykmeldingStatusKafkaMessageDTO.event.sykmeldingId, sykmeldingStatusKafkaMessageDTO ) ) .get() } catch (ex: Exception) { logger.error("Kunne ikke sende slettet-melding til topic", ex) throw ex } } } class SykmeldingStatusKafkaProducerDevelopment : SykmeldingStatusKafkaProducer { override fun send(sykmeldingStatusKafkaEventDTO: SykmeldingStatusKafkaEventDTO, fnr: String) { logger.info( "Later som vi skriver statusendring for sykmelding med id {} til topic", sykmeldingStatusKafkaEventDTO.sykmeldingId, ) } }
2
Kotlin
1
1
cd6e423e2e2fded4644a21e50d7a2f7d433b890f
2,893
teamsykmelding-mock
MIT License
kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/sdk/httpclient/Ok3ResponseTest.kt
spinnaker
19,836,152
false
null
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.kork.plugins.sdk.httpclient import com.fasterxml.jackson.databind.ObjectMapper import dev.minutest.junit.JUnit5Minutests import dev.minutest.rootContext import io.mockk.mockk import java.io.IOException import okhttp3.MediaType import okhttp3.Protocol import okhttp3.Response import okhttp3.ResponseBody import strikt.api.expectThat import strikt.assertions.isFalse import strikt.assertions.isTrue internal class Ok3ResponseTest : JUnit5Minutests { fun tests() = rootContext<Fixture> { fixture { Fixture() } test("should flag the response as success") { expectThat(status200Subject.isError).isFalse() } test("should flag the response as error if exception received") { expectThat(exceptionSubject.isError).isTrue() } test("should flag the response as error if response received with status > 4xx or 5xx") { expectThat(status404Subject.isError).isTrue() expectThat(status500Subject.isError).isTrue() } } private inner class Fixture { val objectMapper: ObjectMapper = mockk(relaxed = true) val response404: Response = buildResponse(404) val response500: Response = buildResponse(500) val response200: Response = buildResponse(200) val exceptionSubject = Ok3Response(objectMapper, null, IOException("error")) val status404Subject = Ok3Response(objectMapper, response404, null) val status500Subject = Ok3Response(objectMapper, response500, null) val status200Subject = Ok3Response(objectMapper, response200, null) } private fun buildResponse(code: Int): Response { return Response.Builder().code(code) .request(mockk(relaxed = true)) .message("OK") .protocol(Protocol.HTTP_1_1) .header("Content-Type", "plain/text") .body(ResponseBody.create(MediaType.parse("plain/text"), "test")) .build() } }
16
null
174
41
e98e84c7f4162fa9570b4c99a6f8cdd48e115d01
2,470
kork
Apache License 2.0
bellatrix.core/src/main/java/solutions/bellatrix/core/plugins/Plugin.kt
AutomateThePlanet
334,964,015
false
null
/* * Copyright 2021 Automate The Planet Ltd. * Author: Anton Angelov * 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 solutions.bellatrix.core.plugins import java.lang.reflect.Method open class Plugin { init { PluginExecutionEngine.addPlugin(this) } open fun preBeforeClass(type: Class<*>) {} open fun postBeforeClass(type: Class<*>) {} open fun beforeClassFailed(e: Exception) {} open fun preBeforeTest(testResult: TestResult, memberInfo: Method) {} open fun postBeforeTest(testResult: TestResult, memberInfo: Method) {} open fun beforeTestFailed(e: Exception?) {} open fun preAfterTest(testResult: TestResult, memberInfo: Method) {} open fun postAfterTest(testResult: TestResult, memberInfo: Method) {} open fun afterTestFailed(e: Exception) {} open fun preAfterClass(type: Class<*>) {} open fun postAfterClass(type: Class<*>) {} open fun afterClassFailed(e: Exception) {} }
1
Kotlin
1
1
5da5e705b47e12c66937d130b3031ac8703b8279
1,450
BELLATRIX-Kotlin
Apache License 2.0
formula-android/src/main/java/com/instacart/formula/android/internal/FormulaFragmentDelegate.kt
instacart
171,923,573
false
{"Kotlin": 565903, "Shell": 1203, "Ruby": 256}
package com.instacart.formula.android.internal import com.instacart.formula.FormulaAndroid import com.instacart.formula.FormulaAndroid.fragmentEnvironment import com.instacart.formula.android.FormulaFragment import com.instacart.formula.android.ViewFactory internal object FormulaFragmentDelegate { fun viewFactory(fragment: FormulaFragment): ViewFactory<Any>? { val appManager = FormulaAndroid.appManagerOrThrow() val activity = fragment.requireActivity() val viewFactory = appManager.findStore(activity)?.viewFactory(fragment) ?: run { // Log view factory is missing if (activity.isDestroyed) { fragmentEnvironment().logger("Missing view factory because activity is destroyed: ${fragment.getFragmentKey()}") } else { val error = IllegalStateException("Formula with ${fragment.getFragmentKey()} is missing view factory.") fragmentEnvironment().onScreenError(fragment.getFragmentKey(), error) } return null } return viewFactory } }
8
Kotlin
14
151
26d544ea41b7a5ab2fa1a3b9ac6b668e69fe4dff
1,090
formula
BSD 3-Clause Clear License
src/main/kotlin/com/idonate/springboot/kotlin/demo/DonationNotFoundException.kt
kellyt1
167,108,150
false
null
package com.idonate.springboot.kotlin.demo import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ResponseStatus @ResponseStatus(HttpStatus.NOT_FOUND) class DonationNotFoundException : RuntimeException()
0
Kotlin
0
0
c66ea419a0cf8141cb9c4d44f4fa610e84ea30f3
240
idonate
Apache License 2.0
livedata/src/androidMain/kotlin/com/bselzer/library/kotlin/extension/livedata/immutable/nullsafe/SafeCharLiveData.kt
Woody230
388,189,330
false
null
package com.bselzer.library.kotlin.extension.livedata.immutable.nullsafe /** * Null-safe live data for booleans. * @param defaultValue the initial value to store. It is also the value to set upon resetting the instance. */ open class SafeBoolLiveData(defaultValue: Boolean = false) : SafeImmutableLiveData<Boolean>(defaultValue)
1
Kotlin
0
0
707e2e20c0765ab40b5951acedbb28783c4af312
332
KotlinExtensions
Apache License 2.0
app/src/main/java/com/persadaditya/app/ui/launch/movie/MovieNavigator.kt
persadaditya
520,727,128
false
null
package com.persadaditya.app.ui.launch.movie import android.app.Activity import android.content.Context interface MovieNavigator { fun activity(): Activity fun context(): Context }
0
Kotlin
0
0
7c808a83b1f39db0bced28f51fb7dd319a453d14
193
movie-omdb-app
Apache License 2.0
trixnity-crypto-core/src/jsMain/kotlin/net/folivo/trixnity/crypto/core/hmacSha256.kt
benkuly
330,904,570
false
null
package net.folivo.trixnity.crypto.core import createHmac import io.ktor.util.* import js.objects.jso import js.promise.await import js.typedarrays.Uint8Array import js.typedarrays.toUint8Array import web.crypto.HmacImportParams import web.crypto.KeyFormat import web.crypto.KeyUsage import web.crypto.crypto import kotlin.js.json actual suspend fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray { return if (PlatformUtils.IS_BROWSER) { val crypto = crypto.subtle val hmacKey = crypto.importKey( format = KeyFormat.raw, keyData = key.toUint8Array(), algorithm = jso<HmacImportParams> { name = "HMAC" hash = json("name" to "SHA-256") }, extractable = false, keyUsages = arrayOf(KeyUsage.sign) ).await() Uint8Array( crypto.sign( algorithm = "HMAC", key = hmacKey, data = data.toUint8Array() ).await() ).toByteArray() } else { val hmac = createHmac(algorithm = "sha256", key = key.toUint8Array()) hmac.update(data.toUint8Array()) Uint8Array(hmac.digest()).toByteArray() } }
0
null
3
30
69cc6ff505b218c1c7d8110fb23e95ca1da4c54b
1,233
trixnity
Apache License 2.0
app/src/main/java/com/example/deamhome/presentation/main/ScreenType.kt
S-OSTeam
686,905,420
false
{"Kotlin": 67631}
package com.example.deamhome.presentation.main import androidx.annotation.IdRes import com.example.deamhome.R sealed class ScreenType(val tag: String, val isChangeBottomTab: Boolean) { sealed class ChangeScreenType(tag: String) : ScreenType(tag, true) { data object Home : ChangeScreenType("HOME") data object MyPage : ChangeScreenType("MY_PAGE") } sealed class PopScreenType(tag: String) : ScreenType(tag, false) { data object Search : PopScreenType("SEARCH") data object Category : PopScreenType("CATEGORY") data object Cart : PopScreenType("CART") } companion object { fun of(@IdRes id: Int): ScreenType { return when (id) { R.id.menu_item_home -> ChangeScreenType.Home R.id.menu_item_my_page -> ChangeScreenType.MyPage R.id.menu_item_search -> PopScreenType.Search R.id.menu_item_category -> PopScreenType.Category R.id.menu_item_cart -> PopScreenType.Cart else -> ChangeScreenType.Home } } } }
0
Kotlin
0
0
753cf19f1ad7e492876b3ed31c96150bd17050e5
1,103
shop-app
MIT License
src/main/java/com/vortexa/refinery/dsl/MetadataEntryDefinition.kt
VorTECHsa
423,415,893
false
{"Kotlin": 171148}
package com.vortexa.refinery.dsl import org.apache.poi.ss.usermodel.Cell /** * Defines where to look for key value data and how to parse it * * @property metadataName name that will be available in metadata * @property matchingCellKey pattern for matching the key cell * @property valueLocation where to look for the data * @property extractor how to parse the data */ data class MetadataEntryDefinition( val metadataName: String, val matchingCellKey: String, val valueLocation: MetadataValueLocation, val extractor: (Cell) -> Any )
3
Kotlin
5
40
d5a95c52ffff9a1be350ef62de6746c8648e56aa
558
refinery
MIT License
src/commonTest/kotlin/kif/instance/InstanceInvokeTest.kt
atomgomba
471,788,383
false
null
package kif.instance import kif.InvokeTest import kif.KifApi import kif.kif class InstanceInvokeTest : InvokeTest() { override lateinit var subject: KifApi override fun initSubject() { subject = kif.new() } }
0
Kotlin
0
7
c1bc950368036916561e45c546ba2140102ca66d
232
kif
Apache License 2.0
src/main/kotlin/Model.kt
h0tk3y
211,847,508
false
null
import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.databind.annotation.JsonNaming import dao.GroupChatId import dao.MessageId import dao.PersonalChatId import dao.UserId import io.ktor.auth.Principal import java.util.* data class User( val id: UserId, val name: String, val email: String, val phoneNumber: String, val login: String, val password: String ) : Principal //@JsonNaming(PropertyNamingStrategy.LowerCaseStrategy::class) data class Message( val id: MessageId, val from: UserId, @JsonProperty("personal") val isPersonal: Boolean, val chat: Long, val text: String, val datetime: Date, @JsonProperty("deleted") val isDeleted: Boolean, @JsonProperty("edited") val isEdited: Boolean ) data class PersonalChat( val id: PersonalChatId, val member1: UserId, val member2: UserId ) data class GroupChat( val id: GroupChatId, val owner: UserId, val chatName: String, val uniqueLink: String? ) data class Contact( val id: Long, val userId: UserId, val contactId: UserId, val name: String )
0
Kotlin
0
1
e9fdfeffc01e8a0f47f1ea056c91b970c3bfee99
1,196
kotlin-spbsu-2019-project-north
Apache License 2.0
src/main/kotlin/it/valeriovaudi/vauthenticator/security/registeredclient/ClientAppRegisteredClientRepository.kt
mrFlick72
191,632,792
false
null
package it.valeriovaudi.vauthenticator.security.registeredclient import it.valeriovaudi.vauthenticator.oauth2.clientapp.ClientAppId import it.valeriovaudi.vauthenticator.oauth2.clientapp.ClientApplicationRepository import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.security.oauth2.core.AuthorizationGrantType import org.springframework.security.oauth2.core.ClientAuthenticationMethod import org.springframework.security.oauth2.server.authorization.client.RegisteredClient import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository import org.springframework.security.oauth2.server.authorization.config.TokenSettings import java.time.Duration class ClientAppRegisteredClientRepository(private val clientApplicationRepository: ClientApplicationRepository) : RegisteredClientRepository { val logger: Logger = LoggerFactory.getLogger(ClientAppRegisteredClientRepository::class.java) override fun save(registeredClient: RegisteredClient) { throw UnsupportedActionException("store client application from ClientAppRegisteredClientRepository is not currently allowed"); } override fun findById(id: String): RegisteredClient = registeredClient(id) override fun findByClientId(clientId: String): RegisteredClient = registeredClient(clientId) private fun registeredClient(id: String) = clientApplicationRepository.findOne(ClientAppId(id)) .map { clientApp -> RegisteredClient.withId(id) .clientId(id) .clientSecret(clientApp.secret.content) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST) .authorizationGrantTypes { authorizationGrantTypes -> authorizationGrantTypes.addAll(clientApp.authorizedGrantTypes.content.map { AuthorizationGrantType( it.name.toLowerCase() ) }) } .scopes { scopes -> scopes.addAll(clientApp.scopes.content.map { it.content }) } .redirectUri(clientApp.webServerRedirectUri.content) .tokenSettings(TokenSettings.builder() .accessTokenTimeToLive(Duration.ofSeconds(clientApp.accessTokenValidity.content.toLong())) .refreshTokenTimeToLive(Duration.ofSeconds(clientApp.refreshTokenValidity.content.toLong())) .reuseRefreshTokens(true) .build()) .build() }.orElseThrow { logger.error("Application with id or client_id: $id not found") RegisteredClientAppNotFound("Application with id or client_id: $id not found") } }
0
Kotlin
1
5
4b5652abac4d47bb6e3c5256242d5dfa1f27b59c
3,086
vauthenticator
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/TextFontSize.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.TextFontSize: ImageVector get() { if (_textFontSize != null) { return _textFontSize!! } _textFontSize = fluentIcon(name = "Regular.TextFontSize") { fluentPath { moveTo(10.21f, 17.11f) lineTo(15.04f, 3.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.37f, -0.11f) lineToRelative(0.05f, 0.1f) lineTo(21.96f, 19.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.38f, 0.6f) lineToRelative(-0.04f, -0.1f) lineToRelative(-1.6f, -4.5f) horizontalLineToRelative(-6.39f) lineToRelative(-1.58f, 4.45f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.35f, 0.45f) lineToRelative(-0.1f, 0.05f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.92f, -0.33f) lineToRelative(-0.05f, -0.1f) lineToRelative(-1.0f, -2.52f) horizontalLineToRelative(-4.1f) lineToRelative(-1.0f, 2.52f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.88f, 0.45f) lineToRelative(-0.1f, -0.03f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.45f, -0.87f) lineToRelative(0.03f, -0.1f) lineToRelative(3.76f, -9.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.34f, -0.1f) lineToRelative(0.05f, 0.1f) lineToRelative(3.01f, 7.64f) lineTo(15.04f, 3.5f) lineTo(10.21f, 17.1f) close() moveTo(6.51f, 11.79f) lineTo(5.03f, 15.5f) horizontalLineToRelative(2.92f) lineTo(6.5f, 11.8f) close() moveTo(15.74f, 6.0f) lineToRelative(-2.67f, 7.51f) horizontalLineToRelative(5.33f) lineTo(15.75f, 6.0f) close() } } return _textFontSize!! } private var _textFontSize: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,390
compose-fluent-ui
Apache License 2.0
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/ui/coursework/yourSubmission/YourSubmissionComponent.kt
denchic45
435,895,363
false
{"Kotlin": 2033820, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.ui.coursework.yourSubmission import com.arkivanov.decompose.ComponentContext import com.arkivanov.decompose.childContext import com.denchic45.studiversity.api.course.element.model.AttachmentRequest import com.denchic45.studiversity.api.course.element.model.CreateFileRequest import com.denchic45.studiversity.api.submission.model.SubmissionResponse import com.denchic45.studiversity.domain.resource.* import com.denchic45.studiversity.domain.usecase.* import com.denchic45.studiversity.ui.attachments.AttachmentsComponent import com.denchic45.studiversity.ui.coursework.SubmissionUiState import com.denchic45.studiversity.ui.coursework.toUiState import com.denchic45.studiversity.ui.model.AttachmentItem import com.denchic45.studiversity.util.componentScope import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import me.tatarka.inject.annotations.Assisted import me.tatarka.inject.annotations.Inject import okio.Path import java.util.* @Inject class YourSubmissionComponent( checkUserCapabilitiesInScopeUseCase: CheckUserCapabilitiesInScopeUseCase, private val addAttachmentToSubmissionUseCase: AddAttachmentToSubmissionUseCase, private val removeAttachmentFromSubmissionUseCase: RemoveAttachmentFromSubmissionUseCase, observeYourSubmissionUseCase: ObserveYourSubmissionUseCase, private val findSubmissionAttachmentsUseCase: FindSubmissionAttachmentsUseCase, private val submitSubmissionUseCase: SubmitSubmissionUseCase, private val cancelSubmissionUseCase: CancelSubmissionUseCase, attachmentsComponent: ( attachments: Flow<Resource<List<AttachmentItem>>>, onAddAttachment: ((AttachmentRequest) -> Unit)?, onRemoveAttachment: ((UUID) -> Unit)?, ComponentContext ) -> AttachmentsComponent, @Assisted private val courseId: UUID, @Assisted private val workId: UUID, @Assisted private val componentContext: ComponentContext, ) : ComponentContext by componentContext { private val componentScope = componentScope() private val _observeYourSubmission = observeYourSubmissionUseCase(courseId, workId) .shareIn(componentScope, SharingStarted.Lazily) private val _updatedYourSubmission = MutableSharedFlow<Resource<SubmissionResponse>>() val attachmentsComponentResource = _observeYourSubmission .filterNotNullValue() .mapResource { submission -> attachmentsComponent( findSubmissionAttachmentsUseCase(submission.id), { componentScope.launch { addAttachmentToSubmissionUseCase(submission.id, it) } }, { componentScope.launch { removeAttachmentFromSubmissionUseCase( submission.id, it ) } }, componentContext.childContext("Attachments") ) }.stateInResource(componentScope) val submission = MutableStateFlow<Resource<SubmissionUiState>>(Resource.Loading) // val sheetExpanded = MutableStateFlow(false) // private val backCallback = BackCallback { sheetExpanded.update { false } } init { // backHandler.register(backCallback) // componentScope.launch { // sheetExpanded.collect { // backCallback.isEnabled = it // } // } componentScope.launch { submission.emitAll( merge(_observeYourSubmission, _updatedYourSubmission) .mapResource(SubmissionResponse::toUiState) ) } } fun onFilesSelect(paths: List<Path>) { submission.value.onSuccess { submissionUiState -> componentScope.launch { paths.map { path -> addAttachmentToSubmissionUseCase( submissionUiState.id, CreateFileRequest(path.toFile()) ) .onSuccess { println("success load: $it") }.onFailure { println("failed load: $it") } } } } } fun onAttachmentRemove(attachmentId: UUID) { submission.value.onSuccess { submission -> componentScope.launch { removeAttachmentFromSubmissionUseCase(submission.id, attachmentId) } } } fun onSubmit() { submission.value.onSuccess { componentScope.launch { _updatedYourSubmission.emit( submitSubmissionUseCase(it.id) ) } } } fun onCancel() { submission.value.onSuccess { componentScope.launch { _updatedYourSubmission.emit( cancelSubmissionUseCase(it.id) ) } } } // fun onExpandChanged(expanded: Boolean) { // sheetExpanded.update { expanded } // } // fun List<AttachmentItem>.toAttachmentRequests(): List<AttachmentRequest> { // return map { attachment -> // when (attachment) { // is AttachmentItem.FileAttachmentItem -> { // CreateFileRequest( // name = attachment.name, // bytes = attachment.path.toFile().readBytes() // ) // } // // is AttachmentItem.LinkAttachmentItem -> CreateLinkRequest( // url = attachment.url // ) // } // } // } }
0
Kotlin
0
7
9d1744ffd9e1652e93af711951e924b739e96dcc
5,700
Studiversity
Apache License 2.0
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/ui/coursework/yourSubmission/YourSubmissionComponent.kt
denchic45
435,895,363
false
{"Kotlin": 2033820, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.ui.coursework.yourSubmission import com.arkivanov.decompose.ComponentContext import com.arkivanov.decompose.childContext import com.denchic45.studiversity.api.course.element.model.AttachmentRequest import com.denchic45.studiversity.api.course.element.model.CreateFileRequest import com.denchic45.studiversity.api.submission.model.SubmissionResponse import com.denchic45.studiversity.domain.resource.* import com.denchic45.studiversity.domain.usecase.* import com.denchic45.studiversity.ui.attachments.AttachmentsComponent import com.denchic45.studiversity.ui.coursework.SubmissionUiState import com.denchic45.studiversity.ui.coursework.toUiState import com.denchic45.studiversity.ui.model.AttachmentItem import com.denchic45.studiversity.util.componentScope import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import me.tatarka.inject.annotations.Assisted import me.tatarka.inject.annotations.Inject import okio.Path import java.util.* @Inject class YourSubmissionComponent( checkUserCapabilitiesInScopeUseCase: CheckUserCapabilitiesInScopeUseCase, private val addAttachmentToSubmissionUseCase: AddAttachmentToSubmissionUseCase, private val removeAttachmentFromSubmissionUseCase: RemoveAttachmentFromSubmissionUseCase, observeYourSubmissionUseCase: ObserveYourSubmissionUseCase, private val findSubmissionAttachmentsUseCase: FindSubmissionAttachmentsUseCase, private val submitSubmissionUseCase: SubmitSubmissionUseCase, private val cancelSubmissionUseCase: CancelSubmissionUseCase, attachmentsComponent: ( attachments: Flow<Resource<List<AttachmentItem>>>, onAddAttachment: ((AttachmentRequest) -> Unit)?, onRemoveAttachment: ((UUID) -> Unit)?, ComponentContext ) -> AttachmentsComponent, @Assisted private val courseId: UUID, @Assisted private val workId: UUID, @Assisted private val componentContext: ComponentContext, ) : ComponentContext by componentContext { private val componentScope = componentScope() private val _observeYourSubmission = observeYourSubmissionUseCase(courseId, workId) .shareIn(componentScope, SharingStarted.Lazily) private val _updatedYourSubmission = MutableSharedFlow<Resource<SubmissionResponse>>() val attachmentsComponentResource = _observeYourSubmission .filterNotNullValue() .mapResource { submission -> attachmentsComponent( findSubmissionAttachmentsUseCase(submission.id), { componentScope.launch { addAttachmentToSubmissionUseCase(submission.id, it) } }, { componentScope.launch { removeAttachmentFromSubmissionUseCase( submission.id, it ) } }, componentContext.childContext("Attachments") ) }.stateInResource(componentScope) val submission = MutableStateFlow<Resource<SubmissionUiState>>(Resource.Loading) // val sheetExpanded = MutableStateFlow(false) // private val backCallback = BackCallback { sheetExpanded.update { false } } init { // backHandler.register(backCallback) // componentScope.launch { // sheetExpanded.collect { // backCallback.isEnabled = it // } // } componentScope.launch { submission.emitAll( merge(_observeYourSubmission, _updatedYourSubmission) .mapResource(SubmissionResponse::toUiState) ) } } fun onFilesSelect(paths: List<Path>) { submission.value.onSuccess { submissionUiState -> componentScope.launch { paths.map { path -> addAttachmentToSubmissionUseCase( submissionUiState.id, CreateFileRequest(path.toFile()) ) .onSuccess { println("success load: $it") }.onFailure { println("failed load: $it") } } } } } fun onAttachmentRemove(attachmentId: UUID) { submission.value.onSuccess { submission -> componentScope.launch { removeAttachmentFromSubmissionUseCase(submission.id, attachmentId) } } } fun onSubmit() { submission.value.onSuccess { componentScope.launch { _updatedYourSubmission.emit( submitSubmissionUseCase(it.id) ) } } } fun onCancel() { submission.value.onSuccess { componentScope.launch { _updatedYourSubmission.emit( cancelSubmissionUseCase(it.id) ) } } } // fun onExpandChanged(expanded: Boolean) { // sheetExpanded.update { expanded } // } // fun List<AttachmentItem>.toAttachmentRequests(): List<AttachmentRequest> { // return map { attachment -> // when (attachment) { // is AttachmentItem.FileAttachmentItem -> { // CreateFileRequest( // name = attachment.name, // bytes = attachment.path.toFile().readBytes() // ) // } // // is AttachmentItem.LinkAttachmentItem -> CreateLinkRequest( // url = attachment.url // ) // } // } // } }
0
Kotlin
0
7
9d1744ffd9e1652e93af711951e924b739e96dcc
5,700
Studiversity
Apache License 2.0
src/main/kotlin/org/arend/formatting/ArendCodeStyleImportsPanelWrapper.kt
JetBrains
96,068,447
false
null
package org.arend.formatting import com.intellij.application.options.CodeStyleAbstractPanel import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.highlighter.EditorHighlighter import com.intellij.openapi.fileTypes.FileType import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.ui.layout.GrowPolicy import com.intellij.ui.layout.panel import com.intellij.ui.layout.selected import org.arend.ArendFileType import org.arend.settings.ArendCustomCodeStyleSettings import org.arend.settings.ArendCustomCodeStyleSettings.OptimizeImportsPolicy import org.arend.util.ArendBundle import javax.swing.JComponent class ArendCodeStyleImportsPanelWrapper(settings: CodeStyleSettings) : CodeStyleAbstractPanel(settings) { var myOptimizeImportsPolicy: OptimizeImportsPolicy = settings.arendSettings().OPTIMIZE_IMPORTS_POLICY var myLimitOfExplicitImports: Int = settings.arendSettings().EXPLICIT_IMPORTS_LIMIT override fun getRightMargin(): Int = 0 override fun createHighlighter(scheme: EditorColorsScheme?): EditorHighlighter? = null override fun getFileType(): FileType = ArendFileType override fun getPreviewText(): String? = null private fun CodeStyleSettings.arendSettings(): ArendCustomCodeStyleSettings = getCustomSettings(ArendCustomCodeStyleSettings::class.java) override fun apply(settings: CodeStyleSettings) { myPanel.apply() val arendSettings = settings.arendSettings() arendSettings.OPTIMIZE_IMPORTS_POLICY = myOptimizeImportsPolicy arendSettings.EXPLICIT_IMPORTS_LIMIT = myLimitOfExplicitImports } override fun isModified(settings: CodeStyleSettings): Boolean { return myPanel.isModified() || settings.arendSettings().OPTIMIZE_IMPORTS_POLICY != myOptimizeImportsPolicy || settings.arendSettings().EXPLICIT_IMPORTS_LIMIT != myLimitOfExplicitImports } override fun resetImpl(settings: CodeStyleSettings) { val arendSettings = settings.arendSettings() myOptimizeImportsPolicy = arendSettings.OPTIMIZE_IMPORTS_POLICY myLimitOfExplicitImports = arendSettings.EXPLICIT_IMPORTS_LIMIT myPanel.reset() } override fun getPanel(): JComponent = myPanel private val myPanel = panel { row(ArendBundle.message("arend.code.style.settings.optimize.imports.policy")) { buttonGroup { row { radioButton( ArendBundle.message("arend.code.style.settings.soft.optimize.imports"), { myOptimizeImportsPolicy == OptimizeImportsPolicy.SOFT }, { myOptimizeImportsPolicy = OptimizeImportsPolicy.SOFT }, ) } row { radioButton( ArendBundle.message("arend.code.style.settings.use.implicit.imports"), { myOptimizeImportsPolicy == OptimizeImportsPolicy.ONLY_IMPLICIT }, { myOptimizeImportsPolicy = OptimizeImportsPolicy.ONLY_IMPLICIT }, ) } row { val button = radioButton( ArendBundle.message("arend.code.style.settings.use.explicit.imports"), { myOptimizeImportsPolicy == OptimizeImportsPolicy.ONLY_EXPLICIT }, { myOptimizeImportsPolicy = OptimizeImportsPolicy.ONLY_EXPLICIT }, ) row { label(ArendBundle.message("arend.code.style.settings.explicit.imports.limit")) intTextField(this@ArendCodeStyleImportsPanelWrapper::myLimitOfExplicitImports, null, 0..5000) .enableIf(button.selected) .growPolicy(GrowPolicy.SHORT_TEXT) } } } } } override fun getTabTitle(): String = ApplicationBundle.INSTANCE.getMessage("title.imports") }
67
Kotlin
13
79
65a989952c2c9830ade7b0b303b09a827ab7dfff
4,119
intellij-arend
Apache License 2.0
src/me/anno/gpu/texture/ITexture2D.kt
AntonioNoack
456,513,348
false
null
package me.anno.gpu.texture import me.anno.cache.ICacheData import me.anno.gpu.DepthMode import me.anno.gpu.framebuffer.IFramebuffer import me.anno.gpu.framebuffer.VRAMToRAM import me.anno.gpu.shader.GPUShader import me.anno.image.raw.IntImage import me.anno.io.files.FileReference interface ITexture2D : ICacheData { val name: String val width: Int val height: Int val samples: Int val channels: Int val isHDR: Boolean val wasCreated: Boolean val isDestroyed: Boolean var depthFunc: DepthMode? val filtering: Filtering val clamping: Clamping fun isCreated(): Boolean { return wasCreated && !isDestroyed } fun bind(index: Int): Boolean = bind(index, filtering, clamping) fun bind(index: Int, filtering: Filtering, clamping: Clamping): Boolean fun bind(shader: GPUShader, texName: String, nearest: Filtering, clamping: Clamping): Boolean { val index = shader.getTextureIndex(texName) return if (index >= 0) { bind(index, nearest, clamping) } else false } fun bindTrulyNearest(index: Int) = bind(index, Filtering.TRULY_NEAREST, Clamping.CLAMP) fun bindTrulyNearest(shader: GPUShader, texName: String): Boolean { val index = shader.getTextureIndex(texName) return if (index >= 0) bindTrulyNearest(index) else false } fun bindTrulyLinear(index: Int) = bind(index, Filtering.TRULY_LINEAR, Clamping.CLAMP) fun bindTrulyLinear(shader: GPUShader, texName: String): Boolean { val index = shader.getTextureIndex(texName) return if (index >= 0) bindTrulyLinear(index) else false } fun write(dst: FileReference, flipY: Boolean = false, withAlpha: Boolean = false) { createImage(flipY, withAlpha).write(dst) } fun wrapAsFramebuffer(): IFramebuffer fun createImage(flipY: Boolean, withAlpha: Boolean): IntImage { return VRAMToRAM.createImage(width, height, VRAMToRAM.zero, flipY, withAlpha) { x2, y2, _, _ -> VRAMToRAM.drawTexturePure(-x2, -y2, width, height, this, !withAlpha) } } }
0
null
3
24
013af4d92e0f89a83958008fbe1d1fdd9a10e992
2,109
RemsEngine
Apache License 2.0
notebooks/visualization/src/org/jetbrains/plugins/notebooks/editor/NotebookIntervalPointer.kt
a1usha
400,360,974
false
null
package org.jetbrains.plugins.notebooks.editor import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.Key /** * Pointer becomes invalid when code cell is edited * Invalid pointer returns null */ interface NotebookIntervalPointer { fun get(): NotebookCellLines.Interval? } private val key = Key.create<NotebookIntervalPointerFactory>(NotebookIntervalPointerFactory::class.java.name) interface NotebookIntervalPointerFactory { /** interval should be valid, return pointer to it */ fun create(interval: NotebookCellLines.Interval): NotebookIntervalPointer companion object { fun get(editor: Editor): NotebookIntervalPointerFactory = key.get(editor) ?: install(editor) private fun install(editor: Editor): NotebookIntervalPointerFactory = NotebookIntervalPointerFactoryImpl(NotebookCellLines.get(editor)).also { key.set(editor, it) } } }
1
null
1
1
6aed5d103e39abb3f6f8276435c3e6059a4a53be
907
intellij-community
Apache License 2.0
src/main/kotlin/org/serenityos/jakt/psi/declaration/JaktParameterMixin.kt
mattco98
494,614,613
false
null
package org.serenityos.jakt.psi.declaration import com.intellij.lang.ASTNode import com.intellij.psi.stubs.IStubElementType import org.serenityos.jakt.psi.api.JaktParameter import org.serenityos.jakt.psi.named.JaktStubbedNamedElement import org.serenityos.jakt.stubs.JaktParameterStub import org.serenityos.jakt.type.Type abstract class JaktParameterMixin : JaktStubbedNamedElement<JaktParameterStub>, JaktParameter { override val jaktType: Type get() = typeAnnotation.jaktType constructor(node: ASTNode) : super(node) constructor(stub: JaktParameterStub, type: IStubElementType<*, *>) : super(stub, type) }
3
Kotlin
3
14
c57f43c1ba5a9aef0def7017a454ac16417b1053
631
jakt-intellij-plugin
MIT License