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
publishing-example-app/src/main/java/com/ably/tracking/example/publisher/PublisherService.kt
ably
313,556,297
false
null
package com.ably.tracking.example.publisher import android.Manifest import android.app.Notification import android.app.Service import android.content.Intent import android.os.IBinder import androidx.annotation.RequiresPermission import androidx.core.app.NotificationCompat import com.ably.tracking.Resolution import com.ably.tracking.connection.Authentication import com.ably.tracking.connection.ConnectionConfiguration import com.ably.tracking.logging.LogHandler import com.ably.tracking.logging.LogLevel import com.ably.tracking.publisher.DefaultResolutionPolicyFactory import com.ably.tracking.publisher.LocationHistoryData import com.ably.tracking.publisher.LocationSource import com.ably.tracking.publisher.MapConfiguration import com.ably.tracking.publisher.Publisher import com.ably.tracking.publisher.PublisherNotificationProvider import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import timber.log.Timber // The public token for the Mapbox SDK. For more details see the README. private const val MAPBOX_ACCESS_TOKEN = BuildConfig.MAPBOX_ACCESS_TOKEN // The client ID for the Ably SDK instance. private const val CLIENT_ID = "<INSERT_CLIENT_ID_HERE>" // The API KEY for the Ably SDK. For more details see the README. private const val ABLY_API_KEY = BuildConfig.ABLY_API_KEY class PublisherService : Service() { // SupervisorJob() is used to keep the scope working after any of its children fail private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) private val NOTIFICATION_ID = 5235 private lateinit var notification: Notification private val binder = Binder() var publisher: Publisher? = null private lateinit var appPreferences: AppPreferences override fun onCreate() { super.onCreate() appPreferences = AppPreferences.getInstance(this) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setContentTitle("Asset Tracking") .setContentText("Publisher is working") .setSmallIcon(R.drawable.ic_launcher_foreground) .build() startForeground(NOTIFICATION_ID, notification) return START_NOT_STICKY } inner class Binder : android.os.Binder() { fun getService(): PublisherService = this@PublisherService } override fun onBind(intent: Intent?): IBinder = binder override fun onDestroy() { // We want to be sure that after the service is stopped the publisher is stopped too. // Otherwise we could end up with multiple active publishers. scope.launch { publisher?.stop() } super.onDestroy() } val isPublisherStarted: Boolean get() = publisher != null /** * Creates and starts the [Publisher]. */ @RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION]) fun startPublisher(locationSource: LocationSource? = null) { if (!isPublisherStarted) { publisher = createPublisher(locationSource).apply { locationHistory .onEach { uploadLocationHistoryData(it) } .launchIn(scope) } } } @RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION]) private fun createPublisher(locationSource: LocationSource?): Publisher = Publisher.publishers() .connection(ConnectionConfiguration(Authentication.basic(CLIENT_ID, ABLY_API_KEY))) .map(MapConfiguration(MAPBOX_ACCESS_TOKEN)) .locationSource(locationSource) .resolutionPolicy(DefaultResolutionPolicyFactory(createDefaultResolution(), this)) .androidContext(this) .profile(appPreferences.getRoutingProfile().toAssetTracking()) .logHandler(object : LogHandler { override fun logMessage(level: LogLevel, message: String, throwable: Throwable?) { when (level) { LogLevel.VERBOSE -> Timber.v(throwable, message) LogLevel.INFO -> Timber.i(throwable, message) LogLevel.DEBUG -> Timber.d(throwable, message) LogLevel.WARN -> Timber.w(throwable, message) LogLevel.ERROR -> Timber.e(throwable, message) } } }) .backgroundTrackingNotificationProvider( object : PublisherNotificationProvider { override fun getNotification(): Notification = notification }, NOTIFICATION_ID ) .rawLocations(appPreferences.shouldSendRawLocations()) .sendResolution(appPreferences.shouldSendResolution()) .constantLocationEngineResolution(createConstantLocationEngineResolution()) .vehicleProfile(appPreferences.getVehicleProfile().toAssetTracking()) .start() private fun createDefaultResolution(): Resolution = Resolution( appPreferences.getResolutionAccuracy(), appPreferences.getResolutionDesiredInterval(), appPreferences.getResolutionMinimumDisplacement().toDouble() ) private fun uploadLocationHistoryData(historyData: LocationHistoryData) { if (appPreferences.getLocationSource() == LocationSourceType.PHONE) { S3Helper.uploadHistoryData( this, historyData ) { showShortToast(R.string.error_s3_not_initialized_history_data_upload_failed) } } } private fun createConstantLocationEngineResolution(): Resolution? = if (appPreferences.isConstantLocationEngineResolutionEnabled()) { appPreferences.getConstantLocationEngineResolution() } else { null } }
83
null
6
9
dca56bac165ebc1474cf2afb863728c2aad4aeb4
6,161
ably-asset-tracking-android
Apache License 2.0
desktop/src/main/java/org/ergoplatform/desktop/wallet/WalletListScreen.kt
ergoplatform
376,102,125
false
null
package org.ergoplatform.desktop.wallet import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.foundation.verticalScroll import androidx.compose.material.LinearProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import org.ergoplatform.desktop.ui.AppScrollbar import org.ergoplatform.desktop.ui.defaultMaxWidth import org.ergoplatform.desktop.ui.defaultPadding import org.ergoplatform.desktop.ui.navigation.ScreenConfig import org.ergoplatform.persistance.Wallet import org.ergoplatform.persistance.WalletConfig @Composable fun WalletListScreen( walletList: List<Wallet>, state: LazyListState, fiatValue: Float, isRefreshing: Boolean, onSendClicked: (WalletConfig) -> Unit, onReceiveClicked: (WalletConfig) -> Unit, onPushScreen: (ScreenConfig) -> Unit, onSettingsClicked: (WalletConfig) -> Unit, onDetailsClicked: (WalletConfig) -> Unit, ) { if (isRefreshing) { LinearProgressIndicator(Modifier.fillMaxWidth()) } Box { LazyColumn( state = state, modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { items(walletList.size) { index -> WalletCard( walletList[index], fiatValue, onSendClicked, onReceiveClicked, onDetailsClicked, onSettingsClicked ) } } VerticalScrollbar( modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), adapter = rememberScrollbarAdapter( scrollState = state ) ) } if (walletList.isEmpty()) { Box(Modifier.fillMaxSize()) { val scrollState = rememberScrollState() Box( Modifier.verticalScroll(scrollState).padding(defaultPadding) .widthIn(max = defaultMaxWidth).align(Alignment.Center) ) { AddWalletChooser(onPushScreen) } AppScrollbar(scrollState) } } }
16
Kotlin
35
94
b5f6e5176cf780a7437eb3c8447820bd9409c8ac
2,553
ergo-wallet-app
Apache License 2.0
src/main/kotlin/dev/ostara/agent/filter/AgentAuthenticationFilter.kt
krud-dev
664,954,220
false
{"Kotlin": 49623, "Dockerfile": 453}
package dev.ostara.agent.filter import dev.ostara.agent.config.AgentProperties import dev.ostara.agent.util.AGENT_KEY_HEADER import jakarta.servlet.FilterChain import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import org.springframework.http.HttpStatus import org.springframework.stereotype.Component import org.springframework.web.filter.OncePerRequestFilter @Component class AgentAuthenticationFilter( private val agentProperties: AgentProperties ) : OncePerRequestFilter() { override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) { val secure = request.isSecure val apiKey = request.getHeader(AGENT_KEY_HEADER) if (!secure) { if (!apiKey.isNullOrBlank()) { response.sendError(HttpStatus.BAD_REQUEST.value(), "$AGENT_KEY_HEADER header is only allowed over https") } else { filterChain.doFilter(request, response) } return } if (apiKey.isNullOrBlank()) { response.sendError(HttpStatus.BAD_REQUEST.value(), "$AGENT_KEY_HEADER header is required") return } if (apiKey != agentProperties.apiKey) { response.sendError(HttpStatus.UNAUTHORIZED.value(), "$AGENT_KEY_HEADER header is incorrect") return } filterChain.doFilter(request, response) } }
11
Kotlin
1
0
21a453757c862864e56625c644eac4932a7d57e8
1,358
ostara-agent
Apache License 2.0
src/main/kotlin/eu/europa/ec/eudi/verifier/endpoint/adapter/out/mso/DeviceResponseValidator.kt
eu-digital-identity-wallet
642,351,759
false
{"Kotlin": 332128, "HTML": 1598}
/* * Copyright (c) 2023 European Commission * * 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 eu.europa.ec.eudi.verifier.endpoint.adapter.out.mso import arrow.core.Either import arrow.core.NonEmptyList import arrow.core.mapOrAccumulate import arrow.core.raise.Raise import arrow.core.raise.either import arrow.core.raise.ensure import id.walt.mdoc.dataretrieval.DeviceResponse import id.walt.mdoc.dataretrieval.DeviceResponseStatus import id.walt.mdoc.doc.MDoc /** * An invalid document inside a device response */ data class InvalidDocument( val index: Int, val documentType: String, val errors: NonEmptyList<DocumentError>, ) /** * Errors related to device response */ sealed interface DeviceResponseError { /** * Given vp_token cannot be decoded to a device response */ data object CannotBeDecoded : DeviceResponseError /** * Device response didn't have an OK status */ data class NotOkDeviceResponseStatus(val status: Number) : DeviceResponseError /** * Invalid documents found within device response */ data class InvalidDocuments(val invalidDocuments: NonEmptyList<InvalidDocument>) : DeviceResponseError } class DeviceResponseValidator( private val documentValidator: DocumentValidator, ) { /** * Validates the given verifier presentation * It could a vp_token or an element of an array vp_token */ fun ensureValid(vp: String): Either<DeviceResponseError, List<MDoc>> = either { val deviceResponse = ensureCanBeDecoded(vp) val validDocuments = ensureValid(deviceResponse).bind() validDocuments } fun ensureValid(deviceResponse: DeviceResponse): Either<DeviceResponseError, List<MDoc>> = either { ensureStatusIsOk(deviceResponse) ensureValidDocuments(deviceResponse, documentValidator) } } private fun Raise<DeviceResponseError.CannotBeDecoded>.ensureCanBeDecoded(vp: String): DeviceResponse = try { DeviceResponse.fromCBORBase64URL(vp) } catch (t: Throwable) { raise(DeviceResponseError.CannotBeDecoded) } private fun Raise<DeviceResponseError.NotOkDeviceResponseStatus>.ensureStatusIsOk(deviceResponse: DeviceResponse) { val status = deviceResponse.status ensure(DeviceResponseStatus.OK.status.toInt() == status.value.toInt()) { DeviceResponseError.NotOkDeviceResponseStatus(status.value) } } private fun Raise<DeviceResponseError.InvalidDocuments>.ensureValidDocuments( deviceResponse: DeviceResponse, documentValidator: DocumentValidator, ): List<MDoc> = deviceResponse.documents.withIndex().mapOrAccumulate { (index, document) -> documentValidator .ensureValid(document) .mapLeft { documentErrors -> InvalidDocument(index, document.docType.value, documentErrors) } .bind() }.mapLeft(DeviceResponseError::InvalidDocuments).bind()
3
Kotlin
15
12
2020868ffb7943c0936f699cb121b0ddca52db54
3,473
eudi-srv-web-verifier-endpoint-23220-4-kt
Apache License 2.0
src/main/kotlin/me/imtoggle/barhud/hud/HotBar.kt
ImToggle
738,141,756
false
{"Kotlin": 22772, "Java": 5038}
package me.imtoggle.barhud.hud import cc.polyfrost.oneconfig.config.annotations.Color import cc.polyfrost.oneconfig.config.annotations.HUD import cc.polyfrost.oneconfig.config.annotations.Slider import cc.polyfrost.oneconfig.config.core.OneColor import cc.polyfrost.oneconfig.config.elements.SubConfig import cc.polyfrost.oneconfig.gui.animations.Animation import cc.polyfrost.oneconfig.gui.animations.DummyAnimation import cc.polyfrost.oneconfig.hud.BasicHud import cc.polyfrost.oneconfig.libs.universal.UGraphics.GL import cc.polyfrost.oneconfig.libs.universal.UMatrixStack import cc.polyfrost.oneconfig.utils.dsl.* import me.imtoggle.barhud.mixin.GuiAccessor import me.imtoggle.barhud.mixin.GuiIngameAccessor import me.imtoggle.barhud.mixin.GuiSpectatorAccessor import me.imtoggle.barhud.utils.Linear import net.minecraft.client.gui.ScaledResolution import net.minecraft.client.gui.spectator.SpectatorMenu import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.renderer.RenderHelper import net.minecraft.entity.player.EntityPlayer object HotBar : SubConfig("HotBar", "barhud/hotbar.json") { @HUD(name = "Hud") var hud = HotBarHud() init { initialize() } class HotBarHud : BasicHud(true, 1920 / 2f - 182 / 2f, 1080 - 22f, 1f, true, true, 4f, 0f, 0f, OneColor(0, 0, 0, 120), false, 2f, OneColor(0, 0, 0)) { @Slider( name = "Animation Duration", min = 0f, max = 500f ) var duration = 200f @Color( name = "Current Slot Color" ) var normalColor = OneColor(0, 0, 0, 63) @Transient var slot = 0 @Transient var slotAnimation: Animation = DummyAnimation(1f) override fun drawAll(matrices: UMatrixStack?, example: Boolean) { super.drawAll(matrices, example) } override fun draw(matrices: UMatrixStack?, x: Float, y: Float, scale: Float, example: Boolean) { val scaledResolution = ScaledResolution(mc) if (mc.playerController.isSpectator) { val accessor: GuiSpectatorAccessor = mc.ingameGUI.spectatorGui as GuiSpectatorAccessor val guiAccessor: GuiAccessor = mc.ingameGUI.spectatorGui as GuiAccessor drawSpec(x, y, accessor.field_175271_i, accessor, guiAccessor, scaledResolution) } else { val accessor: GuiIngameAccessor = mc.ingameGUI as GuiIngameAccessor if (mc.thePlayer.inventory.currentItem >= 0) { checkSlotChange(mc.thePlayer.inventory.currentItem) nanoVG(true) { translate(x + slotAnimation.get() * 20 * scale, y) scale(scale, scale) drawRoundedRect(0f, 0f, 22, 22, cornerRadius, normalColor.rgb) } } if (mc.renderViewEntity is EntityPlayer) { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f) mc.textureManager.bindTexture(accessor.widgetsTexPath) val entityPlayer = mc.renderViewEntity as EntityPlayer GlStateManager.enableRescaleNormal() GlStateManager.enableBlend() GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0) RenderHelper.enableGUIStandardItemLighting() for (j in 0..8) { val item = entityPlayer.inventory.mainInventory[j] ?: continue val itemRenderer = mc.renderItem GlStateManager.pushMatrix() GlStateManager.translate(x + (j * 20 + 3) * scale, y + 3 * scale, 0f) GlStateManager.scale(scale, scale, 1f) itemRenderer.renderItemAndEffectIntoGUI(item, 0, 0) itemRenderer.renderItemOverlayIntoGUI(mc.fontRendererObj, item, 0, 0, null) GlStateManager.enableAlpha() GlStateManager.popMatrix() } RenderHelper.disableStandardItemLighting() GlStateManager.disableRescaleNormal() GlStateManager.disableBlend() } } } override fun getWidth(scale: Float, example: Boolean): Float { return 182f * scale } override fun getHeight(scale: Float, example: Boolean): Float { return 22f * scale } private fun drawSpec(x: Float, y: Float, menu: SpectatorMenu?, specAccessor: GuiSpectatorAccessor, guiAccessor: GuiAccessor, scaledResolution: ScaledResolution) { if (menu != null) { val g = specAccessor.alpha() if (g <= 0.0f) { menu.func_178641_d() } else { val h = guiAccessor.zLevel guiAccessor.zLevel = -90.0f val spectatorDetails = menu.func_178646_f() if (spectatorDetails.func_178681_b() >= 0) { checkSlotChange(spectatorDetails.func_178681_b()) nanoVG(true) { translate(x + slotAnimation.get() * 20 * scale, y) scale(scale, scale) drawRoundedRect(0f, 0f, 22, 22, cornerRadius, normalColor.rgb) } } GL.pushMatrix() GL.scale(scale, scale, scale) GlStateManager.enableRescaleNormal() GlStateManager.enableBlend() GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0) GlStateManager.color(1.0f, 1.0f, 1.0f, g) mc.textureManager.bindTexture(specAccessor.field_175267_f) RenderHelper.enableGUIStandardItemLighting() for (j in 0..8) { specAccessor.drawItem(j, (x / hud.getScale() + j * 20 + 3).toInt(), y / scale + 3.0f, 1.0f, spectatorDetails.func_178680_a(j)) } RenderHelper.disableStandardItemLighting() GlStateManager.disableRescaleNormal() GlStateManager.disableBlend() GL.popMatrix() guiAccessor.zLevel = h } } } private fun checkSlotChange(slot: Int) { if (slot != this.slot) { slotAnimation = Linear(duration, slotAnimation.get(), slot.toFloat(), false) this.slot = slot } } override fun shouldShow(): Boolean { val accessor = mc.ingameGUI.spectatorGui as GuiSpectatorAccessor return super.shouldShow() && (!mc.thePlayer.isSpectator || accessor.alpha() > 0f) } } }
0
Kotlin
0
0
53e31c0c976b71f729e130fcda354299637dc1b9
6,930
BarHud
The Unlicense
build-scan-notifier-agent/src/test/kotlin/dev/erichaag/NotifierAgentApplicationTests.kt
erichaagdev
606,245,678
false
{"Kotlin": 12541}
package dev.erichaag import org.junit.jupiter.api.Test class NotifierAgentApplicationTests { @Test fun test() { } }
0
Kotlin
0
0
57bb109c1d559818edcb2f06808597319410d1e8
126
gradle-enterprise-build-scan-notifier
MIT License
app/src/main/java/com/srtp/assistant/ui/work/WorkViewModel.kt
FallingStars-5
359,435,558
false
null
package com.srtp.assistant.ui.work import android.content.Context import androidx.lifecycle.ViewModel import com.srtp.assistant.logic.Repository import com.srtp.assistant.logic.model.WorkSettings class WorkViewModel:ViewModel() { var workSetting = WorkSettings() var workList = Repository.findAllNotCompletedWork() fun showAllWork(){ workList = Repository.findAllWork() } fun getSavedWorkSettings(context: Context) = Repository.getSavedWorkSettings(context) fun saveWorkSettings(context: Context){ Repository.saveWorkSettings(context,workSetting) } fun showCompletedWork(){ workList = Repository.findAllCompletedWork() } fun showNotCompletedWork(){ workList = Repository.findAllNotCompletedWork() } fun showOverTimeAndNotCompletedWork(){ workList = Repository.findAllOvertimeNotCompletedWork() } }
0
Kotlin
1
1
ec1c0a9409b44b5d4a58d5e0cf4912b6bf74cdf4
899
UniversityStudentAssistant
Apache License 2.0
ant-viewver/src/main/java/com/antourage/weaverlib/other/networking/Status.kt
antourage
381,353,643
false
null
package com.antourage.weaverlib.other.networking internal sealed class Status<T> { class Loading<T> : Status<T>() data class Failure<T>(val errorMessage: String, val errorCode: Int?) : Status<T>() data class CachedData<T>(val data: T?) : Status<T>() data class Success<T>(val data: T?) : Status<T>() }
1
Kotlin
0
0
57263ef0c3174355d1dde62291a025b242087de0
319
viewer-sdk-android
MIT License
ant-viewver/src/main/java/com/antourage/weaverlib/other/networking/Status.kt
antourage
381,353,643
false
null
package com.antourage.weaverlib.other.networking internal sealed class Status<T> { class Loading<T> : Status<T>() data class Failure<T>(val errorMessage: String, val errorCode: Int?) : Status<T>() data class CachedData<T>(val data: T?) : Status<T>() data class Success<T>(val data: T?) : Status<T>() }
1
Kotlin
0
0
57263ef0c3174355d1dde62291a025b242087de0
319
viewer-sdk-android
MIT License
app/src/main/java/io/homeassistant/companion/android/lock/LockView.kt
grote
250,287,852
true
null
package io.homeassistant.companion.android.lock interface LockView { fun displayWebview() }
0
null
0
12
f6618527d4f5f1233e7e0515f9816eb3ac282e5b
97
home-assistant-android
Apache License 2.0
app/src/main/kotlin/pe/aioo/openmoa/view/keytouchlistener/CrossKeyTouchListener.kt
AiOO
556,034,007
false
{"Kotlin": 91457}
package pe.aioo.openmoa.view.keytouchlistener import android.annotation.SuppressLint import android.content.Context import android.view.MotionEvent import android.view.View import pe.aioo.openmoa.view.message.BaseKeyMessage import kotlin.math.* class CrossKeyTouchListener( context: Context, private val keyList: List<BaseKeyMessage>, ) : BaseKeyTouchListener(context) { private var startX: Float = 0f private var startY: Float = 0f @SuppressLint("ClickableViewAccessibility") override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { when (motionEvent.action) { MotionEvent.ACTION_DOWN -> { startX = motionEvent.x startY = motionEvent.y } MotionEvent.ACTION_UP -> { val currentX = motionEvent.x val currentY = motionEvent.y val distance = sqrt( (currentX - startX).pow(2) + (currentY - startY).pow(2) ) if (distance > config.gestureThreshold) { val degree = (atan2(currentY - startY, currentX - startX) * 180f) / PI startX = currentX startY = currentY if (abs(degree) < 45f) { sendKeyMessage(keyList[1]) } else if (abs(degree) < 135f) { sendKeyMessage(if (degree > 0) keyList[2] else keyList[0]) } else { sendKeyMessage(keyList[3]) } } else { sendKeyMessage(keyList[2]) } } } return super.onTouch(view, motionEvent) } }
2
Kotlin
2
14
707e30d6eb02372dc6a8f89c9e4a6867764768c2
1,733
OpenMoa
MIT License
src/main/kotlin/org/teamvoided/shippost/TheShippostMod.kt
TeamVoided
648,231,566
false
null
package org.teamvoided.shippost import net.fabricmc.api.ModInitializer import net.minecraft.block.Block import net.minecraft.item.Item import net.minecraft.registry.Registries import net.minecraft.util.Identifier import org.slf4j.LoggerFactory import org.teamvoided.shippost.registries.SpBlocks import org.teamvoided.shippost.registries.SpItems import org.teamvoided.shippost.registries.SpTabs object TheShippostMod : ModInitializer { const val MODID = "shippost" val LOGGER = LoggerFactory.getLogger(MODID) fun id(path: String): Identifier = Identifier(MODID, path) override fun onInitialize() { LOGGER.info("hi, Gun :gun:") BoneInjection.init() SpItems.init() SpBlocks.init() SpTabs.init() } fun getId(item: Item): Identifier = Registries.ITEM.getId(item) fun getId(block: Block): Identifier = Registries.BLOCK.getId(block) }
0
Kotlin
0
2
bd8eca7f5ea4247cdc2bdecfadbd13e6abb67428
899
TheShippostMod
MIT License
support/src/main/java/com/landside/support/extensions/ToastExt.kt
landscapeside
350,730,923
false
null
package com.landside.support.extensions import android.app.Dialog import android.content.Context import android.widget.Toast import androidx.annotation.StringRes import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity fun Context.toast(value: String) = toast { value } fun FragmentActivity.toast(value: String) = toast { value } fun FragmentActivity.toast(@StringRes resId: Int) = popToast(this, resId) inline fun Context.toast(value: () -> String) = popToast(context = this, message = value()) inline fun Fragment.toast(value: () -> String) = popToast(activity as Context, value()) fun Context.toast(@StringRes resId: Int) = popToast(this, resId) inline fun Fragment.toast(@StringRes resId: Int) = popToast(activity as Context, resId) inline fun Dialog.toast(value: () -> String) = popToast(context, value()) fun popToast( context: Context, message: String ) { val toast = Toast.makeText(context, "", Toast.LENGTH_SHORT) toast.setText(message) toast.show() } fun popToast( context: Context, @StringRes resId: Int ) { val toast = Toast.makeText(context, "", Toast.LENGTH_SHORT) toast.setText(resId) toast.show() }
0
Kotlin
0
0
75829542431d5b2e53facf4bfd1e13076e5661d8
1,186
support
MIT License
kotlin-examples/src/main/kotlin/top/viclau/magicbox/kotlin/examples/sdk/experimental/MeasureTime.kt
xingyuli
578,005,859
false
null
/* * Copyright (c) 2022 Vic Lau * * Distributed under MIT license. * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ package top.viclau.magicbox.kotlin.examples.sdk.experimental import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue @ExperimentalTime fun main() { useClockMark() useMeasureTimedValue() } @ExperimentalTime private fun useClockMark() { val mark = TimeSource.Monotonic.markNow() // might be inside the first function Thread.sleep(10) // action println(mark.elapsedNow()) // might be inside the second function } @ExperimentalTime private fun useMeasureTimedValue() { val (value, duration) = measureTimedValue { Thread.sleep(100) 42 } println(value) println(duration) }
0
Kotlin
0
0
b1c702f3cfd1c64ccd37a3465a8ce42b3f346ba3
826
magicbox
MIT License
app/src/main/java/app/klimatic/ui/search/presentation/viewmodel/SearchViewModel.kt
developer-shivam
374,342,429
false
null
package app.klimatic.ui.search.presentation.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import app.klimatic.data.model.weather.Location import app.klimatic.data.pref.AppSharedPreferences import app.klimatic.data.response.Response import app.klimatic.ui.base.BaseCurrentSelectedLocationViewModel import app.klimatic.ui.search.domain.SearchDataManager import app.klimatic.ui.utils.ViewState import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch class SearchViewModel( appSharedPreferences: AppSharedPreferences, private val dataManager: SearchDataManager ) : BaseCurrentSelectedLocationViewModel(appSharedPreferences) { private val locationsLiveData: MutableLiveData<ViewState<List<Location>>> = MutableLiveData() val locations: LiveData<ViewState<List<Location>>> = locationsLiveData private var searchJob: Job? = null init { // fetch location initially with auto:ip searchLocationByQuery() } fun searchLocationByLatLon(lat: Double, long: Double) { searchLocation(query = "$lat,$long") } fun searchLocationByQuery(query: String = DEFAULT_QUERY) { searchLocation(query = query) } private fun searchLocation(query: String) { searchJob?.cancel() searchJob = ioScope.launch { if (query != DEFAULT_QUERY) { delay(300) } fetchData(query) } } private suspend fun fetchData(query: String) { val viewState: ViewState<List<Location>> = when (val response = dataManager.searchLocation(query)) { is Response.Success -> { ViewState.Success(data = response.data) } is Response.Error -> ViewState.Error(code = response.errorCode) } locationsLiveData.postValue(viewState) } }
0
Kotlin
2
34
a46582676223c4faaba5e8dad436dbc46da70f8b
1,944
Klimatic
Apache License 2.0
app/src/main/java/com/softvision/mvi_mvrx_hilt_kotlin/viewmodel/TVShowsViewModel.kt
blavi
338,291,420
false
null
package com.softvision.mvi_mvrx_hilt_kotlin.viewmodel import com.airbnb.mvrx.* import com.softvision.domain.base.BaseFetchGenresUseCase import com.softvision.domain.base.BaseFetchItemsUseCase import com.softvision.domain.di.TvShowGenresInteractor import com.softvision.domain.di.TvShowsByGenreInteractor import com.softvision.domain.model.BaseItemDetails import com.softvision.domain.model.GenreDetails import com.softvision.domain.mvi.TVShowsByGenreState import com.softvision.mvi_mvrx_hilt_kotlin.ui.TVShowsFragment import com.squareup.inject.assisted.Assisted import com.squareup.inject.assisted.AssistedInject import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import timber.log.Timber class TVShowsViewModel @AssistedInject constructor( @Assisted initialState: TVShowsByGenreState, @TvShowsByGenreInteractor private val tvShowsInteractor: BaseFetchItemsUseCase<String, BaseItemDetails, Int>, @TvShowGenresInteractor private val genresInteractor: BaseFetchGenresUseCase<BaseItemDetails> ) : BaseViewModel<TVShowsByGenreState>(initialState) { private var disposables: CompositeDisposable = CompositeDisposable() init { loadGenresAndTvShows() } private fun loadGenresAndTvShows() { fetchGenres() } private fun fetchGenres() { Timber.i("Movies: movie genres invoke") val genresDisposable = genresInteractor.invoke() .subscribeOn(Schedulers.io()) .execute { copy( genresRequest = it, genres = it.invoke() ?: emptyList(), displayedGenre = it.invoke()?.get(0) ) } disposables.add(genresDisposable) } fun fetchTvShowsByGenre(offset: Int = 0) = withState { state -> (state.displayedGenre as? GenreDetails)?.id?.let { id -> Timber.i("Explore State: genre id: %s", id) val moviesByGenreDisposable = tvShowsInteractor.invoke(id.toString(), offset / 20 + 1) .subscribeOn(Schedulers.io()) .execute { copy( tvShowsByGenreRequest = it, tvShowsByGenreList = combineMoviesByGenre(offset, id, it) ) } disposables.add(moviesByGenreDisposable) } Timber.i("Movies: %s", this) } fun loadMoreMoviesWithSelectedGenre() = withState { it.apply { if (tvShowsByGenreRequest.complete && tvShowsByGenreList.isNotEmpty() && displayedGenre != null) { fetchTvShowsByGenre(tvShowsByGenreList.count()) } } } fun setSelectedItem(item: BaseItemDetails?) { setState { copy(selectedItem = item) } } fun updateSelectedGenre(genreDetails: GenreDetails) { Timber.i("Explore State: update selected genre id: %s", genreDetails.name) setState { copy(displayedGenre = genreDetails) } } @AssistedInject.Factory interface Factory { fun create(initialState: TVShowsByGenreState): TVShowsViewModel } companion object : MavericksViewModelFactory<TVShowsViewModel, TVShowsByGenreState> { override fun create( viewModelContext: ViewModelContext, state: TVShowsByGenreState ): TVShowsViewModel = (viewModelContext as FragmentViewModelContext) .fragment<TVShowsFragment>() .viewModelFactory.create(state) } override fun onCleared() { super.onCleared() disposables.clear() } }
0
Kotlin
1
0
e7cdb5955017eaed7e63d5283fdcd95ae949cfdb
3,673
MVI-MvRx-Hilt-Kotlin
Apache License 2.0
src/main/kotlin/com/petitcl/fddd4k/domain/products/Product.kt
petitcl
699,501,534
false
{"Kotlin": 12222}
package com.petitcl.fddd4k.domain.products import com.petitcl.fddd4k.domain.common.Money import java.util.UUID @JvmInline value class ProductId(val value: UUID) { companion object { fun new(): ProductId = ProductId(UUID.randomUUID()) } } @JvmInline value class ProductName(val value: String) { init { require(value.isNotBlank()) { "Product name cannot be blank" } } } data class Product( val productId: ProductId, val productName: ProductName, val description: String, val price: Money, )
0
Kotlin
0
0
8359c1f31110668056c21cb7a2467dcb8c91b26f
541
fddd4k-spring-sample
Apache License 2.0
core/src/main/java/com/kienht/dagger/hilt/core/di/ActivityViewModelModule.kt
hantrungkien
295,121,449
false
null
package com.viswa.core.di import android.app.Activity import android.app.Application import androidx.hilt.lifecycle.ViewModelAssistedFactory import androidx.lifecycle.SavedStateViewModelFactory import androidx.lifecycle.ViewModel import androidx.savedstate.SavedStateRegistryOwner import com.viswa.core.DFMSavedStateViewModelFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityComponent import javax.inject.Provider /** * @author kienht * @since 15/09/2020 */ @Module @InstallIn(ActivityComponent::class) object ActivityViewModelModule { @Provides fun provideSavedStateViewModelFactory( application: Application, activity: Activity, viewModelFactories: @JvmSuppressWildcards Map<String, Provider<ViewModelAssistedFactory<out ViewModel>>>, ): DFMSavedStateViewModelFactory { val owner = activity as SavedStateRegistryOwner val defaultArgs = activity.intent?.extras val delegate = SavedStateViewModelFactory(application, owner, defaultArgs) return DFMSavedStateViewModelFactory(owner, defaultArgs, delegate, viewModelFactories) } }
1
null
4
22
481c51b0ec971dd590e1232e99ccf612526405a8
1,183
Dagger-Hilt-DFM
Apache License 2.0
libs/serialization/serialization-amqp/src/test/kotlin/net/corda/internal/serialization/amqp/UuidTest.kt
corda
346,070,752
false
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.internal.serialization.amqp import net.corda.internal.serialization.amqp.ReusableSerialiseDeserializeAssert.Companion.serializeDeserializeAssert import net.corda.v5.base.annotations.CordaSerializable import org.junit.jupiter.api.Test import java.util.UUID class UuidTest { @Test fun random() { serializeDeserializeAssert(UUID.randomUUID()) } @Test fun insideDataClass() { serializeDeserializeAssert(UuidContainer(UUID.randomUUID())) } @CordaSerializable data class UuidContainer(val uuid: UUID) }
14
Kotlin
27
69
0766222eb6284c01ba321633e12b70f1a93ca04e
566
corda-runtime-os
Apache License 2.0
common/di/src/main/java/com/quintallabs/common/di/database/DrinkDatabaseModule.kt
thiagoalexb
739,844,654
false
{"Kotlin": 77090}
package com.quintallabs.common.di.database import com.quintallabs.repository.datasource.db.DrinkDatabase import org.koin.dsl.module val drinkDatabaseModule = module { factory { DrinkDatabase() } }
0
Kotlin
0
0
e139dd7beefd6cef3d7cc2ee6b49ca6a5e06475f
201
randomDrink
Apache License 2.0
src/main/kotlin/com/tradeshift/blayze/features/Multinomial.kt
Bhanditz
168,971,373
true
{"Kotlin": 65750}
package com.tradeshift.blayze.features import com.tradeshift.blayze.Protos import com.tradeshift.blayze.collection.Counter import com.tradeshift.blayze.collection.SparseIntVector import com.tradeshift.blayze.dto.Outcome import com.tradeshift.blayze.logBeta import java.lang.Math.log import kotlin.math.pow class Multinomial private constructor( private val includeFeatureProbability: Double = 1.0, private val pseudoCount: Double = 0.1, private val outcomeToIdx: Map<Outcome, Int>, private val features: Map<String, SparseIntVector> ) : Feature<Multinomial, Counter<String>> { /** * A feature for multinomial data. * * @property includeFeatureProbability Include new features with this probability. See Ad Click Prediction: a View from the Trenches, Table 2 * @property pseudoCount Effectively adds this number to all counts, even zero counts. */ constructor(includeFeatureProbability: Double = 1.0, pseudoCount: Double = 0.1) : this(includeFeatureProbability, pseudoCount, HashMap(), HashMap()) /** * The number of features seen for each outcome */ private val nFeaturesPerOutcome: IntArray by lazy { val res = IntArray(outcomeToIdx.size) for (vec in features.values) { for ((idx, count) in vec) { res[idx] += count } } res } private val idxToOutcome: Map<Int, Outcome> by lazy { outcomeToIdx.map { it.value to it.key }.toMap() } override fun batchUpdate(updates: List<Pair<Outcome, Counter<String>>>): Multinomial { val featuresCopy = features.toMutableMap() val outcomesCopy = outcomeToIdx.toMutableMap() fun getOrCreateIndex(key: Outcome) = outcomesCopy.getOrPut(key) { outcomesCopy.size } val formattedUpdates = invertUpdates(sampleUpdates(updates.asSequence())) for ((feature, counter) in formattedUpdates) { val indexToUpdate = counter.mapKeys { getOrCreateIndex(it.key) } val vec = SparseIntVector.fromMap(indexToUpdate) featuresCopy[feature] = featuresCopy[feature]?.add(vec) ?: vec } return Multinomial(includeFeatureProbability, pseudoCount, outcomesCopy, featuresCopy) } /* See https://en.wikipedia.org/wiki/Dirichlet-multinomial_distribution#Dirichlet-multinomial_as_a_compound_distribution This implementation could be a lot simpler by iterating over every outcome and then every feature in value (e.g. words) If N is the number of outcomes, and W is the number of words in value that would cost O(NW). We assume the occurrence of words are sparse, such that on average A outcomes have non-zero counts for a given word. The current implementation uses this to achieve O(W+N+AW). It does this by first computing the posterior predictive assuming every outcome has observed every word 0 times in O(W+N). Then it corrects the mistakes it made in O(AW). */ override fun logPosteriorPredictive(outcomes: Set<Outcome>, value: Counter<String>): Map<Outcome, Double> { val filtered = value.filter { features[it.key] != null } //hack, ensures unseen words does not influence posterior of outcomes val n = filtered.values.sum() if (n == 0 || features.isEmpty()) { // empty input or empty model return outcomes.map { it to 0.0 }.toMap() } val result = mutableMapOf<String, Double>() val logBetaZeroCounts = filtered.mapValues { log(it.value.toDouble()) + logBeta(0 + pseudoCount, it.value.toDouble()) } //O(W) val logBetaZeroCountsSum = logBetaZeroCounts.map { it.value }.sum() for (outcome in outcomes) { //O(N) val outcomeIdx = outcomeToIdx[outcome] val alpha_0 = if (outcomeIdx != null) { nFeaturesPerOutcome[outcomeIdx] } else { 0 } val numerator = log(n.toDouble()) + logBeta(alpha_0 + features.size * pseudoCount, n.toDouble()) result[outcome] = numerator - logBetaZeroCountsSum //assuming every outcome has seen every word 0 times } for ((word, count) in filtered) { //O(W) val alpha_kc = features[word] if (alpha_kc != null) { val wrong = logBetaZeroCounts[word]!! for ((outcomeIdx, i) in alpha_kc) { //O(A) val outcome = idxToOutcome[outcomeIdx]!! val prev = result[outcome] if (prev != null) { //outcomes may be a subset of all the outcomes we've observed val correct = log(count.toDouble()) + logBeta(i + pseudoCount, count.toDouble()) result[outcome] = prev - (-wrong + correct) //subtract error, add correct value } } } } return result } private fun sampleUpdates(updates: Sequence<Pair<Outcome, Counter<String>>>): Sequence<Pair<Outcome, Counter<String>>> { fun sampleFeature(count: Int) = Math.random() < (1.0 - (1.0 - includeFeatureProbability).pow(count)) val knownFeatures = features.keys.toMutableSet() return updates.map { (outcome, counter) -> val filteredFeatures = counter.filter { it.key in knownFeatures || sampleFeature(it.value) } knownFeatures.addAll(filteredFeatures.keys) outcome to Counter(filteredFeatures) } } private fun invertUpdates(updates: Sequence<Pair<Outcome, Counter<String>>>): Map<String, Counter<Outcome>> { val flipped = HashMap<String, HashMap<Outcome, Int>>() for ((outcome, counter) in updates) { for ((feature, count) in counter) { val outcomeCounter = flipped.getOrPut(feature, { HashMap() }) outcomeCounter[outcome] = count + (outcomeCounter[outcome] ?: 0) } } return flipped.mapValues { Counter(it.value) } } fun toProto(): Protos.Multinomial = Protos.Multinomial.newBuilder() .setIncludeFeatureProbability(includeFeatureProbability) .setPseudoCount(pseudoCount) .putAllOutcomes(outcomeToIdx) .putAllFeatures(features.mapValues { it.value.toProto() }) .build() companion object { fun fromProto(proto: Protos.Multinomial) = Multinomial( proto.includeFeatureProbability, proto.pseudoCount, proto.outcomesMap, proto.featuresMap.mapValues { SparseIntVector.fromProto(it.value) }) } }
0
Kotlin
0
0
cdd3cd6f17587c34bb24df51f2a768a7a0d9ff0a
6,627
blayze
MIT License
app/src/main/java/com/github/skytoph/simpleweather/core/presentation/adapter/BaseDiffUtil.kt
skytoph
482,520,275
false
{"Kotlin": 386525}
package com.github.skytoph.simpleweather.core.presentation.adapter import androidx.recyclerview.widget.DiffUtil import com.github.skytoph.simpleweather.core.Matcher abstract class BaseDiffUtil<T : Matcher<T>> : DiffUtil.ItemCallback<T>() { override fun areItemsTheSame(oldItem: T, newItem: T): Boolean = oldItem.matches(newItem) override fun areContentsTheSame(oldItem: T, newItem: T): Boolean = oldItem.contentMatches(newItem) }
0
Kotlin
0
0
4bb138a54ffb3e09be89302e9da3ccd439bebee6
456
SimpleWeather
MIT License
src/app/src/main/java/com/example/dummyjson_products/common/RetrofitInstance.kt
Hasuk1
768,593,694
false
{"Kotlin": 21324}
package com.example.dummyjson_products.common import com.example.dummyjson_products.data.DummyJsonApi import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitInstance { private val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } private val client: OkHttpClient = OkHttpClient.Builder() .addInterceptor(interceptor) .build() val api: DummyJsonApi = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(DummyJsonApi.BASE_URL) .client(client) .build() .create(DummyJsonApi::class.java) }
0
Kotlin
0
0
1299b8b9c0338a1e2f99cf418cef60d885ff7ab6
735
dummyjson_products
MIT License
dataforge-context/src/jsMain/kotlin/space/kscience/dataforge/context/loggingJs.kt
SciProgCentre
148,831,678
false
{"Kotlin": 408170}
package space.kscience.dataforge.context import space.kscience.dataforge.meta.Meta import space.kscience.dataforge.names.Name public class ConsoleLogManager : AbstractPlugin(), LogManager { override fun logger(name: Name): Logger = Logger { tag, body -> val message: String = body.safe when (tag) { // TODO depends on https://youtrack.jetbrains.com/issue/KT-33595/ LogManager.DEBUG -> console.asDynamic().debug("[${context.name}] $name: $message") LogManager.INFO -> console.info("[${context.name}] $name: $message") LogManager.WARNING -> console.warn("[${context.name}] $name: $message") LogManager.ERROR -> console.error("[${context.name}] $name: $message") else -> console.log("[${context.name}] $name: $message") } } override val defaultLogger: Logger = logger(Name.EMPTY) override val tag: PluginTag get() = Companion.tag public companion object : PluginFactory<ConsoleLogManager> { override fun build(context: Context, meta: Meta): ConsoleLogManager = ConsoleLogManager() override val tag: PluginTag = PluginTag(group = PluginTag.DATAFORGE_GROUP, name = "log.jsConsole") } } internal actual fun getGlobalLoggerFactory(): PluginFactory<out LogManager> = ConsoleLogManager
14
Kotlin
3
25
d80846d5fbd4d232b7506f5b4124cddfdc61d17e
1,325
dataforge-core
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/twotone/Menu.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.twotone import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.TwotoneGroup public val TwotoneGroup.Menu: ImageVector get() { if (_menu != null) { return _menu!! } _menu = Builder(name = "Menu", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.5401f, 8.3101f) curveTo(18.8987f, 8.3101f, 20.0001f, 7.2088f, 20.0001f, 5.8501f) curveTo(20.0001f, 4.4915f, 18.8987f, 3.3901f, 17.5401f, 3.3901f) curveTo(16.1814f, 3.3901f, 15.0801f, 4.4915f, 15.0801f, 5.8501f) curveTo(15.0801f, 7.2088f, 16.1814f, 8.3101f, 17.5401f, 8.3101f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.46f, 8.3101f) curveTo(7.8186f, 8.3101f, 8.92f, 7.2088f, 8.92f, 5.8501f) curveTo(8.92f, 4.4915f, 7.8186f, 3.3901f, 6.46f, 3.3901f) curveTo(5.1014f, 3.3901f, 4.0f, 4.4915f, 4.0f, 5.8501f) curveTo(4.0f, 7.2088f, 5.1014f, 8.3101f, 6.46f, 8.3101f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.5401f, 20.6099f) curveTo(18.8987f, 20.6099f, 20.0001f, 19.5086f, 20.0001f, 18.1499f) curveTo(20.0001f, 16.7913f, 18.8987f, 15.6899f, 17.5401f, 15.6899f) curveTo(16.1814f, 15.6899f, 15.0801f, 16.7913f, 15.0801f, 18.1499f) curveTo(15.0801f, 19.5086f, 16.1814f, 20.6099f, 17.5401f, 20.6099f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.46f, 20.6099f) curveTo(7.8186f, 20.6099f, 8.92f, 19.5086f, 8.92f, 18.1499f) curveTo(8.92f, 16.7913f, 7.8186f, 15.6899f, 6.46f, 15.6899f) curveTo(5.1014f, 15.6899f, 4.0f, 16.7913f, 4.0f, 18.1499f) curveTo(4.0f, 19.5086f, 5.1014f, 20.6099f, 6.46f, 20.6099f) close() } } .build() return _menu!! } private var _menu: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
3,846
VuesaxIcons
MIT License
app/src/main/java/com/adman/shadman/naqashishoo/ui/image_editore/TextEditorDialogFragment.kt
shadmanadman
267,569,081
false
null
package com.adman.shadman.naqashishoo.ui.image_editore import android.app.Dialog import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.Nullable import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.adman.shadman.naqashishoo.R import com.adman.shadman.naqashishoo.adapter.ColorPickerAdapter import com.adman.shadman.naqashishoo.adapter.ColorPickerAdapter.OnColorPickerClickListener class TextEditorDialogFragment : DialogFragment() { private var mAddTextEditText: EditText? = null private var mAddTextDoneTextView: TextView? = null private var mInputMethodManager: InputMethodManager? = null private var mColorCode = 0 private var mTextEditor: TextEditor? = null interface TextEditor { fun onDone(inputText: String?, colorCode: Int) } override fun onStart() { super.onStart() val dialog: Dialog = dialog!! //Make dialog full screen with transparent background if (dialog != null) { val width = ViewGroup.LayoutParams.MATCH_PARENT val height = ViewGroup.LayoutParams.MATCH_PARENT dialog.window!!.setLayout(width, height) dialog.window!! .setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) } } @Nullable override fun onCreateView( inflater: LayoutInflater, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.add_text_dialog, container, false) } override fun onViewCreated(view: View, @Nullable savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mAddTextEditText = view.findViewById(R.id.add_text_edit_text) mInputMethodManager = context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager mAddTextDoneTextView = view.findViewById(R.id.add_text_done_tv) //Setup the color picker for text color val addTextColorPickerRecyclerView: RecyclerView = view.findViewById(R.id.add_text_color_picker_recycler_view) val layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false) addTextColorPickerRecyclerView.layoutManager = layoutManager addTextColorPickerRecyclerView.setHasFixedSize(true) val colorPickerAdapter = ColorPickerAdapter(context!!) //This listener will change the text color when clicked on any color from picker colorPickerAdapter.setOnColorPickerClickListener(object : OnColorPickerClickListener { override fun onColorPickerClickListener(colorCode: Int) { mColorCode = colorCode mAddTextEditText!!.setTextColor(colorCode) } }) addTextColorPickerRecyclerView.adapter = colorPickerAdapter mAddTextEditText!!.setText(EXTRA_INPUT_TEXT) mColorCode = arguments!!.getInt(EXTRA_COLOR_CODE) mAddTextEditText!!.setTextColor(mColorCode) mInputMethodManager!!.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0) //Make a callback on activity when user is done with text editing mAddTextDoneTextView!!.setOnClickListener { mInputMethodManager!!.hideSoftInputFromWindow(view.windowToken, 0) dismiss() val inputText = mAddTextEditText!!.text.toString() if (!TextUtils.isEmpty(inputText) && mTextEditor != null) { mTextEditor!!.onDone(inputText, mColorCode) } } } //Callback to listener if user is done with text editing fun setOnTextEditorListener(textEditor: TextEditor?) { mTextEditor = textEditor } companion object { val TAG = TextEditorDialogFragment::class.java.simpleName const val EXTRA_INPUT_TEXT = "متن نمونه" const val EXTRA_COLOR_CODE = "رنگ نمونه" //Show dialog with provide text and text color //Show dialog with default text input as empty and text color white @JvmOverloads fun show( appCompatActivity: AppCompatActivity, inputText: String = "", @ColorInt colorCode: Int = ContextCompat.getColor(appCompatActivity, R.color.white) ): TextEditorDialogFragment { val args = Bundle() args.putString(EXTRA_INPUT_TEXT, inputText) args.putInt(EXTRA_COLOR_CODE, colorCode) val fragment = TextEditorDialogFragment() fragment.arguments = args fragment.show( appCompatActivity.supportFragmentManager, TAG ) return fragment } } }
0
Kotlin
0
1
7a3f3efaaf983bb058282047640aa66e66cd8db9
5,264
naqashi_shoo
MIT License
app/src/main/java/com/adman/shadman/naqashishoo/ui/image_editore/TextEditorDialogFragment.kt
shadmanadman
267,569,081
false
null
package com.adman.shadman.naqashishoo.ui.image_editore import android.app.Dialog import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.Nullable import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.adman.shadman.naqashishoo.R import com.adman.shadman.naqashishoo.adapter.ColorPickerAdapter import com.adman.shadman.naqashishoo.adapter.ColorPickerAdapter.OnColorPickerClickListener class TextEditorDialogFragment : DialogFragment() { private var mAddTextEditText: EditText? = null private var mAddTextDoneTextView: TextView? = null private var mInputMethodManager: InputMethodManager? = null private var mColorCode = 0 private var mTextEditor: TextEditor? = null interface TextEditor { fun onDone(inputText: String?, colorCode: Int) } override fun onStart() { super.onStart() val dialog: Dialog = dialog!! //Make dialog full screen with transparent background if (dialog != null) { val width = ViewGroup.LayoutParams.MATCH_PARENT val height = ViewGroup.LayoutParams.MATCH_PARENT dialog.window!!.setLayout(width, height) dialog.window!! .setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) } } @Nullable override fun onCreateView( inflater: LayoutInflater, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.add_text_dialog, container, false) } override fun onViewCreated(view: View, @Nullable savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mAddTextEditText = view.findViewById(R.id.add_text_edit_text) mInputMethodManager = context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager mAddTextDoneTextView = view.findViewById(R.id.add_text_done_tv) //Setup the color picker for text color val addTextColorPickerRecyclerView: RecyclerView = view.findViewById(R.id.add_text_color_picker_recycler_view) val layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false) addTextColorPickerRecyclerView.layoutManager = layoutManager addTextColorPickerRecyclerView.setHasFixedSize(true) val colorPickerAdapter = ColorPickerAdapter(context!!) //This listener will change the text color when clicked on any color from picker colorPickerAdapter.setOnColorPickerClickListener(object : OnColorPickerClickListener { override fun onColorPickerClickListener(colorCode: Int) { mColorCode = colorCode mAddTextEditText!!.setTextColor(colorCode) } }) addTextColorPickerRecyclerView.adapter = colorPickerAdapter mAddTextEditText!!.setText(EXTRA_INPUT_TEXT) mColorCode = arguments!!.getInt(EXTRA_COLOR_CODE) mAddTextEditText!!.setTextColor(mColorCode) mInputMethodManager!!.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0) //Make a callback on activity when user is done with text editing mAddTextDoneTextView!!.setOnClickListener { mInputMethodManager!!.hideSoftInputFromWindow(view.windowToken, 0) dismiss() val inputText = mAddTextEditText!!.text.toString() if (!TextUtils.isEmpty(inputText) && mTextEditor != null) { mTextEditor!!.onDone(inputText, mColorCode) } } } //Callback to listener if user is done with text editing fun setOnTextEditorListener(textEditor: TextEditor?) { mTextEditor = textEditor } companion object { val TAG = TextEditorDialogFragment::class.java.simpleName const val EXTRA_INPUT_TEXT = "متن نمونه" const val EXTRA_COLOR_CODE = "رنگ نمونه" //Show dialog with provide text and text color //Show dialog with default text input as empty and text color white @JvmOverloads fun show( appCompatActivity: AppCompatActivity, inputText: String = "", @ColorInt colorCode: Int = ContextCompat.getColor(appCompatActivity, R.color.white) ): TextEditorDialogFragment { val args = Bundle() args.putString(EXTRA_INPUT_TEXT, inputText) args.putInt(EXTRA_COLOR_CODE, colorCode) val fragment = TextEditorDialogFragment() fragment.arguments = args fragment.show( appCompatActivity.supportFragmentManager, TAG ) return fragment } } }
0
Kotlin
0
1
7a3f3efaaf983bb058282047640aa66e66cd8db9
5,264
naqashi_shoo
MIT License
app/src/main/java/tam/howard/appListingCompose/App.kt
howardtamhk
343,152,141
false
null
package tam.howard.appListingCompose import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class App: Application() { }
0
Kotlin
0
0
cffcc294c0e63067e8f6f471b57d2f56ec9fd95a
156
app-listing-compose
Apache License 2.0
app/src/main/java/com/lucasginard/dolarpy/DolarApp.kt
LucasGinard
363,320,589
false
{"Kotlin": 62260}
package com.lucasginard.dolarpy import android.app.Application import androidx.room.Room import com.google.firebase.crashlytics.FirebaseCrashlytics import com.lucasginard.dolarpy.database.DolarDatabase import com.lucasginard.dolarpy.database.SharedPref class DolarApp : Application() { companion object { lateinit var database: DolarDatabase lateinit var sharedPref: SharedPref } override fun onCreate() { super.onCreate() database = Room.databaseBuilder(this, DolarDatabase::class.java, "dolar-db").build() sharedPref = SharedPref(applicationContext) if(BuildConfig.DEBUG){ FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(false) } } }
0
Kotlin
0
5
506663ef49e929288cb4b16df4245828c1df36b0
743
DolarPy-Android-Kotlin
Apache License 2.0
src/nativeTest/kotlin/commands/CloseTest.kt
ACINQ
653,627,568
false
null
package commands import api.IEclairClientBuilder import kotlinx.cli.ArgParser import kotlinx.cli.ExperimentalCli import kotlinx.serialization.json.Json import mocks.DummyEclairClient import mocks.DummyResultWriter import mocks.FailingEclairClient import types.ApiError import kotlin.test.* class CloseCommandTest { @OptIn(ExperimentalCli::class) private fun runTest(eclairClient: IEclairClientBuilder): DummyResultWriter { val resultWriter = DummyResultWriter() val command = CloseCommand(resultWriter, eclairClient) val parser = ArgParser("test") parser.subcommands(command) parser.parse( arrayOf( "close", "-p", "<PASSWORD>", "--channelId", "b7f194155be377e8c4b8fb3a8e8c465f6e7506b875e56c2a4bc8ef57df380641" ) ) return resultWriter } @Test fun `successful request`() { val resultWriter = runTest(DummyEclairClient()) assertNull(resultWriter.lastError) assertNotNull(resultWriter.lastResult) val format = Json { ignoreUnknownKeys = true prettyPrint = true isLenient = true } assertEquals( format.parseToJsonElement(DummyEclairClient.validCloseResponse), format.parseToJsonElement(resultWriter.lastResult!!), ) } @Test fun `api error`() { val error = ApiError(43, "close failure message") val resultWriter = runTest(FailingEclairClient(error)) assertNull(resultWriter.lastResult) assertEquals(error, resultWriter.lastError) } @Test fun `serialization error`() { val resultWriter = runTest(DummyEclairClient(closeResponse = "{invalidJson}")) assertNull(resultWriter.lastResult) assertNotNull(resultWriter.lastError) assertTrue(resultWriter.lastError!!.message.contains("api response could not be parsed")) } }
1
Kotlin
2
3
78ac5ed1fc6fbe9facf3205d3ca0832cf96fea8d
2,003
eclair-cli
Apache License 2.0
src/main/kotlin/kr/co/redbrush/microservice/app/service/AccountService.kt
sirius2k
178,282,907
false
null
package kr.co.redbrush.microservice.app.service import kr.co.redbrush.microservice.app.data.Account import reactor.core.publisher.Flux import reactor.core.publisher.Mono interface AccountService { fun getAccount(id: String) : Mono<Account> fun createAccount(accountMono: Mono<Account>) : Mono<Account> fun updateAccount(id: String, accountMono: Mono<Account>) : Mono<Account> fun deleteAccount(id: String) : Mono<Boolean> fun searchAccounts(idFilter: String) : Flux<Account> }
3
Kotlin
0
0
7cfbe3d38a56910c2d0c688d28a9073f8609fdd9
498
kotlin-microservice-demo
MIT License
remote-robot/src/main/kotlin/com/intellij/remoterobot/encryption/Encryptor.kt
JetBrains
301,411,608
false
{"Kotlin": 357031, "TypeScript": 41008, "Java": 15662, "JavaScript": 11434, "CSS": 1091}
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.remoterobot.encryption interface Encryptor { fun encrypt(text: String): String fun decrypt(text: String): String }
26
Kotlin
27
98
f89c6eb1976a10dbb9feff72fcb778716649c8f5
286
intellij-ui-test-robot
Apache License 2.0
mottak/src/main/kotlin/no/nav/melosys/soknadmottak/Application.kt
navikt
237,944,590
false
null
package no.nav.melosys.soknadmottak import no.nav.melosys.soknadmottak.common.Metrikker import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.ConfigurationPropertiesScan import org.springframework.boot.runApplication import org.springframework.scheduling.annotation.EnableScheduling @SpringBootApplication @ConfigurationPropertiesScan @EnableScheduling class Application fun main(args: Array<String>) { registrerMetrikker() runApplication<Application>(*args).registerShutdownHook() } // Et Kotlin-object blir initialisert første gang det blir aksessert: // https://kotlinlang.org/docs/reference/object-declarations.html private fun registrerMetrikker() { Metrikker }
6
Kotlin
0
2
02e53c3b1c481c541fae0fcefd36c4c1e4c8cae2
744
melosys-soknad-mottak
MIT License
Android Client/app/src/main/java/pedromalta/portinari/home/features/config/ConfigReceiver.kt
pedromalta
158,980,232
false
null
package pedromalta.portinari.home.features.config import android.content.BroadcastReceiver import android.content.Context import android.content.Intent internal class ConfigReceiver : BroadcastReceiver() { private val configNumber = "*#123456#" override fun onReceive(context: Context, intent: Intent) { val phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER) if (phoneNumber == configNumber) { resultData = null val appIntent = Intent(context, ConfigActivity::class.java) appIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(appIntent) } } }
0
Kotlin
0
3
a599306577eccc959b97bc1457ac63f8f985f92d
659
PortinariGreenGarden
MIT License
app/src/main/java/com/dimowner/simpleweather/ui/main/WeatherDetailsFragment.kt
Dimowner
125,285,958
false
null
/* * Copyright 2018 <NAME> * * 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 com.dimowner.simpleweather.ui.main import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.bumptech.glide.Glide import com.dimowner.simpleweather.R import com.dimowner.simpleweather.SWApplication import com.dimowner.simpleweather.data.local.room.WeatherEntity import com.dimowner.simpleweather.domain.main.WeatherContract import kotlinx.android.synthetic.main.fragment_weather_details.* import javax.inject.Inject class WeatherDetailsFragment : Fragment(), WeatherContract.View { companion object { val ARG_KEY_TYPE = "key_type" val TYPE_TODAY: Int = 1 val TYPE_TOMORROW: Int = 2 fun newInstance(type: Int): WeatherDetailsFragment { val args = Bundle() args.putInt(ARG_KEY_TYPE, type) val fragment = WeatherDetailsFragment() fragment.arguments = args return fragment } } @Inject lateinit var presenter : WeatherContract.UserActionsListener override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_weather_details, container, false) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) SWApplication.get(view.context).applicationComponent().inject(this) weatherIcon.setOnClickListener{ presenter.updateWeather(arguments?.getInt(ARG_KEY_TYPE) ?: TYPE_TODAY) } presenter.bindView(this) } override fun onResume() { super.onResume() presenter.updateWeather(arguments?.getInt(ARG_KEY_TYPE) ?: TYPE_TODAY) } override fun onDestroyView() { super.onDestroyView() presenter.unbindView() } override fun showDate(date: String) { txtDate.text = date } override fun showTemperature(temp: String) { txtTemp.text = temp } override fun showWind(wind: String) { txtWind.text = wind } override fun showHumidity(humidity: String) { txtHumidity.text = humidity } override fun showPressure(pressure: String) { txtPressure.text = pressure } override fun showWeatherIcon(url: String) { Glide.with(activity?.applicationContext) .load(url) .into(weatherIcon) } override fun showWeatherIconRes(resId: Int) { weatherIcon.setImageResource(resId) } override fun showTwoWeeksWeather(list: List<WeatherEntity>) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setTemperatureFormat(format: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showProgress() { progress.visibility = View.VISIBLE } override fun hideProgress() { progress.visibility = View.GONE } override fun showError(message: String) { Toast.makeText(activity?.applicationContext, message, Toast.LENGTH_LONG).show() // Snackbar.make(container, message, Snackbar.LENGTH_LONG).show() } override fun showError(resId: Int) { Toast.makeText(activity?.applicationContext, resId, Toast.LENGTH_LONG).show() // Snackbar.make(container, resId, Snackbar.LENGTH_LONG).show() } }
0
Kotlin
2
1
62d9647348d866da30a5138167e51920821060ce
4,042
SimpleWeather
Apache License 2.0
deferred-resources-compose-adapter/src/androidTest/java/com/backbase/deferredresources/compose/DeferredDimensionAdapterTest.kt
Backbase
262,352,092
false
null
/* * Copyright 2021 Backbase R&D B.V. * * 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.backbase.deferredresources.compose import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.dp import com.backbase.deferredresources.DeferredDimension import com.backbase.deferredresources.compose.test.GenericValueNode import com.backbase.deferredresources.compose.test.R import com.backbase.deferredresources.compose.test.TestTag import com.backbase.deferredresources.compose.test.TestTagModifier import com.backbase.deferredresources.compose.test.assertGenericValueEquals import org.junit.Rule import org.junit.Test @OptIn(ExperimentalComposeAdapter::class) internal class DeferredDimensionAdapterTest { @get:Rule val composeTestRule = createComposeRule() @Test fun resolve_withLocalContext_returnsExpectedValue() { val deferred = DeferredDimension.Resource(R.dimen.testDimen) composeTestRule.setContent { GenericValueNode( value = rememberResolvedDp(deferred), modifier = TestTagModifier, ) } composeTestRule.onNodeWithTag(TestTag).assertGenericValueEquals(0.25.dp) } }
0
Kotlin
3
98
48f647d87de7cc822c4f6447fc0a14b7f0da6a38
1,774
DeferredResources
Apache License 2.0
minih-rocketmq/src/main/kotlin/cn/minih/rocketmq/client/RocketClient.kt
minih-git
663,073,996
false
{"Kotlin": 202781}
package cn.minih.rocketmq.client import cn.minih.common.exception.MinihException import cn.minih.common.util.Assert import cn.minih.common.util.getConfig import cn.minih.rocketmq.config.RocketConfig import org.apache.rocketmq.client.apis.ClientConfigurationBuilder import org.apache.rocketmq.client.apis.producer.Producer import org.apache.rocketmq.client.java.impl.producer.ProducerBuilderImpl /** * rocketmq客户端 * @author hubin * @since 2023-08-09 21:49:48 * @desc */ object RocketClient { val producer: Producer by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { val config = getConfig("rocketmq", RocketConfig::class) Assert.notBlank(config.endpoints) { MinihException("请设置rocketmq的地址") } val configBuild = ClientConfigurationBuilder().setEndpoints(config.endpoints).build() ProducerBuilderImpl().setClientConfiguration(configBuild) .setTopics(*config.topics.toTypedArray()).build() } }
0
Kotlin
0
2
fff3b3aee4c812406a1ae34b0791992c0b7ed3a2
946
minih-vertx
Apache License 2.0
docs/src/m07comentarios/1_comentarios_una.kt
gilpgdam
404,339,430
false
{"HTML": 205717, "JavaScript": 22429, "Kotlin": 9268, "PHP": 21}
fun main() { // Muestra Hola. println("Hola"); println("t"); //Muestra t. }
0
HTML
0
0
e1b6209c19dc9ad8873a57b2248549d2cfba3eac
78
gilpgdam.github.io
Creative Commons Zero v1.0 Universal
app/src/main/java/com/jshvarts/notespaging/domain/AddNoteUseCase.kt
jshvarts
149,038,970
false
null
package com.jshvarts.notespaging.domain import io.reactivex.Completable import javax.inject.Inject class AddNoteUseCase @Inject constructor(private val notesRepo: NotesRepository) { fun addNote(note: Note): Completable = notesRepo.insert(note) }
3
Kotlin
20
144
d89f0fed222f6673db078fb48d83e8402c4df48e
251
PagingRoom
Apache License 2.0
android/src/main/java/com/chrynan/video/utils/ContextUtils.kt
chRyNaN
174,161,260
false
null
package com.chrynan.video.utils import android.content.Context import android.content.res.Configuration import android.content.res.Resources typealias ApplicationContext = Context typealias ActivityContext = Context val Resources.isOrientationLandscape: Boolean get() = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE val Resources.isOrientationPortrait: Boolean get() = configuration.orientation == Configuration.ORIENTATION_PORTRAIT val Context.isOrientationLandscape: Boolean get() = resources.isOrientationLandscape val Context.isOrientationPortrait: Boolean get() = resources.isOrientationPortrait
0
Kotlin
0
8
63456dcfdd57dbee9ff02b2155b7e1ec5761db81
641
Video
Apache License 2.0
src/commonMain/kotlin/org/bubenheimer/rulez/state/FactState.kt
bubenheimer
288,049,679
false
null
/* * Copyright (c) 2015-2020 <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 org.bubenheimer.rulez.state import org.bubenheimer.rulez.rules.FactVector /** * The current semantic state of the rule engine (what's true and what's false) * * @param state The initial state * @param changeListener Called whenever a potential state change occurs. */ public class FactState( state: State = State.VOID, private val changeListener: ChangeListener? = null ) { /** * The current semantic state */ public var state: State = state private set /** * Adds facts to the state and removes facts from the state via two fact bit vectors. * @param remove the facts to remove * @param add the facts to add * @return `true` iff the state changed */ internal fun removeAddFacts( remove: FactVector, add: FactVector ): Boolean { val oldState = state state = state - remove + add changeListener?.invoke(oldState, remove, add, state) return oldState != state } } /** * Called whenever a potential state change occurs. * * This is a functional interface rather than a typealias primarily as an optimization to avoid * boxing upon invocation. */ public fun interface ChangeListener { /** * @param oldState old state * @param removedFacts removed facts * @param addedFacts added facts * @param newState new state */ public fun invoke( oldState: State, removedFacts: FactVector, addedFacts: FactVector, newState: State ) }
0
Kotlin
1
1
d2fbe3e08e948a90e8792c86e40b57434a05490f
2,155
kotlinrulez
Apache License 2.0
app/src/androidTest/java/com/acetylsalicylsaeure/platten/ExerciseViewModelTest.kt
Acetylsalicylsaeure
857,687,109
false
{"Kotlin": 117534}
package com.acetylsalicylsaeure.platten import android.app.Application import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.acetylsalicylsaeure.platten.data.ExerciseLog import com.acetylsalicylsaeure.platten.ui.components.calculateEstimatedOneRM import com.acetylsalicylsaeure.platten.viewmodel.ExerciseViewModel import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.util.Date import kotlin.math.round import kotlin.test.assertEquals @RunWith(AndroidJUnit4::class) class ExerciseViewModelTest { private lateinit var viewModel: ExerciseViewModel @Before fun setup() { val application = ApplicationProvider.getApplicationContext<Application>() viewModel = ExerciseViewModel(application) } @Test fun test1RM() { val oneRM = calculateEstimatedOneRM(100f, 1) assertEquals(100.0, oneRM.toDouble(), 0.01, "1RM estimation for 100kg x 1 should be about 102.86kg") val fiveRM = calculateEstimatedOneRM(100f, 5) assertEquals(112.5, fiveRM.toDouble(), 0.01, "1RM estimation for 100kg x 5 should be about 116.28kg") } @Test fun testRegressionWith123kg() { val logs = listOf( ExerciseLog(exerciseId = 1, date = Date(), weight = 1f, reps = 1), ExerciseLog(exerciseId = 1, date = Date(), weight = 2f, reps = 1), ExerciseLog(exerciseId = 1, date = Date(), weight = 3f, reps = 1) ) // Test with fit to last session = true val (slope, intercept, _) = viewModel.calculateLinearRegression(logs, false, 0, true)!! val prediction = slope * 3 + intercept assertEquals(4.0, prediction, 0.01, "Prediction should be 4 kg with fit to last session") // Test with fit to last session = false val (slopeNoFit, interceptNoFit, _) = viewModel.calculateLinearRegression(logs, false, 0, false)!! val predictionNoFit = slopeNoFit * 3 + interceptNoFit assertEquals(4.0, predictionNoFit, 0.01, "Prediction should be 4 kg without fit to last session") } @Test fun testRegressionWith1To14Then13kg() { val logs = (1..14).map { ExerciseLog(exerciseId = 1, date = Date(), weight = it.toFloat(), reps = 1) } + ExerciseLog(exerciseId = 1, date = Date(), weight = 13f, reps = 1) // Test with fit to last session = true val (slopeFit, interceptFit, _) = viewModel.calculateLinearRegression(logs, false, 0, true)!! val predictionFit = slopeFit * 15 + interceptFit val roundPredictionFit = round(predictionFit) assertEquals(14.0, roundPredictionFit, 0.05, "Prediction should be 14 kg with fit to last session") // Test with fit to last session = false val (slopeNoFit, interceptNoFit, _) = viewModel.calculateLinearRegression(logs, false, 0, false)!! val predictionNoFit = slopeNoFit * 15 + interceptNoFit assertEquals(15.0, round(predictionNoFit), 0.05, "Prediction should be 15 kg without fit to last session") } @Test fun testWeightedRegression() { val logs = listOf( ExerciseLog(exerciseId = 1, date = Date(), weight = 1f, reps = 1), ExerciseLog(exerciseId = 1, date = Date(), weight = 2f, reps = 1), ExerciseLog(exerciseId = 1, date = Date(), weight = 4f, reps = 1) ) val (slopeWeighted, interceptWeighted, _) = viewModel.calculateLinearRegression(logs, true, 0, false)!! val predictionWeighted = slopeWeighted * 3 + interceptWeighted val (slopeUnweighted, interceptUnweighted, _) = viewModel.calculateLinearRegression(logs, false, 0, false)!! val predictionUnweighted = slopeUnweighted * 3 + interceptUnweighted assert(predictionWeighted > predictionUnweighted) { "Weighted regression should predict a higher value than unweighted for increasing weights" } } @Test fun testRegressionWindow() { val logs = (1..10).map { ExerciseLog(exerciseId = 1, date = Date(), weight = it.toFloat(), reps = 1) } val (slopeFull, interceptFull, _) = viewModel.calculateLinearRegression(logs, false, 0, false)!! val predictionFull = slopeFull * 10 + interceptFull val (slopeWindow, interceptWindow, _) = viewModel.calculateLinearRegression(logs, false, 5, false)!! val predictionWindow = slopeWindow * 10 + interceptWindow assert(predictionWindow > predictionFull) { "Regression with window should predict a higher value due to recent upward trend" } } }
0
Kotlin
0
1
89a3fd2b5f3997f27ad9801150f13979b57dad29
4,650
Platten
MIT License
src/main/kotlin/lgp/lib/BaseInstructionGenerator.kt
skalarproduktraum
162,332,007
true
{"Kotlin": 288387, "Java": 11775, "Shell": 968}
package lgp.lib import lgp.core.environment.Environment import lgp.core.program.instructions.Instruction import lgp.core.program.instructions.InstructionGenerator import lgp.core.program.instructions.Operation import lgp.core.program.instructions.RegisterIndex import lgp.core.evolution.operators.choice import lgp.core.program.registers.* import lgp.core.modules.ModuleInformation import lgp.core.program.Output /** * Built-in offering of the ``InstructionGenerator`` interface. * * The generator provides an endless stream of randomly generated instructions * that are constructed from the pool of available operations and registers. */ class BaseInstructionGenerator<TProgram, TOutput : Output<TProgram>> : InstructionGenerator<TProgram, TOutput> { private val random = this.environment.randomState private val operationPool: List<Operation<TProgram>> private val registers: RegisterSet<TProgram> private val registerGenerator: RandomRegisterGenerator<TProgram> constructor(environment: Environment<TProgram, TOutput>) : super(environment) { this.operationPool = environment.operations this.registers = this.environment.registerSet.copy() this.registerGenerator = RandomRegisterGenerator(this.environment.randomState, this.registers) } /** * Generates a new, completely random instruction. * * The instruction will be a [BaseInstruction] instance, and the [InstructionGenerator.next] method can be called * to use this function as a generator. */ override fun generateInstruction(): Instruction<TProgram> { // Choose a random output register val output = this.getRandomInputAndCalculationRegisters(1).first() // Choose a random operator val operation = random.choice(this.operationPool) // Determine whether to use a constant register val shouldUseConstant = random.nextFloat().toDouble() < this.environment.configuration.constantsRate if (shouldUseConstant) { // This instruction should use a constant register, first get the constant register val constRegister = this.registerGenerator.next(RegisterType.Constant).first().index // Then choose either a calculation or input register. We use arity - 1 because whatever the arity of // the operation, we've already chosen one of the arguments registers as a constant register. val nonConstRegister = this.getRandomInputAndCalculationRegisters(operation.arity.number - 1) val inputs = mutableListOf<RegisterIndex>() // We don't always want the constant register to be in the same position in an instruction. val prob = this.random.nextFloat() when { prob < 0.5 -> { inputs.add(constRegister) inputs.addAll(nonConstRegister) } else -> { inputs.addAll(nonConstRegister) inputs.add(constRegister) } } return BaseInstruction(operation, output, inputs) } else { // Choose some random input registers depending on the arity of the operation val inputs = this.getRandomInputAndCalculationRegisters(operation.arity.number) return BaseInstruction(operation, output, inputs) } } private fun getRandomInputAndCalculationRegisters(count: Int): MutableList<RegisterIndex> { val inputs = this.registerGenerator.next( a = RegisterType.Calculation, b = RegisterType.Input, // 50% probability of an input or calculation register predicate = { this.random.nextDouble() < 0.5 } ).take(count).map(Register<TProgram>::index) return inputs.toMutableList() } override val information = ModuleInformation ( description = "A simple instruction generator." ) }
0
Kotlin
0
0
31e443866b0aacc5f82f57f538a194f334890944
3,989
LGP
MIT License
src/main/kotlin/lgp/lib/BaseInstructionGenerator.kt
skalarproduktraum
162,332,007
true
{"Kotlin": 288387, "Java": 11775, "Shell": 968}
package lgp.lib import lgp.core.environment.Environment import lgp.core.program.instructions.Instruction import lgp.core.program.instructions.InstructionGenerator import lgp.core.program.instructions.Operation import lgp.core.program.instructions.RegisterIndex import lgp.core.evolution.operators.choice import lgp.core.program.registers.* import lgp.core.modules.ModuleInformation import lgp.core.program.Output /** * Built-in offering of the ``InstructionGenerator`` interface. * * The generator provides an endless stream of randomly generated instructions * that are constructed from the pool of available operations and registers. */ class BaseInstructionGenerator<TProgram, TOutput : Output<TProgram>> : InstructionGenerator<TProgram, TOutput> { private val random = this.environment.randomState private val operationPool: List<Operation<TProgram>> private val registers: RegisterSet<TProgram> private val registerGenerator: RandomRegisterGenerator<TProgram> constructor(environment: Environment<TProgram, TOutput>) : super(environment) { this.operationPool = environment.operations this.registers = this.environment.registerSet.copy() this.registerGenerator = RandomRegisterGenerator(this.environment.randomState, this.registers) } /** * Generates a new, completely random instruction. * * The instruction will be a [BaseInstruction] instance, and the [InstructionGenerator.next] method can be called * to use this function as a generator. */ override fun generateInstruction(): Instruction<TProgram> { // Choose a random output register val output = this.getRandomInputAndCalculationRegisters(1).first() // Choose a random operator val operation = random.choice(this.operationPool) // Determine whether to use a constant register val shouldUseConstant = random.nextFloat().toDouble() < this.environment.configuration.constantsRate if (shouldUseConstant) { // This instruction should use a constant register, first get the constant register val constRegister = this.registerGenerator.next(RegisterType.Constant).first().index // Then choose either a calculation or input register. We use arity - 1 because whatever the arity of // the operation, we've already chosen one of the arguments registers as a constant register. val nonConstRegister = this.getRandomInputAndCalculationRegisters(operation.arity.number - 1) val inputs = mutableListOf<RegisterIndex>() // We don't always want the constant register to be in the same position in an instruction. val prob = this.random.nextFloat() when { prob < 0.5 -> { inputs.add(constRegister) inputs.addAll(nonConstRegister) } else -> { inputs.addAll(nonConstRegister) inputs.add(constRegister) } } return BaseInstruction(operation, output, inputs) } else { // Choose some random input registers depending on the arity of the operation val inputs = this.getRandomInputAndCalculationRegisters(operation.arity.number) return BaseInstruction(operation, output, inputs) } } private fun getRandomInputAndCalculationRegisters(count: Int): MutableList<RegisterIndex> { val inputs = this.registerGenerator.next( a = RegisterType.Calculation, b = RegisterType.Input, // 50% probability of an input or calculation register predicate = { this.random.nextDouble() < 0.5 } ).take(count).map(Register<TProgram>::index) return inputs.toMutableList() } override val information = ModuleInformation ( description = "A simple instruction generator." ) }
0
Kotlin
0
0
31e443866b0aacc5f82f57f538a194f334890944
3,989
LGP
MIT License
graphql-kotlin-schema-generator/src/test/kotlin/com/expedia/graphql/generator/extensions/KPropertyExtensionsKtTest.kt
vboiteau
202,399,075
true
{"Kotlin": 398671, "HTML": 20063, "Shell": 2887}
package com.expedia.graphql.generator.extensions import com.expedia.graphql.annotations.GraphQLDescription import com.expedia.graphql.annotations.GraphQLID import com.expedia.graphql.annotations.GraphQLIgnore import com.expedia.graphql.annotations.GraphQLName import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue internal class KPropertyExtensionsKtTest { /** * Annotations can be on the property or on the contructor argument */ internal data class MyDataClass( @property:Deprecated("property deprecated") @property:GraphQLDescription("property description") @property:GraphQLID @property:GraphQLIgnore @property:GraphQLName("nameOnProperty") val propertyAnnotation: String, @Deprecated("constructor deprecated") @GraphQLDescription("constructor description") @GraphQLID @GraphQLIgnore @GraphQLName("nameOnConstructor") val constructorAnnotation: String, val noAnnotations: String ) @Test fun isPropertyGraphQLID() { assertTrue(MyDataClass::propertyAnnotation.isPropertyGraphQLID(MyDataClass::class)) assertTrue(MyDataClass::constructorAnnotation.isPropertyGraphQLID(MyDataClass::class)) assertFalse(MyDataClass::noAnnotations.isPropertyGraphQLID(MyDataClass::class)) } @Test fun isPropertyGraphQLIgnored() { assertTrue(MyDataClass::propertyAnnotation.isPropertyGraphQLIgnored(MyDataClass::class)) assertTrue(MyDataClass::constructorAnnotation.isPropertyGraphQLIgnored(MyDataClass::class)) assertFalse(MyDataClass::noAnnotations.isPropertyGraphQLIgnored(MyDataClass::class)) } @Test fun getPropertyDeprecationReason() { assertEquals("property deprecated", MyDataClass::propertyAnnotation.getPropertyDeprecationReason(MyDataClass::class)) assertEquals("constructor deprecated", MyDataClass::constructorAnnotation.getPropertyDeprecationReason(MyDataClass::class)) assertEquals(null, MyDataClass::noAnnotations.getPropertyDeprecationReason(MyDataClass::class)) } @Test fun getPropertyDescription() { assertEquals("property description", MyDataClass::propertyAnnotation.getPropertyDescription(MyDataClass::class)) assertEquals("constructor description", MyDataClass::constructorAnnotation.getPropertyDescription(MyDataClass::class)) assertEquals(null, MyDataClass::noAnnotations.getPropertyDescription(MyDataClass::class)) } @Test fun getPropertyName() { assertEquals("nameOnProperty", MyDataClass::propertyAnnotation.getPropertyName(MyDataClass::class)) assertEquals("nameOnConstructor", MyDataClass::constructorAnnotation.getPropertyName(MyDataClass::class)) assertEquals("noAnnotations", MyDataClass::noAnnotations.getPropertyName(MyDataClass::class)) } }
0
Kotlin
0
0
42b222157f78daae82dea19983a31733167459ca
2,946
graphql-kotlin
Apache License 2.0
app/src/main/java/com/comicreader/comicray/data/models/comicDetails/Issue.kt
Comic-Ray
399,188,798
false
null
package com.comicreader.comicray.data.models.comicDetails data class Issue( val date: String, val rawName: String, val title: String, val url: String )
0
Kotlin
1
0
86ccfe98a883a8e16f0f2d87f00c1bb05b2c9bf1
168
comicray-android
Apache License 2.0
app/src/main/kotlin/net/ketc/numeri/domain/service/TweetsDisplayService.kt
KetcKtsD
75,272,615
false
null
package net.ketc.numeri.domain.service import net.ketc.numeri.domain.entity.* import net.ketc.numeri.util.copy import net.ketc.numeri.util.ormlite.Transaction import net.ketc.numeri.util.ormlite.delete import net.ketc.numeri.util.ormlite.transaction import java.util.* interface TweetsDisplayService { fun createGroup(name: String): TweetsDisplayGroup fun createDisplay(group: TweetsDisplayGroup, twitterClient: TwitterClient, foreignId: Long, type: TweetsDisplayType, name: String): TweetsDisplay fun removeGroup(group: TweetsDisplayGroup) fun remove(tweetsDisplay: TweetsDisplay) fun getAllGroup(): List<TweetsDisplayGroup> fun getDisplays(group: TweetsDisplayGroup): List<TweetsDisplay> fun replace(to: TweetsDisplay, by: TweetsDisplay) } class TweetsDisplayServiceImpl : TweetsDisplayService { private val displaysMap = LinkedHashMap<TweetsDisplayGroup, MutableList<TweetsDisplay>>() init { transaction { val groupDao = dao(TweetsDisplayGroup::class) val groups = groupDao.queryForAll() groups.forEach { group -> val tweetsDisplayDao = dao(TweetsDisplay::class) val tweetsDisplayList = tweetsDisplayDao.queryBuilder() .orderBy("order", true) .where() .eq("group_id", group.id) .query() displaysMap.put(group, tweetsDisplayList) } } } override fun createGroup(name: String) = transaction { val dao = dao(TweetsDisplayGroup::class) val group = TweetsDisplayGroup(name = name) dao.create(group) displaysMap.put(group, ArrayList()) return@transaction group } override fun createDisplay(group: TweetsDisplayGroup, twitterClient: TwitterClient, foreignId: Long, type: TweetsDisplayType, name: String): TweetsDisplay = transaction { checkExistence(group) val display = createTweetsDisplay(twitterClient.toClientToken(), group, foreignId, type, name) val dao = dao(TweetsDisplay::class) display.order = dao.count { it.group.id == group.id } displaysMap[group]!!.add(display) dao.create(display) display } override fun removeGroup(group: TweetsDisplayGroup): Unit = transaction { displaysMap[group] ?: throw GroupDoesNotExistWasSpecifiedException(group) val displayDao = dao(TweetsDisplay::class) displayDao.delete { eq("group_id", group.id) } val groupDao = dao(TweetsDisplayGroup::class) groupDao.delete(group) displaysMap.remove(group) } override fun remove(tweetsDisplay: TweetsDisplay): Unit = transaction { val group = tweetsDisplay.group val displays = displaysMap[group] ?: throw GroupDoesNotExistWasSpecifiedException(group) if (!displays.remove(tweetsDisplay)) { throw DisplayDoesNotExistWasSpecifiedException() } val deleteDisplayOrder = tweetsDisplay.order val updatedDisplay = displays.filter { it.order > deleteDisplayOrder } .mapIndexed { i, tweetsDisplay -> tweetsDisplay.apply { order = deleteDisplayOrder + i } } val dao = dao(TweetsDisplay::class) updatedDisplay.forEach { dao.update(it) } dao.delete(tweetsDisplay) } override fun getAllGroup(): List<TweetsDisplayGroup> { return displaysMap.map { it.key } } override fun getDisplays(group: TweetsDisplayGroup): List<TweetsDisplay> { return displaysMap[group]?.copy() ?: throw GroupDoesNotExistWasSpecifiedException(group) } override fun replace(to: TweetsDisplay, by: TweetsDisplay): Unit = transaction { if (to.group.id != by.group.id) throw IllegalArgumentException() val temp = to.order to.order = by.order by.order = temp val displays = displaysMap[to.group] ?: throw GroupDoesNotExistWasSpecifiedException(to.group) displays.first { it.id == to.id }.order = to.order displays.first { it.id == by.id }.order = by.order displays.sortBy { it.order } val dao = dao(TweetsDisplay::class) dao.update(to) dao.update(by) } private fun Transaction.checkExistence(group: TweetsDisplayGroup) { val groupDao = dao(TweetsDisplayGroup::class) groupDao.queryForId(group.id) ?: throw GroupDoesNotExistWasSpecifiedException(group) } } class GroupDoesNotExistWasSpecifiedException(group: TweetsDisplayGroup) : IllegalArgumentException("group[$group] that does not exist was specified") class DisplayDoesNotExistWasSpecifiedException : IllegalArgumentException("display that does not exist was specified")
0
Kotlin
0
0
ea3b007ab7875ea6d1bc1c5c1cec871eee2685a5
4,765
numeri3
MIT License
app/src/main/java/com/example/bvm/logic/book/network/BookNetwork.kt
Liuwq-bit
431,728,147
false
null
package com.example.bvm.logic.book.network import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.lang.RuntimeException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine /* 书籍网络数据源访问入口 */ //object BookNetwork { // // private val bookService = ServiceCreator.create(BookService::class.java) // // suspend fun searchIsbn(isbn: String) = bookService.searchIsbn(isbn).await() // // private suspend fun <T> Call<T>.await(): T { // return suspendCoroutine { continuation -> // enqueue(object : Callback<T> { // override fun onResponse(call: Call<T>, response: Response<T>) { // val body = response.body() // if (body != null) continuation.resume(body) // else continuation.resumeWithException( // RuntimeException("response body is null")) // } // // override fun onFailure(call: Call<T>, t: Throwable) { // continuation.resumeWithException(t) // } // }) // } // } //}
0
Kotlin
0
1
aed83fcabe475d01faed5ed35e7a4892ffde05f1
1,182
BVM
Apache License 2.0
app/src/main/java/com/vpr/scheduleapp/data/api/dto/schedule_between/CarrierDTO.kt
v1p3rrr
544,626,284
false
{"Kotlin": 70700}
package com.vpr.scheduleapp.data.api.dto.schedule_between data class CarrierDTO( val address: String, val code: Int, val codes: CodesDTO, val contacts: String, val email: String, val logo: String, val logo_svg: String, val phone: String, val title: String, val url: String )
0
Kotlin
0
1
3cd08a8424b5e613f3ab9c7c915b386a4d685d56
315
ScheduleApp
MIT License
app/src/main/java/com/kpstv/yts/data/models/TorrentJob.kt
KaustubhPatange
248,727,800
false
null
package com.kpstv.yts.data.models import com.kpstv.bindings.AutoGenerateConverter import com.kpstv.bindings.ConverterType import java.io.Serializable @AutoGenerateConverter(using = ConverterType.GSON) data class TorrentJob ( val title: String, val bannerUrl: String, val progress: Int, val seeds: Int, val downloadSpeed: Float, val currentSize: Long, val totalSize: Long? = null, val isPlay: Boolean, var status: String, val peers: Int, val magnetHash: String ) : Serializable { companion object { fun from(model: Torrent, status: String = "Paused") = TorrentJob( title = model.title, bannerUrl = model.banner_url, progress = 0, seeds = model.seeds, downloadSpeed = 0f, currentSize = 0, totalSize = model.size, isPlay = false, status = status, peers = model.peers, magnetHash = model.hash ) } }
3
Kotlin
34
211
dd9aa97ef9aa1b864d17898a54172ab23c7b04e3
1,060
Moviesy
Apache License 2.0
mui-kotlin/src/jsMain/kotlin/mui/material/FormLabel.ext.kt
karakum-team
387,062,541
false
{"Kotlin": 3038356, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! package mui.material typealias FormLabelBaseProps = react.dom.html.LabelHTMLAttributes<web.html.HTMLLabelElement> @Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) // language=JavaScript @JsName("""(/*union*/{primary: 'primary', secondary: 'secondary', error: 'error', info: 'info', success: 'success', warning: 'warning'}/*union*/)""") sealed external interface FormLabelColor { companion object { val primary: FormLabelColor val secondary: FormLabelColor val error: FormLabelColor val info: FormLabelColor val success: FormLabelColor val warning: FormLabelColor } }
0
Kotlin
5
34
a5270a395943b069d41891c29e904d4d2f776789
711
mui-kotlin
Apache License 2.0
app/src/main/java/com/davedevab/spotifyuiclone/home/Home.kt
DaveDeveloper117
690,739,458
false
{"Kotlin": 20497}
package com.davedevab.spotifyuiclone.home import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment import com.davedevab.spotifyuiclone.R import com.davedevab.spotifyuiclone.databinding.ActivityHomeBinding import com.davedevab.spotifyuiclone.home.content.Home import com.davedevab.spotifyuiclone.home.content.Library import com.davedevab.spotifyuiclone.home.content.Search class Home : AppCompatActivity() { private lateinit var binding: ActivityHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHomeBinding.inflate(layoutInflater) setContentView(binding.root) replaceFragment(Home()) binding.bottomNavigationView.setOnItemSelectedListener { item -> when(item.itemId){ R.id.home -> replaceFragment(Home()) R.id.search -> replaceFragment(Search()) R.id.library -> replaceFragment(Library()) else ->{ } } true } } private fun replaceFragment(fragment: Fragment){ val fragmentManager = supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() fragmentTransaction.replace(R.id.frame_layout, fragment) fragmentTransaction.commit() } }
0
Kotlin
0
0
cfcc1754dbc4ae9b1e97ba0931a09f82680ae65c
1,403
Spotify_UI_Clone
MIT License
app/src/main/java/com/davedevab/spotifyuiclone/home/Home.kt
DaveDeveloper117
690,739,458
false
{"Kotlin": 20497}
package com.davedevab.spotifyuiclone.home import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment import com.davedevab.spotifyuiclone.R import com.davedevab.spotifyuiclone.databinding.ActivityHomeBinding import com.davedevab.spotifyuiclone.home.content.Home import com.davedevab.spotifyuiclone.home.content.Library import com.davedevab.spotifyuiclone.home.content.Search class Home : AppCompatActivity() { private lateinit var binding: ActivityHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHomeBinding.inflate(layoutInflater) setContentView(binding.root) replaceFragment(Home()) binding.bottomNavigationView.setOnItemSelectedListener { item -> when(item.itemId){ R.id.home -> replaceFragment(Home()) R.id.search -> replaceFragment(Search()) R.id.library -> replaceFragment(Library()) else ->{ } } true } } private fun replaceFragment(fragment: Fragment){ val fragmentManager = supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() fragmentTransaction.replace(R.id.frame_layout, fragment) fragmentTransaction.commit() } }
0
Kotlin
0
0
cfcc1754dbc4ae9b1e97ba0931a09f82680ae65c
1,403
Spotify_UI_Clone
MIT License
common/src/main/kotlin/com/daylifecraft/common/exception/EnvironmentVariableNullException.kt
daylifecraft
786,506,082
false
{"Kotlin": 565827, "Java": 16608, "Dockerfile": 751}
package com.daylifecraft.common.exception import com.daylifecraft.common.variable.Variable class EnvironmentVariableNullException(variable: Variable) : RuntimeException("Environment variable <" + variable.name + "> is not assigned")
1
Kotlin
1
6
60ce20adc7005c2f4fae9175600e58c14992a782
235
minigames
Apache License 2.0
mpp-library/feature/article/src/commonMain/kotlin/org/example/library/feature/article/presentation/ArticleViewModel.kt
RezMike
284,020,863
false
null
/* * Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package org.example.library.feature.article.presentation import dev.icerock.moko.mvvm.State import dev.icerock.moko.mvvm.asState import dev.icerock.moko.mvvm.livedata.LiveData import dev.icerock.moko.mvvm.livedata.MutableLiveData import dev.icerock.moko.mvvm.livedata.errorTransform import dev.icerock.moko.mvvm.livedata.map import dev.icerock.moko.mvvm.viewmodel.ViewModel import dev.icerock.moko.resources.StringResource import dev.icerock.moko.resources.desc.StringDesc import dev.icerock.moko.resources.desc.desc import kotlinx.coroutines.launch import org.example.library.feature.article.model.ArticleSource class ArticleViewModel<K, T>( private val articleSource: ArticleSource<K, T>, private val strings: Strings, private val id: K ) : ViewModel() { private val _state: MutableLiveData<State<T, String?>> = MutableLiveData(initialValue = State.Loading()) val state: LiveData<State<T, StringDesc>> = _state .errorTransform { // new type inference require set types map<String?, StringDesc> { it?.desc() ?: strings.unknownError.desc() } } init { loadArticle() } private fun loadArticle() { viewModelScope.launch { try { _state.value = State.Loading() val article = articleSource.getArticle(id) _state.value = article?.asState() ?: State.Empty() } catch (error: Throwable) { _state.value = State.Error(error.message) } } } interface Strings { val unknownError: StringResource } }
0
Kotlin
0
0
1cbf25cbf044795dd6d98a9f3ae1794792e10846
1,723
MokoTestProject
Apache License 2.0
app/src/main/java/com/hms/quickline/ui/contacts/ContactsAdapter.kt
Explore-In-HMS
519,198,080
false
{"Kotlin": 190120, "Java": 6564}
/* * Copyright 2022. Explore in HMS. All rights reserved. * * 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.hms.quickline.ui.contacts import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.hms.quickline.R import com.hms.quickline.core.util.getStatus import com.hms.quickline.core.util.layoutInflaterFactory import com.hms.quickline.data.model.Users import com.hms.quickline.databinding.CardCallDialogBinding class ContactsAdapter(list: ArrayList<Users>, listener: ICallDialogAdapter) : RecyclerView.Adapter<ContactsAdapter.ViewHolder>() { private var itemList: ArrayList<Users> = list private var itemListener = listener private lateinit var binding: CardCallDialogBinding override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { binding = CardCallDialogBinding.inflate(parent.layoutInflaterFactory(), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(itemList[position]) inner class ViewHolder(binding: CardCallDialogBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(user: Users) { with(binding) { userData = user if (user.isAvailable) { user.lastSeen?.let { when (getStatus(it)) { root.context.getString(R.string.available) -> { tvState.text = root.context.getString(R.string.available) imgStateAvailable.backgroundTintList = ContextCompat.getColorStateList(root.context, R.color.available_color) imgStateAvailable.setImageResource(R.drawable.ic_check_12) } root.context.getString(R.string.away) -> { tvState.text = root.context.getString(R.string.away) imgStateAvailable.backgroundTintList = ContextCompat.getColorStateList(root.context, R.color.away_color) imgStateAvailable.setImageResource(R.drawable.ic_recent) } root.context.getString(R.string.offline) -> { tvState.text = root.context.getString(R.string.offline) imgStateAvailable.backgroundTintList = ContextCompat.getColorStateList(root.context, R.color.offline_color) imgStateAvailable.setImageResource(0) } } } ?: run { tvState.text = root.context.getString(R.string.available) imgStateAvailable.backgroundTintList = ContextCompat.getColorStateList(root.context, R.color.available_color) imgStateAvailable.setImageResource(R.drawable.ic_check_12) } } else { tvState.text = root.context.getString(R.string.busy) imgStateAvailable.backgroundTintList = ContextCompat.getColorStateList(root.context, R.color.busy_color) imgStateAvailable.setImageResource(R.drawable.ic_phone_24) } imgVoiceCall.setOnClickListener { itemListener.onItemSelected(true, user) } imgVideoCall.setOnClickListener { itemListener.onItemSelected(false, user) } } } } override fun getItemCount() = itemList.size interface ICallDialogAdapter { fun onItemSelected(isVoiceCall: Boolean, user: Users) } }
0
Kotlin
1
5
5711f868442a1ca52259419a0e87c2761e051ded
4,345
QuickLine
Apache License 2.0
src/main/kotlin/org/move/lang/core/types/infer/TypeDeclarations.kt
pontem-network
279,299,159
false
null
package org.move.lang.core.types.infer import com.intellij.psi.util.parentOfType import org.move.ide.annotator.INTEGER_TYPE_IDENTIFIERS import org.move.ide.annotator.SPEC_INTEGER_TYPE_IDENTIFIERS import org.move.lang.core.psi.* import org.move.lang.core.psi.ext.mutable import org.move.lang.core.psi.ext.typeArguments import org.move.lang.core.types.ty.* fun inferBuiltinTypeTy(moveType: MvPathType, inferenceCtx: InferenceContext): Ty { val refName = moveType.path.referenceName ?: return TyUnknown if (inferenceCtx.msl && refName in SPEC_INTEGER_TYPE_IDENTIFIERS) return TyInteger.fromName("num") return when (refName) { in INTEGER_TYPE_IDENTIFIERS -> TyInteger.fromName(refName) "bool" -> TyBool "address" -> TyAddress "signer" -> TySigner "vector" -> { val itemTy = moveType.path.typeArguments .firstOrNull() ?.type ?.let { inferTypeTy(it, inferenceCtx) } ?: TyUnknown return TyVector(itemTy) } else -> TyUnknown } } fun inferTypeTy( moveType: MvType, inferenceCtx: InferenceContext, ): Ty { val existingTy = inferenceCtx.typeTypes[moveType] if (existingTy != null) { return existingTy } val ty = when (moveType) { is MvPathType -> run { val namedItem = moveType.path.reference?.resolve() ?: return@run inferBuiltinTypeTy(moveType, inferenceCtx) when (namedItem) { is MvTypeParameter -> TyTypeParameter(namedItem) is MvStruct -> { // check that it's not a recursive type val parentStruct = moveType.parentOfType<MvStruct>() if (parentStruct != null && namedItem == parentStruct) { inferenceCtx.typeErrors.add(TypeError.CircularType(moveType, parentStruct)) return TyUnknown } val typeArgs = moveType.path.typeArguments.map { inferTypeTy(it.type, inferenceCtx) } val structTy = instantiateItemTy(namedItem, inferenceCtx) as? TyStruct ?: return TyUnknown val ctx = InferenceContext(inferenceCtx.msl) for ((tyVar, tyArg) in structTy.typeVars.zip(typeArgs)) { ctx.addConstraint(tyVar, tyArg) } ctx.processConstraints() ctx.resolveTy(structTy) } else -> TyUnknown } } is MvRefType -> run { val mutabilities = RefPermissions.valueOf(moveType.mutable) val innerTypeRef = moveType.type ?: return@run TyReference(TyUnknown, mutabilities, inferenceCtx.msl) val innerTy = inferTypeTy(innerTypeRef, inferenceCtx) TyReference(innerTy, mutabilities, inferenceCtx.msl) } is MvTupleType -> { val innerTypes = moveType.typeList.map { inferTypeTy(it, inferenceCtx) } TyTuple(innerTypes) } is MvUnitType -> TyUnit else -> TyUnknown } inferenceCtx.cacheTypeTy(moveType, ty) return ty }
4
Kotlin
11
47
53ddd0e698722532aa8a9a080cc06b948f98473d
3,231
intellij-move
MIT License
ktor-server-app/src/main/kotlin/io/architecture/playground/Application.kt
vitaliystoyanov
750,598,499
false
{"Kotlin": 134187, "Java": 390}
package io.architecture.playground import io.architecture.network.websocket.api.model.NetworkClientTime import io.architecture.playground.modules.LOGGER import io.architecture.playground.modules.configureSockets import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.server.plugins.callloging.CallLogging import io.ktor.server.request.httpMethod import io.ktor.server.request.path import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.encodeToHexString import kotlinx.serialization.protobuf.ProtoBuf import org.slf4j.event.Level fun main() { embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module) .start(wait = true) } @OptIn(ExperimentalSerializationApi::class) fun Application.module() { configureSockets() install(CallLogging) { level = Level.INFO filter { call -> call.request.path().startsWith("/") } format { call -> val status = call.response.status() val httpMethod = call.request.httpMethod.value val userAgent = call.request.headers["User-Agent"] "Status: $status, HTTP method: $httpMethod, User agent: $userAgent" } } LOGGER.debug( "Test binary message for NetworkClientTime: ${ ProtoBuf.encodeToHexString<NetworkClientTime>( NetworkClientTime(System.currentTimeMillis()) ) }" ) }
3
Kotlin
0
1
918a551b8abc1d557a8b81569c36df8fc3345a72
1,570
trace-node-tracking-playground
MIT License
ktor-server-app/src/main/kotlin/io/architecture/playground/Application.kt
vitaliystoyanov
750,598,499
false
{"Kotlin": 134187, "Java": 390}
package io.architecture.playground import io.architecture.network.websocket.api.model.NetworkClientTime import io.architecture.playground.modules.LOGGER import io.architecture.playground.modules.configureSockets import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.server.plugins.callloging.CallLogging import io.ktor.server.request.httpMethod import io.ktor.server.request.path import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.encodeToHexString import kotlinx.serialization.protobuf.ProtoBuf import org.slf4j.event.Level fun main() { embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module) .start(wait = true) } @OptIn(ExperimentalSerializationApi::class) fun Application.module() { configureSockets() install(CallLogging) { level = Level.INFO filter { call -> call.request.path().startsWith("/") } format { call -> val status = call.response.status() val httpMethod = call.request.httpMethod.value val userAgent = call.request.headers["User-Agent"] "Status: $status, HTTP method: $httpMethod, User agent: $userAgent" } } LOGGER.debug( "Test binary message for NetworkClientTime: ${ ProtoBuf.encodeToHexString<NetworkClientTime>( NetworkClientTime(System.currentTimeMillis()) ) }" ) }
3
Kotlin
0
1
918a551b8abc1d557a8b81569c36df8fc3345a72
1,570
trace-node-tracking-playground
MIT License
backend/src/main/kotlin/es/guillermoorellana/keynotedex/backend/data/sessions/Session.kt
wiyarmir
116,376,394
false
null
package es.guillermoorellana.keynotedex.backend.data.sessions import es.guillermoorellana.keynotedex.backend.data.hashids import es.guillermoorellana.keynotedex.datasource.dto.SessionVisibility import es.guillermoorellana.keynotedex.datasource.requests.SessionCreateRequest import es.guillermoorellana.keynotedex.datasource.dto.Session as DtoSubmission data class Session( val id: Long, val title: String, val abstract: String?, val isPublic: Boolean, val submitterId: String ) fun DtoSubmission.toDao(): Session = Session( id = hashids.decode(sessionId).first(), submitterId = userId, title = title, abstract = abstract, isPublic = visibility == SessionVisibility.PUBLIC ) fun SessionCreateRequest.toDao(userId: String): Session = Session( id = -1, submitterId = userId, title = title, abstract = abstract, isPublic = visibility == SessionVisibility.PUBLIC )
6
Kotlin
3
51
ec6d7e50d5c7285e6d26f06caaca03a279af38c6
980
keynotedex
Apache License 2.0
app/src/main/java/com/vhontar/reviewimagesapp/business/utils/AppConstants.kt
vhontar
529,318,348
false
{"Kotlin": 58809, "Java": 544}
package com.vhontar.reviewimagesapp.business.utils object AppConstants { const val DEFAULT_PAGE_INDEX = 1 const val DEFAULT_IMAGES_PER_PAGE = 20 const val DATABASE_NAME = "images.db" const val DEFAULT_REQUEST = "fruits" }
0
Kotlin
0
0
0b124971af7120e9e851d083b47fbb03b96158d6
239
review-images-app
Apache License 2.0
dataforge-meta/src/commonMain/kotlin/space/kscience/dataforge/meta/descriptors/schemeDescriptor.kt
SciProgCentre
148,831,678
false
{"Kotlin": 408170}
package space.kscience.dataforge.meta.descriptors import space.kscience.dataforge.meta.Scheme import space.kscience.dataforge.meta.SchemeSpec import space.kscience.dataforge.meta.ValueType import kotlin.reflect.KProperty1 import kotlin.reflect.typeOf /** * Add a value item to a [MetaDescriptor] inferring some of its properties from the type */ public inline fun <S : Scheme, reified T> MetaDescriptorBuilder.value( property: KProperty1<S, T>, noinline block: MetaDescriptorBuilder.() -> Unit = {}, ): Unit = when (typeOf<T>()) { typeOf<Number>(), typeOf<Int>(), typeOf<Double>(), typeOf<Short>(), typeOf<Long>(), typeOf<Float>() -> value(property.name, ValueType.NUMBER) { block() } typeOf<Number?>(), typeOf<Int?>(), typeOf<Double?>(), typeOf<Short?>(), typeOf<Long?>(), typeOf<Float?>() -> value(property.name, ValueType.NUMBER) { block() } typeOf<Boolean>() -> value(property.name, ValueType.BOOLEAN) { block() } typeOf<List<Number>>(), typeOf<List<Int>>(), typeOf<List<Double>>(), typeOf<List<Short>>(), typeOf<List<Long>>(), typeOf<List<Float>>(), typeOf<IntArray>(), typeOf<DoubleArray>(), typeOf<ShortArray>(), typeOf<LongArray>(), typeOf<FloatArray>(), -> value(property.name, ValueType.NUMBER) { multiple = true block() } typeOf<String>() -> value(property.name, ValueType.STRING) { block() } typeOf<List<String>>(), typeOf<Array<String>>() -> value(property.name, ValueType.STRING) { multiple = true block() } else -> node(property.name, block) } /** * Add a schem-based branch to a [MetaDescriptor] */ public inline fun <S : Scheme, reified T : Scheme> MetaDescriptorBuilder.scheme( property: KProperty1<S, T>, spec: SchemeSpec<T>, noinline block: MetaDescriptorBuilder.() -> Unit = {}, ) { node(property.name, spec, block) }
14
Kotlin
3
25
d80846d5fbd4d232b7506f5b4124cddfdc61d17e
1,925
dataforge-core
Apache License 2.0
server/engine/src/main/kotlin/io/rsbox/server/engine/service/serializer/JsonPlayerSerializer.kt
rsbox
704,269,853
false
{"Java": 2428938, "Kotlin": 633136}
package io.rsbox.server.engine.service.serializer import io.rsbox.server.engine.model.Appearance import io.rsbox.server.engine.model.Privilege import io.rsbox.server.engine.model.coord.Tile import io.rsbox.server.engine.model.entity.Player import io.rsbox.server.engine.model.ui.DisplayMode import io.rsbox.server.engine.net.login.LoginRequest import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.io.File class JsonPlayerSerializer : PlayerSerializer { override fun create(request: LoginRequest): Player { val player = Player.create(request) save(player) return player } override fun load(request: LoginRequest): Player? { val file = File("data/saves/${request.username}.json") if(!file.exists()) return null val data = Json.decodeFromString<PlayerData>(file.readText()) val player = Player.create(request) player.username = data.username player.displayName = data.displayName player.passwordHash = data.passwordHash player.session.reconnectXteas = data.xteas player.privilege = data.privilege player.isMember = data.isMember player.displayMode = data.displayMode player.appearance = data.appearance player.tile = data.tile return player } override fun save(player: Player) { val file = File("data/saves/${player.username}.json") if(file.exists()) file.delete() val data = PlayerData( player.username, player.passwordHash, player.session.xteas, player.displayName, player.privilege, player.isMember, player.displayMode, player.appearance, player.tile ) val json = Json { prettyPrint = true } val text = json.encodeToString(data) file.createNewFile() file.writeText(text) } @Serializable private data class PlayerData( val username: String, val passwordHash: String, val xteas: IntArray, val displayName: String, val privilege: Privilege, val isMember: Boolean, val displayMode: DisplayMode, val appearance: Appearance, val tile: Tile ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PlayerData if (username != other.username) return false if (passwordHash != other.passwordHash) return false if (!xteas.contentEquals(other.xteas)) return false if (displayName != other.displayName) return false if (privilege != other.privilege) return false if (isMember != other.isMember) return false if (displayMode != other.displayMode) return false if (appearance != other.appearance) return false return tile == other.tile } override fun hashCode(): Int { var result = username.hashCode() result = 31 * result + passwordHash.hashCode() result = 31 * result + xteas.contentHashCode() result = 31 * result + displayName.hashCode() result = 31 * result + privilege.hashCode() result = 31 * result + isMember.hashCode() result = 31 * result + displayMode.hashCode() result = 31 * result + appearance.hashCode() result = 31 * result + tile.hashCode() return result } } }
1
null
1
1
187049de600faa9d8de244ee2ed14785d9123475
3,656
rsbox
Apache License 2.0
kool-core/src/desktopMain/kotlin/de/fabmax/kool/pipeline/backend/vk/OnScreenRenderPass.kt
kool-engine
81,503,047
false
{"Kotlin": 5929566, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597}
package de.fabmax.kool.pipeline.backend.vk import de.fabmax.kool.util.logD import de.fabmax.kool.util.logE import de.fabmax.kool.util.memStack import org.lwjgl.vulkan.KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR import org.lwjgl.vulkan.VK10.* import org.lwjgl.vulkan.VkCommandBuffer class OnScreenRenderPass(val swapChain: SwapChain) : VkRenderPass(swapChain.sys, swapChain.extent.width(), swapChain.extent.height(), listOf(swapChain.imageFormat)) { override val vkRenderPass: Long init { memStack { val attachments = callocVkAttachmentDescriptionN(3) { this[0] .format(swapChain.imageFormat) .samples(swapChain.sys.physicalDevice.msaaSamples) .loadOp(VK_ATTACHMENT_LOAD_OP_CLEAR) .storeOp(VK_ATTACHMENT_STORE_OP_STORE) .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) .initialLayout(VK_IMAGE_LAYOUT_UNDEFINED) .finalLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) this[1] .format(swapChain.sys.physicalDevice.depthFormat) .samples(swapChain.sys.physicalDevice.msaaSamples) .loadOp(VK_ATTACHMENT_LOAD_OP_CLEAR) .storeOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) .initialLayout(VK_IMAGE_LAYOUT_UNDEFINED) .finalLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) this[2] .format(swapChain.imageFormat) .samples(VK_SAMPLE_COUNT_1_BIT) .loadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) .storeOp(VK_ATTACHMENT_STORE_OP_STORE) .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) .initialLayout(VK_IMAGE_LAYOUT_UNDEFINED) .finalLayout(VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) } val colorAttachmentRef = callocVkAttachmentReferenceN(1) { attachment(0) layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) } val depthAttachmentRef = callocVkAttachmentReferenceN(1) { attachment(1) layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) } val colorAttachmentResolveRef = callocVkAttachmentReferenceN(1) { attachment(2) layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) } val subpass = callocVkSubpassDescriptionN(1) { pipelineBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS) colorAttachmentCount(1) pColorAttachments(colorAttachmentRef) pDepthStencilAttachment(depthAttachmentRef[0]) pResolveAttachments(colorAttachmentResolveRef) } val dependency = callocVkSubpassDependencyN(1) { srcSubpass(VK_SUBPASS_EXTERNAL) dstSubpass(0) srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) srcAccessMask(0) dstStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_READ_BIT or VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) } val renderPassInfo = callocVkRenderPassCreateInfo { sType(VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO) pAttachments(attachments) pSubpasses(subpass) pDependencies(dependency) } vkRenderPass = checkCreatePointer { vkCreateRenderPass(swapChain.sys.device.vkDevice, renderPassInfo, null, it) } } swapChain.addDependingResource(this) logD { "Created render pass" } } fun blitFrom(src: VkOffscreenPass2d, commandBuffer: VkCommandBuffer, mipLevel: Int) { logE { "Blitting render passes is not yet implemented on Vulkan backend" } val rp = src.renderPass ?: return val srcWidth = src.parentPass.width shr mipLevel val srcHeight = src.parentPass.height shr mipLevel val width = maxWidth val height = maxHeight if (srcWidth != width || srcHeight != height) { logE { "Render pass blitting requires source and destination pass to have the same size" } } memStack { val srcImage = rp.images[0] swapChain.colorImage.transitionLayout(this, commandBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) srcImage.transitionLayout(this, commandBuffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) val imageCopy = callocVkImageCopyN(1) { srcSubresource { it.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT) it.mipLevel(mipLevel) it.baseArrayLayer(0) it.layerCount(1) } srcOffset { it.set(0, 0, 0) } dstSubresource { it.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT) it.mipLevel(mipLevel) it.baseArrayLayer(0) it.layerCount(1) } dstOffset { it.set(0, 0, 0) } extent { it.set(width, height, 1) } } vkCmdCopyImage(commandBuffer, srcImage.vkImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, swapChain.colorImage.vkImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, imageCopy) srcImage.transitionLayout(this, commandBuffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) swapChain.colorImage.transitionLayout(this, commandBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) } } override fun freeResources() { vkDestroyRenderPass(sys.device.vkDevice, vkRenderPass, null) logD { "Destroyed render pass" } } }
12
Kotlin
20
303
8d05acd3e72ff2fc115d0939bf021a5f421469a5
6,145
kool
Apache License 2.0
src/main/kotlin/ui/TimeInput.kt
dangari
347,605,683
false
null
package ui import controller.Store import javafx.beans.property.SimpleObjectProperty import tornadofx.* import java.time.LocalDate class TimeInput: View() { private val store: Store by inject() private val date = SimpleObjectProperty<LocalDate>() override val root = vbox { label("Time Entry") hbox { textfield { promptText = "Enter Time" action { store.addTimeEntry(text, date.get()) clear() } } datepicker(date) { value = LocalDate.now() }} } }
0
Kotlin
0
0
73cc52e96e3775d42f3e9bcf349b048581c20aa4
635
TimeKeeper
MIT License
app/src/main/java/com/astroscoding/jokesapp/presentation/core/component/JokesState.kt
Astroa7m
459,685,492
false
{"Kotlin": 134726}
package com.astroscoding.jokesapp.presentation.core.component import com.astroscoding.jokesapp.domain.model.Joke data class JokesState( val isLoading: Boolean = false, val jokes: List<Joke> = emptyList(), val errorMessage: String = "" )
0
Kotlin
2
5
691a420baf3b7be90d24f1bfdd988d944837a8d4
251
clean_architecture_mvvm_jokes_app
MIT License
src/main/kotlin/com/faforever/palantir/model/UserModel.kt
FAForever
815,962,809
false
{"Kotlin": 20685, "HTML": 20544}
package com.faforever.palantir.model import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import java.time.Instant @JvmRecord data class UserModel( val name: String, val id: Int, val email: String, val accountLinks: List<AccountLink>, val ipAddress: String?, val registeredAt: Instant, val lastLoginAt: Instant?, val lastUpdatedAt: Instant?, val uids: List<UniqueId>, ) { @JvmRecord data class AccountLink( val id: String, val type: Type, val serviceId: String, ) { enum class Type { STEAM, GOG, DISCORD, PATREON, @JsonEnumDefaultValue UNKNOWN, } } @JvmRecord data class UniqueId( val hash: String?, val uuid: String?, val memorySerialNumber: String?, val deviceId: String?, val manufacturer: String?, val name: String?, val processorId: String?, val smbiosbiosVersion: String?, val serialNumber: String?, val volumeSerialNumber: String?, ) }
0
Kotlin
0
1
b69b24177fcbaa26f3b5114fc5a363f649ad06de
1,111
faf-palantir
MIT License
app/src/main/java/com/cobeisfresh/azil/data/request/UserRequest.kt
vejathegreat
162,910,055
false
null
package com.cobeisfresh.azil.data.request /** * Created by <NAME> on 22/08/2017. */ data class UserRequest(var name: String = "")
0
Kotlin
0
0
174c15f617b5766bd2f093a7780c7d090b632d40
133
Azil-Osijek-Android
The Unlicense
app/src/main/kotlin/com/dmko/bulldogvods/features/vods/presentation/recycler/vods/VodItemsAdapter.kt
dmitrykochanov
477,314,891
false
null
package com.dmko.bulldogvods.features.vods.presentation.recycler.vods import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.PagingDataAdapter import com.dmko.bulldogvods.app.common.image.loader.ImageLoader import com.dmko.bulldogvods.databinding.ListItemVodBinding import com.dmko.bulldogvods.features.vods.presentation.entities.VodItem class VodItemsAdapter( private val imageLoader: ImageLoader, private val onVodClickListener: (String) -> Unit, private val onVodChaptersClickListener: (String) -> Unit ) : PagingDataAdapter<VodItem, VodItemViewHolder>(VodItemDiffUtil()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VodItemViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = ListItemVodBinding.inflate(inflater, parent, false) return VodItemViewHolder(binding, imageLoader) } override fun onBindViewHolder(holder: VodItemViewHolder, position: Int) { val vodItem = requireNotNull(getItem(position)) holder.bindVodItem(vodItem) holder.setOnVodClickListener { onVodClickListener.invoke(vodItem.id) } holder.setOnVodChaptersClickListener { onVodChaptersClickListener.invoke(vodItem.id) } } }
0
Kotlin
0
1
0aa6ec12113a0366c81c236cc6288e72ed15798c
1,263
BulldogVods
MIT License
app/src/main/java/com/example/custom_keyboard_example/MainActivity.kt
KotlinKing
469,885,506
false
{"Kotlin": 16715}
package com.example.custom_keyboard_example import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.InputType import android.view.View import android.view.inputmethod.EditorInfo import androidx.databinding.DataBindingUtil import com.example.custom_keyboard_example.R import com.example.custom_keyboard_example.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(R.layout.activity_main) binding = DataBindingUtil.setContentView(this,R.layout.activity_main) showKeyboard() val ic = binding.etInput.onCreateInputConnection(EditorInfo()) binding.keyboard.setInputConnection(ic) } private fun showKeyboard() { binding.etInput.visibility = View.VISIBLE binding.etInput.setRawInputType(InputType.TYPE_CLASS_TEXT) binding.etInput.setTextIsSelectable(true) binding.etInput.showSoftInputOnFocus = false binding.etInput.requestFocus() } }
0
Kotlin
0
0
1923f45f7136182818c75aa1093213100b82bc3c
1,154
Custom_Keyboard_Example
MIT License
app/src/main/java/tech/acruxsolutions/atomnote/adapters/LabelsAdapter.kt
manhnvacrux
287,846,541
false
null
package tech.acruxsolutions.atomnote.adapters import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import tech.acruxsolutions.atomenote.databinding.LabelItemBinding import tech.acruxsolutions.atomnote.viewholders.LabelsViewHolder class LabelsAdapter(private val context: Context) : ListAdapter<String, LabelsViewHolder>( DiffCallback() ) { var onLabelClicked: ((position: Int) -> Unit)? = null var onLabelLongClicked: ((position: Int) -> Unit)? = null override fun onBindViewHolder(holder: LabelsViewHolder, position: Int) { val label = getItem(position) holder.bind(label) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LabelsViewHolder { val binding = LabelItemBinding.inflate(LayoutInflater.from(context), parent, false) return LabelsViewHolder( binding, onLabelClicked, onLabelLongClicked ) } class DiffCallback : DiffUtil.ItemCallback<String>() { override fun areItemsTheSame(oldItem: String, newItem: String): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: String, newItem: String): Boolean { return oldItem == newItem } } }
0
Kotlin
0
0
7ac7c03b8652ec0a6d684466f920ceb36c31d889
1,408
atom-note
MIT License
libwoff2dec/src/androidTest/java/com/github/khoben/libwoff2dec/BaseTest.kt
khoben
527,465,175
false
{"Kotlin": 18857, "Python": 6179, "C++": 2710, "CMake": 1527}
package com.github.khoben.libwoff2dec import android.content.Context import android.content.res.AssetManager import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.runner.RunWith import java.io.File @RunWith(AndroidJUnit4::class) abstract class BaseTest { private val context: Context = InstrumentationRegistry.getInstrumentation().context private val assets: AssetManager = context.assets protected fun getTempFile(): File { return File.createTempFile("test", null, context.cacheDir) } protected fun getFileFromAssets(filename: String): File { val temp = getTempFile() temp.outputStream().use { output -> assets.open(filename).use { input -> input.copyTo(output) } } return temp } }
0
Kotlin
1
1
370ea786df6b597ef6bacca85f8321ab00d48c9b
865
woff2-android
Apache License 2.0
octicons/src/commonMain/kotlin/compose/icons/octicons/Sync16.kt
DevSrSouza
311,134,756
false
null
package compose.icons.octicons 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 compose.icons.Octicons public val Octicons.Sync16: ImageVector get() { if (_sync16 != null) { return _sync16!! } _sync16 = Builder(name = "Sync16", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(8.0f, 2.5f) arcToRelative(5.487f, 5.487f, 0.0f, false, false, -4.131f, 1.869f) lineToRelative(1.204f, 1.204f) arcTo(0.25f, 0.25f, 0.0f, false, true, 4.896f, 6.0f) horizontalLineTo(1.25f) arcTo(0.25f, 0.25f, 0.0f, false, true, 1.0f, 5.75f) verticalLineTo(2.104f) arcToRelative(0.25f, 0.25f, 0.0f, false, true, 0.427f, -0.177f) lineToRelative(1.38f, 1.38f) arcTo(7.001f, 7.001f, 0.0f, false, true, 14.95f, 7.16f) arcToRelative(0.75f, 0.75f, 0.0f, true, true, -1.49f, 0.178f) arcTo(5.501f, 5.501f, 0.0f, false, false, 8.0f, 2.5f) close() moveTo(1.705f, 8.005f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.834f, 0.656f) arcToRelative(5.501f, 5.501f, 0.0f, false, false, 9.592f, 2.97f) lineToRelative(-1.204f, -1.204f) arcToRelative(0.25f, 0.25f, 0.0f, false, true, 0.177f, -0.427f) horizontalLineToRelative(3.646f) arcToRelative(0.25f, 0.25f, 0.0f, false, true, 0.25f, 0.25f) verticalLineToRelative(3.646f) arcToRelative(0.25f, 0.25f, 0.0f, false, true, -0.427f, 0.177f) lineToRelative(-1.38f, -1.38f) arcTo(7.001f, 7.001f, 0.0f, false, true, 1.05f, 8.84f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.656f, -0.834f) close() } } .build() return _sync16!! } private var _sync16: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,726
compose-icons
MIT License
app/src/main/java/ffeltrinelli/textualclock/domain/Randomizer.kt
ffeltrinelli
838,364,681
false
{"Kotlin": 31589}
package ffeltrinelli.textualclock.domain import kotlin.random.Random class Randomizer(private val random: Random) { fun nextLetter() = random.nextInt('a'.code, 'z'.code + 1).toChar() }
0
Kotlin
0
0
87c9c7735d0bed8735adf655cef97dfca8531b38
191
textual-clock-android
Apache License 2.0
src/main/kotlin/uk/gov/justice/hmpps/architecture/model/TokenVerificationApi.kt
ministryofjustice
272,753,130
false
{"Kotlin": 197063, "Shell": 1167}
package uk.gov.justice.hmpps.architecture.model import com.structurizr.model.Container import com.structurizr.model.Model import com.structurizr.model.SoftwareSystem import com.structurizr.view.ViewSet import uk.gov.justice.hmpps.architecture.HMPPSSoftwareSystem import uk.gov.justice.hmpps.architecture.annotations.Capability import uk.gov.justice.hmpps.architecture.annotations.Tags class TokenVerificationApi private constructor() { companion object : HMPPSSoftwareSystem { lateinit var system: SoftwareSystem lateinit var api: Container override fun defineModelEntities(model: Model) { system = model.addSoftwareSystem( "Token verification API", "Verifies API tokens issues by HMPPS Auth to ensure they haven't expired or been revoked" ).apply { Capability.IDENTITY.addTo(this) } api = system.addContainer("API", "API", "Kotlin + Spring Boot").apply { url = "https://github.com/ministryofjustice/token-verification-api" } val redis = system.addContainer("REDIS", "Tokens storage", "REDIS").apply { Tags.DATABASE.addTo(this) } api.uses(redis, "connects to") } override fun defineRelationships() { } override fun defineViews(views: ViewSet) { } } }
5
Kotlin
3
17
a18f85184c43e37bec36f758effb662a3d068ece
1,283
hmpps-architecture-as-code
MIT License
compiler-plugin/src/main/java/com/anatawa12/autoVisitor/compiler/visitor/UserDatas.kt
anatawa12
334,377,620
false
null
package com.anatawa12.autoVisitor.compiler.visitor import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor data class VisitMethodData( val superClass: ClassDescriptor?, val name: String?, ) { companion object : CallableDescriptor.UserDataKey<VisitMethodData> }
9
Kotlin
1
2
55cb569955ea0bec42c58291da733bf5bfa604f2
334
auto-visitor
MIT License
presentation/mate/src/main/java/com/depromeet/threedays/mate/ClapAdapter.kt
depromeet12th
548,194,728
false
null
package com.depromeet.threedays.mate import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.depromeet.threedays.mate.model.StampUI class ClapAdapter : ListAdapter<StampUI, ClapViewHolder>(DIFF_UTIL) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ClapViewHolder.create(parent = parent, attachToParent = false) override fun onBindViewHolder(holder: ClapViewHolder, position: Int) { holder.onBind(getItem(position)) } override fun getItemCount(): Int = currentList.size override fun getItemId(position: Int): Long { return getItem(position).stampCount } companion object { private val DIFF_UTIL = object : DiffUtil.ItemCallback<StampUI>() { override fun areItemsTheSame(oldItem: StampUI, newItem: StampUI): Boolean { return oldItem.stampCount == newItem.stampCount } override fun areContentsTheSame(oldItem: StampUI, newItem: StampUI): Boolean { return oldItem == newItem } } } }
0
Kotlin
1
15
1cc08fcf2b038924ab0fe5feaaff548974f40f4d
1,139
three-days-android
MIT License
app/src/main/java/com/arpadfodor/android/chain_reaction/presenter/IMainView.kt
aaronfodor
175,170,645
false
null
package com.arpadfodor.android.chain_reaction.presenter import com.google.firebase.auth.FirebaseUser interface IMainView { /** * Notifies the user about AI loading result * * @param isLoaded True if loaded, false otherwise */ fun loadedAI(isLoaded: Boolean) /** * Notifies the user that AI component is not loaded */ fun notLoadedAI() /** * Shows the Google Play login status * * @param user A nullable FirebaseUser object to show its data - if null, user is not signed in */ fun showLoginStatus(user: FirebaseUser?) }
0
Kotlin
0
0
c76abf247016cfb1837d7e2ee3beff733e4ab895
608
ChainReaction
MIT License
src/main/java/com/metriql/service/suggestion/SuggestionCacheService.kt
metriql
370,169,788
false
null
package com.metriql.service.suggestion import com.metriql.service.auth.ProjectAuth import com.metriql.service.dataset.DatasetName import com.metriql.service.dataset.DimensionName import java.time.Instant interface SuggestionCacheService { fun getCommon(auth: ProjectAuth, datasetName: DatasetName, dimensionName: DimensionName): Suggestion? fun search(auth: ProjectAuth, datasetName: DatasetName, dimensionName: DimensionName, filter: String): Suggestion? fun set(auth: ProjectAuth, datasetName: DatasetName, dimensionName: DimensionName, values: List<String>) data class Suggestion(val items: List<String>, val lastUpdated: Instant) }
30
Kotlin
19
253
10fa42434c19d1dbfb9a3d04becea679bb82d0f1
655
metriql
Apache License 2.0
integration-test/android/src/main/kotlin/com/moriatsushi/koject/integrationtest/android/viewmodel/ContextViewModel.kt
mori-atsushi
605,139,896
false
null
package com.moriatsushi.koject.integrationtest.android.viewmodel import android.annotation.SuppressLint import android.content.Context import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import com.moriatsushi.koject.Provides import com.moriatsushi.koject.android.viewmodel.ViewModelComponent @Provides @ViewModelComponent @SuppressLint("StaticFieldLeak") class ContextViewModel( val context: Context, ) : ViewModel() @Provides @ViewModelComponent @SuppressLint("StaticFieldLeak") class ContextWithSavedStateViewModel( val context: Context, val savedStateHandle: SavedStateHandle, ) : ViewModel()
13
Kotlin
2
96
c22286b39a3e6249842d148ff0a22f1fb7d37d47
639
koject
Apache License 2.0
generator/src/test/kotlin/com/google/api/kotlin/KotlinClientGeneratorTest.kt
JasonFoxTrot
169,916,879
true
{"Kotlin": 450799, "Shell": 6394, "Dockerfile": 3353}
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.api.kotlin import com.google.api.kotlin.config.Configuration import com.google.api.kotlin.config.LegacyConfigurationFactory import com.google.api.kotlin.config.ServiceOptions import com.google.api.kotlin.generator.GRPCGenerator import com.google.common.truth.Truth.assertThat import com.google.protobuf.DescriptorProtos import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.check import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.doThrow import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.TypeSpec import kotlin.test.Test internal class KotlinClientGeneratorTest : BaseClientGeneratorTest(GRPCGenerator()) { @Test fun `generates a class with context and a license`() { val clientGenerator: ClientGenerator = mock { on { generateServiceClient(any()) }.doReturn( listOf( GeneratedSource( "google.example", "TestServiceClient", listOf(TypeSpec.classBuilder("TestServiceClient").build()) ) ) ) } val config = getMockedConfig(ServiceOptions()) val clientConfigFactory: LegacyConfigurationFactory = mock { on { fromProto(any()) }.doReturn(config) } val generator = KotlinClientGenerator(clientGenerator, clientConfigFactory) val result = generator.generate(generatorRequest, typeMap) assertThat(result.sourceCode.fileCount).isEqualTo(1) val testClient = result.sourceCode.fileList.first { it.name == "google/example/TestServiceClient.kt" } assertThat(testClient.content).contains("Copyright") assertThat(testClient.content).contains("class TestServiceClient") verify(clientGenerator).generateServiceClient(check { assertThat(it.className).isEqualTo(ClassName("google.example", "TestServiceClient")) assertThat(it.metadata).isEqualTo(config) assertThat(it.proto).isEqualTo(proto) assertThat(it.service).isEqualTo(proto.serviceList.find { s -> s.name == "TestService" }) }) } @Test fun `generates builders along with class`() { val clientGenerator: ClientGenerator = mock { on { generateServiceClient(any()) }.doReturn( listOf( GeneratedSource( "google.example", "FooService", listOf(TypeSpec.classBuilder("FooService").build()) ) ) ) } val builderGenerator: BuilderGenerator = mock { on { generate(any()) }.doReturn( listOf( GeneratedSource( "foo.bar", "Baz", listOf(TypeSpec.classBuilder("Baz").build()) ) ) ) } val config = getMockedConfig(ServiceOptions()) val clientConfigFactory: LegacyConfigurationFactory = mock { on { fromProto(any()) }.doReturn(config) } val generator = KotlinClientGenerator(clientGenerator, clientConfigFactory, builderGenerator) val result = generator.generate(generatorRequest, typeMap) assertThat(result.sourceCode.fileCount).isEqualTo(2) assertThat(result.sourceCode.fileList.map { it.name }).containsExactly( "google/example/FooService.kt", "foo/bar/Baz.kt" ) result.sourceCode.fileList.forEach { assertThat(it.content).contains("Copyright") } } @Test fun `can wrap text`() { assertThat("abcde ".repeat(1000).wrap(50)?.split("\n".toRegex())?.all { it.length <= 50 }).isTrue() assertThat("abcde ".wrap(50)?.trim()).isEqualTo("abcde") val nullString: String? = null assertThat(nullString.wrap()).isNull() } @Test fun `context uses given service options`() { val options: ServiceOptions = mock() val metadata: Configuration = mock { on { get(any<DescriptorProtos.ServiceDescriptorProto>()) } doReturn options } val service: DescriptorProtos.ServiceDescriptorProto = mock() val context = GeneratorContext(mock(), service, metadata, mock(), mock(), ClientPluginOptions()) assertThat(context.serviceOptions).isEqualTo(options) verify(metadata).get(eq(service)) } @Test fun `can handle exceptions`() { val clientGenerator: ClientGenerator = mock { on { generateServiceClient(any()) } doThrow SomeException() } val config = getMockedConfig(ServiceOptions()) val clientConfigFactory: LegacyConfigurationFactory = mock { on { fromProto(any()) }.doReturn(config) } val generator = KotlinClientGenerator(clientGenerator, clientConfigFactory) val result = generator.generate(generatorRequest, typeMap) assertThat(result.sourceCode.fileCount).isEqualTo(0) assertThat(result.testCode.fileCount).isEqualTo(0) } } private class SomeException : RuntimeException()
0
Kotlin
0
0
eca06217f013f0ecc318dcca5eb9b6d95d7801d6
5,978
gapic-generator-kotlin
Apache License 2.0
falkon-dao/src/main/kotlin/com/jayrave/falkon/dao/DaoImpl.kt
jayrave
65,279,209
false
null
package com.jayrave.falkon.dao import com.jayrave.falkon.dao.delete.DeleteBuilder import com.jayrave.falkon.dao.delete.DeleteBuilderImpl import com.jayrave.falkon.dao.insert.InsertBuilder import com.jayrave.falkon.dao.insert.InsertBuilderImpl import com.jayrave.falkon.dao.insertOrReplace.InsertOrReplaceBuilder import com.jayrave.falkon.dao.insertOrReplace.InsertOrReplaceBuilderImpl import com.jayrave.falkon.dao.query.QueryBuilder import com.jayrave.falkon.dao.query.QueryBuilderImpl import com.jayrave.falkon.dao.update.UpdateBuilder import com.jayrave.falkon.dao.update.UpdateBuilderImpl import com.jayrave.falkon.mapper.Table import com.jayrave.falkon.sqlBuilders.* import com.jayrave.falkon.dao.query.lenient.QueryBuilder as LenientQueryBuilder import com.jayrave.falkon.dao.query.lenient.QueryBuilderImpl as LenientQueryBuilderImpl /** * @param [insertSqlBuilder] to build SQL `INSERT INTO...` statements from components * @param [updateSqlBuilder] to build SQL `UPDATE...` statements from components * @param [deleteSqlBuilder] to build SQL `DELETE FROM...` statements from components * @param [insertOrReplaceSqlBuilder] to build statements similar to `insert or replace` * @param [querySqlBuilder] to build SQL `SELECT FROM...` statements from components */ open class DaoImpl<T : Any, in ID : Any>( override val table: Table<T, ID>, private val insertSqlBuilder: InsertSqlBuilder, private val updateSqlBuilder: UpdateSqlBuilder, private val deleteSqlBuilder: DeleteSqlBuilder, private val insertOrReplaceSqlBuilder: InsertOrReplaceSqlBuilder, private val querySqlBuilder: QuerySqlBuilder) : Dao<T, ID> { override final fun insertBuilder(): InsertBuilder<T> = InsertBuilderImpl( table, insertSqlBuilder ) override final fun updateBuilder(): UpdateBuilder<T> = UpdateBuilderImpl( table, updateSqlBuilder ) override final fun deleteBuilder(): DeleteBuilder<T> = DeleteBuilderImpl( table, deleteSqlBuilder ) override fun insertOrReplaceBuilder(): InsertOrReplaceBuilder<T> = InsertOrReplaceBuilderImpl( table, insertOrReplaceSqlBuilder ) override final fun queryBuilder(): QueryBuilder<T> = QueryBuilderImpl( table, querySqlBuilder ) /** * Use this when [QueryBuilder] is too restrictive */ fun lenientQueryBuilder(): LenientQueryBuilder = lenientQueryBuilder(querySqlBuilder) }
6
Kotlin
2
12
ce42d553c578cd8e509bbfd7effc5d56bf3cdedd
2,467
falkon
Apache License 2.0
app/src/main/java/com/example/marvel/app/api/responses/CharacterResponse.kt
ahmeddyounes
842,107,601
false
{"Kotlin": 155384}
package com.example.marvel.app.api.responses data class CharacterResponse( val id: Int, val name: String, val description: String, val thumbnail: ThumbnailResponse )
0
Kotlin
0
0
b03e737a6e2edbc86e1cfba7c58a8a3b4b273eeb
182
Marvel
MIT License
app/src/main/java/br/com/kaiki/devhub/network/model/GitHubRepositoryWeb.kt
Kaiki098
791,865,247
false
{"Kotlin": 23327}
package br.com.kaiki.devhub.network.model import br.com.kaiki.devhub.model.GitHubRepository data class GitHubRepositoryWeb ( val name: String, val description: String? ) fun GitHubRepositoryWeb.toGitHubRepository() = GitHubRepository ( name = name, description = description ?: "" )
0
Kotlin
0
1
6b593e287cb65d8a15901735ad19d6487a3ceb20
301
DevHub
MIT License
core/src/main/java/org/futo/circles/core/feature/room/update/UpdateRoomDialogFragment.kt
circles-project
615,347,618
false
{"Kotlin": 1307644, "C": 137821, "C++": 12364, "Shell": 3202, "CMake": 1680, "Ruby": 922}
package org.futo.circles.core.feature.room.update import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import androidx.core.widget.doAfterTextChanged import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import dagger.hilt.android.AndroidEntryPoint import org.futo.circles.core.R import org.futo.circles.core.base.fragment.BaseFullscreenDialogFragment import org.futo.circles.core.base.fragment.HasLoadingState import org.futo.circles.core.databinding.DialogFragmentUpdateRoomBinding import org.futo.circles.core.extensions.getRoleNameResId import org.futo.circles.core.extensions.getText import org.futo.circles.core.extensions.loadRoomProfileIcon import org.futo.circles.core.extensions.observeData import org.futo.circles.core.extensions.observeResponse import org.futo.circles.core.extensions.onBackPressed import org.futo.circles.core.extensions.setIsVisible import org.futo.circles.core.extensions.showSuccess import org.futo.circles.core.extensions.toRoomInfo import org.futo.circles.core.feature.picker.helper.MediaPickerHelper import org.futo.circles.core.model.AccessLevel import org.futo.circles.core.model.CircleRoomTypeArg import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.session.room.model.usersDefaultOrDefault import org.matrix.android.sdk.api.session.room.powerlevels.Role @AndroidEntryPoint class UpdateRoomDialogFragment : BaseFullscreenDialogFragment<DialogFragmentUpdateRoomBinding>(DialogFragmentUpdateRoomBinding::inflate), HasLoadingState { override val fragment: Fragment = this private val args: UpdateRoomDialogFragmentArgs by navArgs() private val viewModel by viewModels<UpdateRoomViewModel>() private val roomType: CircleRoomTypeArg get() = args.type private val mediaPickerHelper = MediaPickerHelper(this) private val circleTypeList = AccessLevel.entries.toTypedArray() private val circleTypeAdapter by lazy { ArrayAdapter(requireContext(), R.layout.view_spinner_item, circleTypeList.map { val role = Role.fromValue(it.levelValue, Role.Default.value) getString(role.getRoleNameResId()) }).apply { setDropDownViewResource(R.layout.view_spinner_item) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViews() setupObservers() } private fun setupViews() { with(binding) { val roomTypeName = getRoomTypeName() toolbar.title = getString(R.string.configure_room_format, roomTypeName) val nameHeader = "$roomTypeName ${getString(R.string.name)}" tvNameHeader.text = nameHeader val isGroup = roomType == CircleRoomTypeArg.Group tvTopicHeader.setIsVisible(isGroup) tilTopic.setIsVisible(isGroup) ivCover.setOnClickListener { changeCoverImage() } btnChangeIcon.setOnClickListener { changeCoverImage() } tilName.editText?.doAfterTextChanged { it?.let { onInputDataChanged() } } tilTopic.editText?.doAfterTextChanged { it?.let { onInputDataChanged() } } btnSave.setOnClickListener { viewModel.update( tilName.getText(), tilTopic.getText(), getSelectedAccessLevel(), roomType ) startLoading(btnSave) } val isCircle = roomType == CircleRoomTypeArg.Circle tvRoleHeader.setIsVisible(!isCircle) spUserRole.apply { setIsVisible(!isCircle) adapter = circleTypeAdapter onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { onInputDataChanged() } override fun onNothingSelected(parent: AdapterView<*>?) { } } } } } private fun setupObservers() { viewModel.selectedImageLiveData.observeData(this) { binding.ivCover.setImageURI(it) onInputDataChanged() } viewModel.updateRoomResponseLiveData.observeResponse(this, success = { showSuccess(getString(R.string.updated)) onBackPressed() }) viewModel.roomSummaryLiveData.observeData(this) { it?.let { setInitialRoomData(it) } } viewModel.roomPowerLevelLiveData.observeData(this) { val userDefaultRoleLevel = it.usersDefaultOrDefault() binding.spUserRole.setSelection(AccessLevel.fromValue(userDefaultRoleLevel).ordinal) } viewModel.isRoomDataChangedLiveData.observeData(this) { binding.btnSave.isEnabled = it } } private fun setInitialRoomData(room: RoomSummary) { with(binding) { val roomInfo = room.toRoomInfo(roomType == CircleRoomTypeArg.Circle) ivCover.loadRoomProfileIcon( roomInfo.avatarUrl, roomInfo.title ) tilName.editText?.setText(roomInfo.title) tilTopic.editText?.setText(room.topic) } } private fun getRoomTypeName() = getString( when (roomType) { CircleRoomTypeArg.Circle -> R.string.circle CircleRoomTypeArg.Group -> R.string.group CircleRoomTypeArg.Photo -> R.string.gallery } ) private fun changeCoverImage() { mediaPickerHelper.showMediaPickerDialog(onImageSelected = { _, uri -> viewModel.setImageUri(uri) }) } private fun onInputDataChanged() { viewModel.handleRoomDataUpdate( binding.tilName.getText(), binding.tilTopic.getText(), getSelectedAccessLevel() ) } private fun getSelectedAccessLevel() = AccessLevel.entries.getOrNull(binding.spUserRole.selectedItemPosition) ?: AccessLevel.User }
8
Kotlin
4
29
7edec708f9c491a7b6f139fc2f2aa3e2b7149112
6,506
circles-android
Apache License 2.0
core/src/main/java/org/futo/circles/core/feature/room/update/UpdateRoomDialogFragment.kt
circles-project
615,347,618
false
{"Kotlin": 1307644, "C": 137821, "C++": 12364, "Shell": 3202, "CMake": 1680, "Ruby": 922}
package org.futo.circles.core.feature.room.update import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import androidx.core.widget.doAfterTextChanged import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import dagger.hilt.android.AndroidEntryPoint import org.futo.circles.core.R import org.futo.circles.core.base.fragment.BaseFullscreenDialogFragment import org.futo.circles.core.base.fragment.HasLoadingState import org.futo.circles.core.databinding.DialogFragmentUpdateRoomBinding import org.futo.circles.core.extensions.getRoleNameResId import org.futo.circles.core.extensions.getText import org.futo.circles.core.extensions.loadRoomProfileIcon import org.futo.circles.core.extensions.observeData import org.futo.circles.core.extensions.observeResponse import org.futo.circles.core.extensions.onBackPressed import org.futo.circles.core.extensions.setIsVisible import org.futo.circles.core.extensions.showSuccess import org.futo.circles.core.extensions.toRoomInfo import org.futo.circles.core.feature.picker.helper.MediaPickerHelper import org.futo.circles.core.model.AccessLevel import org.futo.circles.core.model.CircleRoomTypeArg import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.session.room.model.usersDefaultOrDefault import org.matrix.android.sdk.api.session.room.powerlevels.Role @AndroidEntryPoint class UpdateRoomDialogFragment : BaseFullscreenDialogFragment<DialogFragmentUpdateRoomBinding>(DialogFragmentUpdateRoomBinding::inflate), HasLoadingState { override val fragment: Fragment = this private val args: UpdateRoomDialogFragmentArgs by navArgs() private val viewModel by viewModels<UpdateRoomViewModel>() private val roomType: CircleRoomTypeArg get() = args.type private val mediaPickerHelper = MediaPickerHelper(this) private val circleTypeList = AccessLevel.entries.toTypedArray() private val circleTypeAdapter by lazy { ArrayAdapter(requireContext(), R.layout.view_spinner_item, circleTypeList.map { val role = Role.fromValue(it.levelValue, Role.Default.value) getString(role.getRoleNameResId()) }).apply { setDropDownViewResource(R.layout.view_spinner_item) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViews() setupObservers() } private fun setupViews() { with(binding) { val roomTypeName = getRoomTypeName() toolbar.title = getString(R.string.configure_room_format, roomTypeName) val nameHeader = "$roomTypeName ${getString(R.string.name)}" tvNameHeader.text = nameHeader val isGroup = roomType == CircleRoomTypeArg.Group tvTopicHeader.setIsVisible(isGroup) tilTopic.setIsVisible(isGroup) ivCover.setOnClickListener { changeCoverImage() } btnChangeIcon.setOnClickListener { changeCoverImage() } tilName.editText?.doAfterTextChanged { it?.let { onInputDataChanged() } } tilTopic.editText?.doAfterTextChanged { it?.let { onInputDataChanged() } } btnSave.setOnClickListener { viewModel.update( tilName.getText(), tilTopic.getText(), getSelectedAccessLevel(), roomType ) startLoading(btnSave) } val isCircle = roomType == CircleRoomTypeArg.Circle tvRoleHeader.setIsVisible(!isCircle) spUserRole.apply { setIsVisible(!isCircle) adapter = circleTypeAdapter onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { onInputDataChanged() } override fun onNothingSelected(parent: AdapterView<*>?) { } } } } } private fun setupObservers() { viewModel.selectedImageLiveData.observeData(this) { binding.ivCover.setImageURI(it) onInputDataChanged() } viewModel.updateRoomResponseLiveData.observeResponse(this, success = { showSuccess(getString(R.string.updated)) onBackPressed() }) viewModel.roomSummaryLiveData.observeData(this) { it?.let { setInitialRoomData(it) } } viewModel.roomPowerLevelLiveData.observeData(this) { val userDefaultRoleLevel = it.usersDefaultOrDefault() binding.spUserRole.setSelection(AccessLevel.fromValue(userDefaultRoleLevel).ordinal) } viewModel.isRoomDataChangedLiveData.observeData(this) { binding.btnSave.isEnabled = it } } private fun setInitialRoomData(room: RoomSummary) { with(binding) { val roomInfo = room.toRoomInfo(roomType == CircleRoomTypeArg.Circle) ivCover.loadRoomProfileIcon( roomInfo.avatarUrl, roomInfo.title ) tilName.editText?.setText(roomInfo.title) tilTopic.editText?.setText(room.topic) } } private fun getRoomTypeName() = getString( when (roomType) { CircleRoomTypeArg.Circle -> R.string.circle CircleRoomTypeArg.Group -> R.string.group CircleRoomTypeArg.Photo -> R.string.gallery } ) private fun changeCoverImage() { mediaPickerHelper.showMediaPickerDialog(onImageSelected = { _, uri -> viewModel.setImageUri(uri) }) } private fun onInputDataChanged() { viewModel.handleRoomDataUpdate( binding.tilName.getText(), binding.tilTopic.getText(), getSelectedAccessLevel() ) } private fun getSelectedAccessLevel() = AccessLevel.entries.getOrNull(binding.spUserRole.selectedItemPosition) ?: AccessLevel.User }
8
Kotlin
4
29
7edec708f9c491a7b6f139fc2f2aa3e2b7149112
6,506
circles-android
Apache License 2.0
feature-weighbridge/src/test/java/android/template/feature/weighbridge/ui/detail/DetailWeighedItemViewModelTest.kt
CrulQRL
814,083,445
false
{"Kotlin": 113475, "Shell": 3210}
package android.template.feature.weighbridge.ui.detail import android.template.feature.weighbridge.FakeWeighedItemRepository import androidx.lifecycle.SavedStateHandle import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class DetailWeighedItemViewModelTest { @Test fun uiState_getUid_6() = runTest { val viewModel = DetailWeighedItemViewModel( SavedStateHandle().apply { set("uid", 6L) }, FakeWeighedItemRepository() ) val item = viewModel.uiState.first() as DetailWeighedItemUiState.Success Assert.assertEquals(item.data.uid, 6) Assert.assertEquals(item.data.driver, "Komang") } }
0
Kotlin
0
0
ec9b16835d8b4d5dae53038d7613b6598814f865
855
WeighBridge
Apache License 2.0
app/src/main/java/com/media/dmitry68/callrecorder/receiver/CallReceiver.kt
dmisuvorov
158,179,357
false
null
package com.media.dmitry68.callrecorder.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.support.v4.content.LocalBroadcastManager import android.telephony.TelephonyManager import android.util.Log import com.media.dmitry68.callrecorder.preferences.ManagerPref import com.media.dmitry68.callrecorder.recorder.Recorder import com.media.dmitry68.callrecorder.service.ModeOfWork import com.media.dmitry68.callrecorder.service.ServiceOnDemandManager import com.media.dmitry68.callrecorder.stateCall.CallStates import com.media.dmitry68.callrecorder.stateCall.Caller import com.media.dmitry68.callrecorder.stateCall.DirectionCallState import com.media.dmitry68.callrecorder.stateCall.TalkStates import java.util.* class CallReceiver : BroadcastReceiver(){ private val TAG = "LOG" private val incomingNumber = TelephonyManager.EXTRA_INCOMING_NUMBER private lateinit var receiverContext: Context private lateinit var recorder: Recorder private lateinit var managerPref: ManagerPref override fun onReceive(context: Context, intent: Intent?) { Log.d(TAG, "On receive") if (intent?.action == IntentActions.PHONE_STAGE_CHANGED) { if (intent.hasExtra(incomingNumber)) { caller.number = intent.getStringExtra(incomingNumber) } receiverContext = context val telephonyManager = receiverContext.getSystemService(Context.TELEPHONY_SERVICE) if (telephonyManager is TelephonyManager) caller.statePhone = telephonyManager.callState Log.d(TAG, "On Receive ${caller.number} ${caller.statePhone} $lastState") managerPref = ManagerPref(receiverContext) when (managerPref.getModeOfWorkInSharedPref()){ ModeOfWork.Background -> { onCallStateChanged(caller.statePhone, this::initRecord, this::stopRecord) } ModeOfWork.OnDemandShake, ModeOfWork.OnDemandButton -> { onCallStateChanged(caller.statePhone, this::messageOnDemandManagerOnCallStateStart, this::messageOnDemandManagerOnCallStateStop) } } } } //INCOMING - IDLE -> RINGING -> OFFHOOK -> IDLE //OUTGOING - IDLE -> OFFHOOK -> IDLE //MISSING - IDLE -> RINGING -> IDLE private inline fun onCallStateChanged(statePhone: Int, onCallStateOffHook: () -> Unit, onCallStop: () -> Unit = {}) { if (lastState == statePhone) return //no change when(statePhone){ CallStates.IDLE -> { when(lastState) { CallStates.RINGING -> { caller.directCallState = DirectionCallState.MISSING Log.d(TAG, "missing incoming call") } CallStates.OFFHOOK -> { when(caller.directCallState){ DirectionCallState.INCOMING -> { with(caller){ talkState = TalkStates.STOP stopTalk = Date() } onCallStop() Log.d(TAG, "stop incoming call") } DirectionCallState.OUTGOING -> { with(caller){ talkState = TalkStates.STOP stopTalk = Date() } onCallStop() Log.d(TAG, "stop outgoing call") } } } } } CallStates.OFFHOOK -> { when(lastState) { CallStates.RINGING -> { with(caller){ directCallState = DirectionCallState.INCOMING talkState = TalkStates.ANSWER startTalk = Date() } onCallStateOffHook() Log.d(TAG, "offHook incoming call ${caller.number}") } CallStates.IDLE -> { with(caller) { directCallState = DirectionCallState.OUTGOING talkState = TalkStates.START startTalk = Date() } onCallStateOffHook() Log.d(TAG, "offHook outgoing call ${caller.number}") } } } CallStates.RINGING -> { with(caller) { directCallState = DirectionCallState.INCOMING talkState = TalkStates.IDLE } Log.d(TAG, "ringing incoming call ${caller.number}") } } lastState = statePhone } private fun initRecord() { recorder = Recorder(caller, receiverContext).apply { startRecord() }//TODO: add stopwatch and text in notification } private fun stopRecord(){ recorder.stopRecord() } private fun messageOnDemandManagerOnCallStateStart(){ val intent = Intent(ServiceOnDemandManager.ON_CALL_STATE_START).apply { putExtra(CALL_NUMBER, caller.number) putExtra(DIRECT_CALL, caller.directCallState) } LocalBroadcastManager.getInstance(receiverContext).sendBroadcast(intent) } private fun messageOnDemandManagerOnCallStateStop(){ val intent = Intent(ServiceOnDemandManager.ON_CALL_STATE_STOP).apply { putExtra(CALL_NUMBER, caller.number) putExtra(DIRECT_CALL, caller.directCallState) } LocalBroadcastManager.getInstance(receiverContext).sendBroadcast(intent) } companion object { private var lastState: Int = CallStates.IDLE private val caller: Caller = Caller() const val CALL_NUMBER = "CALL_NUMBER" const val DIRECT_CALL = "DIRECT_CALL" } }
0
Kotlin
0
0
34414f28a9c41aa39c4c05c8af073d3b564148a5
6,267
CallRecorder
Apache License 2.0
linea/src/commonMain/kotlin/compose/icons/lineaicons/arrows/DragDownDashed.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineaicons.arrows import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Bevel 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 compose.icons.lineaicons.ArrowsGroup public val ArrowsGroup.DragDownDashed: ImageVector get() { if (_dragDownDashed != null) { return _dragDownDashed!! } _dragDownDashed = Builder(name = "DragDownDashed", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp, viewportWidth = 64.0f, viewportHeight = 64.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(32.0f, 31.0f) lineTo(32.0f, 63.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(32.0f, 16.0f) moveToRelative(-15.0f, 0.0f) arcToRelative(15.0f, 15.0f, 0.0f, true, true, 30.0f, 0.0f) arcToRelative(15.0f, 15.0f, 0.0f, true, true, -30.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(23.0f, 54.0f) lineToRelative(9.0f, 9.0f) lineToRelative(9.0f, -9.0f) } } .build() return _dragDownDashed!! } private var _dragDownDashed: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,454
compose-icons
MIT License
src/main/kotlin/com/glancebar/apiboilerplate/exceptions/ParamsException.kt
yisen-cai
575,810,398
false
null
package com.glancebar.apiboilerplate.exceptions import com.glancebar.apiboilerplate.utils.ErrResult /** * * @author YISEN * @date 2020/12/15 */ class ParamsException( errResult: ErrResult = ErrResult("参数错误", 1, null) ) : APIException(errResult)
0
Kotlin
0
0
edae30dfdac4a547fcbee3245ae1cd81993220a8
255
api-boilerplate
Apache License 2.0
server/src/main/kotlin/dev/chargedbyte/reaktor_summer_2022/feature/game/routing/GamesPagedResponse.kt
ChargedByte
448,422,989
false
null
package dev.chargedbyte.reaktor_summer_2022.feature.game.routing import dev.chargedbyte.reaktor_summer_2022.feature.game.GameDto data class GamesPagedResponse(val totalPages: Long, val games: List<GameDto>)
0
Kotlin
0
0
9e518e2b52be1b4e32b0cc4a8bc0a46db46a3544
209
reaktor-summer-2022
MIT License
app/src/main/java/com/cogitator/justnavigation/MainActivity.kt
AnkitDroidGit
151,366,321
false
null
package com.cogitator.justnavigation import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.GravityCompat import androidx.navigation.Navigation.findNavController import androidx.navigation.ui.NavigationUI.* import kotlinx.android.synthetic.main.activity_main.* /** * @author Ankit Kumar on 03/10/2018 */ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) setupNavigation() } override fun onSupportNavigateUp(): Boolean { return navigateUp(drawerLayout, findNavController(this, R.id.host_fragment)) } override fun onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } private fun setupNavigation() { val navController = findNavController(this, R.id.host_fragment) // Update action bar to reflect navigation setupActionBarWithNavController(this, navController, drawerLayout) // Handle nav drawer item clicks navigationView.setNavigationItemSelectedListener { menuItem -> menuItem.isChecked = true drawerLayout.closeDrawers() true } // Tie nav graph to items in nav drawer setupWithNavController(navigationView, navController) } }
0
Kotlin
1
3
d319f418606afb6318ff28798fd9e9082f2d8980
1,550
JustNavigation
Apache License 2.0
fcl/src/main/java/com/portto/fcl/model/signable/Roles.kt
portto
505,659,431
false
null
package com.portto.fcl.model.signable import kotlinx.serialization.Serializable @Serializable data class Roles( var authorizer: Boolean = false, var payer: Boolean = false, var proposer: Boolean = false ) { fun merge(role: Roles) { proposer = proposer || role.proposer authorizer = authorizer || role.authorizer payer = payer || role.payer } }
0
Kotlin
3
21
48526162272dc07fec5774762d83a47dabfe5a1f
390
fcl-android
MIT License
src/main/kotlin/jsonsql/functions/Function.kt
tim-patterson
131,454,972
false
null
package jsonsql.functions; sealed class Function { abstract fun validateParameterCount(count: Int) : Boolean abstract class ScalarFunction: Function() { abstract fun execute(args: List<Any?>): Any? } abstract class AggregateFunction: Function() { abstract fun executor(): AggregateFunctionExecutor } } val functionRegistry = mapOf<String, Function>( //math "add" to AddFunction, "minus" to MinusFunction, "multiply" to MultiplyFunction, "divide" to DivideFunction, "gt" to GTFunction, "gte" to GTEFunction, "lt" to LTFunction, "lte" to LTEFunction, "equal" to EqFunction, "not_equal" to NEqFunction, // util "idx" to IndexFunction, "is_null" to IsNullFunction, "is_not_null" to IsNotNullFunction, "number" to NumberFunction, "or" to OrFunction, "and" to AndFunction, "coalesce" to CoalesceFunction, // Aggregate Functions "count" to CountFunction, "sum" to SumFunction, "min" to MinFunction, "max" to MaxFunction, "max_row" to MaxRowFunction )
1
Kotlin
1
3
1fc28152476ad9ebcc2b1aefce1c2c6636a98083
1,184
jsonsql
MIT License
app/src/main/java/com/disfluency/model/Paciente.kt
UTN-FRBA-Mobile
638,009,160
false
null
package com.disfluency.model import java.time.LocalDate import java.time.Period data class Paciente(val name: String, val lastName: String, val dateOfBirth: LocalDate, val id: Int, val account: String, val joinedSince: LocalDate, val profilePic: Int){ fun initials(): String { return (name.first().toString() + lastName.first().toString()).uppercase() } fun fullName(): String{ return "$name $lastName" } fun fullNameFormal(): String{ return "$lastName, $name" } fun age(): Int{ return Period.between( dateOfBirth, LocalDate.now() ).years } }
2
Kotlin
0
0
23662f8f39ada8ec2e5180d54b21fb021b03b8ca
644
Disfluency
MIT License
idea/tests/testData/structuralsearch/binaryExpression/binaryRem.kt
JetBrains
278,369,660
false
null
val a = <warning descr="SSR">1 % 2</warning> val b = <warning descr="SSR">1.rem(2)</warning> val c = 1 % 3 val d = 1.rem(3)
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
126
intellij-kotlin
Apache License 2.0
utils-android/src/main/java/io/github/boopited/droidutils/listeners/SimpleAnimatorListener.kt
boopited
217,223,466
false
null
package io.github.boopited.droidutils.listeners import android.animation.Animator interface SimpleAnimatorListener: Animator.AnimatorListener { override fun onAnimationRepeat(animator: Animator) { // Extender only need override necessary method } override fun onAnimationEnd(animator: Animator) { // Extender only need override necessary method } override fun onAnimationCancel(animator: Animator) { // Extender only need override necessary method } override fun onAnimationStart(animator: Animator) { // Extender only need override necessary method } }
0
Kotlin
0
0
0ad6a2b069f8e9503be7ac569cf22884c24c7ca4
622
utils-android
Apache License 2.0
app/src/main/java/com/oscarliang/knews/di/FragmentBuildersModule.kt
iamoscarliang
761,140,560
false
{"Kotlin": 151931}
package com.oscarliang.knews.di import com.oscarliang.knews.ui.bookmarks.BookmarksFragment import com.oscarliang.knews.ui.breakingnews.BreakingNewsFragment import com.oscarliang.knews.ui.newsdetail.NewsDetailFragment import com.oscarliang.knews.ui.search.SearchFragment import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class FragmentBuildersModule { @ContributesAndroidInjector abstract fun contributeBreakingNewsFragment(): BreakingNewsFragment @ContributesAndroidInjector abstract fun contributeSearchFragment(): SearchFragment @ContributesAndroidInjector abstract fun contributeBookmarksFragment(): BookmarksFragment @ContributesAndroidInjector abstract fun contributeNewsDetailFragment(): NewsDetailFragment }
0
Kotlin
0
0
c03764f4d80338cff8fa98bc59a72ecbd892af6d
790
k-news
MIT License
android/app/src/main/kotlin/com/example/carousel_app_scaffold/MainActivity.kt
henlamk
288,693,361
false
{"Dart": 26409, "Swift": 404, "Kotlin": 138, "Objective-C": 38}
package com.example.carousel_app_scaffold import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
a7daf2214965e84998c0ebc4538d0208b898faf6
138
carousel_app_scaffold
MIT License
rx-location-manager-nmea/src/test/kotlin/net/samystudio/rxlocationmanager/nmea/GLLTest.kt
balao7
241,983,601
true
{"Kotlin": 108910, "Shell": 949}
package net.samystudio.rxlocationmanager.nmea import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class GLLTest { @Test fun validate() { val gll = GLL("\$GPGLL,3342.6618,N,11751.3858,W,002153.000,A*29") assertEquals("GPGLL", gll.type) assertEquals(33.71103, gll.latitude!!, PRECISION) assertEquals(-117.85643, gll.longitude!!, PRECISION) assertEquals("002153.000", gll.time) assertEquals(GLL.Status.A, gll.status) assertEquals("29", gll.checksum) } @Test fun validateEmpty() { val gll = GLL("\$GPGLL,,,,,,*50") assertEquals("GPGLL", gll.type) assertEquals(null, gll.latitude) assertEquals(null, gll.longitude) assertEquals("", gll.time) assertEquals(null, gll.status) assertEquals("50", gll.checksum) } @Test fun validateTypeError() { val message = "\$GPGL,3342.6618,N,11751.3858,W,002153.000,A*29" val expected = NmeaException( Nmea.getParseErrorMessage( 0, TypeValidator::class.java.simpleName, message ), 0 ) var result: NmeaException? = null try { GLL(message) } catch (e: NmeaException) { result = e } assertEquals(expected, result) } @Test fun validateLatitudeError() { val message = "\$GPGLL,33426618,N,11751.3858,W,002153.000,A*29" val expected = NmeaException( Nmea.getParseErrorMessage( 1, LatitudeValidator::class.java.simpleName, message ), 1 ) var result: NmeaException? = null try { GLL(message) } catch (e: NmeaException) { result = e } assertEquals(expected, result) } @Test fun validateLatitudeDirectionError() { val message = "\$GPGLL,3342.6618,z,11751.3858,W,002153.000,A*29" val expected = NmeaException( Nmea.getParseErrorMessage( 2, EnumValidator::class.java.simpleName, message ), 2 ) var result: NmeaException? = null try { GLL(message) } catch (e: NmeaException) { result = e } assertEquals(expected, result) } @Test fun validateLongitudeError() { val message = "\$GPGLL,3342.6618,N,117513858,W,002153.000,A*29" val expected = NmeaException( Nmea.getParseErrorMessage( 3, LongitudeValidator::class.java.simpleName, message ), 3 ) var result: NmeaException? = null try { GLL(message) } catch (e: NmeaException) { result = e } assertEquals(expected, result) } @Test fun validateLongitudeDirectionError() { val message = "\$GPGLL,3342.6618,N,11751.3858,z,002153.000,A*29" val expected = NmeaException( Nmea.getParseErrorMessage( 4, EnumValidator::class.java.simpleName, message ), 4 ) var result: NmeaException? = null try { GLL(message) } catch (e: NmeaException) { result = e } assertEquals(expected, result) } @Test fun validateTimeError() { val message = "\$GPGLL,3342.6618,N,11751.3858,W,002153000,A*29" val expected = NmeaException( Nmea.getParseErrorMessage( 5, TimeValidator::class.java.simpleName, message ), 5 ) var result: NmeaException? = null try { GLL(message) } catch (e: NmeaException) { result = e } assertEquals(expected, result) } @Test fun validateStatusError() { val message = "\$GPGLL,3342.6618,N,11751.3858,W,002153.000,z*29" val expected = NmeaException( Nmea.getParseErrorMessage( 6, EnumValidator::class.java.simpleName, message ), 6 ) var result: NmeaException? = null try { GLL(message) } catch (e: NmeaException) { result = e } assertEquals(expected, result) } companion object { private const val PRECISION = 0.0000001 } }
0
null
0
0
8e909fa7a63755686b81977c6f7607ba64f51e37
4,991
RxLocationManager-1
Apache License 2.0