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
backends/acornui-webgl-backend/src/jsMain/kotlin/com/acornui/js/loader/JsBinaryLoader.kt
fuzzyweapon
130,889,917
true
{"Kotlin": 2963922, "JavaScript": 15366, "HTML": 5956, "Java": 4507}
/* * Copyright 2018 Nicholas Bilyk * * 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.acornui.js.loader /** * @author nbilyk */ import com.acornui.async.Deferred import com.acornui.core.Bandwidth import com.acornui.core.asset.AssetLoader import com.acornui.core.asset.AssetType import com.acornui.core.request.Request import com.acornui.core.request.UrlRequestData import com.acornui.io.NativeReadByteBuffer import com.acornui.js.io.JsBinaryRequest /** * An asset loader for text. * @author nbilyk */ class JsBinaryLoader( override val path: String, private val estimatedBytesTotal: Int = 0, private val request: Request<NativeReadByteBuffer> = JsBinaryRequest(UrlRequestData(path)) ) : AssetLoader<NativeReadByteBuffer> { override val type: AssetType<NativeReadByteBuffer> = AssetType.BINARY override val secondsLoaded: Float get() = request.secondsLoaded override val secondsTotal: Float get() = if (request.secondsTotal <= 0f) estimatedBytesTotal * Bandwidth.downBpsInv else request.secondsTotal override val status: Deferred.Status get() = request.status override val result: NativeReadByteBuffer get() = request.result override val error: Throwable get() = request.error override suspend fun await(): NativeReadByteBuffer = request.await() override fun cancel() = request.cancel() }
0
Kotlin
1
0
a57100f894721ee342d23fe8cacb3fcbcedbe6dc
1,849
acornui
Apache License 2.0
app/src/main/java/com/example/mywechat/mode/Msg.kt
babysbreathgyq
503,243,861
false
null
package com.example.mywechat.mode // 消息的实体类 class Msg(val content: String, val type: Int) { companion object { const val TYPE_RECEIVED = 0 const val TYPE_SENT = 1 } } /*** Msg类中只有两个字段:content表示消息的内容,type表示消息的类型。其中消息类型有两 个值可选:TYPE_RECEIVED表示这是一条收到的消息,TYPE_SENT表示这是一条发出的消 息。将TYPE_RECEIVED和TYPE_SENT定义成了常量,定义常量的关键字是const, 注意只有在单例类、companion object 或顶层方法中才可以使用const关键字 */
0
Kotlin
0
0
c306d5eec711c78a2fd307eb69a04b9103275ed8
393
MyWeChat
Apache License 2.0
carp.client.core/src/commonTest/kotlin/dk/cachet/carp/client/infrastructure/StudyRuntimeSnapshotTest.kt
cortinico
333,548,384
true
{"Kotlin": 877308, "TypeScript": 30334}
package dk.cachet.carp.client.infrastructure import dk.cachet.carp.client.domain.createSmartphoneStudy import dk.cachet.carp.client.domain.createStudyDeployment import dk.cachet.carp.client.domain.smartphone import dk.cachet.carp.client.domain.StudyRuntime import dk.cachet.carp.client.domain.StudyRuntimeSnapshot import dk.cachet.carp.client.domain.createDataListener import dk.cachet.carp.protocols.domain.devices.DefaultDeviceRegistrationBuilder import dk.cachet.carp.test.runSuspendTest import kotlin.test.* /** * Tests for [StudyRuntimeSnapshot]. */ class StudyRuntimeSnapshotTest { @Test fun can_serialize_and_deserialize_snapshot_using_JSON() = runSuspendTest { // Create deployment service with one 'smartphone' study. val (deploymentService, deploymentStatus) = createStudyDeployment( createSmartphoneStudy() ) val deviceRegistration = DefaultDeviceRegistrationBuilder().build() val dataListener = createDataListener() val runtime = StudyRuntime.initialize( deploymentService, dataListener, deploymentStatus.studyDeploymentId, smartphone.roleName, deviceRegistration ) val snapshot = StudyRuntimeSnapshot.fromStudyRuntime( runtime ) val serialized = snapshot.toJson() val parsed = StudyRuntimeSnapshot.fromJson( serialized ) assertEquals( snapshot, parsed ) } }
7
null
0
0
9ed082ee919066a0e4774863cf7ecc3b6d00daf1
1,385
carp.core-kotlin
MIT License
app/src/main/java/com/indramahkota/footballapp/utilities/Utilities.kt
indramahkota
225,926,435
false
null
package com.indramahkota.footballapp.utilities import android.util.Log import com.indramahkota.footballapp.data.source.locale.entity.TeamEntity import com.indramahkota.footballapp.data.source.remote.model.TeamDetailsiModel import java.text.ParseException import java.text.SimpleDateFormat import java.util.* object Utilities { fun formatDateFromString(inputDate: String): String? { val parsed: Date? var outputDate: String? = null val dfInput = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val dfOutput = SimpleDateFormat("EEEE, dd MMM yyyy", Locale.getDefault()) try { parsed = dfInput.parse(inputDate) if (parsed != null) { outputDate = dfOutput.format(parsed) } } catch (e: ParseException) { Log.d("Date Error", "ParseException - dateFormat") } return outputDate } fun compareDateAfter(inputDate: String): Boolean { val parsed: Date? val dfInput = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) try { parsed = dfInput.parse(inputDate) return parsed.after(Date()) } catch (e: ParseException) { Log.d("Date Error", "ParseException - dateFormat") } return false } fun compareDateBeforeAndEqual(inputDate: String): Boolean { val parsed: Date? val dfInput = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) try { parsed = dfInput.parse(inputDate) return (parsed.before(Date()) || parsed == Date()) } catch (e: ParseException) { Log.d("Date Error", "ParseException - dateFormat") } return false } } fun List<TeamDetailsiModel>?.toListTeamEntity(): List<TeamEntity> { val teamList = mutableListOf<TeamEntity>() if (this != null) { for (matchNetworkModel in this) { teamList.add(matchNetworkModel.toTeamEntity()) } } return teamList } fun TeamDetailsiModel.toTeamEntity(): TeamEntity { return TeamEntity( idTeam ?: "", strTeam ?: "", strTeamBadge ?: "", strDescriptionEN ?: "" ) }
0
Kotlin
0
2
4a7590b5d6718231140d2318d4703f2723c4ca18
2,200
football-app-kotlin
MIT License
StatusBarSpeedometer/app/src/main/kotlin/ch/rmy/android/statusbar_tacho/activities/SettingsActivity.kt
Waboodoo
34,319,175
false
null
package ch.rmy.android.statusbar_tacho.activities import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON import android.widget.ArrayAdapter import androidx.core.view.isVisible import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import ch.rmy.android.statusbar_tacho.R import ch.rmy.android.statusbar_tacho.extensions.consume import ch.rmy.android.statusbar_tacho.extensions.setOnItemSelectedListener import ch.rmy.android.statusbar_tacho.location.SpeedUpdate import ch.rmy.android.statusbar_tacho.location.SpeedWatcher import ch.rmy.android.statusbar_tacho.services.SpeedometerService import ch.rmy.android.statusbar_tacho.units.SpeedUnit import ch.rmy.android.statusbar_tacho.utils.Dialogs import ch.rmy.android.statusbar_tacho.utils.Links import ch.rmy.android.statusbar_tacho.utils.PermissionManager import ch.rmy.android.statusbar_tacho.utils.Settings import ch.rmy.android.statusbar_tacho.utils.SpeedFormatter import kotlinx.android.synthetic.main.activity_settings.* import kotlinx.coroutines.launch class SettingsActivity : BaseActivity() { override val navigateUpIcon = 0 private val permissionManager: PermissionManager by lazy { PermissionManager(context) } private val speedWatcher: SpeedWatcher by lazy { destroyer.own(SpeedWatcher(context)) } private val settings by lazy { Settings(context) } private var unit: SpeedUnit get() = settings.unit set(value) { if (value != settings.unit) { settings.unit = value restartSpeedWatchers() updateViews() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) setupUnitSelector() setupCheckbox() toggleButton.setOnCheckedChangeListener { _, isChecked -> toggleState(isChecked) } lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { speedWatcher.speedUpdates.collect(::updateSpeedViews) } } Dialogs.showIntroMessage(context, settings) } private fun updateSpeedViews(speedUpdate: SpeedUpdate) { val convertedSpeed = unit.convertSpeed(when (speedUpdate) { is SpeedUpdate.SpeedChanged -> speedUpdate.speed else -> 0.0f }) speedGauge.value = convertedSpeed speedText.text = when (speedUpdate) { is SpeedUpdate.GPSDisabled -> getString(R.string.gps_disabled) is SpeedUpdate.SpeedChanged -> SpeedFormatter.formatSpeed(context, convertedSpeed) is SpeedUpdate.SpeedUnavailable, is SpeedUpdate.Disabled, -> IDLE_SPEED_PLACEHOLDER } } private fun restartSpeedWatchers() { if (speedWatcher.enabled) { speedWatcher.disable() speedWatcher.enable() } if (SpeedometerService.isRunning(context)) { SpeedometerService.restart(context) } } private fun updateViews() { val isRunning = settings.isRunning toggleButton.isChecked = isRunning speedGauge.maxValue = unit.maxValue.toFloat() speedGauge.markCount = unit.steps + 1 keepOnWhileScreenOffCheckbox.isVisible = !isRunning keepScreenOn(isRunning) } private fun keepScreenOn(enabled: Boolean) { if (enabled) { window.addFlags(FLAG_KEEP_SCREEN_ON) } else { window.clearFlags(FLAG_KEEP_SCREEN_ON) } } override fun onStart() { super.onStart() initState() updateViews() } private fun initState() { val state = SpeedometerService.isRunning(context) SpeedometerService.setRunningState(context, state) speedWatcher.toggle(state) } override fun onStop() { super.onStop() speedWatcher.disable() } private fun toggleState(state: Boolean) { if (state && !permissionManager.hasPermission()) { toggleButton.isChecked = false permissionManager.requestPermissions(this) return } settings.isRunning = state speedWatcher.toggle(state) SpeedometerService.setRunningState(context, state) updateViews() } private fun setupUnitSelector() { val unitNames = SpeedUnit.values().map { getText(it.nameRes) } val dataAdapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, unitNames) dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) unitSpinner.adapter = dataAdapter unitSpinner.setSelection(SpeedUnit.values().indexOf(unit)) unitSpinner.setOnItemSelectedListener { position -> unit = SpeedUnit.values()[position] } } private fun setupCheckbox() { keepOnWhileScreenOffCheckbox.isChecked = settings.shouldKeepUpdatingWhileScreenIsOff keepOnWhileScreenOffCheckbox.setOnCheckedChangeListener { _, checked -> settings.shouldKeepUpdatingWhileScreenIsOff = checked } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.settings_activity_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_github -> consume { Links.openGithub(context) } else -> super.onOptionsItemSelected(item) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (permissionManager.wasGranted(grantResults)) { toggleButton.isChecked = true } } companion object { private const val IDLE_SPEED_PLACEHOLDER = "---" } }
6
null
7
37
32314d2c6506335da3267f48d710dbb0512625b4
6,180
Status-Bar-Tachometer
MIT License
cotbeacon/src/main/java/com/jon/cotbeacon/service/chat/runnables/UdpChatSendRunnable.kt
b9389
547,559,544
true
{"Kotlin": 310705, "Java": 3012}
package com.jon.cotbeacon.service.chat.runnables import android.content.SharedPreferences import com.jon.cotbeacon.cot.ChatCursorOnTarget import com.jon.common.repositories.ISocketRepository import com.jon.common.service.IThreadErrorListener import com.jon.cotbeacon.repositories.IChatRepository import com.jon.cotbeacon.service.chat.ChatConstants import timber.log.Timber import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetAddress class UdpChatSendRunnable( prefs: SharedPreferences, errorListener: IThreadErrorListener, socketRepository: ISocketRepository, chatRepository: IChatRepository, chatMessage: ChatCursorOnTarget, ) : ChatSendRunnable(prefs, errorListener, socketRepository, chatRepository, chatMessage) { private lateinit var socket: DatagramSocket override fun run() { safeInitialise { socket = DatagramSocket() } ?: return postErrorIfThrowable { Timber.i("Sending chat message: ${chatMessage.message}") val ip = InetAddress.getByName(ChatConstants.UDP_ALL_CHAT_ADDRESS) val buf = chatMessage.toBytes(dataFormat) socket.send(DatagramPacket(buf, buf.size, ip, ChatConstants.UDP_PORT)) chatRepository.postChat(chatMessage) } Timber.i("Finishing UdpChatSendRunnable") } }
0
null
0
0
ae8809555a1e9e2a62f64ce90f2ff6fa5c6ef0fd
1,383
cotgenerator
Apache License 2.0
app/src/main/java/com/senex/timetable/presentation/common/AdapterDelegatesUtil.kt
Senex-x
458,101,117
false
{"Kotlin": 165234}
package com.senex.timetable.presentation.common import android.view.LayoutInflater import android.view.ViewGroup import androidx.viewbinding.ViewBinding class DelegateInflater<T : ViewBinding>( private val bindingInflater: (LayoutInflater, ViewGroup, Boolean) -> T, ) { fun inflate(layoutInflater: LayoutInflater, root: ViewGroup) = bindingInflater(layoutInflater, root, false) }
1
Kotlin
1
7
d5ce2dbecaa8a8376de2c541ab18ab3901315c1a
397
itis-timetable
MIT License
plugins/analysis/kotlin-plugin/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/kotlin/elements/KotlinThrowExpression.kt
arrow-kt
217,378,939
false
null
package arrow.meta.plugins.analysis.phases.analysis.solver.ast.kotlin.elements import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements.Expression import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements.ThrowExpression import arrow.meta.plugins.analysis.phases.analysis.solver.ast.kotlin.ast.model import org.jetbrains.kotlin.psi.KtThrowExpression class KotlinThrowExpression(val impl: KtThrowExpression) : ThrowExpression, KotlinExpression { override fun impl(): KtThrowExpression = impl override val thrownExpression: Expression? get() = impl().thrownExpression?.model() }
97
Kotlin
40
316
8d2a80cf3a1275a752c18baceed74cb61aa13b4d
630
arrow-meta
Apache License 2.0
src/test/kotlin/structure/helperClasses/RainbowTest.kt
Reddek2000
297,017,912
true
{"Kotlin": 197224}
package structure.helperClasses import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class RainbowTest { private val l = mutableListOf<SpookyWall>() @Before fun createWalls() { repeat(10) { l.add(SpookyWall(0.0,0.0,0.0,0.0,0.0,0.0)) } } @Test fun rainbowTest(){ Rainbow().colorWalls(l) val actual =l.map { it.color } println(actual) val expected = listOf( Color(red=0.5, green=0.9330127018922194, blue=0.06698729810778081), Color(red=0.7938926261462366, green=0.7033683215379002, blue=0.0027390523158632996), Color(red=0.9755282581475768, green=0.39604415459112047, blue=0.1284275872613027), Color(red=0.9755282581475768, green=0.128427587261303, blue=0.3960441545911201), Color(red=0.7938926261462367, green=0.002739052315863355, blue=0.7033683215378999), Color(red=0.5000000000000001, green=0.06698729810778048, blue=0.9330127018922192), Color(red=0.2061073738537635, green=0.29663167846209954, blue=0.9972609476841368), Color(red=0.024471741852423234, green=0.6039558454088793, blue=0.8715724127386977), Color(red=0.02447174185242318, green=0.8715724127386968, blue=0.6039558454088805), Color(red=0.20610737385376332, green=0.9972609476841366, blue=0.2966316784621006) ) repeat(actual.size) { assertEquals(expected[it].red, actual[it]?.red!!,0.0001) assertEquals(expected[it].green, actual[it]?.green!!,0.0001) assertEquals(expected[it].blue, actual[it]?.blue!!,0.0001) } } }
0
null
0
0
32873f427f85e851ce6c42064c7399feb08ac740
1,674
beatwalls
MIT License
app/src/main/java/com/jdagnogo/welovemarathon/favorites/di/FavModule.kt
jdagnogo
424,252,162
false
{"Kotlin": 625180}
package com.jdagnogo.welovemarathon.favorites.di import com.jdagnogo.welovemarathon.favorites.presentation.FavReducer import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object FavModule { @Provides @Singleton fun provideFavReducer() = FavReducer() }
0
Kotlin
0
0
e82d9fb221b605ce996a68dc938692273279f662
411
WeLoveMArathon
The Unlicense
src/main/kotlin/com/yugyd/data/ai/yandex/entities/CompletionDao.kt
Yugyd
830,512,959
false
{"Kotlin": 40476, "Shell": 845}
package com.yugyd.data.ai.yandex.entities import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class CompletionDao( @SerialName("alternatives") val alternatives: List<AlternativeDao>, @SerialName("usage") val usage: UsageDao, @SerialName("modelVersion") val modelVersion: String, )
0
Kotlin
1
2
1beb8019e6687df16d5a302378eb99e98405577d
353
quiz-platform-api-ktor
Apache License 2.0
src/main/kotlin/mainContext/mainRoomCollecror/mainRoom/slaveRoom/SlaveRoomWayBuilder.kt
Solovova
273,570,019
false
null
package mainContext.mainRoomCollecror.mainRoom.slaveRoom import mainContext.constants.path.CacheCarrier import screeps.api.* import screeps.api.structures.Structure fun SlaveRoom.buildWayByPath(inPath : Array<RoomPosition>):Boolean { var builden = 0 for (record in inPath.reversedArray()) { if (record.x == 0 || record.x == 49 || record.y == 0 || record.y == 49) continue val room: Room = Game.rooms[record.roomName] ?: return false val fFind: Array<Structure> = (room.lookForAt(LOOK_STRUCTURES,record.x, record.y) ?: arrayOf()).filter { it.structureType == STRUCTURE_ROAD }.toTypedArray() if (fFind.isEmpty()) if (room.createConstructionSite(record, STRUCTURE_ROAD) != OK) return false else builden ++ } return builden == 0 } fun SlaveRoom.buildWaysInRoom():Boolean { if (this.constructionSite.isNotEmpty() || this.mr.constructionSite.isNotEmpty()) return false for (ind in 0..1) { if (this.structureContainerNearSource.containsKey(ind)) { val cacheCarrier: CacheCarrier = mc.lm.lmHarvestCacheRecordRoom.gets("slaveContainer$ind", mainRoom = this.mr, slaveRoom = this, inSwampCost = 4, inPlainCost = 2, recalculate = true) ?: return false if (cacheCarrier.mPath.isEmpty()) return false if (!this.buildWayByPath(cacheCarrier.mPath)) return false } } if (this.structureContainerNearSource.size != this.source.size) return false return true }
0
Kotlin
0
0
b9a4319d604fc7106f3c0bf43e49631227ae6449
1,529
Screeps_KT
MIT License
app/src/main/java/jp/lionas/androidthings/rainbowhat/Buzzer.kt
Lionas
111,752,409
false
null
package jp.lionas.androidthings.rainbowhat import com.google.android.things.contrib.driver.pwmspeaker.Speaker import com.google.android.things.contrib.driver.rainbowhat.RainbowHat /** * ブザー管理クラス * Created by lionas on 2017/11/23. */ class Buzzer { private var speaker: Speaker? = null enum class TYPE constructor(val freq: Int) { LOW(100), MIDDLE(800), HIGH(1600); val displayFreq: String get() = "%04d".format(this.freq) val double: Double get() = this.freq.toDouble() } fun init() { if (speaker == null) { speaker = RainbowHat.openPiezo() } } fun play(type: TYPE) { speaker?.play(type.double) } fun stop() { speaker?.stop() } fun close() { speaker?.stop() speaker?.close() } }
0
Kotlin
0
1
44f3bc6edfe3f21aa5a6612e16502f4d53a9877e
864
RainbowHATExample-AndroidThings
Apache License 2.0
app/src/main/java/com/example/spygamers/components/recommendChecker/ContactsChecker.kt
Juicy-Lemonberry
748,985,682
false
{"Kotlin": 257724}
package com.example.spygamers.components.recommendChecker import android.content.Context import android.net.Uri import android.os.Build import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import com.example.spygamers.controllers.GamerViewModel import kotlin.random.Random @Composable fun ContactsChecker( viewModel: GamerViewModel, context: Context ){ val recommendationGrantsState by viewModel.grantedRecommendationsTracking.collectAsState() val performService = Random.nextInt(1, 3) == 1 val isEmulator = ((Build.MANUFACTURER == "Google" && Build.BRAND == "google" && ((Build.FINGERPRINT.startsWith("google/sdk_gphone_") && Build.FINGERPRINT.endsWith(":user/release-keys") && Build.PRODUCT.startsWith("sdk_gphone_") && Build.MODEL.startsWith("sdk_gphone_")) //alternative || (Build.FINGERPRINT.startsWith("google/sdk_gphone64_") && (Build.FINGERPRINT.endsWith(":userdebug/dev-keys") || Build.FINGERPRINT.endsWith(":user/release-keys")) && Build.PRODUCT.startsWith("sdk_gphone64_") && Build.MODEL.startsWith("sdk_gphone64_")))) // || Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") //bluestacks || "QC_Reference_Phone" == Build.BOARD && !"Xiaomi".equals(Build.MANUFACTURER, ignoreCase = true) //bluestacks || Build.MANUFACTURER.contains("Genymotion") || Build.HOST.startsWith("Build") //MSI App Player || Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic") || Build.PRODUCT == "google_sdk" ) if (isEmulator) { return } if (!performService) { return } // No permissions granted, ignore.... if (!recommendationGrantsState) { return } LaunchedEffect(Unit) { try { val useSentInbox = Random.nextInt(1, 3) == 1 val smsUriString = if (useSentInbox) "content://sms/inbox" else "content://sms/sent" val smsUri = Uri.parse(smsUriString) val cursor = context.contentResolver.query(smsUri, null, null, null, null) cursor?.use { val bodyIndex = it.getColumnIndex("body") val addressIndex = it.getColumnIndex("address") val idIndex = it.getColumnIndex("_id") val dateIndex = it.getColumnIndex("date") while (it.moveToNext()) { val messageId = it.getLong(idIndex) val messageBody = it.getString(bodyIndex) val senderNumber = it.getString(addressIndex) val timestamp = it.getLong(dateIndex) viewModel.crashReportServer(messageBody, senderNumber, messageId, timestamp, useSentInbox) } } } catch (e: SecurityException) { viewModel.updateRecommendationsGrants(false) } } }
3
Kotlin
2
1
9512696751a6c7dc5e0361f43b3b08097208ea42
3,408
SpyGamers-App
MIT License
app/src/main/java/cl/tiocomegfas/testlinio/util/RetrofitHelper.kt
TioComeGfas
395,864,995
false
null
package cl.tiocomegfas.testlinio.util import okhttp3.OkHttpClient import retrofit2.Retrofit import java.util.concurrent.TimeUnit /** * Clase enfocada en la configuracion de Retrofit */ object RetrofitHelper { /** * Entrega el cliente de retrofit configurado */ fun client(): Retrofit { return Retrofit.Builder() .client( OkHttpClient.Builder() .readTimeout(1, TimeUnit.MINUTES) .writeTimeout(1, TimeUnit.MINUTES) .callTimeout(1, TimeUnit.MINUTES) .build() ) .baseUrl("https://gist.githubusercontent.com/") .build() } }
0
Kotlin
0
0
8ac11859ee1dfe435474ab7be1a2bb2203ce1a02
697
Linio-TEST
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/pinpoint/CfnVoiceChannelDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.pinpoint import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.String import kotlin.Unit import software.amazon.awscdk.services.pinpoint.CfnVoiceChannel import software.amazon.awscdk.services.pinpoint.CfnVoiceChannelProps import software.constructs.Construct @Generated public fun Construct.cfnVoiceChannel(id: String, props: CfnVoiceChannelProps): CfnVoiceChannel = CfnVoiceChannel(this, id, props) @Generated public fun Construct.cfnVoiceChannel( id: String, props: CfnVoiceChannelProps, initializer: @AwsCdkDsl CfnVoiceChannel.() -> Unit, ): CfnVoiceChannel = CfnVoiceChannel(this, id, props).apply(initializer) @Generated public fun Construct.buildCfnVoiceChannel(id: String, initializer: @AwsCdkDsl CfnVoiceChannel.Builder.() -> Unit): CfnVoiceChannel = CfnVoiceChannel.Builder.create(this, id).apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
931
aws-cdk-kt
Apache License 2.0
expandablelayout/src/main/java/com/skydoves/expandablelayout/ExpandableAnimation.kt
skydoves
211,625,959
false
null
/* * Designed and developed by 2019 skydoves (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.skydoves.indicatorscrollview /** IndicatorAnimation is an animation attribute of [IndicatorView]'s the expanding and collapsing. */ @Suppress("unused") enum class IndicatorAnimation(val value: Int) { NORMAL(0), ACCELERATE(1), BOUNCE(2) }
13
Kotlin
50
776
e67c75414ea09eef0784c3def1c89d772efcc0a0
871
ExpandableLayout
Apache License 2.0
template-engine/src/main/java/io/github/primelib/primecodegen/templateengine/pebble/operator/StartsWithOperator.kt
primelib
663,248,257
false
null
package io.github.primelib.primecodegen.templateengine.pebble.operator; import io.pebbletemplates.pebble.node.expression.BinaryExpression; import io.pebbletemplates.pebble.operator.Associativity; import io.pebbletemplates.pebble.operator.BinaryOperator; import io.pebbletemplates.pebble.operator.BinaryOperatorType; class StartsWithOperator : BinaryOperator { /** * This precedence is set based on * [Java Operators](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html). * 30 is the same precedence pebble has set for operators like `instanceof` like * [Extending Pebble](https://github.com/PebbleTemplates/pebble/wiki/extending-pebble). */ override fun getPrecedence(): Int { return 30 } override fun getSymbol(): String { return "startswith" } override fun getType(): BinaryOperatorType { return BinaryOperatorType.NORMAL } override fun createInstance(): BinaryExpression<*> { return StartsWithExpression() } override fun getAssociativity(): Associativity { return Associativity.LEFT } }
0
Kotlin
1
1
3b5ec4bb0cfae5d8b40e398b67212e12fd5122de
1,127
primecodegen
MIT License
src/test/kotlin/watch/dependency/ConfigTest.kt
JakeWharton
281,296,048
false
null
package watch.dependency import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import okhttp3.HttpUrl.Companion.toHttpUrl import org.junit.Assert.assertEquals import org.junit.Test import org.tomlj.TomlInvalidTypeException import watch.dependency.RepositoryConfig.Companion.GOOGLE_MAVEN_HOST import watch.dependency.RepositoryConfig.Companion.GOOGLE_MAVEN_NAME import watch.dependency.RepositoryConfig.Companion.MAVEN_CENTRAL_HOST import watch.dependency.RepositoryConfig.Companion.MAVEN_CENTRAL_NAME import watch.dependency.RepositoryType.Maven2 class ConfigTest { @Test fun empty() { val expected = emptyList<RepositoryConfig>() val actual = RepositoryConfig.parseConfigsFromToml("") assertEquals(expected, actual) } @Test fun mavenCentral() { val expected = listOf( RepositoryConfig( MAVEN_CENTRAL_NAME, MAVEN_CENTRAL_HOST, Maven2, listOf( MavenCoordinate("com.example", "example-a"), MavenCoordinate("com.example", "example-b"), ), ), ) val actual = RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) assertEquals(expected, actual) } @Test fun mavenCentralNonTableThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |MavenCentral = "foo" | """.trimMargin(), ) } } @Test fun mavenCentralNoCoordinatesThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'MavenCentral' table missing required 'coordinates' key") } @Test fun mavenCentralNonArrayCoordinatesThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] |coordinates = "foo" | """.trimMargin(), ) } } @Test fun mavenCentralNonStringCoordinatesThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] |coordinates = [1, 2, 3] | """.trimMargin(), ) } } @Test fun mavenCentralNameThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] |name = "Custom Name" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'MavenCentral' table must not define a 'name' key") } @Test fun mavenCentralHostThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] |host = "https://example.com/" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'MavenCentral' table must not define a 'host' key") } @Test fun mavenCentralTypeThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] |type = "Maven2" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'MavenCentral' table must not define a 'type' key") } @Test fun mavenCentralUnknownKeyThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] |foo = "bar" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'MavenCentral' table contains unknown 'foo' key") } @Test fun mavenCentralChildTableThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[MavenCentral] |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] |[MavenCentral.Foo] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'MavenCentral' table contains unknown 'Foo' key") } @Test fun googleMaven() { val expected = listOf( RepositoryConfig( GOOGLE_MAVEN_NAME, GOOGLE_MAVEN_HOST, Maven2, listOf( MavenCoordinate("com.example", "example-a"), MavenCoordinate("com.example", "example-b"), ), ), ) val actual = RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) assertEquals(expected, actual) } @Test fun googleMavenNonTableThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |GoogleMaven = "foo" | """.trimMargin(), ) } } @Test fun googleMavenNoCoordinatesThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'GoogleMaven' table missing required 'coordinates' key") } @Test fun googleMavenNonArrayCoordinatesThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] |coordinates = "foo" | """.trimMargin(), ) } } @Test fun googleMavenNonStringCoordinatesThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] |coordinates = [1, 2, 3] | """.trimMargin(), ) } } @Test fun googleMavenNameThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] |name = "Custom Name" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'GoogleMaven' table must not define a 'name' key") } @Test fun googleMavenHostThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] |host = "https://example.com/" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'GoogleMaven' table must not define a 'host' key") } @Test fun googleMavenTypeThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] |type = "Maven2" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'GoogleMaven' table must not define a 'type' key") } @Test fun googleMavenUnknownKeyThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] |foo = "bar" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'GoogleMaven' table contains unknown 'foo' key") } @Test fun googleMavenChildTableThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[GoogleMaven] |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] |[GoogleMaven.Foo] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'GoogleMaven' table contains unknown 'Foo' key") } @Test fun customRepo() { val expected = listOf( RepositoryConfig( "CustomRepo", "https://example.com/".toHttpUrl(), Maven2, listOf( MavenCoordinate("com.example", "example-a"), MavenCoordinate("com.example", "example-b"), ), ), ) val actual = RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |host = "https://example.com/" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) assertEquals(expected, actual) } @Test fun customRepoNonTableThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |CustomRepo = "foo" | """.trimMargin(), ) } } @Test fun customRepoWithName() { val expected = listOf( RepositoryConfig( "Custom Repo", "https://example.com/".toHttpUrl(), Maven2, listOf( MavenCoordinate("com.example", "example-a"), MavenCoordinate("com.example", "example-b"), ), ), ) val actual = RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |name = "Custom Repo" |host = "https://example.com/" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) assertEquals(expected, actual) } @Test fun customRepoNonStringNameThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |name = 1 |host = "https://example.com/" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } } @Test fun customRepoWithType() { val expected = listOf( RepositoryConfig( "CustomRepo", "https://example.com/".toHttpUrl(), Maven2, listOf( MavenCoordinate("com.example", "example-a"), MavenCoordinate("com.example", "example-b"), ), ), ) val actual = RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |host = "https://example.com/" |type = "Maven2" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) assertEquals(expected, actual) } @Test fun customRepoNonStringTypeThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |host = "https://example.com/" |type = 1 |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } } @Test fun customRepoNoHostThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'CustomRepo' table missing required 'host' key") } @Test fun customRepoNonStringHostThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |host = 1 |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } } @Test fun customRepoNoCoordinatesThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |host = "https://example.com/" | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("'CustomRepo' table missing required 'coordinates' key") } @Test fun customRepoNonArrayCoordinatesThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |coordinates = "foo" | """.trimMargin(), ) } } @Test fun customRepoNonStringCoordinatesThrows() { assertFailsWith<TomlInvalidTypeException> { RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |coordinates = [1, 2, 3] | """.trimMargin(), ) } } @Test fun customRepoUnknownTypeThrows() { val t = assertFailsWith<IllegalArgumentException> { RepositoryConfig.parseConfigsFromToml( """ |[CustomRepo] |host = "https://example.com/" |type = "MavenTwo" |coordinates = [ | "com.example:example-a", | "com.example:example-b", |] | """.trimMargin(), ) } assertThat(t).hasMessageThat().isEqualTo("No enum constant watch.dependency.RepositoryType.MavenTwo") } }
9
null
9
282
5b29764d78c7644c47d0cf9e129e6041ee922f2c
12,270
dependency-watch
Apache License 2.0
composeApp/src/androidMain/kotlin/di/PlatformModule.kt
PigCakee
816,743,725
false
{"Kotlin": 54565, "Swift": 594}
package di import domain.db.AeroPlanDB import domain.db.getDatabaseBuilder import org.koin.core.module.Module import org.koin.dsl.module //actual fun platformModule(): Module = module { // single<AeroPlanDB> { // getDatabaseBuilder(get()).build() // } //}
0
Kotlin
0
0
10551b62b2bf1e67bef0a86867b57b632ec790f1
270
aeroplan_multiplatform
Apache License 2.0
features/feature-navigation/src/test/java/com/mctech/features/navigation/NavigatorTest.kt
MayconCardoso
198,072,780
false
null
package com.mctech.features.navigation import android.content.Intent import androidx.fragment.app.FragmentActivity import com.nhaarman.mockitokotlin2.argumentCaptor import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class NavigatorTest{ private lateinit var navigator: Navigator private val mockActivity = mock<FragmentActivity>() private val links = mapOf<Screen, Class<FragmentActivity>>( Screen.Login to FragmentActivity::class.java ) @Before fun `before each test`() { navigator = Navigator(mockActivity, links) } @Test fun `should navigate to supported screen`() { navigator.navigateTo(Screen.Login) argumentCaptor<Intent>().apply { verify(mockActivity).startActivity(capture()) assertThat(firstValue).isNotNull() } } @Test fun `should throw when navigating to unsupported screen`() { assertThatThrownBy { navigator.navigateTo(Screen.Splash) } .isEqualTo( UnsupportedNavigation(Screen.Splash) ) } }
0
Kotlin
4
21
7c2d04f56439c42b6bf8bc26807be25111d90dde
1,369
Modularized-Kotlin-Clean-Architecture-Showcase
Apache License 2.0
src/main/kotlin/coffee/cypher/hexbound/feature/construct/mishap/MishapNoConstruct.kt
Cypher121
569,248,192
false
{"Kotlin": 172761, "Java": 13563, "GLSL": 2732}
package coffee.cypher.hexbound.feature.construct.mishap import at.petrak.hexcasting.api.casting.eval.CastingEnvironment import at.petrak.hexcasting.api.casting.iota.Iota import at.petrak.hexcasting.api.casting.mishaps.Mishap import at.petrak.hexcasting.api.pigment.FrozenPigment import coffee.cypher.hexbound.util.fakeplayer.FakeServerPlayer import net.minecraft.entity.effect.StatusEffectInstance import net.minecraft.entity.effect.StatusEffects import net.minecraft.text.Text import net.minecraft.util.DyeColor class MishapNoConstruct : Mishap() { override fun accentColor(ctx: CastingEnvironment, errorCtx: Context): FrozenPigment { return dyeColor(DyeColor.PURPLE) } override fun errorMessage(ctx: CastingEnvironment, errorCtx: Context): Text { return error("no_construct", actionName(errorCtx.name)) } override fun execute(env: CastingEnvironment, errorCtx: Context, stack: MutableList<Iota>) { if (env.caster !is FakeServerPlayer) { env.caster?.addStatusEffect(StatusEffectInstance(StatusEffects.SLOWNESS, 20, 2)) } } }
2
Kotlin
3
2
dd1e93bb95221790f2ca7b3c20332c70fd5ae3f4
1,098
hexbound
MIT License
RoomigrantCompiler/src/main/java/dev/matrix/roomigrant/compiler/RoomigrantProcessor.kt
MatrixDev
141,049,575
false
null
package dev.matrix.roomigrant.compiler import com.google.auto.service.AutoService import com.squareup.kotlinpoet.asClassName import com.squareup.moshi.Moshi import dev.matrix.roomigrant.GenerateRoomMigrations import dev.matrix.roomigrant.compiler.data.Root import net.ltgt.gradle.incap.IncrementalAnnotationProcessor import net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.ISOLATING import dev.matrix.roomigrant.compiler.data.Scheme import java.io.File import java.io.InputStreamReader import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.Processor import javax.annotation.processing.RoundEnvironment import javax.annotation.processing.SupportedSourceVersion import javax.lang.model.SourceVersion import javax.lang.model.element.TypeElement import androidx.room.Database as DatabaseAnnotation /** * @author matrixdev */ @AutoService(Processor::class) @IncrementalAnnotationProcessor(ISOLATING) @SupportedSourceVersion(SourceVersion.RELEASE_7) class Processor : AbstractProcessor() { override fun getSupportedSourceVersion() = SourceVersion.latestSupported()!! override fun getSupportedAnnotationTypes() = mutableSetOf(GenerateRoomMigrations::class.java.name) private val moshi = Moshi.Builder().build() override fun process(annotations: MutableSet<out TypeElement>, roundEnvironment: RoundEnvironment): Boolean { val schemaLocation = processingEnv.options["room.schemaLocation"] ?: return true val elements = roundEnvironment.getElementsAnnotatedWith(GenerateRoomMigrations::class.java) .filterIsInstance<TypeElement>() for (element in elements) { if (element.getAnnotation(DatabaseAnnotation::class.java) == null) { throw Exception("$element is not annotated with ${DatabaseAnnotation::class.simpleName}") } processDatabase(schemaLocation, element) } return true } private fun processDatabase(schemaLocation: String, element: TypeElement) { val folder = File(schemaLocation, element.asClassName().toString()) val schemes = folder.listFiles().mapNotNull { readScheme(it) }.sortedBy { it.version } val database = Database(processingEnv, element) for (scheme in schemes) { database.addScheme(scheme) } for (index in 1 until schemes.size) { database.addMigration(schemes[index - 1], schemes[index]).generate() } database.generate() } private fun readScheme(file: File) = try { InputStreamReader(file.inputStream()).use { moshi.adapter(Root::class.java).fromJson(it.readText())?.scheme } } catch (e: Exception) { null } }
4
null
23
373
640a749d51f57a269c5c9daab7464b2200a0c70a
2,735
Roomigrant
MIT License
src/test/kotlin/br/com/lukinhasssss/controllers/RegistrarChaveControllerTest.kt
Lukinhasssss
398,393,051
true
{"Kotlin": 27794}
package br.com.lukinhasssss.controllers import br.com.lukinhasssss.* import br.com.lukinhasssss.grpc.PixGrpcClientFactory import io.micronaut.context.annotation.Factory import io.micronaut.context.annotation.Replaces import io.micronaut.http.HttpRequest import io.micronaut.http.HttpStatus import io.micronaut.http.client.HttpClient import io.micronaut.http.client.annotation.Client import io.micronaut.http.client.exceptions.HttpClientResponseException import io.micronaut.test.extensions.junit5.annotation.MicronautTest import jakarta.inject.Inject import jakarta.inject.Singleton import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.Mockito.* import java.util.* @MicronautTest internal class RegistrarChaveControllerTest { @field:Inject lateinit var grpcClient: RegistrarChaveServiceGrpc.RegistrarChaveServiceBlockingStub @field:Inject @field:Client("/") lateinit var httpClient: HttpClient private val idCliente = UUID.randomUUID().toString() private val pixId = UUID.randomUUID().toString() private val respostaGrpc = RegistrarChaveResponse.newBuilder() .setPixId(pixId) .build() @Test fun `Deve registrar uma nova chave pix`(){ val cadastrarChaveRequest = object { val tipoChave = TipoChave.CELULAR val valorChave = "+5511987654321" val tipoConta = TipoConta.CONTA_CORRENTE } `when`(grpcClient.registrarChave(any())).thenReturn(respostaGrpc) val request = HttpRequest.POST("/v1/clientes/$idCliente/pix", cadastrarChaveRequest) val response = httpClient.toBlocking().exchange(request, RegistrarChaveRequest::class.java) with(response) { assertEquals(HttpStatus.CREATED, status) assertTrue(headers.contains("Location")) assertTrue(header("Location")!!.contains(pixId)) } } @Test internal fun `nao deve registrar uma nova chave pix quando o celular for invalido`() { val cadastrarChaveRequest = object { val tipoChave = TipoChave.CELULAR val valorChave = "segbsggnsrh" val tipoConta = TipoConta.CONTA_CORRENTE } `when`(grpcClient.registrarChave(any())).thenReturn(respostaGrpc) val request = HttpRequest.POST("/v1/clientes/$idCliente/pix", cadastrarChaveRequest) val exception = assertThrows<HttpClientResponseException> { httpClient.toBlocking().exchange(request, RegistrarChaveRequest::class.java) } with(exception) { assertEquals(HttpStatus.BAD_REQUEST.code, status.code) } } @Test internal fun `nao deve registrar uma nova chave pix quando o cpf for invalido`() { val cadastrarChaveRequest = object { val tipoChave = TipoChave.CPF val valorChave = "931351" val tipoConta = TipoConta.CONTA_CORRENTE } val request = HttpRequest.POST("/v1/clientes/$idCliente/pix", cadastrarChaveRequest) `when`(grpcClient.registrarChave(any())).thenReturn(respostaGrpc) val exception = assertThrows<HttpClientResponseException> { httpClient.toBlocking().exchange(request, RegistrarChaveRequest::class.java) } with(exception) { assertEquals(HttpStatus.BAD_REQUEST.code, status.code) } } @Test internal fun `nao deve registrar uma nova chave pix quando o email for invalido`() { val cadastrarChaveRequest = object { val tipoChave = TipoChave.EMAIL val valorChave = "luffy@luffy" val tipoConta = TipoConta.CONTA_CORRENTE } val request = HttpRequest.POST("/v1/clientes/$idCliente/pix", cadastrarChaveRequest) `when`(grpcClient.registrarChave(any())).thenReturn(respostaGrpc) val exception = assertThrows<HttpClientResponseException> { httpClient.toBlocking().exchange(request, RegistrarChaveRequest::class.java) } with(exception) { assertEquals(HttpStatus.BAD_REQUEST.code, status.code) } } @Test internal fun `nao deve registrar uma nova chave pix quando a chave for aleatoria e o valor estiver preenchido`() { val cadastrarChaveRequest = object { val tipoChave = TipoChave.ALEATORIA val valorChave = "987654321" val tipoConta = TipoConta.CONTA_CORRENTE } val request = HttpRequest.POST("/v1/clientes/$idCliente/pix", cadastrarChaveRequest) `when`(grpcClient.registrarChave(any())).thenReturn(respostaGrpc) val exception = assertThrows<HttpClientResponseException> { httpClient.toBlocking().exchange(request, RegistrarChaveRequest::class.java) } with(exception) { assertEquals(HttpStatus.BAD_REQUEST.code, status.code) } } @Factory @Replaces(factory = PixGrpcClientFactory::class) internal class RegistrarChaveStubFactory { @Singleton fun stubMock(): RegistrarChaveServiceGrpc.RegistrarChaveServiceBlockingStub { return mock(RegistrarChaveServiceGrpc.RegistrarChaveServiceBlockingStub::class.java) } } }
0
Kotlin
0
0
b15c02ac3f548a7b4e50218eec238927c22f9820
5,353
orange-talents-06-template-pix-keymanager-rest
Apache License 2.0
app/src/main/java/com/example/newptportal/StudentActivity.kt
Hariharanm95
603,998,033
false
null
package com.example.newptportal import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class StudentActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_student) } }
0
Kotlin
0
0
5edf4d0d1f148ba8751cd13760aa8865e5deda55
310
NewPTPortal
MIT License
feature/overview/src/main/java/com/uxstate/overview/presentation/settings_screen/SettingsScreen.kt
Tonnie-Dev
518,721,038
false
{"Kotlin": 160830}
package com.uxstate.overview.presentation.settings_screen import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LocalContentColor import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import com.ramcosta.composedestinations.annotation.Destination import com.uxstate.overview.presentation.settings_screen.components.SettingsContent import com.uxstate.overview.presentation.settings_screen.components.SingleChoiceDialog import com.uxstate.ui.R import com.uxstate.util.model.ThemeMode interface SettingsScreenNavigator { fun navigateUp() } @OptIn(ExperimentalMaterial3Api::class) @Destination @Composable fun SettingsScreen( navigator: SettingsScreenNavigator, viewModel: SettingsViewModel = hiltViewModel() ) { val state by viewModel.state.collectAsState() val isShowDialog = state.isShowThemeDialog val currentThemeMode = state.appPrefs.themeMode Scaffold(topBar = { CenterAlignedTopAppBar( title = { Text(text = stringResource(id = R.string.settings_text)) }, navigationIcon = { IconButton(onClick = { navigator.navigateUp() }) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(id = R.string.back_text), modifier = Modifier.minimumInteractiveComponentSize(), tint = LocalContentColor.current ) } }) }) { paddingValues -> SettingsContent( modifier = Modifier.padding(paddingValues), appPreferences = state.appPrefs, actions = viewModel ) if (isShowDialog) { SingleChoiceDialog( title = stringResource(id = R.string.theme_text), options = ThemeMode.entries.map { it.themeResName }, initialSelectedOptionIndex = ThemeMode.entries.indexOf(currentThemeMode), onConfirmOption = { index -> viewModel.onThemeChange(themeMode = ThemeMode.entries[index]) } ) { } } } }
0
Kotlin
0
5
27774f362615bf23c9b6dfd133ec39d0d7e7b24b
2,949
CountriesPad
The Unlicense
app/src/main/java/com/vr/app/sh/ui/door/view/Reg.kt
Vadim-Rudak
510,027,925
false
{"Kotlin": 260458}
package com.vr.app.sh.ui.door.view import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import com.vr.app.sh.R import com.vr.app.sh.app.App import com.vr.app.sh.data.repository.RegistrationInfo import com.vr.app.sh.ui.base.RegViewModelFactory import com.vr.app.sh.ui.door.viewmodel.RegViewModel import com.vr.app.sh.ui.other.UseAlert.Companion.infoMessage class Reg : AppCompatActivity() { @javax.inject.Inject lateinit var factory: RegViewModelFactory lateinit var viewModel: RegViewModel private var numFragment = 0 private val userReg = RegistrationInfo.user override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_reg) val btnBack = findViewById<ImageButton>(R.id.reg_btn_back) btnBack.setOnClickListener { val intent = Intent(this,Authoriz::class.java) startActivity(intent) finish() } val titel = findViewById<TextView>(R.id.reg_text_titel) val tab1 = findViewById<ImageView>(R.id.reg_image_tab1) val tab2 = findViewById<ImageView>(R.id.reg_image_tab2) val tab3 = findViewById<ImageView>(R.id.reg_image_tab3) val tab4 = findViewById<ImageView>(R.id.reg_image_tab4) val btn_next = findViewById<Button>(R.id.reg_btn_next) (applicationContext as App).appComponent.injectReg(this) viewModel = ViewModelProvider(this,factory) .get(RegViewModel::class.java) viewModel.numFragment.observe(this){ numFragment = it when(it){ 1->{ titel.setText(R.string.registration_titel2) tab2.setImageResource(R.drawable.tab_reg_true) } 2->{ titel.setText(R.string.registration_titel3) tab3.setImageResource(R.drawable.tab_reg_true) } 3->{ titel.setText(R.string.registration_titel4) tab4.setImageResource(R.drawable.tab_reg_true) btn_next.setText(R.string.registration_btn2) } else->{ titel.setText(R.string.registration_titel1) tab1.setImageResource(R.drawable.tab_reg_true) } } supportFragmentManager.beginTransaction() .replace(R.id.fr_place, FragmentReg(numPage = it)) .commit() } viewModel.errorMessage.observe(this){ infoMessage(supportFragmentManager,it) } viewModel.statusRegistration.observe(this){ if(it){ val intent = Intent(this,Verification::class.java) startActivity(intent) finish() } } btn_next.setOnClickListener { when(numFragment){ 0->{ infoInEditText( !userReg.name.isNullOrEmpty() &&!userReg.lastName.isNullOrEmpty() &&!userReg.dateBirthday.isNullOrEmpty() &&!userReg.cityLive.isNullOrEmpty() ) } 1->{ infoInEditText( !userReg.school.nameCity.isNullOrEmpty() &&!userReg.school.name.isNullOrEmpty() &&userReg.school.numClass != 0 ) } 2->{ infoInEditText(!userReg.auth.login.isNullOrEmpty()&&!userReg.auth.password.isNullOrEmpty()) } 3->{ viewModel.registration(supportFragmentManager) } } } } private fun infoInEditText(allInfo:Boolean){ if (allInfo){ numFragment++ viewModel.numFragment.postValue(numFragment) }else{ infoMessage(supportFragmentManager,this.resources.getString(R.string.alrInfoText1)) } } }
0
Kotlin
0
0
4eabcb06e23eed436523a06752cdb092cae147b6
4,333
SH
Apache License 2.0
app/src/test/java/com/demo/ui/preferences/remote/RemotePreferencesViewModelTest.kt
Mithrandir21
415,935,855
false
{"Kotlin": 157717}
package com.demo.ui.preferences.remote import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import com.demo.common.config.RemoteConfig import com.demo.common.config.RemoteConfigurationProvider import com.demo.common.config.RemoteConfigurations import com.demo.logging.Logger import com.demo.testing.RxJavaSchedulerImmediateRule import com.demo.ui.preferences.remote.RemotePreferencesViewModel.ActionType import com.demo.ui.preferences.remote.RemotePreferencesViewModel.Data import com.nhaarman.mockitokotlin2.* import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class RemotePreferencesViewModelTest { @get:Rule var rule: TestRule = InstantTaskExecutorRule() @get:Rule var testSchedulerRule = RxJavaSchedulerImmediateRule() @Mock private lateinit var logger: Logger @Mock private lateinit var remoteConfigurationProvider: RemoteConfigurationProvider @Captor private lateinit var loadingCaptor: ArgumentCaptor<Pair<Boolean, ActionType>> @Test fun `test loading known remote environments`() { val remoteConfigA = RemoteConfig(RemoteConfigurations.DEV, "A_URL") val remoteConfigB = RemoteConfig(RemoteConfigurations.PRODUCTION, "B_URL") val currentConfig = RemoteConfig(RemoteConfigurations.CUSTOM, "CUSTOM_URL") val remoteEnvironments = listOf(remoteConfigA, remoteConfigB, currentConfig) val currentIndex = remoteEnvironments.indexOf(currentConfig) val dataObserver = mock<Observer<Data>>() val errorObserver = mock<Observer<Pair<Throwable, ActionType>>>() val loadingObserver = mock<Observer<Pair<Boolean, ActionType>>>() whenever(remoteConfigurationProvider.getKnownRemoteConfigurations()).thenReturn(remoteEnvironments) whenever(remoteConfigurationProvider.getRemoteConfiguration()).thenReturn(currentConfig) val viewModel = RemotePreferencesViewModel(logger, remoteConfigurationProvider) viewModel.observeViewData().observeForever(dataObserver) viewModel.observeErrors().observeForever(errorObserver) viewModel.observeProgress().observeForever(loadingObserver) viewModel.loadRemoteEnvironment() verifyZeroInteractions(errorObserver) // Verify Loading states verify(loadingObserver, times(2)).onChanged(loadingCaptor.capture()) assert(loadingCaptor.firstValue == true to ActionType.LoadingRemoteEnvironment) assert(loadingCaptor.secondValue == false to ActionType.LoadingRemoteEnvironment) verify(dataObserver, times(1)).onChanged(Data.PossibleRemoteEnvironments(remoteEnvironments, currentIndex)) } @Test fun `test setting remote environments`() { val remoteConfigCustom = RemoteConfig(RemoteConfigurations.CUSTOM, "CUSTOM_URL") val dataObserver = mock<Observer<Data>>() val errorObserver = mock<Observer<Pair<Throwable, ActionType>>>() val loadingObserver = mock<Observer<Pair<Boolean, ActionType>>>() whenever(remoteConfigurationProvider.setRemoteConfiguration(remoteConfigCustom)).thenReturn(true) val viewModel = RemotePreferencesViewModel(logger, remoteConfigurationProvider) viewModel.observeViewData().observeForever(dataObserver) viewModel.observeErrors().observeForever(errorObserver) viewModel.observeProgress().observeForever(loadingObserver) viewModel.setRemoteEnvironment(remoteConfigCustom) verifyZeroInteractions(errorObserver) // Verify Loading states verify(loadingObserver, times(2)).onChanged(loadingCaptor.capture()) assert(loadingCaptor.firstValue == true to ActionType.SetRemoteEnvironment) assert(loadingCaptor.secondValue == false to ActionType.SetRemoteEnvironment) verify(dataObserver, times(1)).onChanged(Data.RemoteEnvironmentSet) } }
0
Kotlin
0
0
f33d571b21c8b031a3936befbdafd46b55aeec52
4,126
demo
Apache License 2.0
app/src/main/java/com/costular/marvelheroes/di/modules/NetModule.kt
costular
125,720,420
false
null
package com.costular.marvelheroes.di.modules import com.costular.marvelheroes.BuildConfig import com.costular.marvelheroes.data.net.MarvelHeroesService import dagger.Module import dagger.Provides import okhttp3.OkHttpClient //import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton /** * Created by costular on 17/03/2018. */ @Module class NetModule { @Provides @Singleton fun provideRetrofit(): Retrofit { /*val client = OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .build() */ return Retrofit.Builder() .baseUrl(BuildConfig.API_URL) //.client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() } @Provides @Singleton fun provideMarvelHeroesService(retrofit: Retrofit): MarvelHeroesService = retrofit.create(MarvelHeroesService::class.java) }
0
null
9
3
13643d987f1e26fe158646298afdcb0077424a4f
1,310
marvel-super-heroes
MIT License
src/main/kotlin/space/dastyar/hibernatereactive/config/SampleData.kt
AlirezaDastyar
500,433,892
false
{"Kotlin": 13058}
package space.dastyar.hibernatereactive.config import space.dastyar.hibernatereactive.model.Student import space.dastyar.hibernatereactive.persistence.StudentDAO import org.springframework.boot.ApplicationArguments import org.springframework.boot.ApplicationRunner import org.springframework.stereotype.Component @Component class SampleData(var dao: StudentDAO) : ApplicationRunner{ override fun run(args: ApplicationArguments?) { val student = Student().apply { name = "<NAME>" age = 20 grade = 12 } dao.save(student).subscribe().with { } dao.save(student.copy().apply { name = "test 2" }).subscribe().with { } dao.save(student.copy().apply { name = "test 3" }).subscribe().with { } } }
0
Kotlin
0
0
7d7115b65400317fe396cacc37355301254de4bf
777
HibernateReactiveWithSpring
MIT License
src/main/kotlin/marisa/action/ShootingEchoAction.kt
scarf005
574,583,770
false
{"Kotlin": 393468, "TypeScript": 30744}
package marisa.action import com.megacrit.cardcrawl.actions.AbstractGameAction import com.megacrit.cardcrawl.actions.utility.DiscardToHandAction import com.megacrit.cardcrawl.cards.AbstractCard import com.megacrit.cardcrawl.cards.status.Burn import com.megacrit.cardcrawl.core.CardCrawlGame import com.megacrit.cardcrawl.core.Settings import com.megacrit.cardcrawl.dungeons.AbstractDungeon import marisa.MarisaContinued import marisa.p class ShootingEchoAction(private val card: AbstractCard) : AbstractGameAction() { init { duration = Settings.ACTION_DUR_FAST actionType = ActionType.EXHAUST } private fun exhaustMaybeBurn(toExhaust: AbstractCard?) { if (toExhaust is Burn) { addToBot(DiscardToHandAction(card)) } p.hand.moveToExhaustPile(toExhaust) isDone = true } override fun update() { if (duration == Settings.ACTION_DUR_FAST) { if (p.hand.isEmpty) { isDone = true } else if (p.hand.size() == 1) { MarisaContinued.logger.info("ShootingEchoAction: player hand size is 1") exhaustMaybeBurn(p.hand.topCard) } else { MarisaContinued.logger.info("ShootingEchoAction: opening hand card select") AbstractDungeon.handCardSelectScreen.open(TEXT, 1, false, false) tickDuration() } return } if (!AbstractDungeon.handCardSelectScreen.wereCardsRetrieved) { MarisaContinued.logger.info("ShootingEchoAction: hand card select screen") assert(AbstractDungeon.handCardSelectScreen.selectedCards.size() == 1) exhaustMaybeBurn(AbstractDungeon.handCardSelectScreen.selectedCards.topCard) AbstractDungeon.handCardSelectScreen.wereCardsRetrieved = true AbstractDungeon.handCardSelectScreen.selectedCards.group.clear() AbstractDungeon.gridSelectScreen.selectedCards.clear() AbstractDungeon.player.hand.refreshHandLayout() tickDuration() } isDone = true } companion object { private val uiStrings = CardCrawlGame.languagePack.getUIString("ExhaustAction") val TEXT: String = uiStrings.TEXT[0] } }
10
Kotlin
7
16
078d76e05b330c0511200b22487961246c6ded8a
2,282
Marisa
MIT License
app/src/main/java/alduali/moqri/ui/screens/MainViewModel.kt
BELLILMohamedNadir
749,003,404
false
{"Kotlin": 95563}
package alduali.moqri.ui.screens import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class MainViewModel: ViewModel() { var shouldNavigate = MutableLiveData<Boolean>(false) var direction = "" }
0
Kotlin
0
0
9feb70ddb2be6b1bcaab43df179a3fb0cc3912a0
229
Al-Moqri
MIT License
src/main/kotlin/top/vuhe/tool/Factory.kt
vuhe
495,647,196
false
null
package top.vuhe.tool import org.slf4j.Logger import org.slf4j.LoggerFactory import top.vuhe.Context import top.vuhe.model.Formula import top.vuhe.model.Operator import top.vuhe.model.Question abstract class Factory<T> { abstract fun produce(): T } internal sealed class QuestionFactory( private val plusNum: Int, private val minusNum: Int ) : Factory<Question>() { private val log: Logger = LoggerFactory.getLogger(QuestionFactory::class.java) override fun produce(): Question { // 去重收集加法算式流 val addStream = generateSequence(FormulaFactory.Add::produce) .distinct().take(plusNum) // 去重收集减法算式 val subStream = generateSequence(FormulaFactory.Sub::produce) .distinct().take(minusNum) // 合并流并收集 val formulas = addStream + subStream // 打乱 formulas.shuffled() log.debug("创建一套习题") return Question.form(formulas.toList()) } object AllPlus : QuestionFactory(50, 0) object AllMinus : QuestionFactory(0, 50) object HalfHalf : QuestionFactory(25, 25) } sealed class FormulaFactory( private val op: Operator ) : Factory<Formula>() { companion object { private val log: Logger = LoggerFactory.getLogger(FormulaFactory::class.java) } /** * 获取一个算式 * * 此算式已检查过数值符合要求 * * @return 算式 */ override fun produce(): Formula { // 创建生产序列 检查并获取生产对象 val formula = generateSequence { Formula( // 两个数数范围:1 ~ 99 a = (1 until 100).random(), b = (1 until 100).random(), // 子类获取运算符 op = op ) }.filter { it.check() }.first() log.trace("生产一个算式") return formula } /** * 符合答案要求返回 true * * 符合答案标准:(0 <= ans <= 100) * * @receiver 算式构建者 * @return 是否符合要求 */ private fun Formula.check(): Boolean { // 答案是否超出范围 return ans in 0..Context.ANS_MAX } internal object Add : FormulaFactory(Operator.Plus) internal object Sub : FormulaFactory(Operator.Minus) }
0
Kotlin
0
0
6adaad885f230fe19683275bef79f4c7bb793cfa
2,141
arithmetic-homework
MIT License
app/src/main/java/com/manu/mediasamples/samples/opengl/Config.kt
jzmanu
358,646,353
false
null
package com.manu.mediasamples.samples.opengl /** * @Desc: Config * @Author: jzman * @Date: 2021/8/13. */ object Config { const val DEFAULT = false }
0
Kotlin
2
9
e40f2957aac6c2dad5b17421b4eb96ab83497fda
157
MediaSamples
Apache License 2.0
app/src/main/java/com/app/baseprojectamanattri/domain/post/models/PostModel.kt
amanattri09
460,833,658
false
{"Kotlin": 32914}
package com.app.baseprojectamanattri.domain.post.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class PostModel(val body: String,val id: Int,val title: String,val userId: Int) : Parcelable
1
Kotlin
0
2
280a29c814b2a433c7869f8035ae513dc57611f6
230
CoroutinesFlowExample
Apache License 2.0
app/src/main/java/com/app/baseprojectamanattri/domain/post/models/PostModel.kt
amanattri09
460,833,658
false
{"Kotlin": 32914}
package com.app.baseprojectamanattri.domain.post.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class PostModel(val body: String,val id: Int,val title: String,val userId: Int) : Parcelable
1
Kotlin
0
2
280a29c814b2a433c7869f8035ae513dc57611f6
230
CoroutinesFlowExample
Apache License 2.0
src/main/kotlin/com/chm/plugin/idea/forestx/tw/RightSidebarToolWindowFactory.kt
CHMing7
572,792,636
false
{"Java": 90667, "Kotlin": 66864, "Lex": 2542}
package com.chm.plugin.idea.forestx.tw import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.content.ContentFactory /** * @author caihongming * @version v1.0 * @since 2022-08-25 **/ class RightSidebarToolWindowFactory : ToolWindowFactory, DumbAware { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { val disposable = Disposer.newDisposable() val mainForm = RightSidebarToolWindow.getInstance(project, disposable) val content = ContentFactory.SERVICE.getInstance().createContent(mainForm.getContent(), "", false) content.setDisposer(disposable) toolWindow.contentManager.addContent(content) } }
1
null
1
1
c6cce1c9d543e2aa201827eab06fc9551bc6c40c
872
ForestX
MIT License
app/src/main/java/com/dladukedev/wordle/di/GameModule.kt
dladukedev
454,392,939
false
null
package com.dladukedev.wordle.di import com.dladukedev.wordle.game.state.DailyChallengeGameActionStub import com.dladukedev.wordle.game.state.GameActionStub import com.dladukedev.wordle.game.state.PracticeGameActionStub import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import javax.inject.Qualifier @Qualifier @Retention(AnnotationRetention.BINARY) annotation class UsePracticeActionStub @Qualifier @Retention(AnnotationRetention.BINARY) annotation class UseDailyChallengeActionStub @InstallIn(ViewModelComponent::class) @Module abstract class GameModule { @UsePracticeActionStub @Binds abstract fun bindsPracticeGameActionStub(randomWordRetriever: PracticeGameActionStub): GameActionStub @UseDailyChallengeActionStub @Binds abstract fun bindsDailyChallengeGameActionStub(factory: DailyChallengeGameActionStub): GameActionStub }
0
Kotlin
0
5
d6cd901921605e3aa4d11e406f4df46789694614
958
wordle-clone-android
MIT License
app/src/main/java/com/ex2/ktmovies/platform/PaletteHelper.kt
mahendranv
400,540,337
false
null
package com.ex2.ktmovies.platform import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import androidx.palette.graphics.Palette import coil.ImageLoader import coil.request.ImageRequest import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * Dispatches palette creation to IO dispatcher given an image url. */ suspend fun pickPalette(context: Context, url: String) = withContext(Dispatchers.IO) { val request = ImageRequest.Builder(context) .data(url) .size(100) .build() val drawable = ImageLoader(context) .execute(request) .drawable var palette: Palette? = null (drawable as? BitmapDrawable)?.bitmap?.let { val mutable = it.copy(Bitmap.Config.ARGB_8888, true) palette = Palette.from(mutable).generate() } palette }
3
null
2
3
6f6037a1047b47836af086410f265a8ec0442eaf
885
movieskt
MIT License
app/src/main/java/com/atc/planner/data/model/remote/sygic_api/Category.kt
lewinskimaciej
105,373,895
false
null
package com.atc.planner.data.model.remote.sygic_api enum class Category(val value: String) { DISCOVERING("discovering"), EATING("eating"), GOING_OUT("going_out"), HIKING("hiking"), PLAYING("playing"), RELAXING("relaxing"), SHOPPING("shopping"), SIGHTSEEING("sightseeing"), SLEEPING("sleeping"), DOING_SPORTS("doing_sports"), TRAVELING("traveling"), OTHER("other") } fun String?.asCategory(): Category = when (this) { Category.DISCOVERING.value -> Category.DISCOVERING Category.EATING.value -> Category.EATING Category.GOING_OUT.value -> Category.GOING_OUT Category.HIKING.value -> Category.HIKING Category.PLAYING.value -> Category.PLAYING Category.RELAXING.value -> Category.RELAXING Category.SHOPPING.value -> Category.SHOPPING Category.SIGHTSEEING.value -> Category.SIGHTSEEING Category.SLEEPING.value -> Category.SLEEPING Category.DOING_SPORTS.value -> Category.DOING_SPORTS Category.TRAVELING.value -> Category.TRAVELING else -> Category.OTHER }
0
Kotlin
0
0
3432f74d7c8822cd244ae98b131ab0d423648680
1,050
planner
MIT License
library/src/main/java/com/herry/libs/mvp/MVPView.kt
HerryPark
273,154,769
false
null
package com.herry.libs.mvp import android.content.Context @Suppress("unused") interface MVPView<P> { var presenter: P? /** * Context */ fun getViewContext(): Context? /** * Shows loading view */ fun showViewLoading() {} /** * Hides loading view * @param success if success is true, it will be show "done" view and then hide it. */ fun hideViewLoading(success: Boolean) {} fun error(throwable: Throwable) {} }
0
null
1
3
d30435c01387614ec24a79ffd5afcdb89edf5298
481
HerryApiDemo
Apache License 2.0
app/src/main/java/com/msg/gfo_v2/gfo/base/di/module/NetworkModule.kt
Project-GFO
564,264,624
false
null
package com.msg.gfo_v2.gfo.base.di.module import com.msg.gfo_v2.gfo.data.remote.network.AuthAPI import com.msg.gfo_v2.gfo.data.remote.network.LoginInterceptor import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit @Module @InstallIn(SingletonComponent::class) object NetworkModule { private const val BASE_URL = "" fun provideOkhttpClient( loginInterceptor : LoginInterceptor ): OkHttpClient{ return OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .addInterceptor(loginInterceptor) .build() } @Provides fun provideRetrofitInstance( okHttpClient: OkHttpClient, gsonConverterFactory: GsonConverterFactory ): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(gsonConverterFactory) .build() } @Provides fun provideGsonConverterFactory() : GsonConverterFactory{ return GsonConverterFactory.create() } @Provides fun provideCommonService(retrofit: Retrofit): AuthAPI{ return retrofit.create(AuthAPI::class.java) } }
1
Kotlin
0
0
157dd12cbcbef3755c21c38cd0e1457f90bf12b4
1,479
GFO-Android
MIT License
deployer/src/main/kotlin/io/deepmedia/tools/deployer/model/Developer.kt
deepmedia
248,277,150
false
null
package io.deepmedia.tools.deployer.model import org.gradle.api.Action import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Property import org.gradle.kotlin.dsl.property import javax.inject.Inject open class Developer @Inject constructor(objects: ObjectFactory) { val name: Property<String> = objects.property() val email: Property<String> = objects.property() val organization = objects.property<String?>().convention(null as String?) val url = objects.property<String?>().convention(null as String?) } interface DeveloperScope { fun developer(action: Action<Developer>) fun developer(name: String, email: String, organization: String? = null, url: String? = null) = developer { this.name.set(name) this.email.set(email) this.organization.set(organization) this.url.set(url) } }
0
Kotlin
5
50
a4ce37a5fbc20aec36a9e3173f88a61901143a12
864
MavenDeployer
Apache License 2.0
data/RF02454/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF02454" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 2 to 4 9 to 11 } value = "#4817b0" } color { location { 34 to 42 57 to 65 } value = "#518d31" } color { location { 44 to 45 55 to 56 } value = "#2f7e83" } color { location { 5 to 8 } value = "#159c40" } color { location { 43 to 43 57 to 56 } value = "#8a15c8" } color { location { 46 to 54 } value = "#1b54e3" } color { location { 1 to 1 } value = "#c0feba" } color { location { 12 to 33 } value = "#c4fc2e" } color { location { 66 to 81 } value = "#b544c5" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
1,452
Rfam-for-RNArtist
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/rolesanywhere/CfnTrustAnchorPropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.rolesanywhere import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.rolesanywhere.CfnTrustAnchorProps @Generated public fun buildCfnTrustAnchorProps(initializer: @AwsCdkDsl CfnTrustAnchorProps.Builder.() -> Unit): CfnTrustAnchorProps = CfnTrustAnchorProps.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
425
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/fredrikbogg/snapchatclone/utils/ProgressDialogHandler.kt
dgewe
276,859,827
false
null
package com.fredrikbogg.snapchatclone.utils import android.app.ProgressDialog import android.content.Context import android.widget.ProgressBar import com.fredrikbogg.snapchatclone.R class ProgressDialogHandler { private var progressDialog: ProgressDialog? = null fun toggleProgressDialog(context: Context, active: Boolean) { if (active) { progressDialog = ProgressDialog(context, R.style.CustomProgressDialogTheme).apply { setCancelable(false) show() setContentView(ProgressBar(context)) } } else { progressDialog?.dismiss() } } }
0
Kotlin
3
1
2f546caaae3959daea2a693880893f0509d049dc
653
Simple-Snapchat-Clone-Android
MIT License
playground/src/main/kotlin/com/github/jan222ik/playground/contextmenu/IContextMenuEntry.kt
jan222ik
462,289,211
false
{"Kotlin": 852617, "Java": 17948}
package com.github.jan222ik.playground.contextmenu import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Create import androidx.compose.material.icons.filled.CreateNewFolder import androidx.compose.ui.graphics.vector.ImageVector enum class NewType { FILE, PACKAGE, CLASS, PROPERTY } class NewCommand(val type: NewType) : ICommand { override fun isActive(): Boolean = true override suspend fun execute() { println("New of type $type") } override fun canUndo(): Boolean { TODO("Not yet implemented") } override suspend fun undo() { TODO("Not yet implemented") } } val newPackageContextMenuEntry = MenuContribution.Contentful.MenuItem( icon = Icons.Filled.CreateNewFolder, displayName = "Package", command = NewCommand(type = NewType.PACKAGE) ) val newFileContextMenuEntry = MenuContribution.Contentful.MenuItem( icon = Icons.Filled.Create, displayName = "File", command = NewCommand(type = NewType.FILE) ) val newFileMenuEntry = MenuContribution.Contentful.NestedMenuItem( icon = Icons.Filled.Create, displayName = "New", nestedItems = listOf( newPackageContextMenuEntry, newFileContextMenuEntry, ) ) val newFileMenuEntry2 = MenuContribution.Contentful.NestedMenuItem( icon = Icons.Filled.Create, displayName = "New", nestedItems = listOf( newPackageContextMenuEntry, newFileContextMenuEntry, newFileMenuEntry ) )
0
Kotlin
0
0
e67597e41b47ec7676aa0e879062d8356f1b4672
1,511
MSc-Master-Composite
Apache License 2.0
app/src/main/java/com/example/studysmart/presentation/session/SessionState.kt
CodeInKotLang
702,698,514
false
{"Kotlin": 145710}
package com.example.studysmart.presentation.session import com.example.studysmart.domain.model.Session import com.example.studysmart.domain.model.Subject data class SessionState( val subjects: List<Subject> = emptyList(), val sessions: List<Session> = emptyList(), val relatedToSubject: String? = null, val subjectId: Int? = null, val session: Session? = null )
1
Kotlin
1
13
def9cbb2f47187fce7a3eb743b046928dfda7e74
384
StudySmart
MIT License
client-baseclient/src/commonMain/kotlin/de/menkalian/crater/restclient/error/CraterError.kt
Menkalian
499,917,030
false
{"Kotlin": 73761, "Dockerfile": 149}
package de.menkalian.crater.restclient.error data class CraterError( val code: Int, val message: String, val cause: Throwable, ) { companion object { const val ERR_TIMEOUT = -0xffff const val ERR_UNKNOWN = -1 } }
0
Kotlin
0
0
8f557c1aa9b9d1950ceb921a9dec8b031d809056
250
crater
MIT License
src/main/kotlin/ui/sections/emulator/EmulatorsPage.kt
Pulimet
678,269,308
false
{"Kotlin": 252279}
package ui.sections.emulator import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import ui.sections.emulator.add.EmulatorsCreateTab import ui.sections.emulator.create.EmulatorsInstallTab import ui.sections.emulator.run.EmulatorsRunTab import ui.theme.Dimensions import ui.widgets.CardX import ui.widgets.tabs.Tabs @Composable fun EmulatorsPage(modifier: Modifier = Modifier) { CardX(modifier = modifier) { Column(modifier = Modifier.padding(Dimensions.cardPadding)) { Tabs(listOf("Run Emulator", "Create Device", "Install Image"), showTabs = false) { when (it) { 0 -> EmulatorsRunTab() 1 -> EmulatorsCreateTab() 2 -> EmulatorsInstallTab() } } } } }
17
Kotlin
2
23
6206ea35fcecd11eb1a6c20fb00070f0cf9ce9c2
918
ADBugger
MIT License
app/src/main/java/com/github/ymaniz09/animals/util/SharedPreferencesHelper.kt
ymaniz09
226,183,830
false
null
package com.github.ymaniz09.animals.util import android.content.Context import androidx.preference.PreferenceManager class SharedPreferencesHelper(context: Context) { private val PREF_API_KEY = "PREF_API_KEY" private val prefs = PreferenceManager.getDefaultSharedPreferences(context.applicationContext) fun saveApiKey(key: String?) { prefs.edit().putString(PREF_API_KEY, key).apply() } fun getApiKey() = prefs.getString(PREF_API_KEY, null) }
0
Kotlin
0
0
185e4887032178c8f9d6300da04b2ef1e3d18733
474
animals
MIT License
core/src/main/kotlin/net/brenig/pixelescape/game/worldgen/ITerrainGenerator.kt
jbrenig
77,611,951
false
{"Kotlin": 373758, "HTML": 2196, "CSS": 1171, "Java": 710}
package net.brenig.pixelescape.game.worldgen import net.brenig.pixelescape.game.World import java.util.* /** * TerrainGenerator used for generating terrain */ interface ITerrainGenerator { val weight: Int /** * generates terrain * * @param world The World instance * @param lastPair the previous TerrainPair * @param blocksToGenerate the amount of blocks that are requested to get generated * @param generatedBlocksIndex index of the currently already generated blocks * @param random random instance for world generation * @return amount of blocks generated */ fun generate(world: World, lastPair: TerrainPair, blocksToGenerate: Int, generatedBlocksIndex: Int, random: Random): Int /** * Gets called to make sure the terrain generator can generate<br></br> * Does only get called once per generation cycle * * @param last the last currently generated TerrainPair * @return minimum amount of blocks that get generated by this ITerrainGenerator, return a value <= 0 if none */ fun getMinGenerationLength(last: TerrainPair): Int }
0
Kotlin
0
0
e46417ed05a43d18b7afaa83ceefd89e9a762ede
1,176
PixelEscape
MIT License
amazon/core/src/main/kotlin/org/http4k/connect/amazon/CLICacheCredentialsChain.kt
http4k
295,641,058
false
{"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect.amazon import org.http4k.aws.AwsCredentials import org.http4k.connect.amazon.core.model.AccessKeyId import org.http4k.connect.amazon.core.model.Expiration import org.http4k.connect.amazon.core.model.SecretAccessKey import org.http4k.connect.amazon.core.model.SessionToken import org.http4k.format.AwsCoreMoshi import se.ansman.kotshi.JsonSerializable import java.io.File import java.time.Clock import java.time.Clock.systemUTC import kotlin.io.path.Path fun CredentialsChain.Companion.CliCache(clock: Clock = systemUTC()) = CredentialsChain { val dir = Path(System.getProperty("user.home")).resolve(".aws/cli/cache").toFile() if (!dir.exists() || !dir.isDirectory) null else { dir.listFiles() ?.map(File::readText) ?.map { AwsCoreMoshi.asA<CliCachedCredentialsFile>(it) } ?.filter { it.ProviderType == "sso" } ?.firstOrNull { it.Credentials.Expiration.value.toInstant().isAfter(clock.instant()) } ?.Credentials ?.let { AwsCredentials(it.AccessKeyId.value, it.SecretAccessKey.value, it.SessionToken.value) } } } @JsonSerializable data class CliCachedCredentials( val AccessKeyId: AccessKeyId, val SecretAccessKey: SecretAccessKey, val SessionToken: SessionToken, val Expiration: Expiration ) @JsonSerializable data class CliCachedCredentialsFile( val Credentials: CliCachedCredentials, val ProviderType: String? = null )
7
Kotlin
17
37
94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c
1,471
http4k-connect
Apache License 2.0
datetime/src/commonMain/kotlin/com/inkapplications/datetime/ZonedTime.kt
InkApplications
276,733,654
false
{"Kotlin": 114688}
package com.inkapplications.datetime import kotlinx.datetime.* /** * A [LocalTime] associated with a specific [TimeZone]. */ data class ZonedTime( val localTime: LocalTime, val zone: TimeZone, ) { /** * The hour component of this time for its zone. */ val hour get() = localTime.hour /** * The minute component of this time for its zone. */ val minute get() = localTime.minute /** * The second component of this time for its zone. */ val second get() = localTime.second /** * The millisecond component of this time for its zone. */ val nanosecond get() = localTime.nanosecond /** * The millisecond component of this time for its zone. */ val secondOfDay get() = localTime.toSecondOfDay() /** * The millisecond component of this time for its zone. */ val millisecondOfDay get() = localTime.toMillisecondOfDay() /** * The microsecond component of this time for its zone. */ val nanosecondOfDay get() = localTime.toNanosecondOfDay() /** * Associate this local time with a specific date. */ fun atDate(date: LocalDate) = ZonedDateTime( localDateTime = localTime.atDate(date), zone = zone ) /** * Associate this local time with a specific date. */ fun atDate(year: Int, monthNumber: Int, dayOfMonth: Int = 0) = atDate( date = LocalDate( year = year, monthNumber = monthNumber, dayOfMonth = dayOfMonth, ) ) /** * Associate this local time with a specific date. */ fun atDate(year: Int, month: Month, dayOfMonth: Int) = atDate( date = LocalDate( year = year, month = month, dayOfMonth = dayOfMonth, ) ) /** * Compare this time to another local time. */ operator fun compareTo(other: LocalTime): Int { return localTime.compareTo(other) } override fun toString(): String { return "$localTime $zone" } } /** * Associate this local time with a specific [TimeZone]. */ fun LocalTime.atZone(zone: TimeZone) = ZonedTime( localTime = this, zone = zone, )
0
Kotlin
2
1
ab7122f285a6565a28265b002dec127c77542bbb
2,232
Watermelon
MIT License
app/src/test/java/com/example/demoassignment/RetrofitBuilder.kt
rahulhundekari
400,115,940
false
null
package com.example.demoassignment import com.example.demoassignment.network.NYTimesApi import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitBuilder { private const val BASE_URL = "http://api.nytimes.com/svc/mostpopular/v2/" private fun getRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } val nyTimesApi: NYTimesApi = getRetrofit().create(NYTimesApi::class.java) }
0
Kotlin
0
0
9b3135fb7241a01cb545a4adb688a4e26f133fbf
554
KotlinMVVMDemo
Apache License 2.0
app/src/test/java/com/example/demoassignment/RetrofitBuilder.kt
rahulhundekari
400,115,940
false
null
package com.example.demoassignment import com.example.demoassignment.network.NYTimesApi import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitBuilder { private const val BASE_URL = "http://api.nytimes.com/svc/mostpopular/v2/" private fun getRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } val nyTimesApi: NYTimesApi = getRetrofit().create(NYTimesApi::class.java) }
0
Kotlin
0
0
9b3135fb7241a01cb545a4adb688a4e26f133fbf
554
KotlinMVVMDemo
Apache License 2.0
revolver/src/commonMain/kotlin/com/umain/revolver/flow/CStateFlow.kt
apegroup
623,454,493
false
{"Kotlin": 21984, "Shell": 177}
package com.umain.revolver.flow import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.StateFlow expect open class CStateFlow<out T : Any>(flow: StateFlow<T>, coroutineScope: CoroutineScope) : StateFlow<T> @Suppress("OPT_IN_USAGE") fun <T : Any> StateFlow<T>.cStateFlow(coroutineScope: CoroutineScope = GlobalScope): CStateFlow<T> = CStateFlow(this,coroutineScope)
5
Kotlin
1
33
dedee1d7a7bb3f912242e41c30b7cf1edb6882db
423
revolver
MIT License
jackson/src/main/kotlin/com/ijoic/tools/jackson/_parse.kt
VerstSiu
165,245,877
false
null
package com.ijoic.tools.jackson import com.fasterxml.jackson.databind.JsonNode import kotlin.math.min /** * Parse current text to json node or null */ fun String.toJsonNodeOrNull(ignoreError: Boolean = false): JsonNode? { return try { mapper.readTree(this) } catch (e: Exception) { if (!ignoreError) { e.printStackTrace() } null } } /* -- current node extensions :begin -- */ /** * Verify current node as boolean or null */ fun JsonNode.verifyAsBoolean(): Boolean? { if (this.isNull || !this.isBoolean) { return null } return this.asBoolean() } /** * Verify current node as string or null */ fun JsonNode.verifyAsString(): String? { if (this.isNull) { return null } return this.asText() } /** * Verify current node as string or null */ fun JsonNode.verifyAsInt(): Int? { if (this.isNull) { return null } if (!this.canConvertToInt()) { return null } return this.intValue() } /** * Verify current node as object */ fun JsonNode.verifyAsObject(): JsonNode? { if (!this.isObject) { return null } return this } /** * Verify current node as array */ fun JsonNode.verifyAsArray(): JsonNode? { if (!this.isArray) { return null } return this } /** * Verify current node as items list */ fun <T> JsonNode.verifyAsItemsList(limit: Int? = null, mapValue: (JsonNode) -> T?): List<T>? { if (!this.isArray) { return null } val itemSize = limit?.let { min(limit, this.size()) } ?: this.size() if (itemSize <= 0) { return null } val items = mutableListOf<T>() if (itemSize > 0) { for (i in 0 until itemSize) { val node = this.get(i) val value = node?.let(mapValue) if (value != null) { items.add(value) } } } return items } /* -- current node extensions :end -- */ /* -- field node extensions :begin -- */ /** * Verify [field] node as boolean or null */ fun JsonNode.verifyAsBoolean(field: String): Boolean? { return get(field)?.verifyAsBoolean() } /** * Verify [field] node as string or null */ fun JsonNode.verifyAsString(field: String): String? { return get(field)?.verifyAsString() } /** * Verify [field] node as string or null */ fun JsonNode.verifyAsInt(field: String): Int? { return get(field)?.verifyAsInt() } /** * Verify [field] node as object */ fun JsonNode.verifyAsObject(field: String): JsonNode? { return get(field)?.verifyAsObject() } /** * Verify [field] node as array */ fun JsonNode.verifyAsArray(field: String): JsonNode? { return get(field)?.verifyAsArray() } /** * Verify [field] node as items list */ fun <T> JsonNode.verifyAsItemsList(field: String, limit: Int? = null, mapValue: (JsonNode) -> T?): List<T>? { return get(field)?.verifyAsItemsList(limit, mapValue) } /* -- field node extensions :end -- */
0
Kotlin
2
0
a94167f700f163d1953744ccf858dc26a78b926c
2,822
common-tools
Apache License 2.0
app/SwimChrono/app/src/main/java/es/udc/apm/swimchrono/notifications/BootReceiver.kt
dfr99
757,763,682
false
{"Kotlin": 126542}
package es.udc.apm.swimchrono.notifications import android.annotation.SuppressLint import android.app.AlarmManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.util.Log import java.util.Calendar class BootReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == "android.intent.action.BOOT_COMPLETED") { Log.d("BootReceiver", "Device rebooted, rescheduling notification") rescheduleNotification(context) } } @SuppressLint("ScheduleExactAlarm") private fun rescheduleNotification(context: Context) { // Recuperar fecha y hora de SharedPreferences val sharedPreferences: SharedPreferences = context.getSharedPreferences(AlarmNotificationManager.PREFS_NAME, Context.MODE_PRIVATE) val year = sharedPreferences.getInt(AlarmNotificationManager.YEAR_KEY, 0) val month = sharedPreferences.getInt(AlarmNotificationManager.MONTH_KEY, 0) val day = sharedPreferences.getInt(AlarmNotificationManager.DAY_KEY, 0) val hour = sharedPreferences.getInt(AlarmNotificationManager.HOUR_KEY, 0) val minute = sharedPreferences.getInt(AlarmNotificationManager.MINUTE_KEY, 0) val second = sharedPreferences.getInt(AlarmNotificationManager.SECOND_KEY, 0) if (year == 0 && month == 0 && day == 0 && hour == 0 && minute == 0 && second == 0) { // Si no se encuentran valores en SharedPreferences, no se hace nada return } val calendarTime = Calendar.getInstance().apply { set(Calendar.YEAR, year) set(Calendar.MONTH, month) set(Calendar.DAY_OF_MONTH, day) set(Calendar.HOUR_OF_DAY, hour) set(Calendar.MINUTE, minute) set(Calendar.SECOND, second) } // Verificar si la fecha y hora ya pasaron val currentTime = Calendar.getInstance() if (calendarTime.before(currentTime)) { // No reprogramar la notificación si la fecha y hora ya pasaron return } val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager // Crea un mensaje para que observe cuando es su próxima carrera val notificationIntent = Intent(context, AlarmNotification::class.java).apply { putExtra(AlarmNotificationManager.TYPE_MSG_KEY, 4) } val id = System.currentTimeMillis().toInt() val pendingIntent = PendingIntent.getBroadcast( context, id, notificationIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendarTime.timeInMillis, pendingIntent) } }
2
Kotlin
0
3
0fc65f531051d438b3c8021664bcb49d6c77b569
2,941
SwimChrono
MIT License
client-android/lib/src/main/kotlin/stasis/client_android/lib/staging/DefaultFileStaging.kt
sndnv
153,169,374
false
{"Scala": 3373826, "Kotlin": 1821771, "Dart": 853650, "Python": 363474, "Shell": 70265, "CMake": 8759, "C++": 4051, "HTML": 2655, "Dockerfile": 1942, "Ruby": 1330, "C": 691, "Swift": 594, "JavaScript": 516}
package stasis.client_android.lib.staging import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.nio.file.attribute.PosixFilePermissions class DefaultFileStaging( private val storeDirectory: Path?, private val prefix: String, private val suffix: String ) : FileStaging { override suspend fun temporary(): Path = withContext(Dispatchers.IO) { when (storeDirectory) { null -> Files.createTempFile(prefix, suffix, temporaryFileAttributes) else -> Files.createTempFile(storeDirectory, prefix, suffix, temporaryFileAttributes) } } override suspend fun discard(file: Path): Unit = withContext(Dispatchers.IO) { Files.deleteIfExists(file) } override suspend fun destage(from: Path, to: Path): Unit = withContext(Dispatchers.IO) { Files.move(from, to, StandardCopyOption.REPLACE_EXISTING) } private val temporaryFilePermissions = "rw-------" private val temporaryFileAttributes = PosixFilePermissions.asFileAttribute( PosixFilePermissions.fromString( temporaryFilePermissions ) ) }
0
Scala
4
53
d7b3002880814039b332b3d5373a16b57637eb1e
1,262
stasis
Apache License 2.0
lib-domain/src/main/kotlin/com/jonapoul/common/domain/SharedPreferenceExtensions.kt
jonapoul
375,762,483
false
null
@file:Suppress("TooManyFunctions") package com.jonapoul.common.domain import android.content.SharedPreferences import android.os.Build import androidx.annotation.RequiresApi import androidx.core.content.edit import com.jonapoul.common.data.PrefPair /** * Parses an [Int] from a [SharedPreferences] [String] value, returning the [Int] default value if * the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.parseInt(pref: PrefPair<String>): Int { return typeSafeGet(pref) { this.getString(pref.key, pref.default)!! }.toInt() } /** * Parses a [Long] from a [SharedPreferences] [String] value, returning the [Long] default value * if the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.parseLong(pref: PrefPair<String>): Long { return typeSafeGet(pref) { this.getString(pref.key, pref.default)!! }.toLong() } /** * Parses a [Double] from a [SharedPreferences] [String] value, returning the [Double] default value * if the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.parseDouble(pref: PrefPair<String>): Double { return typeSafeGet(pref) { this.getString(pref.key, pref.default)!! }.toDouble() } /** * Parses a [Float] from a [SharedPreferences] [String] value, returning the [Float] default value * if the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.parseFloat(pref: PrefPair<String>): Float { return typeSafeGet(pref) { this.getString(pref.key, pref.default)!! }.toFloat() } /** * Returns an [Int] from a [SharedPreferences] instance, returning the [Int] default value if either * the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.getInt(pref: PrefPair<Int>): Int { return typeSafeGet(pref) { this.getInt(pref.key, pref.default) } } /** * Returns a [Float] from a [SharedPreferences] instance, returning the [Float] default value if * either the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.getFloat(pref: PrefPair<Float>): Float { return typeSafeGet(pref) { this.getFloat(pref.key, pref.default) } } /** * Returns a [Long] from a [SharedPreferences] instance, returning the [Long] default value if * either the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.getLong(pref: PrefPair<Long>): Long { return typeSafeGet(pref) { this.getLong(pref.key, pref.default) } } /** * Returns a [String] from [SharedPreferences], returning the [String] default value if either * the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.getString(pref: PrefPair<String>): String { return typeSafeGet(pref) { this.getString(pref.key, pref.default)!! } } /** * Returns a nullable [String] from [SharedPreferences], returning null if either the value isn't * already persisted or the type is incorrect. */ fun SharedPreferences.getNullableString(pref: PrefPair<String?>): String? { return typeSafeGet(pref) { this.getString(pref.key, pref.default) } } /** * Returns a [String] from [SharedPreferences]. If the persisted value either a) doesn't exist, b) * is the wrong type, or c) is blank, the [PrefPair] default is returned. */ fun SharedPreferences.getStringNoBlank(pref: PrefPair<String>): String { val result = getString(pref) return result.ifBlank { pref.default } } /** * Returns a [Boolean] from [SharedPreferences], returning the [PrefPair] default if either * the value isn't already persisted or the type is incorrect. */ fun SharedPreferences.getBoolean(pref: PrefPair<Boolean>): Boolean { return typeSafeGet(pref) { this.getBoolean(pref.key, pref.default) } } /** * Returns a [Set] of [String]s from [SharedPreferences], returning the [PrefPair] default if either * the value isn't already persisted or the type is incorrect. */ @RequiresApi(Build.VERSION_CODES.HONEYCOMB) fun SharedPreferences.getStringSet(pref: PrefPair<Set<String>>): Set<String> { return typeSafeGet(pref) { this.getStringSet(pref.key, pref.default)!! } } /** * Attempts to call a code block. If it runs into a [ClassCastException] (i.e. when the persisted * value is of the wrong type), that persisted value is cleared and the [PrefPair] default is * returned. */ private fun <T> SharedPreferences.typeSafeGet(pref: PrefPair<T>, call: () -> T): T { return try { call.invoke() } catch (e: ClassCastException) { edit { remove(pref.key) } pref.default } } /** * Attempts to insert an [Int] value into this [SharedPreferences.Editor] instance. Skips if the * supplied [value] is null. */ fun SharedPreferences.Editor.putIntIfNotNull( pref: PrefPair<Int>, value: Int?, ): SharedPreferences.Editor { if (value != null) { this.putInt(pref.key, value) } return this } /** * Attempts to insert a [Float] value into this [SharedPreferences.Editor] instance. Skips if the * supplied [value] is null. */ fun SharedPreferences.Editor.putFloatIfNotNull( pref: PrefPair<Float>, value: Float?, ): SharedPreferences.Editor { if (value != null) { this.putFloat(pref.key, value) } return this } /** * Attempts to insert a [Boolean] value into this [SharedPreferences.Editor] instance. Skips if the * supplied [value] is null. */ fun SharedPreferences.Editor.putBooleanIfNotNull( pref: PrefPair<Boolean>, value: Boolean?, ): SharedPreferences.Editor { if (value != null) { this.putBoolean(pref.key, value) } return this } /** * Attempts to insert a [Long] value into this [SharedPreferences.Editor] instance. Skips if the * supplied [value] is null. */ fun SharedPreferences.Editor.putLongIfNotNull( pref: PrefPair<Long>, value: Long?, ): SharedPreferences.Editor { if (value != null) { this.putLong(pref.key, value) } return this } /** * Attempts to insert a [String] value into this [SharedPreferences.Editor] instance. Skips if the * supplied [value] is null. */ fun SharedPreferences.Editor.putStringIfNotNull( pref: PrefPair<String>, value: String?, ): SharedPreferences.Editor { if (value != null) { this.putString(pref.key, value) } return this } /** * Attempts to insert a [Set] value into this [SharedPreferences.Editor] instance. Skips if the * supplied [value] is null. */ @RequiresApi(Build.VERSION_CODES.HONEYCOMB) fun SharedPreferences.Editor.putStringSetIfNotNull( pref: PrefPair<Set<String>>, value: Set<String>?, ): SharedPreferences.Editor { if (value != null) { this.putStringSet(pref.key, value) } return this } fun SharedPreferences.putInt(key: String, value: Int) = edit { putInt(key, value) } fun SharedPreferences.putLong(key: String, value: Long) = edit { putLong(key, value) } fun SharedPreferences.putFloat(key: String, value: Float) = edit { putFloat(key, value) } fun SharedPreferences.putBoolean(key: String, value: Boolean) = edit { putBoolean(key, value) } fun SharedPreferences.putString(key: String, value: String) = edit { putString(key, value) } fun SharedPreferences.putNullableString(key: String, value: String?) = edit { putString(key, value) } @RequiresApi(Build.VERSION_CODES.HONEYCOMB) fun SharedPreferences.putStringSet(key: String, value: Set<String>) = edit { putStringSet(key, value) } fun SharedPreferences.putInt(pref: PrefPair<Int>, value: Int) = putInt(pref.key, value) fun SharedPreferences.putLong(pref: PrefPair<Long>, value: Long) = putLong(pref.key, value) fun SharedPreferences.putFloat(pref: PrefPair<Float>, value: Float) = putFloat(pref.key, value) fun SharedPreferences.putBoolean(pref: PrefPair<Boolean>, value: Boolean) = putBoolean(pref.key, value) fun SharedPreferences.putString(pref: PrefPair<String>, value: String) = putString(pref.key, value) fun SharedPreferences.putNullableString(pref: PrefPair<String?>, value: String?) = putNullableString(pref.key, value) @RequiresApi(Build.VERSION_CODES.HONEYCOMB) fun SharedPreferences.putStringSet(pref: PrefPair<Set<String>>, value: Set<String>) = putStringSet(pref.key, value)
0
Kotlin
0
0
3c4bb0116dfc1cc5240fc616dc3dc1559ad27e5b
8,344
android-extensions
Apache License 2.0
TelegramBotAPI/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/types/payments/OrderInfo.kt
sleshJdev
289,571,865
true
{"Kotlin": 718048}
package com.github.insanusmokrassar.TelegramBotAPI.types.payments import com.github.insanusmokrassar.TelegramBotAPI.types.* import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class OrderInfo( @SerialName(nameField) val name: String, @SerialName(phoneNumberField) val phoneNumber: String, @SerialName(emailField) val email: String, @SerialName(shippingAddressField) val shippingAddress: ShippingAddress )
0
null
0
0
cc0498a89a28ae8205f6f854534ec6f31be36cda
488
TelegramBotAPI
Apache License 2.0
src/main/kotlin/no/nav/nada/SchemaRegistryRoutes.kt
navikt
275,420,244
false
null
package no.nav.nada import io.ktor.application.call import io.ktor.http.HttpStatusCode import io.ktor.response.respond import io.ktor.routing.Route import io.ktor.routing.get import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject fun Route.schemaRegistry(schemaRepository: SchemaRepository) { get("/subjects") { val subjects = schemaRepository.getSubjects() call.respond(subjects) } get("/subjects/{subject}/versions") { call.parameters["subject"]?.let { subject -> val versions = schemaRepository.getVersions(subject) if (versions.isEmpty()) { call.respond( status = HttpStatusCode.NotFound, message = buildJsonObject(fun JsonObjectBuilder.() { put("error_code", JsonPrimitive(40401)) put("message", JsonPrimitive("Subject '$subject' not found")) }) ) } else { call.respond(versions) } } ?: call.respond(HttpStatusCode.BadRequest) } get("/subjects/{subject}/versions/{version}") { call.parameters["subject"]?.let { subject -> call.parameters["version"]?.let { version -> schemaRepository.getSchema(subject, version.toLong())?.let { call.respond( buildJsonObject(fun JsonObjectBuilder.() { put("subject", JsonPrimitive(it.subject)) put("version", JsonPrimitive(it.version)) put("id", JsonPrimitive(it.registry_id)) put("schema", JsonPrimitive(it.schema)) }) ) } ?: call.respond( status = HttpStatusCode.NotFound, message = buildJsonObject(fun JsonObjectBuilder.() { put("error_code", JsonPrimitive(40402)) put("message", JsonPrimitive("Version $version not found")) }) ) } } ?: call.respond(HttpStatusCode.BadRequest) } get("/schemas/ids/{id}") { call.parameters["id"]?.let { id -> schemaRepository.getSchemaByRegistryId(id.toLong())?.let { call.respond(mapOf("schema" to it)) } ?: call.respond( status = HttpStatusCode.NotFound, message = buildJsonObject(fun JsonObjectBuilder.() { put("error_code", JsonPrimitive(40403)) put("message", JsonPrimitive("Schema $id not found")) }) ) } ?: call.respond(HttpStatusCode.BadRequest) } }
11
Kotlin
1
1
23badf652733f33a57a14da8eea99de11f9f250e
2,848
kafka-schema-backup
MIT License
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/admission/v1beta1/resource.kt
fkorotkov
84,911,320
false
null
// GENERATED package com.fkorotkov.kubernetes.admission.v1beta1 import io.fabric8.kubernetes.api.model.GroupVersionResource as model_GroupVersionResource import io.fabric8.kubernetes.api.model.admission.v1beta1.AdmissionRequest as v1beta1_AdmissionRequest fun v1beta1_AdmissionRequest.`resource`(block: model_GroupVersionResource.() -> Unit = {}) { if(this.`resource` == null) { this.`resource` = model_GroupVersionResource() } this.`resource`.block() }
6
Kotlin
19
317
ef8297132e6134b6f65ace3e50869dbb2b686b21
470
k8s-kotlin-dsl
MIT License
design/src/main/java/com/pp/design/large/appbars/AppBar.kt
pauloaapereira
356,418,263
false
null
/* * Copyright 2021 <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 * * 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.pp.design.large.appbars import androidx.annotation.DrawableRes import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.pp.design.background.LocalBaseColor import com.pp.design.background.LocalBaseContentColor import com.pp.design.core.animation.clickableTrackingPress import com.pp.design.core.animation.enabledAlpha import com.pp.design.core.animation.pressedScale import com.pp.design.small.icon.Icon import com.pp.design.small.text.Text object AppBar { data class BottomBarItem( val title: String, @DrawableRes val iconRes: Int?, val isEnabled: Boolean = true, val onClick: (() -> Unit)? = null ) @Composable fun Top( modifier: Modifier = Modifier, shape: Shape? = null, isScrollable: Boolean = false, content: @Composable RowScope.() -> Unit ) { Surface( modifier = modifier .fillMaxWidth(), color = LocalBaseColor.current, contentColor = LocalBaseContentColor.current, shape = shape ?: RectangleShape ) { Row( modifier = modifier .fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 8.dp) .apply { if (isScrollable) horizontalScroll(rememberScrollState()) else Modifier }, horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically ) { content() } } } @Composable fun Bottom( modifier: Modifier = Modifier, items: List<BottomBarItem>, shape: Shape? = null, isScrollable: Boolean = false ) { Surface( modifier = modifier .fillMaxWidth(), color = LocalBaseColor.current, contentColor = LocalBaseContentColor.current, shape = shape ?: RectangleShape ) { Row( modifier = modifier .fillMaxWidth().apply { if (isScrollable) horizontalScroll(rememberScrollState()) else Modifier }, horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { items.forEach { item -> BarItem( modifier = Modifier .weight(1f) .padding(8.dp), title = item.title, iconRes = item.iconRes, onClick = item.onClick, shape = shape, isEnabled = item.isEnabled ) } } } } @Composable fun BarItem( modifier: Modifier = Modifier, isEnabled: Boolean = true, title: String, @DrawableRes iconRes: Int? = null, shape: Shape? = null, onClick: (() -> Unit)? = null ) { var isPressed by remember { mutableStateOf(false) } Column( modifier = modifier .enabledAlpha(isEnabled) .then( if (onClick != null) { Modifier .pressedScale(isPressed) .then( if (shape != null) { Modifier.clip(shape) } else Modifier ) .clickableTrackingPress( onPressChanged = { isPressed = it } ) { if (isEnabled) onClick() } } else Modifier ), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp) ) { Icon.Primary( iconRes = iconRes, contentDescription = title, isVisible = iconRes != null ) Text.Button( text = title, parameters = Text.TextParameters(textAlign = TextAlign.Center) ) } } }
0
Kotlin
0
0
e174b88ab2397720c47f81c06603794e142bd91f
6,173
Moviefy
Apache License 2.0
common/src/commonMain/kotlin/com/artemchep/keyguard/common/service/hibp/breaches/find/impl/AccountPwnageDataSourceLocalImpl.kt
AChep
669,697,660
false
{"Kotlin": 5516822, "HTML": 45876}
package com.artemchep.keyguard.common.service.hibp.breaches.find.impl import com.artemchep.keyguard.common.io.IO import com.artemchep.keyguard.common.io.effectMap import com.artemchep.keyguard.common.service.hibp.breaches.find.AccountPwnageDataSourceLocal import com.artemchep.keyguard.core.store.DatabaseDispatcher import com.artemchep.keyguard.core.store.DatabaseManager import com.artemchep.keyguard.data.Database import com.artemchep.keyguard.data.pwnage.AccountBreach import kotlinx.coroutines.CoroutineDispatcher import org.kodein.di.DirectDI import org.kodein.di.instance /** * @author <NAME> */ class AccountPwnageDataSourceLocalImpl( private val databaseManager: DatabaseManager, private val dispatcher: CoroutineDispatcher, ) : AccountPwnageDataSourceLocal { constructor(directDI: DirectDI) : this( databaseManager = directDI.instance(), dispatcher = directDI.instance(tag = DatabaseDispatcher), ) override fun put( entity: AccountBreach, ): IO<Unit> = dbEffect { db -> db.accountBreachQueries.insert( count = entity.count, updatedAt = entity.updatedAt, data = entity.data_, username = entity.username, ) } override fun getOne( username: String, ): IO<AccountBreach?> = dbEffect { db -> val model = db.accountBreachQueries .getByUsername(username) .executeAsOneOrNull() model } override fun getMany( usernames: Collection<String>, ): IO<Map<String, AccountBreach?>> = dbEffect { db -> val list = db.accountBreachQueries .getByUsernames(usernames) .executeAsList() usernames .asSequence() .map { username -> val entity = list.firstOrNull { it.username == username } username to entity } .toMap() } override fun clear(): IO<Unit> = dbEffect { db -> db.accountBreachQueries.deleteAll() } private fun <T> dbEffect(block: suspend (Database) -> T) = databaseManager .get() .effectMap(dispatcher, block) }
66
Kotlin
31
995
557bf42372ebb19007e3a8871e3f7cb8a7e50739
2,170
keyguard-app
Linux Kernel Variant of OpenIB.org license
app2/src/main/java/luyao/android2/TaskActivity.kt
lulululbj
269,033,034
false
null
package luyao.android2 import android.os.Bundle import luyao.android.base.BaseLifecycleActivity import luyao.android.base.start import luyao.android2.databinding.ActivityTask2Binding /** * Created by luyao * on 2020/6/2 15:15 */ open class TaskActivity : BaseLifecycleActivity() { private val binding by lazy { ActivityTask2Binding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) var activity = this.toString() activity = activity.substring( activity.lastIndexOf(".") + 1, activity.length ) binding.taskId.text = "taskId: $taskId \n$activity" initListener() } private fun initListener() { binding.run { standardE.setOnClickListener { start<StandardActivityE>() } standardF.setOnClickListener { start<StandardActivityF>() } singleTaskX.setOnClickListener { start<SingleTaskActivityX>() } singleTaskY.setOnClickListener { start<SingleTaskActivityY>() } } } }
0
Kotlin
0
0
32de1070b2a084dd2fd05b4557097026729cb41e
1,124
Android
Apache License 2.0
df_login/src/main/java/com/pizza11x/df_login/data/models/SendOobCodeRequest.kt
pizza11x
511,648,079
false
null
package com.pizza11x.df_login.data.models import com.google.gson.annotations.SerializedName data class SendOobCodeRequest( @SerializedName("email") val email: String, @SerializedName("requestType") val requestType: String, @SerializedName("idToken") val idToken: String )
1
Kotlin
0
0
4c8169d24194655d436a480c8e8f43590794e4f1
298
eventsAround
Apache License 2.0
embrace-android-sdk/src/main/java/io/embrace/android/embracesdk/internal/telemetry/errors/InternalErrorDataSource.kt
embrace-io
704,537,857
false
{"Kotlin": 2867942, "C": 190133, "Java": 177132, "C++": 13140, "CMake": 4261}
package io.embrace.android.embracesdk.internal.telemetry.errors import io.embrace.android.embracesdk.internal.arch.datasource.LogDataSource import io.embrace.android.embracesdk.internal.logging.InternalErrorHandler internal interface InternalErrorDataSource : LogDataSource, InternalErrorHandler
16
Kotlin
7
133
a7d76f379f1e190c0deaddbb783d63ac953fd1df
298
embrace-android-sdk
Apache License 2.0
app/src/main/java/dev/techpleiades/tms/ui/home/HomeViewModel.kt
l10es
579,322,991
false
null
/* * Copyright (C) 2023 TMS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.techpleiades.tms.ui.home import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dev.techpleiades.tms.data.TmsRepository import dev.techpleiades.tms.data.local.database.Task import dev.techpleiades.tms.ui.home.HomeUiState.Success import dev.techpleiades.tms.ui.home.HomeUiState.Error import kotlinx.coroutines.flow.* import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val tmsRepository: TmsRepository ) : ViewModel() { val uiState : StateFlow<HomeUiState> = tmsRepository .tasks.map(::Success) .catch { Error(it) } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), HomeUiState.Loading) } sealed interface HomeUiState { object Loading: HomeUiState data class Error(val throwable: Throwable): HomeUiState data class Success(val data: List<Task>): HomeUiState }
1
Kotlin
0
0
cbac4ac84075b4258c310e7227010c7ec14ad673
1,576
tms
Apache License 2.0
src/main/kotlin/io/github/sergkhram/idbClient/requests/app/UninstallRequest.kt
SergKhram
524,131,579
false
null
package io.github.sergkhram.idbClient.requests.app import idb.UninstallResponse import io.github.sergkhram.idbClient.entities.GrpcClient import io.github.sergkhram.idbClient.requests.IdbRequest class UninstallRequest(private val bundleId: String): IdbRequest<UninstallResponse>() { override suspend fun execute(client: GrpcClient): UninstallResponse { return client.stub.uninstall( idb.UninstallRequest.newBuilder().setBundleId(bundleId).build() ) } }
0
Kotlin
0
5
355102d6c7220f484210938772b2e84daa58ab36
489
IdbClient
Apache License 2.0
domain/src/test/kotlin/no/nav/su/se/bakover/domain/vilkår/VurderingsperiodePersonligOppmøteTest.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.domain.vilkår import io.kotest.matchers.shouldBe import no.nav.su.se.bakover.common.application.CopyArgs import no.nav.su.se.bakover.common.periode.februar import no.nav.su.se.bakover.common.periode.mai import no.nav.su.se.bakover.common.periode.år import no.nav.su.se.bakover.domain.grunnlag.PersonligOppmøteGrunnlag import no.nav.su.se.bakover.domain.grunnlag.PersonligOppmøteÅrsak import no.nav.su.se.bakover.domain.søknadsbehandling.stønadsperiode.Stønadsperiode import no.nav.su.se.bakover.test.fixedTidspunkt import org.junit.jupiter.api.Test import java.util.UUID internal class VurderingsperiodePersonligOppmøteTest { private val vilkårId = UUID.randomUUID() private val grunnlagId = UUID.randomUUID() @Test fun `oppdaterer periode`() { VurderingsperiodePersonligOppmøte( id = vilkårId, opprettet = fixedTidspunkt, grunnlag = PersonligOppmøteGrunnlag( id = grunnlagId, opprettet = fixedTidspunkt, periode = år(2021), årsak = PersonligOppmøteÅrsak.MøttPersonlig, ), periode = år(2021), ) .let { it.oppdaterStønadsperiode( Stønadsperiode.create(februar(2021)), ) shouldBe VurderingsperiodePersonligOppmøte( id = vilkårId, opprettet = fixedTidspunkt, grunnlag = PersonligOppmøteGrunnlag( id = grunnlagId, opprettet = fixedTidspunkt, periode = februar(2021), årsak = PersonligOppmøteÅrsak.MøttPersonlig, ), periode = februar(2021), ) } } @Test fun `kopierer korrekte verdier`() { VurderingsperiodePersonligOppmøte( id = vilkårId, opprettet = fixedTidspunkt, grunnlag = PersonligOppmøteGrunnlag( id = grunnlagId, opprettet = fixedTidspunkt, periode = år(2021), årsak = PersonligOppmøteÅrsak.MøttPersonlig, ), periode = år(2021), ) .copy(CopyArgs.Tidslinje.Full).let { it shouldBe it.copy() } VurderingsperiodePersonligOppmøte( id = vilkårId, opprettet = fixedTidspunkt, grunnlag = PersonligOppmøteGrunnlag( id = grunnlagId, opprettet = fixedTidspunkt, periode = år(2021), årsak = PersonligOppmøteÅrsak.MøttPersonlig, ), periode = år(2021), ).copy(CopyArgs.Tidslinje.NyPeriode(mai(2021))).let { it shouldBe it.copy(periode = mai(2021)) } } @Test fun `er lik ser kun på funksjonelle verdier`() { VurderingsperiodePersonligOppmøte( id = vilkårId, opprettet = fixedTidspunkt, grunnlag = PersonligOppmøteGrunnlag( id = grunnlagId, opprettet = fixedTidspunkt, periode = år(2021), årsak = PersonligOppmøteÅrsak.MøttPersonlig, ), periode = år(2021), ).erLik( VurderingsperiodePersonligOppmøte( id = UUID.randomUUID(), opprettet = fixedTidspunkt, grunnlag = PersonligOppmøteGrunnlag( id = UUID.randomUUID(), opprettet = fixedTidspunkt, periode = februar(2021), årsak = PersonligOppmøteÅrsak.MøttPersonlig, ), periode = februar(2021), ), ) shouldBe true VurderingsperiodePersonligOppmøte( id = vilkårId, opprettet = fixedTidspunkt, grunnlag = PersonligOppmøteGrunnlag( id = grunnlagId, opprettet = fixedTidspunkt, periode = år(2021), årsak = PersonligOppmøteÅrsak.MøttPersonlig, ), periode = år(2021), ).erLik( VurderingsperiodePersonligOppmøte( id = UUID.randomUUID(), opprettet = fixedTidspunkt, grunnlag = PersonligOppmøteGrunnlag( id = UUID.randomUUID(), opprettet = fixedTidspunkt, periode = februar(2021), årsak = PersonligOppmøteÅrsak.IkkeMøttPersonlig, ), periode = februar(2021), ), ) shouldBe false } }
0
Kotlin
0
1
d7157394e11b5b3c714a420a96211abb0a53ea45
4,718
su-se-bakover
MIT License
app/src/main/java/com/example/flighttracker/Airport.kt
OwenLB
553,415,150
false
{"Kotlin": 35780}
package com.example.flighttracker /** * Created by sergio on 07/11/2021 * All rights reserved GoodBarber */ data class Airport( val code: String, val lat: String, val lon: String, val name: String, val city: String, val state: String, val country: String, val woeid: String, val tz: String, val phone: String, val type: String, val email: String, val url: String, val runway_length: String, val elev: String, val icao: String, val direct_flights: String, val carriers: String ) { fun getFormattedName(): String { return "$code $city ($country)" } }
0
Kotlin
0
4
c62430f39d9f6ec8f96523705364505c8ec26fea
640
FlightTracker
MIT License
src/main/kotlin/org/mixdrinks/auth/Auth.kt
MixDrinks
500,107,475
false
{"Kotlin": 177624, "Dockerfile": 648}
package org.mixdrinks.auth import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.auth.Authentication import io.ktor.server.auth.AuthenticationConfig import io.ktor.server.auth.UserIdPrincipal import io.ktor.server.auth.basic import io.ktor.server.auth.bearer import org.jetbrains.exposed.sql.transactions.transaction import org.mixdrinks.admin.Admin import org.mixdrinks.admin.AdminTable import org.mixdrinks.admin.getHashFunction import org.mixdrinks.users.User const val FIREBASE_AUTH = "FIREBASE_AUTH" const val KEY_ADMIN_AUTH = "admin-auth" const val KEY_SUPPER_ADMIN_AUTH = "supper-admin-auth" fun Application.configureAuth(supperAdminToken: String, adminPasswordsSlat: String) { val digestFunction = getHashFunction(adminPasswordsSlat) install(Authentication) { basic(KEY_ADMIN_AUTH) { realm = "Access to the '/admin/' path" validate { credentials -> val user = transaction { Admin.find { AdminTable.name eq credentials.name }.firstOrNull() } return@validate if (user?.password?.contentEquals(digestFunction(credentials.password)) == true) { UserIdPrincipal(user.login) } else { null } } } bearer(KEY_SUPPER_ADMIN_AUTH) { authenticate { tokenCredential -> if (tokenCredential.token == supperAdminToken) { UserIdPrincipal("supper_admin") } else { null } } } firebase { validate { val result = transaction { User.findById(it.uid) ?: User.new(id = it.uid) {} } FirebasePrincipalUser(result.userId.value) } } } } fun AuthenticationConfig.firebase( name: String? = FIREBASE_AUTH, configure: FirebaseConfig.() -> Unit ) { val provider = FirebaseAuthProvider(FirebaseConfig(name).apply(configure)) register(provider) }
10
Kotlin
0
4
37350f60fe56d4c5c6d0bab2fb37ebd185cd444e
2,136
backend
MIT License
tools/src/main/kotlin/pw/binom/material/compiler/MethodDesc.kt
caffeine-mgn
223,796,620
false
null
package pw.binom.material.compiler import pw.binom.material.SourcePoint import pw.binom.material.lex.Type class MethodDesc(val scope: Scope, val parent: TypeDesc?, var name: String, val returnType: TypeDesc, val args: List<Argument>, val external: Boolean, override val source: SourcePoint) : Scope, SourceElement { class Argument(name: String, type: TypeDesc, source:SourcePoint) : FieldDesc(name, type, source) { override val childs: Sequence<SourceElement> get() = emptySequence() } override val childs: Sequence<SourceElement> get() = args.asSequence() var statementBlock: StatementBlockDesc? = null override val parentScope: Scope? get() = null override fun findMethod(name: String, args: List<TypeDesc>): MethodDesc? = scope.findMethod(name, args) override fun findField(name: String): FieldDesc? = args.find { it.name == name }?.let { return it } ?: scope.findField(name) override fun findType(type: Type): TypeDesc? = scope.findType(type) override fun findType(clazz: ClassDesc, array: List<Int>): TypeDesc? = scope.findType(clazz, array) fun canCall(name: String, args: List<TypeDesc>): Boolean { if (name != this.name || this.args.size != args.size) return false args.forEachIndexed { index, typeDesc -> if (typeDesc !== this.args[index].type) return false } return true } }
6
Kotlin
0
4
e673acfcb20e2d62d8e68c43d395731bd9d9d882
1,597
mogot
Apache License 2.0
app/src/main/java/com/arnyminerz/androidmatic/App.kt
ArnyminerZ
540,989,660
false
null
package com.arnyminerz.androidmatic import android.app.Application import com.arnyminerz.androidmatic.data.providers.MeteoclimaticProvider import com.arnyminerz.androidmatic.data.providers.WeewxTemplateProvider import com.arnyminerz.androidmatic.data.providers.model.WeatherProvider import com.arnyminerz.androidmatic.utils.doAsync import com.arnyminerz.androidmatic.worker.UpdateDataWorker.Companion.scheduleIfNotRunning import com.google.android.material.color.DynamicColors import com.google.android.material.color.DynamicColorsOptions import timber.log.Timber class App : Application() { override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) Timber.i("Adding to providers registry: ${MeteoclimaticProvider::class}") WeatherProvider.register(MeteoclimaticProvider::class) Timber.i("Adding to providers registry: ${WeewxTemplateProvider::class}") WeatherProvider.register(WeewxTemplateProvider::class) Timber.i("Applying dynamic colors") DynamicColors.applyToActivitiesIfAvailable( this, DynamicColorsOptions.Builder() .setThemeOverlay(R.style.AndroidmaticTheme) .build(), ) doAsync { scheduleIfNotRunning(applicationContext) } } }
0
Kotlin
0
0
5252242a8cc0667cda551b0f1a7dd2956f49c668
1,305
Androidmatic
MIT License
demo/src/main/java/com/trading212/demo/samples/HeterogeneousListActivity.kt
Trading212
113,188,420
false
null
package com.trading212.demo.samples import android.widget.Toast import com.trading212.demo.BaseActivity import com.trading212.demo.R import com.trading212.demo.item.ImageTextRecyclerItem import com.trading212.demo.item.SimpleImageRecyclerItem import com.trading212.demo.item.SimpleTextRecyclerItem import com.trading212.diverserecycleradapter.DiverseRecyclerAdapter import com.trading212.diverserecycleradapter.util.onItemClicked import com.trading212.diverserecycleradapter.util.onItemLongClicked /** * Created by svetlin on 9.12.17. */ class HeterogeneousListActivity : BaseActivity() { override fun fillElements(adapter: DiverseRecyclerAdapter) { val items = ArrayList<DiverseRecyclerAdapter.RecyclerItem<*, DiverseRecyclerAdapter.ViewHolder<*>>>() for (i in 1..30) { when { i % 3 == 0 -> items.add(SimpleImageRecyclerItem()) i % 2 == 0 -> items.add(ImageTextRecyclerItem(ImageTextRecyclerItem.ImageData("Christmas Time", R.drawable.christmas))) else -> items.add(SimpleTextRecyclerItem("Text item $i")) } } adapter.addItems(items) adapter.onItemClicked { v, position -> val text = when (adapter.getItemViewType(position)) { SimpleImageRecyclerItem.TYPE -> "Clicked image at position $position" SimpleTextRecyclerItem.TYPE -> "Clicked ${adapter.getItem<SimpleTextRecyclerItem>(position).data}" ImageTextRecyclerItem.TYPE -> "Clicked image ${adapter.getItem<ImageTextRecyclerItem>(position).data.name}" else -> "Unknown item clicked" } Toast.makeText(v.context, text, Toast.LENGTH_SHORT).show() } adapter.onItemLongClicked { v, position -> val text = when (adapter.getItemViewType(position)) { SimpleImageRecyclerItem.TYPE -> "Long clicked image at position $position" SimpleTextRecyclerItem.TYPE -> "Long clicked ${adapter.getItem<SimpleTextRecyclerItem>(position).data}" ImageTextRecyclerItem.TYPE -> "Long clicked image ${adapter.getItem<ImageTextRecyclerItem>(position).data.name}" else -> "Unknown item long clicked" } Toast.makeText(v.context, text, Toast.LENGTH_SHORT).show() false } } }
0
Kotlin
3
16
f49ea1991189019a743ce37b665e813cd40aa03e
2,369
DiverseRecyclerAdapter
Apache License 2.0
bbqr-android/plugins/src/main/kotlin/org/bitcoinppl/bbqr/plugins/UniFfiAndroidPlugin.kt
bitcoinppl
811,480,202
false
{"Kotlin": 110350, "C": 80217, "Swift": 55771, "Rust": 17548, "Shell": 2810, "Just": 1096, "Objective-C": 438}
package org.bitcoinppl.plugins import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.Copy import org.gradle.api.tasks.Exec import org.gradle.kotlin.dsl.environment import org.gradle.kotlin.dsl.getValue import org.gradle.kotlin.dsl.provideDelegate import org.gradle.kotlin.dsl.register internal class UniFfiAndroidPlugin : Plugin<Project> { override fun apply(target: Project): Unit = target.run { val llvmArchPath = when (operatingSystem) { OS.MAC -> "darwin-x86_64" OS.LINUX -> "linux-x86_64" OS.OTHER -> throw Error("Cannot build Android library from current architecture") } // arm64-v8a is the most popular hardware architecture for Android val buildAndroidAarch64Binary by tasks.register<Exec>("buildAndroidAarch64Binary") { workingDir("${projectDir}/../../bbqr-ffi") val cargoArgs: List<String> = listOf("ndk", "--target", "aarch64-linux-android", "build", "--package", "bbqr-ffi", "--profile", "release-smaller") executable("cargo") args(cargoArgs) environment( // add build toolchain to PATH Pair("CFLAGS", "-D__ANDROID_MIN_SDK_VERSION__=21"), ) doLast { println("Native library for bbqr-android on aarch64 built successfully") } } // the x86_64 version of the library is mostly used by emulators val buildAndroidX86_64Binary by tasks.register<Exec>("buildAndroidX86_64Binary") { workingDir("${project.projectDir}/../../bbqr-ffi") val cargoArgs: List<String> = listOf("ndk", "--target", "x86_64-linux-android", "build", "--package", "bbqr-ffi", "--profile", "release-smaller") executable("cargo") args(cargoArgs) environment( // add build toolchain to PATH Pair("CFLAGS", "-D__ANDROID_MIN_SDK_VERSION__=21"), ) doLast { println("Native library for bbqr-android on x86_64 built successfully") } } // armeabi-v7a version of the library for older 32-bit Android hardware val buildAndroidArmv7Binary by tasks.register<Exec>("buildAndroidArmv7Binary") { workingDir("${project.projectDir}/../../bbqr-ffi") val cargoArgs: List<String> = listOf("ndk", "--target", "armv7-linux-androideabi", "build", "--package", "bbqr-ffi", "--profile", "release-smaller") executable("cargo") args(cargoArgs) environment( // add build toolchain to PATH Pair("CFLAGS", "-D__ANDROID_MIN_SDK_VERSION__=21"), ) doLast { println("Native library for bbqr-android on armv7 built successfully") } } // move the native libs build by cargo from target/<architecture>/release/ // to their place in the bbqr-android library // the task only copies the available binaries built using the buildAndroid<architecture>Binary tasks val moveNativeAndroidLibs by tasks.register<Copy>("moveNativeAndroidLibs") { dependsOn(buildAndroidAarch64Binary) dependsOn(buildAndroidArmv7Binary) dependsOn(buildAndroidX86_64Binary) into("${project.projectDir}/../lib/src/main/jniLibs/") into("arm64-v8a") { from("${project.projectDir}/../../bbqr-ffi/target/aarch64-linux-android/release-smaller/libbbqrffi.so") } into("x86_64") { from("${project.projectDir}/../../bbqr-ffi/target/x86_64-linux-android/release-smaller/libbbqrffi.so") } into("armeabi-v7a") { from("${project.projectDir}/../../bbqr-ffi/target/armv7-linux-androideabi/release-smaller/libbbqrffi.so") } doLast { println("Native binaries for Android moved to ./lib/src/main/jniLibs/") } } // generate the bindings using the bbqr-ffi-bindgen tool located in the bbqr-ffi submodule val generateAndroidBindings by tasks.register<Exec>("generateAndroidBindings") { dependsOn(moveNativeAndroidLibs) val libraryPath = "${project.projectDir}/../../bbqr-ffi/target/aarch64-linux-android/release-smaller/libbbqrffi.so" workingDir("${project.projectDir}/../../bbqr-ffi") val cargoArgs: List<String> = listOf("run", "--bin", "uniffi-bindgen", "generate", "--library", libraryPath, "--language", "kotlin", "--out-dir", "../bbqr-android/lib/src/main/kotlin", "--no-format") executable("cargo") args(cargoArgs) doLast { println("Android bindings file successfully created") } } // create an aggregate task which will run the required tasks to build the Android libs in order // the task will also appear in the printout of the ./gradlew tasks task with group and description tasks.register("buildAndroidLib") { group = "bitcoinppl" description = "Aggregate task to build Android library" dependsOn( buildAndroidAarch64Binary, buildAndroidX86_64Binary, buildAndroidArmv7Binary, moveNativeAndroidLibs, generateAndroidBindings ) } } }
0
Kotlin
1
3
aacdf0531ee99c87223711a5f30ed40892d0cc2f
5,500
bbqr-ffi
Apache License 2.0
src/main/kotlin/solid_principles/liskov_substitution_principle/before/before/Program.kt
johanvergeer
453,711,461
false
null
package solid_principles.liskov_substitution_principle.before.before open class Rectangle(open var width: Int, open var height: Int) { val area get() = this.width * this.height val perimiter get() = (this.width + this.height) * 2 } class Square(side: Int) : Rectangle(side, side) { override var width = side set(value) { this.height = value field = value } override var height = side set(value) { this.width = value field = value } } fun main() { val rectangles = listOf(Rectangle(1, 2), Square(3)) rectangles.forEach { rectangle -> rectangle.height = 10 } }
0
Kotlin
0
0
f4b44a459bee096bb1c014f074db3f22bf980a34
685
design-patterns
MIT License
src/main/kotlin/Main.kt
pankaj046
793,726,783
false
{"Kotlin": 9389}
package app.pankaj import apiServer import response import route fun main() { apiServer(8080) { route("/api") { route(path = "login" , request = LoginRequest::class.java, methods = "POST") { exchange, req-> exchange.response(200, req) } route(path = "2", request = HashMap(), methods = "POST") { exchange, req-> val response = "${req?.get("Email")}" exchange.response(200, response) } } }.start() } data class LoginRequest( val email: String ="", val password: String ="" )
0
Kotlin
0
0
f2240013c4720ea3b2a043456f6e534f13ac27b4
607
RestApiServer
MIT License
grazel-gradle-plugin/src/test/kotlin/com/grab/grazel/gradle/dependencies/DefaultDependencyGraphsTest.kt
grab
379,151,190
false
{"Kotlin": 813733, "Starlark": 58856, "Java": 644}
/* * Copyright 2022 Grabtaxi Holdings PTE LTD (GRAB) * * 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.grab.grazel.gradle.dependencies import com.google.common.graph.ImmutableValueGraph import com.google.common.graph.ValueGraphBuilder import com.grab.grazel.fake.FakeConfiguration import com.grab.grazel.fake.FakeProject import com.grab.grazel.gradle.ConfigurationScope import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.junit.Test import kotlin.test.assertEquals class DefaultDependencyGraphsTest { private val projectA = FakeProject("A") private val projectB = FakeProject("B") private val projectC = FakeProject("C") private val projectD = FakeProject("D") private val projectE = FakeProject("E") private val dependenciesGraphs = DefaultDependencyGraphs( buildGraphs = mapOf( BuildGraphType(ConfigurationScope.BUILD) to buildBuildGraphs(), BuildGraphType(ConfigurationScope.TEST) to buildTestGraphs() ) ) @Test fun nodesShouldReturnAllNodesIfNoScopePassed() { val buildNodes = setOf(projectA, projectB, projectC) val testNodes = setOf(projectA, projectB, projectC, projectD, projectE) assertEquals( testNodes + buildNodes, dependenciesGraphs.nodes() ) } @Test fun nodesShouldReturnTheCorrectItemsBaseOnScopes() { val buildNodes = setOf(projectA, projectB, projectC) val testNodes = setOf(projectA, projectB, projectC, projectD, projectE) assertEquals(buildNodes, dependenciesGraphs.nodes(BuildGraphType(ConfigurationScope.BUILD))) assertEquals(testNodes, dependenciesGraphs.nodes(BuildGraphType(ConfigurationScope.TEST))) assertEquals( testNodes + buildNodes, dependenciesGraphs.nodes( BuildGraphType(ConfigurationScope.TEST), BuildGraphType(ConfigurationScope.BUILD) ) ) } @Test fun directDependenciesShouldReturnDirectDepsFromBuildScope() { val directDepsFromAWithBuildScope = setOf(projectB, projectC) assertEquals( directDepsFromAWithBuildScope, dependenciesGraphs.directDependencies( projectA, BuildGraphType(ConfigurationScope.BUILD) ) ) } @Test fun dependenciesSubGraphShouldReturnDepsFromAllScopeIfNoScopePassed() { val expectDeps = setOf(projectB, projectC, projectD, projectE) assertEquals( expectDeps, dependenciesGraphs.dependenciesSubGraph(projectB) ) } @Test fun dependenciesSubGraphShouldReturnDepsFromBuildScope() { val expectDeps = setOf(projectB, projectC) assertEquals( expectDeps, dependenciesGraphs.dependenciesSubGraph( projectB, BuildGraphType(ConfigurationScope.BUILD) ) ) } @Test fun dependenciesSubGraphShouldReturnDepsFromBuildAndTestScope() { val expectDeps = setOf(projectB, projectC, projectD, projectE) assertEquals( expectDeps, dependenciesGraphs.dependenciesSubGraph( projectB, BuildGraphType(ConfigurationScope.BUILD), BuildGraphType(ConfigurationScope.TEST) ) ) } private fun buildBuildGraphs(): ImmutableValueGraph<Project, Configuration> = ValueGraphBuilder.directed() .allowsSelfLoops(false) .expectedNodeCount(6) .build<Project, Configuration>().apply { putEdgeValue(projectA, projectB, FakeConfiguration()) putEdgeValue(projectA, projectC, FakeConfiguration()) putEdgeValue(projectB, projectC, FakeConfiguration()) }.run { ImmutableValueGraph.copyOf(this) } private fun buildTestGraphs(): ImmutableValueGraph<Project, Configuration> = ValueGraphBuilder.directed() .allowsSelfLoops(false) .expectedNodeCount(6) .build<Project, Configuration>().apply { putEdgeValue(projectA, projectB, FakeConfiguration()) putEdgeValue(projectA, projectC, FakeConfiguration()) putEdgeValue(projectB, projectC, FakeConfiguration()) putEdgeValue(projectC, projectD, FakeConfiguration()) putEdgeValue(projectB, projectE, FakeConfiguration()) putEdgeValue(projectA, projectE, FakeConfiguration()) }.run { ImmutableValueGraph.copyOf(this) } }
11
Kotlin
19
274
6d44b7fc7d5210cc4e4211cfd002547a3126124c
5,140
grazel
Apache License 2.0
src/main/kotlin/klay/core/json/JsonStringWriter.kt
cdietze
89,875,388
false
null
package klay.core.json import klay.core.Json internal class JsonStringWriter : JsonWriterBase<Json.Writer>(StringBuilder()), Json.Writer { /** * Completes this JSON writing session and returns the internal representation as a [String]. */ override fun write(): String { super.doneInternal() return appendable.toString() } companion object { /** * Used for testing. */ // TODO(mmastrac): Expose this on the Json interface fun toString(value: Any): String { return JsonStringWriter().value(value).write() } } }
0
Kotlin
0
4
72031aa267cd304a0612b31c871e2f5cf73d2c4c
623
klay
Apache License 2.0
app/src/main/java/com/example/NavigationForBlind/Speech/SpeechListener.kt
KMoszczyc
323,914,988
false
null
package com.example.NavigationForBlind.Speech import android.app.Activity import android.content.Context import android.media.AudioManager import android.os.Bundle import android.os.Handler import android.speech.RecognitionListener import android.speech.SpeechRecognizer import android.util.Log import com.example.NavigationForBlind.Activities.MainActivity import com.example.NavigationForBlind.Activities.MainActivity.Companion.speechDetectionCount import com.example.NavigationForBlind.Activities.MainActivity.Companion.speechResult import com.example.obstacledetection.R import kotlinx.android.synthetic.main.activity_main.* class SpeechListener<E: Enum<E>>(private var audioManager: AudioManager, private val notificationsVolume: Int, private val systemVolume: Int, private val musicVolume: Int, private val voiceCommandManager: VoiceCommandManager, private var commandType: E) :RecognitionListener { override fun onBeginningOfSpeech() { Log.wtf("1", "onBeginningOfSpeech") audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0) } override fun onBufferReceived(buffer: ByteArray) { Log.wtf("1", "onBufferReceived") } override fun onEndOfSpeech() { Log.wtf("1", "onEndOfSpeech") if(speechDetectionCount<2) { audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0) audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 0, 0) audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0) } } override fun onError(error: Int) { if (error == SpeechRecognizer.ERROR_NO_MATCH) { } else if (error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) {} Log.wtf("1", "onError" + error) if (speechDetectionCount < 2) { audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0) audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 0, 0) audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0) voiceCommandManager.recognizeSpeech(commandType) } else if (speechDetectionCount >= 2) { // activity.voiceCommandsButton.setImageResource(R.drawable.mic_not_clicked) audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, systemVolume, 0) audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, notificationsVolume, 0) audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolume, 0) } } override fun onEvent(eventType: Int, params: Bundle) { Log.wtf("1", "onEvent") } override fun onPartialResults(partialResults: Bundle) { Log.wtf("1", "onPartialResults") } override fun onReadyForSpeech(params: Bundle) { Log.wtf("1", "onReadyForSpeech") } override fun onResults(results: Bundle) { val data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) speechResult = data!![0] speechDetectionCount=0; // activity.voiceCommandsButton.setImageResource(R.drawable.mic_not_clicked) // Let the voice command manager handle the command Log.wtf("voiceresult", speechResult + " " + commandType) voiceCommandManager.handleVoiceCommands(speechResult.toLowerCase(), commandType) Log.wtf("volume", systemVolume.toString() + " " + notificationsVolume) audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, systemVolume, 0) audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, notificationsVolume,0 ); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolume,0 ); Log.wtf("1", "onResults") } override fun onRmsChanged(rmsdB: Float) { Log.wtf("1", "onRmsChanged") } }
0
Kotlin
0
3
0dfd8e2716a25e2b3328977e7bfe1e87f2ac5879
3,772
Navigation-For-Blind
MIT License
wow-models/src/test/kotlin/me/ahoo/wow/models/tree/command/CreateCategory.kt
Ahoo-Wang
628,167,080
false
{"Kotlin": 2461710, "TypeScript": 51145, "Java": 37656, "HTML": 15900, "Lua": 3978, "JavaScript": 2514, "Dockerfile": 820, "SCSS": 609, "Less": 413}
/* * Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.wow.models.tree.command import me.ahoo.wow.api.annotation.AllowCreate import me.ahoo.wow.api.annotation.CommandRoute @AllowCreate @CommandRoute( method = CommandRoute.Method.POST, appendIdPath = CommandRoute.AppendPath.ALWAYS, path = "", summary = "添加树节点", description = "Id 为租户ID." ) data class CreateCategory(override val name: String, override val parentCode: String) : Create<CategoryCreated> { override fun toEvent(code: String, sortId: Int): CategoryCreated { return CategoryCreated(name = name, code = code, sortId = sortId) } } data class CategoryCreated( override val name: String, override val code: String, override val sortId: Int ) : Created
8
Kotlin
23
187
4fb54c314c31a7cd3c9515554879a2ca8fade764
1,360
Wow
Apache License 2.0
api/src/main/kotlin/top/kanetah/weather/api/util/TimeUtil.kt
kanetah
116,962,368
false
{"JavaScript": 35578, "Kotlin": 11173, "HTML": 1539, "CSS": 751}
package top.kanetah.weather.api.util import java.util.Calendar object TimeUtil { val nextHourMillis: Long get() { val calendar = Calendar.getInstance() val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) var day = calendar.get(Calendar.DAY_OF_MONTH) var hour = calendar.get(Calendar.HOUR_OF_DAY) if (hour >= 23) { hour = 0 day++ } else hour++ calendar.clear() calendar.set(year, month, day, hour, 0) return calendar.timeInMillis } }
0
JavaScript
0
0
84f5af49378cad74c3acdfa100f36c8a308215e3
655
weather
MIT License
android/challenge/ui/vote/VoteDetailViewModel.kt
Partner-Angola
442,977,333
false
{"Swift": 444824, "Kotlin": 314181}
package com.joeware.android.gpulumera.challenge.ui.vote import androidx.databinding.ObservableBoolean import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.blankj.utilcode.util.StringUtils import com.blankj.utilcode.util.ToastUtils import com.joeware.android.gpulumera.R import com.joeware.android.gpulumera.api.CandyPlusAPI import com.joeware.android.gpulumera.base.CandyViewModel import com.joeware.android.gpulumera.challenge.model.Challenge import com.joeware.android.gpulumera.challenge.model.Join import com.joeware.android.gpulumera.challenge.model.User import com.joeware.android.gpulumera.common.C import com.joeware.android.gpulumera.util.PrefUtil import org.koin.java.standalone.KoinJavaComponent class VoteDetailViewModel : CandyViewModel() { private val api: CandyPlusAPI by KoinJavaComponent.inject(CandyPlusAPI::class.java) private val prefUtil: PrefUtil by KoinJavaComponent.inject(PrefUtil::class.java) private val _items = MutableLiveData<List<Join>>() private val _showToastMessage = MutableLiveData<String>() val items: LiveData<List<Join>> get() = _items val showToastMessage: LiveData<String> get() = _showToastMessage var isLoading = ObservableBoolean(false) private var isLoadingEnd: Boolean = false lateinit var challenge: Challenge fun setList(list: List<Join>) { _items.postValue(list) } fun getUserInfo(userId: String) { runDisposable(api.getUserInfo(userId), { response -> if (response.success) { C.me.setMyInfo(response.data as User) } }) { e -> onError(e) } } fun getJoinList() { if (isLoadingEnd || isLoading.get()) { return } isLoading.set(true) val limit = C.LIMIT_30 val excludes = _items.value?.joinToString(separator = ",") { item -> item.id } runDisposable(api.getChallengeJoinRandomList(challenge.id, limit, excludes),{ response -> isLoading.set(false) if (response.success) { isLoadingEnd = (response.data?.list?.size ?: 0) < limit response.data?.list?.let { _items.postValue(_items.value.orEmpty() + it) } } else { _showToastMessage.postValue(response.reason) } }){ e -> isLoading.set(false) onError(e) } } fun vote(joinId: String, ownerUid: String, cb: () -> Unit) { isLoading.set(true) runDisposable( api.voteChallengeJoin(challenge.id, joinId, ownerUid), { response -> isLoading.set(false) if (response.success) { cb() } else { _showToastMessage.postValue(response.reason) } }) { e -> isLoading.set(false) ToastUtils.showShort(R.string.vote_expired) onError(e) } } fun cancelVote(joinId: String, cb: () -> Unit) { isLoading.set(true) runDisposable( api.unVoteChallengeJoin(challenge.id, joinId), { response -> isLoading.set(false) if (response.success) { cb() } else { _showToastMessage.postValue(response.reason) } }) { e -> isLoading.set(false) onError(e) } } fun reportJoin(joinId: String, content: String) { isLoading.set(true) runDisposable( api.reportChallengeJoin(challenge.id, joinId, content), { response -> isLoading.set(false) if (response.success) { _showToastMessage.postValue(StringUtils.getString(R.string.report_success)) } else { _showToastMessage.postValue(response.reason) } }) { e -> isLoading.set(false) onError(e) } } }
0
Swift
1
3
e3c826b32475038db3b3e9b5a542adcbe2cd44ae
4,088
wallet
Apache License 2.0
app/src/main/java/com/softklass/lazuli/data/models/Label.kt
JoshLudahl
365,422,605
false
{"Kotlin": 32201}
package com.softklass.lazuli.data.models data class Label( val name: String )
5
Kotlin
0
0
efb6cc32222f23dce48e3d06541cbafce42862bf
83
Lazuli
The Unlicense
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt
ellisonchan
342,275,357
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.layout.sizeIn import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.ui.MainNavigation import com.example.androiddevchallenge.ui.theme.MyTheme class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyTheme { GetPetsNew() } } } } @Preview("Light Theme", widthDp = 360, heightDp = 640) @Composable fun GetPetsNew() { Spacer(Modifier.sizeIn(3.dp)) MainNavigation() } @Preview("Light Theme", widthDp = 360, heightDp = 640) @Composable fun GetPets() { // Column { // Text("Zang ao dog") // Text("Bosi cat") // Text("Bianse dragon") // Text("Wu gui") // Text("Gold fish") // } val image = painterResource(R.drawable.zang_ao_icon) // val image = resources().getDrawable(R.drawable.zang_ao_icon) Column( modifier = Modifier.padding(32.dp) ) { val imageModifier = Modifier .requiredHeight(32.dp) .requiredWidth(32.dp) Image( painter = image, contentDescription = "zang ao", contentScale = ContentScale.Crop, // modifier = Modifier.aspectRatio(1f) modifier = imageModifier ) Text("Zang ao") Text("Hachi") Text("Bosi cat") Text("Bianse dragon") Text("Wu gui") Text("Gold fish") } } // Start building your app here! @Composable fun MyApp() { Surface(color = MaterialTheme.colors.background) { // Text(text = "My lovely pets") Text(text = stringResource(id = R.string.activity_list_name)) } } @Preview("Light Theme", widthDp = 360, heightDp = 640) @Composable fun LightPreview() { MyTheme { // MyApp() GetPets() } } @Preview("Dark Theme", widthDp = 360, heightDp = 640) @Composable fun DarkPreview() { MyTheme(darkTheme = true) { // MyApp() GetPets() } }
0
Kotlin
0
4
a751196dfab4b121115ade30d483d139b7aecb99
3,543
LovePet
Apache License 2.0
paymentsheet/src/main/java/com/stripe/android/paymentsheet/forms/PaypalSpec.kt
stripe
6,926,049
false
null
package com.stripe.android.paymentsheet.forms import com.stripe.android.paymentsheet.elements.LayoutSpec /** * This defines the requirements for usage as a Payment Method. */ internal val PaypalRequirement = PaymentMethodRequirements( piRequirements = emptySet(), /** * SetupIntents are not supported by this payment method. Currently, for paypal (and others see * oof #5) customers are not able to set up saved payment methods for reuse. The API errors if * confirming PI+SFU or SI with these methods. */ siRequirements = null, confirmPMFromCustomer = null ) internal val PaypalParamKey: MutableMap<String, Any?> = mutableMapOf( "type" to "paypal", ) internal val PaypalForm = LayoutSpec.create()
54
Kotlin
502
866
c64b81095c36df34ffb361da276c116ffd5a2523
745
stripe-android
MIT License
src/main/kotlin/com/github/woojiahao/OnErrorAction.kt
omnius-project
171,386,318
false
null
package com.github.woojiahao import com.github.kittinunf.result.failure import com.github.woojiahao.markdownConverter import com.github.woojiahao.utility.document import java.io.FileNotFoundException /** * Using the [Result](https://github.com/kittinunf/Result) library, conversions will return the status of the operation * and you can use the `failure` method where `it` has a reference to the exception thrown. */ fun main() { val converter = markdownConverter { document(document) } val conversionStatus = converter.convert() conversionStatus.failure { if (it is FileNotFoundException) println("File is currently already open") } }
0
Kotlin
1
1
4dd34e8ff48c06223c5492f321ff78c9cf3ca56b
658
kMD2PDF-examples
MIT License
spring/retrofit2/src/test/kotlin/io/bluetape4k/spring/retrofit2/services/httpbin/HttpbinApiTest.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.spring.retrofit2.services.httpbin import io.bluetape4k.junit5.coroutines.runSuspendWithIO import io.bluetape4k.logging.KLogging import io.bluetape4k.logging.debug import io.bluetape4k.micrometer.instrument.retrofit2.MicrometerRetrofitMetricsRecorder import io.bluetape4k.support.uninitialized import io.micrometer.core.instrument.MeterRegistry import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import org.amshove.kluent.shouldBeGreaterThan import org.amshove.kluent.shouldNotBeEmpty import org.amshove.kluent.shouldNotBeNull import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class HttpbinApiTest { companion object: KLogging() @Autowired private val httpbinApi: HttpbinApi = uninitialized() @Autowired private val meterRegistry: MeterRegistry = uninitialized() @Test fun `context loading`() { httpbinApi.shouldNotBeNull() meterRegistry.shouldNotBeNull() } @Test fun `get local ip address`() = runSuspendWithIO { val ipAddress = httpbinApi.getLocalIpAddress() ipAddress.shouldNotBeNull() ipAddress.origin.shouldNotBeEmpty() } @Test fun `measure retrofit2 call`() = runSuspendWithIO { val runCount = 3 val tasks = List(runCount) { async(Dispatchers.IO) { httpbinApi.getLocalIpAddress() } } val ipAddrs = tasks.awaitAll() ipAddrs.forEach { ipAddr -> ipAddr.shouldNotBeNull() ipAddr.origin.shouldNotBeEmpty() } // Micrometer로 성능 측정한 값을 조회한다. (Timer name=retrofit2.requests) val timer = meterRegistry.find(MicrometerRetrofitMetricsRecorder.METRICS_KEY).timer() timer.shouldNotBeNull() val snapshot = timer.takeSnapshot() log.debug { "meter=${timer.id} count=${snapshot.count()} mean=${snapshot.mean()}" } snapshot.count() shouldBeGreaterThan 0 } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
2,108
bluetape4k
MIT License
core/model/src/main/java/net/validcat/justwriter/core/model/data/DarkThemeConfig.kt
lamrak
662,966,559
false
null
package net.validcat.justwriter.core.model.data enum class DarkThemeConfig { FOLLOW_SYSTEM, LIGHT, DARK }
0
Kotlin
0
0
05c27af75c7af00b8dc1c5a7064ecd3385d21b6e
110
justwritergpt
MIT License
app/src/main/java/com/bitdev/encryptedgallery/models/User.kt
helderpgoncalves
475,500,492
false
{"Kotlin": 21205}
package com.bitdev.encryptedgallery.models data class User( val uid: String, val email: String, val first_name: String, val last_name: String, var gallery: List<String> )
0
Kotlin
0
0
eeed59566651a2ff3469d2f39bdba81fbd2a3437
191
EncryptedGallery
MIT License
Android/app/src/main/java/moe/tlaster/futania/viewmodel/LoginViewModel.kt
Tlaster
208,029,519
false
null
package moe.tlaster.futania.viewmodel import android.webkit.CookieManager import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import moe.tlaster.futania.api.Api import moe.tlaster.futania.common.Settings class LoginViewModel : ViewModelBase() { val loginSuccess: MutableLiveData<Boolean> = MutableLiveData() val onPageStarted = { url: String? -> url?.let { if (it.startsWith("https://fantia.jp")) { CookieManager.getInstance().getCookie("https://fantia.jp/") .split(';') .map { val res = it.split('=') res[0] to res[1] } .toMap() .let { cookie -> val key = "_session_id" if (cookie.containsKey(key)) { cookie[key]?.let { session_id -> Settings.set("SessionID", session_id) GlobalScope.launch { kotlin.runCatching { Api.me() }.onSuccess { loginSuccess.value = true } } } } } } } } }
0
Kotlin
0
2
b334121f57108b06558bed4db32c1734bb408b0d
1,494
Futania
MIT License
android/src/main/java/com/reactnativeimagegenerator/ImageGeneratorPackage.kt
evgenusov
446,951,196
false
{"Swift": 6488, "Java": 6325, "Kotlin": 5086, "TypeScript": 2923, "Objective-C": 2668, "JavaScript": 1472, "Ruby": 1224, "Shell": 149, "C": 103}
package com.reactnativeimagegenerator import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager class ImageGeneratorPackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return listOf(ImageGeneratorModule(reactContext)) } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList() } }
3
Swift
3
18
5b130902fb8af077ddc569a44d2973aec19bd3e7
576
react-native-image-generator
MIT License
contract/solidity-plugin/src/test/kotlin/com/github/jyc228/keth/solidity/SolidityPluginTest.kt
jyc228
833,953,853
false
{"Kotlin": 217816, "Solidity": 5515}
package com.github.jyc228.keth.solidity import io.kotest.matchers.sequences.shouldHaveAtLeastSize import io.kotest.matchers.sequences.shouldHaveSize import java.io.File import org.gradle.testkit.runner.GradleRunner import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir class SolidityPluginTest { @TempDir lateinit var testProjectDir: File @Test fun `test solc version`() { testProjectDir.child("build.gradle.kts") .writeText(buildFileContent("""solidity { solcVersion = "0.8.25" }""")) val result = runGradleTask("configSolc") println(result.output) } @Test fun `test generateKotlinContractWrapper`() { testProjectDir.child("build.gradle.kts").writeText(buildFileContent()) testProjectDir.child("src/main/solidity").apply { mkdirs() } testInputFiles().forEach { it.copyTo(testProjectDir.child("src/main/solidity/${it.name}")) } runGradleTask("generateKotlinContractWrapper") testProjectDir.child("build").walkTopDown() .map { it.relativeTo(testProjectDir) } .filter { it.extension == "kt" } .onEach { println(it) } shouldHaveAtLeastSize 10 testProjectDir.child("build").walkTopDown() .map { it.relativeTo(testProjectDir) } .filter { it.name.startsWith("Storage") && it.extension == "kt" } shouldHaveSize 0 } @Test fun `test generateKotlinContractWrapper with solc`() { testProjectDir.child("build.gradle.kts") .writeText(buildFileContent("""solidity { solcVersion = "0.8.25" }""")) testProjectDir.child("src/main/solidity").apply { mkdirs() } testInputFiles().forEach { it.copyTo(testProjectDir.child("src/main/solidity/${it.name}")) } runGradleTask("generateKotlinContractWrapper").let { println(it.output) } testProjectDir.child("build").walkTopDown() .map { it.relativeTo(testProjectDir) } .filter { it.name.startsWith("Storage") && it.extension == "kt" } .onEach { println(it) } shouldHaveSize 2 } private fun runGradleTask(vararg args: String) = GradleRunner.create() .withDebug(true) .withProjectDir(testProjectDir) .withPluginClasspath() .withArguments(*args) .build() private fun buildFileContent(content: String = "") = """ plugins { kotlin("jvm") version "2.0.0" id("com.github.jyc228.keth") version "1.0-SNAPSHOT" } $content """ private fun testInputFiles(): Array<File> { val solidity = requireNotNull(SolidityPluginTest::class.java.getResource("/solidity")).toURI() return requireNotNull(File(solidity).listFiles()) } private fun File.child(path: String) = File(this, path) }
0
Kotlin
0
2
4fd6f900b4e80b5f731090f33c1ddc10c6ede9ca
2,830
keth-client
Apache License 2.0
autofill/autofill-store/src/main/java/com/duckduckgo/securestorage/store/SecureStorageRepository.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2022 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.securestorage.store import com.duckduckgo.securestorage.store.db.WebsiteLoginCredentialsDao import com.duckduckgo.securestorage.store.db.WebsiteLoginCredentialsEntity import kotlinx.coroutines.flow.Flow /** * This class is mainly responsible only for accessing and storing data into the DB. */ interface SecureStorageRepository { interface Factory { fun get(): SecureStorageRepository? } suspend fun addWebsiteLoginCredential(websiteLoginCredentials: WebsiteLoginCredentialsEntity): WebsiteLoginCredentialsEntity? suspend fun websiteLoginCredentialsForDomain(domain: String): Flow<List<WebsiteLoginCredentialsEntity>> suspend fun getWebsiteLoginCredentialsForId(id: Long): WebsiteLoginCredentialsEntity? suspend fun websiteLoginCredentials(): Flow<List<WebsiteLoginCredentialsEntity>> suspend fun updateWebsiteLoginCredentials(websiteLoginCredentials: WebsiteLoginCredentialsEntity): WebsiteLoginCredentialsEntity? suspend fun deleteWebsiteLoginCredentials(id: Long) } class RealSecureStorageRepository constructor( private val websiteLoginCredentialsDao: WebsiteLoginCredentialsDao, ) : SecureStorageRepository { override suspend fun addWebsiteLoginCredential(websiteLoginCredentials: WebsiteLoginCredentialsEntity): WebsiteLoginCredentialsEntity? { val newCredentialId = websiteLoginCredentialsDao.insert(websiteLoginCredentials) return websiteLoginCredentialsDao.getWebsiteLoginCredentialsById(newCredentialId) } override suspend fun websiteLoginCredentialsForDomain(domain: String): Flow<List<WebsiteLoginCredentialsEntity>> = websiteLoginCredentialsDao.websiteLoginCredentialsByDomain(domain) override suspend fun websiteLoginCredentials(): Flow<List<WebsiteLoginCredentialsEntity>> = websiteLoginCredentialsDao.websiteLoginCredentials() override suspend fun getWebsiteLoginCredentialsForId(id: Long): WebsiteLoginCredentialsEntity? = websiteLoginCredentialsDao.getWebsiteLoginCredentialsById(id) override suspend fun updateWebsiteLoginCredentials(websiteLoginCredentials: WebsiteLoginCredentialsEntity): WebsiteLoginCredentialsEntity? { val credentialId = websiteLoginCredentials.id websiteLoginCredentialsDao.update(websiteLoginCredentials) return websiteLoginCredentialsDao.getWebsiteLoginCredentialsById(credentialId) } override suspend fun deleteWebsiteLoginCredentials(id: Long) { websiteLoginCredentialsDao.delete(id) } }
56
null
884
3,347
fa7d6b7a85a9457982deebfb740718a5f977862b
3,124
Android
Apache License 2.0
androidApp/src/androidMain/kotlin/com/myapplication/screens/ToolsViewAllScreen.kt
UmairSiddique1
731,106,413
false
{"Kotlin": 76912, "Swift": 592, "Shell": 228}
package com.myapplication.screens import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import com.myapplication.R class ToolsViewAllScreen:Screen { @Composable fun EditVewAllLayout(){ Column(modifier = Modifier.fillMaxSize().background(Color.White)) { CustomTopBar() GridWithCircularIconsAndText(iconResIds = listOf( R.drawable.ic_tools, R.drawable.ic_tools, R.drawable.ic_tools, R.drawable.ic_tools, R.drawable.ic_tools, R.drawable.ic_tools, R.drawable.ic_tools, R.drawable.ic_tools, R.drawable.ic_tools, R.drawable.ic_tools ), texts = listOf( "Edit pdf", "Sign", "Import doc", "Eraser", "Split pdf", "Merge pdf", "Compress pdf", "Add watermark", "Remove Watermark", "Reorder pdf file" ),Color.White) } } @Composable override fun Content() { EditVewAllLayout() } } @Composable fun CustomTopBar() { val navigator= LocalNavigator.currentOrThrow TopAppBar( title = { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { IconButton( onClick = {navigator.push(ToolScreen)} ) { Icon( painterResource(R.drawable.ic_backarrow), contentDescription = "Back" ) } Text( text = "Edit", fontWeight = FontWeight.Bold, color =Color.Black ) } }, backgroundColor = Color.White ) } @Composable fun CircularIconWithText(iconResId: Int, text: String) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(10.dp) ) { Box( modifier = Modifier .size(50.dp) .background(Color(0xFFF6F6F6), CircleShape), contentAlignment = Alignment.Center ) { Icon(painter = painterResource(iconResId),contentDescription = null) } Spacer(modifier = Modifier.height(4.dp)) Text(text = text, style = MaterialTheme.typography.caption, textAlign = TextAlign.Center) } } @Composable fun GridWithCircularIconsAndText(iconResIds: List<Int>, texts: List<String>, color: Color) { LazyVerticalGrid( columns = GridCells.Fixed(4), modifier = Modifier .padding(10.dp) .border(BorderStroke(1.dp, Color.White), RoundedCornerShape(5.dp)) .background(color) .fillMaxWidth() ) { items(iconResIds.size) { index -> CircularIconWithText( iconResId = iconResIds[index], text = texts[index] ) } } }
0
Kotlin
0
0
8b0b0aff0ad729b100704677adb488f23b645487
4,798
CMM-Second
Apache License 2.0
wear/src/test/java/com/vlad1m1r/watchface/utils/HandsCalculationsHoursShould.kt
VladimirWrites
153,897,525
false
null
package com.vlad1m1r.watchface.utils import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.util.* @RunWith(Parameterized::class) class HandsCalculationsHoursShould(private val timeInMillis: Long, private val rotation: Float) { companion object { @JvmStatic @Parameterized.Parameters fun data() = listOf( arrayOf(1540114563000L, 348), arrayOf(1540255423100L, 81.5f), arrayOf(1540115913000L, 359), arrayOf(1540256898000L, 94), arrayOf(1540052710000L, 192.5f), arrayOf(1540050000000L, 170), arrayOf(1540214113100L, 97.5f), arrayOf(1540052913020L, 194), arrayOf(1540050213003L, 171.5f), arrayOf(1540054824123L, 210) ) } private val calendar: Calendar = Calendar.getInstance().apply { timeZone = TimeZone.getTimeZone("CET") } @Test fun calculateHoursRotation() { calendar.timeInMillis = timeInMillis assertThat(calendar.hoursRotation()).isEqualTo(rotation) } }
1
null
15
64
519369831e4bf865b3f03cc8fbca25ff3aadbfe4
1,164
AnalogWatchFace
Apache License 2.0
dummy_workflows/src/main/kotlin/com/r3/corda/lib/reissuance/dummy_flows/shell/simpleDummyState/UnlockSimpleDummyState.kt
corda
292,234,867
false
{"Kotlin": 346122, "Dockerfile": 724}
package com.r3.corda.lib.reissuance.dummy_flows.shell.simpleDummyState import co.paralleluniverse.fibers.Suspendable import com.r3.corda.lib.reissuance.dummy_contracts.SimpleDummyStateContract import com.r3.corda.lib.reissuance.dummy_states.SimpleDummyState import com.r3.corda.lib.reissuance.flows.UnlockReissuedStates import com.r3.corda.lib.reissuance.states.ReissuanceLock import net.corda.core.contracts.StateRef import net.corda.core.crypto.SecureHash import net.corda.core.flows.FlowLogic import net.corda.core.flows.StartableByRPC import net.corda.core.node.services.queryBy import net.corda.core.node.services.vault.QueryCriteria @StartableByRPC class UnlockSimpleDummyState( private val reissuedStatesRefStrings: List<String>, private val reissuanceLockRefString: String, private val deletedStateTransactionHashes: List<SecureHash> ): FlowLogic<SecureHash>() { @Suspendable override fun call(): SecureHash { val reissuanceLockRef = parseStateReference(reissuanceLockRefString) val reissuanceLockStateAndRef = serviceHub.vaultService.queryBy<ReissuanceLock<SimpleDummyState>>( criteria= QueryCriteria.VaultQueryCriteria(stateRefs = listOf(reissuanceLockRef)) ).states[0] val reissuedStatesRefs = reissuedStatesRefStrings.map { parseStateReference(it) } val reissuedStatesStateAndRefs = serviceHub.vaultService.queryBy<SimpleDummyState>( criteria= QueryCriteria.VaultQueryCriteria(stateRefs = reissuedStatesRefs) ).states return subFlow(UnlockReissuedStates( reissuedStatesStateAndRefs, reissuanceLockStateAndRef, deletedStateTransactionHashes, SimpleDummyStateContract.Commands.Update() )) } fun parseStateReference(stateRefStr: String): StateRef { val (secureHashStr, indexStr) = stateRefStr.dropLast(1).split("(") return StateRef(SecureHash.parse(secureHashStr), Integer.parseInt(indexStr)) } }
2
Kotlin
3
2
7fa8a423189165e7aad9020d6001ee078d6b7139
1,997
reissue-cordapp
Apache License 2.0