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
api/src/main/kotlin/io/sparkled/api/DashboardController.kt
sparkled
53,776,686
false
null
package io.sparkled.api import io.micronaut.http.HttpResponse import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import io.micronaut.scheduling.TaskExecutors import io.micronaut.scheduling.annotation.ExecuteOn import io.micronaut.security.annotation.Secured import io.micronaut.security.rules.SecurityRule import io.sparkled.model.entity.v2.* import io.sparkled.persistence.DbService import io.sparkled.persistence.getAll import io.sparkled.viewmodel.* import org.springframework.transaction.annotation.Transactional @ExecuteOn(TaskExecutors.IO) @Secured(SecurityRule.IS_ANONYMOUS) @Controller("/api/dashboard") class DashboardController( private val db: DbService ) { @Get("/") @Transactional(readOnly = true) fun getDashboard(): HttpResponse<Any> { val playlists = db.getAll<PlaylistEntity>(orderBy = "name") val playlistNames = playlists.associate { it.id to it.name } val scheduledTasks = db.getAll<ScheduledTaskEntity>(orderBy = "id") val sequences = db.getAll<SequenceEntity>(orderBy = "name") val playlistSequences = db.getAll<PlaylistSequenceEntity>().groupBy { it.playlistId } val songs = db.getAll<SongEntity>(orderBy = "name") val stages = db.getAll<StageEntity>(orderBy = "name") val dashboard = DashboardViewModel( playlists = playlists.map { PlaylistSummaryViewModel.fromModel( it, playlistSequences = playlistSequences[it.id] ?: emptyList(), sequences = sequences, songs = songs, ) }, scheduledTasks = scheduledTasks.map { ScheduledTaskSummaryViewModel.fromModel(it, playlistNames) }, sequences = sequences.map { SequenceSummaryViewModel.fromModel( it, song = songs.first { song -> song.id == it.songId }, stage = stages.first { stage -> stage.id == it.stageId }, ) }, songs = songs.map { SongViewModel.fromModel(it) }, stages = stages.map { StageSummaryViewModel.fromModel(it) }, ) return HttpResponse.ok(dashboard) } }
28
Kotlin
21
72
562e917af188c2ebf98c8e729446cde101f96dc2
2,293
sparkled
MIT License
part2/chapter5/Calc2/app/src/main/java/org/techtown/calc2/MainActivity.kt
mike-jung
281,814,310
false
null
package org.techtown.calc2 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { val calc1 = Calc() val result1 = calc1.subtract(20, 10) textView.setText("빼기 : ${result1}") val calc2:Calculator = Calc2() val result2 = calc2.add(10, 10) textView.append(" 더하기 : ${result2}") } button2.setOnClickListener { val calc3 = Calc3("John") val result3 = calc3.add(10, 10) textView.setText("계산기 ${calc3.name} - 더하기 : ${result3}") val calc4 = Calc4() val result4 = calc4.add(10, 10) textView.append(" 계산기 ${calc4.name} - 더하기 : ${result4}") } button3.setOnClickListener { val calc1 = object: CalcAdapter() { override fun subtract(a:Int, b:Int):Int { return a - b } } val result1 = calc1.subtract(20, 10) textView.setText("결과 : ${result1}") } button4.setOnClickListener { val calc1 = object: Calculator { override fun add(a:Int, b:Int):Int { return a - b } } val result1 = calc1.add(20, 10) textView.setText("결과 : ${result1}") } } }
0
Kotlin
17
13
f7b6f1df6d5445bee3b02c63527c997da22157f1
1,637
kotlin-android
Apache License 2.0
jdrfandroidbleparser/src/main/java/org/ehealthinnovation/jdrfandroidbleparser/encodedvalue/bgmmeasurement/Flags.kt
markiantorno
138,645,708
false
{"Kotlin": 123751}
package org.ehealthinnovation.jdrfandroidbleparser.bgm.encodedvalue.bgmmeasurement import java.util.* /** * These flags define which data fields are present in the Characteristic value * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.glucose_measurement.xml */ enum class Flags constructor(val bit: Int) { TIME_OFFSET_PRESENT(1 shl 0), GLUCOSE_CONCENTRATION_TYPE_SAMPLE_LOCATION_PRESENT(1 shl 1), GLUCOSE_CONCENTRATION_UNITS(1 shl 2), SENSOR_STATUS_ANNUNCIATION_PRESENT(1 shl 3), CONTEXT_INFORMATION_FOLLOWS(1 shl 4); companion object { /** * Takes a passed in 8bit flag value and extracts the set mask values. Returns an * [EnumSet]<[Flags]> of set properties */ fun parsFlags(characteristicFlags: Int): EnumSet<Flags> { val setFlags = EnumSet.noneOf(Flags::class.java) Flags.values().forEach { val flag = it.bit if (flag and characteristicFlags == flag) setFlags.add(it) } return setFlags } } }
1
Kotlin
0
0
8e350cbbcdc3bb301e1fa1d3e570e8e8b2659855
1,114
JDRFAndroidBLEParser
MIT License
app/src/main/java/app/notes/data/NotesRepository.kt
hazyuun
567,870,046
false
{"Kotlin": 13282}
package app.notes.data import androidx.lifecycle.LiveData class NotesRepository(private val noteDao: NoteDao) { val allNotes: LiveData<List<Note>> = noteDao.getAll() suspend fun insert(note: Note) { noteDao.insert(note.apply { modifiedAt = System.currentTimeMillis() }) } suspend fun delete(note: Note) { noteDao.delete(note) } suspend fun upsert(note: Note) { noteDao.upsert(note.apply { modifiedAt = System.currentTimeMillis() }) } }
0
Kotlin
0
0
0928173362613c871f7e6c0c9de67e6853646ebb
532
Notes
The Unlicense
android-sdk/src/main/java/com/checkout/android_sdk/Architecture/UiState.kt
checkout
140,300,675
false
null
package com.checkout.android_sdk.Architecture interface UiState
12
null
20
24
c6d7b35c9b11e82a8f817dd083988a2fafc8ca86
66
frames-android
MIT License
app/src/main/kotlin/com/aquamorph/frcmanager/models/tba/Tab.kt
AquaMorph
43,819,985
false
null
package com.aquamorph.frcmanager.models import androidx.fragment.app.Fragment /** * Store information about tabs. * * @author <NAME> * @version 3/30/2018 */ class Tab(name: String, var fragment: Fragment) : Comparable<Tab> { var name = "" init { this.name = name } override operator fun compareTo(other: Tab): Int { return getTabOrder(this.name) - getTabOrder(other.name) } private fun getTabOrder(name: String): Int { return when (name) { "Team Schedule" -> 0 "Event Schedule" -> 1 "Rankings" -> 2 "Teams" -> 3 "Alliances" -> 4 "Awards" -> 5 else -> 10 } } }
12
Kotlin
1
0
a6a2c35c06a8e7a06b19f75dee0021d1fa5e92aa
715
FRC-Manager
Apache License 2.0
app/src/main/java/com/myth/tdd_note_app/presentation/notes_list/components/MainAppBar.kt
MichaelGift
731,576,947
false
{"Kotlin": 55171}
package com.myth.tdd_note_app.presentation.notes_list.components import androidx.compose.animation.AnimatedVisibility import androidx.compose.runtime.Composable import com.myth.tdd_note_app.presentation.notes_list.states.SearchWidgetState @Composable fun MainAppBar( searchWidgetState: SearchWidgetState, searchTextState: String, onTextChange: (String) -> Unit, onCloseClicked: () -> Unit, onSearchClicked: (String) -> Unit, onSearchTriggered: () -> Unit ) { when (searchWidgetState) { SearchWidgetState.CLOSED -> { CustomTopAppBar( onClickSearchIcon = onSearchTriggered ) } SearchWidgetState.OPENED -> { AnimatedVisibility( visible = searchWidgetState == SearchWidgetState.OPENED ) { CustomSearchBar( text = searchTextState, onTextChange = onTextChange, onCloseClicked = onCloseClicked, onSearchClicked = onSearchClicked ) } } } }
0
Kotlin
0
0
bb56de555c65ac858fbe0962e3afdbab480b070d
1,103
TDD-Note-App
MIT License
domain/src/main/java/com/tirgei/domain/enums/CharacterStatus.kt
tirgei
362,710,268
false
null
package com.tirgei.domain.enums import com.tirgei.domain.interfaces.HasKey /** * Enum class to indicate status of the [Character] */ enum class CharacterStatus : HasKey<CharacterStatus> { DEAD, ALIVE, UNKNOWN; override fun fromKey(key: String?): CharacterStatus { return when(key) { "Alive" -> ALIVE "Dead" -> DEAD else -> UNKNOWN } } override fun toKey(): String { return when (this) { ALIVE -> "Alive" DEAD -> "Dead" else -> "Unknown" } } }
0
Kotlin
0
1
bcd982386c09c470da51c960ab38b4bdcc6a357f
580
rick-and-morty
The Unlicense
webrtc-kmp/src/commonMain/kotlin/com/shepeliev/webrtckmp/RtcStatsReport.kt
shepeliev
329,550,581
false
null
package com.shepeliev.webrtckmp expect class RtcStatsReport { val timestampUs: Long val stats: Map<String, RtcStats> override fun toString(): String }
5
Kotlin
22
93
9bb316a4413a578cfdbf4cf7af5485decd2bde88
165
webrtc-kmp
Apache License 2.0
src/main/kotlin/org/geepawhill/base/MainView.kt
GeePawHill
282,904,393
false
null
package org.geepawhill.base import tornadofx.* class MainView : View("My View") { override val root = stackpane { label { text = "Test" } } }
0
Kotlin
0
1
45ab0d8cd1ed0fd399a93809d8e63bd3b5ed0c73
180
base
MIT License
tgbotapi.api/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/api/send/media/SendMediaGroup.kt
InsanusMokrassar
163,152,024
false
null
package dev.inmo.tgbotapi.extensions.api.send.media import dev.inmo.tgbotapi.bot.TelegramBot import dev.inmo.tgbotapi.requests.send.media.* import dev.inmo.tgbotapi.types.ChatIdentifier import dev.inmo.tgbotapi.types.media.* import dev.inmo.tgbotapi.types.MessageIdentifier import dev.inmo.tgbotapi.types.chat.Chat import dev.inmo.tgbotapi.types.message.content.MediaGroupContent import dev.inmo.tgbotapi.types.message.content.VisualMediaGroupContent import dev.inmo.tgbotapi.types.message.content.AudioContent import dev.inmo.tgbotapi.types.message.content.DocumentContent import dev.inmo.tgbotapi.utils.RiskFeature import kotlin.jvm.JvmName /** * @see SendMediaGroup */ @RiskFeature(rawSendingMediaGroupsWarning) suspend fun TelegramBot.sendMediaGroup( chatId: ChatIdentifier, media: List<MediaGroupMemberTelegramMedia>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = execute( SendMediaGroup<MediaGroupContent>( chatId, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) ) /** * @see SendMediaGroup */ @RiskFeature(rawSendingMediaGroupsWarning) suspend fun TelegramBot.sendMediaGroup( chat: Chat, media: List<MediaGroupMemberTelegramMedia>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendMediaGroup( chat.id, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendMediaGroup */ @RiskFeature(rawSendingMediaGroupsWarning) @JvmName("sendMedaGroupByContent") suspend fun TelegramBot.sendMediaGroup( chatId: ChatIdentifier, media: List<MediaGroupContent>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendMediaGroup( chatId, media.map { it.toMediaGroupMemberTelegramMedia() }, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendMediaGroup */ @RiskFeature(rawSendingMediaGroupsWarning) @JvmName("sendMedaGroupByContent") suspend fun TelegramBot.sendMediaGroup( chat: Chat, media: List<MediaGroupContent>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendMediaGroup( chat.id, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendPlaylist */ suspend fun TelegramBot.sendPlaylist( chatId: ChatIdentifier, media: List<AudioMediaGroupMemberTelegramMedia>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = execute( SendPlaylist( chatId, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) ) /** * @see SendPlaylist */ suspend fun TelegramBot.sendPlaylist( chat: Chat, media: List<AudioMediaGroupMemberTelegramMedia>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendPlaylist( chat.id, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendPlaylist */ @JvmName("sendPlaylistByContent") suspend fun TelegramBot.sendPlaylist( chatId: ChatIdentifier, media: List<AudioContent>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendPlaylist( chatId, media.map { it.toMediaGroupMemberTelegramMedia() }, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendPlaylist */ @JvmName("sendPlaylistByContent") suspend fun TelegramBot.sendPlaylist( chat: Chat, media: List<AudioContent>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendPlaylist( chat.id, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendDocumentsGroup */ suspend fun TelegramBot.sendDocumentsGroup( chatId: ChatIdentifier, media: List<DocumentMediaGroupMemberTelegramMedia>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = execute( SendDocumentsGroup( chatId, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) ) /** * @see SendDocumentsGroup */ suspend fun TelegramBot.sendDocumentsGroup( chat: Chat, media: List<DocumentMediaGroupMemberTelegramMedia>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendDocumentsGroup( chat.id, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendDocumentsGroup */ @JvmName("sendDocumentsByContent") suspend fun TelegramBot.sendDocumentsGroup( chatId: ChatIdentifier, media: List<DocumentContent>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendDocumentsGroup( chatId, media.map { it.toMediaGroupMemberTelegramMedia() }, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendDocumentsGroup */ @JvmName("sendDocumentsByContent") suspend fun TelegramBot.sendDocumentsGroup( chat: Chat, media: List<DocumentContent>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendDocumentsGroup( chat.id, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendVisualMediaGroup */ suspend fun TelegramBot.sendVisualMediaGroup( chatId: ChatIdentifier, media: List<VisualMediaGroupMemberTelegramMedia>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = execute( SendVisualMediaGroup( chatId, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) ) /** * @see SendVisualMediaGroup */ suspend fun TelegramBot.sendVisualMediaGroup( chat: Chat, media: List<VisualMediaGroupMemberTelegramMedia>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendVisualMediaGroup( chat.id, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendVisualMediaGroup */ @JvmName("sendVisualMediaGroupByContent") suspend fun TelegramBot.sendVisualMediaGroup( chatId: ChatIdentifier, media: List<VisualMediaGroupContent>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendVisualMediaGroup( chatId, media.map { it.toMediaGroupMemberTelegramMedia() }, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply ) /** * @see SendVisualMediaGroup */ @JvmName("sendVisualMediaGroupByContent") suspend fun TelegramBot.sendVisualMediaGroup( chat: Chat, media: List<VisualMediaGroupContent>, disableNotification: Boolean = false, protectContent: Boolean = false, replyToMessageId: MessageIdentifier? = null, allowSendingWithoutReply: Boolean? = null ) = sendVisualMediaGroup( chat.id, media, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply )
12
null
14
159
ca01ce7843f510e958aaa4e8fe9920a531b1daa5
8,435
TelegramBotAPI
Apache License 2.0
PushNotification/app/src/main/java/com/juhwan/anyang_yi/data/di/RemoteDataModule.kt
juhwankim-dev
324,930,598
false
null
package com.juhwan.anyang_yi.data.di import com.juhwan.anyang_yi.data.api.* import com.juhwan.anyang_yi.data.repository.ari.AriRemoteDataSource import com.juhwan.anyang_yi.data.repository.ari.AriRemoteDataSourceImpl import com.juhwan.anyang_yi.data.repository.kakao.KakaoRemoteDataSource import com.juhwan.anyang_yi.data.repository.kakao.KakaoRemoteDataSourceImpl import com.juhwan.anyang_yi.data.repository.nonsubject.NonsubjectRemoteDataSource import com.juhwan.anyang_yi.data.repository.nonsubject.NonsubjectRemoteDataSourceImpl import com.juhwan.anyang_yi.data.repository.schedule.ScheduleRemoteDataSource import com.juhwan.anyang_yi.data.repository.schedule.ScheduleRemoteDataSourceImpl import com.juhwan.anyang_yi.data.repository.univ.UnivRemoteDataSource import com.juhwan.anyang_yi.data.repository.univ.UnivRemoteDataSourceImpl import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class RemoteDataModule { @Provides @Singleton fun provideAriRemoteDataSource(ariApi: AriApi): AriRemoteDataSource { return AriRemoteDataSourceImpl(ariApi) } @Provides @Singleton fun provideKakaoRemoteDataSource(kakaoApi: KakaoApi): KakaoRemoteDataSource { return KakaoRemoteDataSourceImpl(kakaoApi) } @Provides @Singleton fun provideNonsubjectRemoteDataSource(nonsubjectApi: NonsubjectApi): NonsubjectRemoteDataSource { return NonsubjectRemoteDataSourceImpl(nonsubjectApi) } @Provides @Singleton fun provideScheduleRemoteDataSource(scheduleApi: ScheduleApi): ScheduleRemoteDataSource { return ScheduleRemoteDataSourceImpl(scheduleApi) } @Provides @Singleton fun provideUnivRemoteDataSource(univApi: UnivApi): UnivRemoteDataSource { return UnivRemoteDataSourceImpl(univApi) } }
1
Kotlin
1
5
ae17bf81ec4bdf7a8704710b742b44cfc84a6b04
1,936
pushNotificationApp
Apache License 2.0
compiler/testData/codegen/bytecodeText/annotationRetentionPolicySource.kt
JakeWharton
99,388,807
false
null
@Ann class MyClass @Retention(AnnotationRetention.SOURCE) annotation class Ann // 0 @LAnn;()
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
94
kotlin
Apache License 2.0
compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/KCallableNameProperty.kt
cpovirk
119,830,321
true
{"Java": 27299655, "Kotlin": 26644510, "JavaScript": 155518, "HTML": 57096, "Lex": 18174, "Groovy": 14207, "ANTLR": 9797, "IDL": 8587, "Shell": 5436, "CSS": 4679, "Batchfile": 4437}
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.codegen.intrinsics import org.jetbrains.kotlin.codegen.ExpressionCodegen import org.jetbrains.kotlin.codegen.JvmCodegenUtil import org.jetbrains.kotlin.codegen.StackValue import org.jetbrains.kotlin.psi.KtCallableReferenceExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.jvm.AsmTypes.JAVA_STRING_TYPE import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.org.objectweb.asm.Type import org.jetbrains.org.objectweb.asm.Type.VOID_TYPE class KCallableNameProperty : IntrinsicPropertyGetter() { override fun generate(resolvedCall: ResolvedCall<*>?, codegen: ExpressionCodegen, returnType: Type, receiver: StackValue): StackValue? { val expressionReceiver = resolvedCall!!.dispatchReceiver as? ExpressionReceiver ?: return null val expression = expressionReceiver.expression as? KtCallableReferenceExpression ?: return null val referenceResolvedCall = expression.callableReference.getResolvedCall(codegen.bindingContext) ?: return null val callableReferenceReceiver = JvmCodegenUtil.getBoundCallableReferenceReceiver(referenceResolvedCall) return StackValue.operation(returnType) { iv -> // Generate the left-hand side of a bound callable reference expression if (callableReferenceReceiver != null && callableReferenceReceiver !is ImplicitClassReceiver) { val stackValue = codegen.generateReceiverValue(callableReferenceReceiver, false) StackValue.coercion(stackValue, codegen.asmType(callableReferenceReceiver.type)).put(VOID_TYPE, iv) } iv.aconst(referenceResolvedCall.resultingDescriptor.name.asString()) StackValue.coerce(JAVA_STRING_TYPE, returnType, iv) } } }
0
Java
0
1
b6ca9118ffe142e729dd17deeecfb35badba1537
2,584
kotlin
Apache License 2.0
src/main/kotlin/com/github/epadronu/balin/config/ConfigurationSetupBuilder.kt
EPadronU
59,879,392
false
null
/****************************************************************************** * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* ***************************************************************************/ package com.github.epadronu.balin.config /* ***************************************************************************/ /* ***************************************************************************/ import org.openqa.selenium.WebDriver /* ***************************************************************************/ /* ***************************************************************************/ /** * Defines the builder used in the configuration DSL that can be interacted * with via the [com.github.epadronu.balin.core.Browser.configure] method. * * @see ConfigurationSetup * @sample com.github.epadronu.balin.config.ConfigurationTests.call_the_configure_method_and_make_changes * * @property autoQuit control whether the driver quits at the end of [com.github.epadronu.balin.core.Browser.drive]. * @property driverFactory the factory that will create the driver to be used when invoking [com.github.epadronu.balin.core.Browser.drive]. * @property waitForSleepTimeInMilliseconds control the amount of time between attempts when using [com.github.epadronu.balin.core.WaitingSupport.waitFor]. * @property waitForTimeOutTimeInSeconds control the total amount of time to wait for a condition evaluated by [com.github.epadronu.balin.core.WaitingSupport.waitFor] to hold. * @constructor Creates a new configuration setup builder. */ open class ConfigurationSetupBuilder { var autoQuit: Boolean = ConfigurationSetup.Default.autoQuit var driverFactory: () -> WebDriver = ConfigurationSetup.Default.driverFactory var waitForSleepTimeInMilliseconds: Long = ConfigurationSetup.Default.waitForSleepTimeInMilliseconds var waitForTimeOutTimeInSeconds: Long = ConfigurationSetup.Default.waitForTimeOutTimeInSeconds /** * Creates a new configuration setup. * * @return a new configuration setup using the options provided to the builder. */ open fun build(): ConfigurationSetup = Configuration( autoQuit, driverFactory, waitForSleepTimeInMilliseconds, waitForTimeOutTimeInSeconds) } /* ***************************************************************************/
0
Kotlin
14
72
4f9b7f224029d8166db8daaf13904ed7265c59bd
2,947
balin
Apache License 2.0
app/src/main/java/com/elfaidy/notes/models/ToDo.kt
Dev-Abdelazim
796,270,378
false
{"Kotlin": 79498}
package com.elfaidy.notes.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class ToDo( val title: String = "", var isChecked: Boolean = false ): Parcelable
0
Kotlin
0
0
4b9ad1251113241477bc6adcf991c41eac13c342
205
Note
MIT License
examples/coroutines/src/test/kotlin/io/bluetape4k/examples/coroutines/flow/FlowBuilderExamples.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.examples.coroutines.flow import app.cash.turbine.test import io.bluetape4k.coroutines.flow.extensions.log import io.bluetape4k.coroutines.tests.assertResult import io.bluetape4k.logging.KLogging import io.bluetape4k.logging.debug import kotlinx.atomicfu.atomic import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.last import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test import org.junit.jupiter.api.fail class FlowBuilderExamples { companion object: KLogging() @Test fun `flowOf - with specific elements`() = runTest { val flow = flowOf(1, 2, 3, 4, 5).log("flow") // like Flux.just(...) var collected = 0 flow.collect { collected = it log.debug { "element=$it" } } collected shouldBeEqualTo flow.last() } @Test fun `empty flow`() = runTest { emptyFlow<Int>() .log("empty") .collect { fail("아무것도 실행되면 안됩니다.") } } @Test fun `convert list to flow - asFlow`() = runTest { var count = 0 mutableListOf(1, 2, 3, 4, 5).asFlow().log("array") .collect { count++ log.debug { "element=$it" } } count shouldBeEqualTo 5 } /** * suspend 함수를 flow 로 만들 수 있다 */ @Test fun `convert function to flow`() = runTest { val function: suspend () -> String = suspend { delay(1000) "UserName" } function.asFlow() .log("function") .assertResult("UserName") } private suspend fun getUserName(): String { delay(1000) return "UserName" } @Test fun `convert regular function to flow`() = runTest { ::getUserName.asFlow().log("function") .assertResult("UserName") } @Test fun `flow builder`() = runTest { val nums = flow { repeat(3) { num -> delay(10) emit(num) } } val counter1 = atomic(0) val counter2 = atomic(0) // flow 를 여러 subscriber 가 중복해서 받아갈 수 있다 coroutineScope { launch { nums.log("job1") .collect { counter1.incrementAndGet() } } launch { // delay 를 줘도 flow 는 cold stream 이므로, buffer 에 쌓여있는 값들은 모두 처리됩니다. delay(15) nums.log("job2") .collect { counter2.incrementAndGet() } } // https://github.com/cashapp/turbine/ // turbine 을 이용하여 assertions 를 수행할 수 있습니다. // flow 는 cold stream 이므로 반복적으로 collect 할 수 있습니다. launch { nums.log("job3") .test { awaitItem() shouldBeEqualTo 0 awaitItem() shouldBeEqualTo 1 awaitItem() shouldBeEqualTo 2 awaitComplete() } } launch { nums.log("job4") .test { awaitItem() shouldBeEqualTo 0 awaitItem() shouldBeEqualTo 1 awaitItem() shouldBeEqualTo 2 awaitComplete() } } } counter1.value shouldBeEqualTo 3 counter2.value shouldBeEqualTo 3 } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
3,847
bluetape4k
MIT License
app/src/main/java/com/project/farmingapp/view/auth/LoginActivity.kt
hetsuthar028
325,234,399
false
null
package com.project.farmingapp.view.auth import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.firebase.auth.FirebaseAuth import com.project.farmingapp.R import com.project.farmingapp.databinding.ActivityLoginBinding import com.project.farmingapp.utilities.hide import com.project.farmingapp.utilities.show import com.project.farmingapp.utilities.toast import com.project.farmingapp.view.dashboard.DashboardActivity import com.project.farmingapp.viewmodel.AuthListener import com.project.farmingapp.viewmodel.AuthViewModel import kotlinx.android.synthetic.main.activity_login.* class LoginActivity : AppCompatActivity(), AuthListener { lateinit var googleSignInClient: GoogleSignInClient val firebaseAuth = FirebaseAuth.getInstance() lateinit var viewModel: AuthViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: ActivityLoginBinding = DataBindingUtil.setContentView(this, R.layout.activity_login) viewModel = ViewModelProviders.of(this).get(AuthViewModel::class.java) binding.authViewModel = viewModel viewModel.authListener = this if (firebaseAuth.currentUser != null) { Intent(this, DashboardActivity::class.java).also { startActivity(it) } } createaccountText.setOnClickListener { Intent(this, SignupActivity::class.java).also { startActivity(it) } } signGoogleBtnLogin.setOnClickListener { signIn() } forgotPasswdTextLogin.setOnClickListener { val userEmail = emailEditLogin.text.toString() if (userEmail.isNullOrEmpty()) { Toast.makeText(this, "Please enter your Email", Toast.LENGTH_SHORT).show() } else { // Toast.makeText(this, "Please enter your Email", Toast.LENGTH_SHORT).show() firebaseAuth.sendPasswordResetEmail(userEmail) .addOnCompleteListener { if (it.isSuccessful) { Toast.makeText(this, "Email Sent", Toast.LENGTH_LONG).show() } } .addOnFailureListener { Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show() } } } } //googlesignIn override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) viewModel.returnActivityResult(requestCode, resultCode, data) } fun signIn() { val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build() googleSignInClient = GoogleSignIn.getClient(this, gso) val signInIntent = googleSignInClient.signInIntent startActivityForResult(signInIntent, RC_SIGN_IN) } override fun onBackPressed() { super.onBackPressed() val a = Intent(Intent.ACTION_MAIN) a.addCategory(Intent.CATEGORY_HOME) a.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(a) } companion object { private const val TAG = "GoogleActivity" private const val RC_SIGN_IN = 9001 } override fun onStarted() { progressLogin.show() } override fun onSuccess(authRepo: LiveData<String>) { authRepo.observe(this, Observer { progressLogin.hide() if (it.toString() == "Success") { toast("Logged In") Toast.makeText(this, it.toString(), Toast.LENGTH_LONG).show() Intent(this, DashboardActivity::class.java).also { startActivity(it) } } }) } override fun onFailure(message: String) { progressLogin.hide() toast("Failure") } }
9
Kotlin
25
58
53cf61fe4158db356d1c7741065820deea7104ce
4,484
Farming-App
MIT License
server/Anket0roo/src/main/kotlin/com/lozanov/anket0roo/controller/QuestionController.kt
GGLozanov
349,700,444
false
{"TypeScript": 103507, "Kotlin": 79912, "JavaScript": 2515, "HTML": 444}
package com.lozanov.anket0roo.controller import com.fasterxml.jackson.databind.ObjectMapper import com.lozanov.anket0roo.advice.Anket0rooResponseEntityExceptionHandler import com.lozanov.anket0roo.model.Question import com.lozanov.anket0roo.request.QuestionCreateRequest import com.lozanov.anket0roo.service.MediaService import com.lozanov.anket0roo.service.QuestionMediaService import com.lozanov.anket0roo.service.QuestionService import com.lozanov.anket0roo.service.UserService import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.ui.Model import org.springframework.web.bind.annotation.* import org.springframework.web.multipart.MultipartFile import org.springframework.web.servlet.support.ServletUriComponentsBuilder import javax.servlet.ServletContext import javax.validation.Valid @RestController @CrossOrigin class QuestionController( private val questionService: QuestionService, private val userService: UserService, private val questionMediaService: QuestionMediaService, ) { private val linkRegex: Regex by lazy { Regex(Regex.escape(ServletUriComponentsBuilder.fromCurrentContextPath() .replacePath(null) .build() .toUriString() + MediaController.QUESTIONNAIRES_MEDIA_PATH + "/") + "[^.]+(\\.png|\\.jpg)") } @GetMapping(value = ["/users/{username}/questions"]) @ResponseBody fun getUserQuestions(@PathVariable username: String): ResponseEntity<*> = ResponseEntity.ok(questionService.findUserQuestions(username)) // TODO: Validation for ModelAttribute @PostMapping(value = ["/users/{username}/questions"], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) @ResponseBody fun createQuestion(@PathVariable username: String, @RequestParam requestParams: Map<String, String>, @RequestPart("image") image: MultipartFile?): ResponseEntity<*> { val sentFile = image != null val question = ObjectMapper().readValue(requestParams["question"], Question::class.java) println(linkRegex.pattern) println(image?.originalFilename) if(sentFile && !linkRegex.containsMatchIn(question.question)) { println("File found but incorrectly assoc w/ question") throw Anket0rooResponseEntityExceptionHandler.RequestFormatException( "Cannot send request with a question containing an image without " + "the image name being present in the form of a regex!") } if(question.ownerId != userService.findUserIdByUsername(username)) { println("Question different owner!") throw Anket0rooResponseEntityExceptionHandler.InvalidFormatException( "Question cannot have a different owner than authenticated user!") } val createdQuestion = questionService.createQuestion(question) if(sentFile) { questionMediaService.saveQuestionImage(image!!) } return ResponseEntity.ok(createdQuestion) } }
0
TypeScript
0
0
e7bcfbc739ff71ecae021c7bbc810ed673ff8212
3,232
Anket0roo
MIT License
features/demos/src/main/kotlin/feature/playground/demos/theme/Shape.kt
shawnthye
420,680,965
false
{"Kotlin": 416438}
package feature.playground.demos.theme import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.ripple.LocalRippleTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.dp @Composable internal fun Shape() { ThemeLayout { ShapeLines( label = "MaterialTheme.shapes.small", text = "S", shape = MaterialTheme.shapes.small, ) ShapeLines( label = "MaterialTheme.shapes.medium", text = "M", shape = MaterialTheme.shapes.medium, ) ShapeLines( label = "MaterialTheme.shapes.large", text = "L", shape = MaterialTheme.shapes.large, ) } } @Composable private fun ColumnScope.ShapeLines(label: String, text: String, shape: Shape) { ThemeLines(label = label) { Surface( shape = shape, color = LocalRippleTheme.current.defaultColor().copy( alpha = LocalRippleTheme.current.rippleAlpha().pressedAlpha, ), border = BorderStroke(width = 1.dp, color = MaterialTheme.colors.onSurface), ) { Box( contentAlignment = Alignment.Center, modifier = Modifier .width(50.dp) .aspectRatio(1.25f), ) { Text(text = text, modifier = Modifier.padding(bottom = 2.dp)) } } } }
0
Kotlin
0
0
15df4f3acc202e88f2de0e62549e6e5386440c9e
1,971
playground
MIT License
src/main/kotlin/co/mercenary/creators/kotlin/util/time/TimeDurationUnit.kt
mercenary-creators
193,142,947
false
null
/* * Copyright (c) 2022, Mercenary Creators Company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.mercenary.creators.kotlin.util.time import co.mercenary.creators.kotlin.util.* import java.time.Duration import java.time.temporal.ChronoUnit enum class TimeDurationUnit(private val system: ChronoUnit, private val mult: Long, private val flag: Boolean = false) { @FrameworkDsl YEARS(ChronoUnit.YEARS, 31556952L), @FrameworkDsl WEEKS(ChronoUnit.WEEKS, 7 * 86400L), @FrameworkDsl DAYS(ChronoUnit.DAYS, 86400L), @FrameworkDsl HOURS(ChronoUnit.HOURS, 3600), @FrameworkDsl MINUTES(ChronoUnit.MINUTES, 60), @FrameworkDsl SECONDS(ChronoUnit.SECONDS, 1), @FrameworkDsl MILLISECONDS(ChronoUnit.MILLIS, 1000000, true), @FrameworkDsl NANOSECONDS(ChronoUnit.NANOS, 1, true); @FrameworkDsl private val lows = name.toLowerCaseEnglish() @FrameworkDsl private val tail = name.toLowerCaseEnglish().tail() @FrameworkDsl fun next(): TimeDurationUnit? = when (this) { MILLISECONDS -> NANOSECONDS SECONDS -> MILLISECONDS MINUTES -> SECONDS HOURS -> MINUTES YEARS -> WEEKS WEEKS -> DAYS DAYS -> HOURS else -> null } @FrameworkDsl fun toSystemTimeUnit(): ChronoUnit = system @FrameworkDsl fun toSystemDuration(): Duration = system.duration @FrameworkDsl @IgnoreForSerialize fun getZeroDuration(): Duration = Duration.ZERO @FrameworkDsl @IgnoreForSerialize fun isNanoSeconds(): Boolean = flag @FrameworkDsl @IgnoreForSerialize fun getMultiplier(): Long = mult @FrameworkDsl fun toSystemDuration(time: Long): Duration { if (time.isZero()) { return getZeroDuration() } if (isNotEstimated()) { return Duration.of(time, toSystemTimeUnit()) } return when (isNanoSeconds()) { true -> Duration.ofNanos(time multipliedBy getMultiplier()) else -> Duration.ofSeconds(time multipliedBy getMultiplier()) } } @FrameworkDsl @IgnoreForSerialize fun isEstimated(): Boolean = toSystemTimeUnit().isDurationEstimated @FrameworkDsl @IgnoreForSerialize fun isNotEstimated(): Boolean = isEstimated().isNotTrue() @FrameworkDsl infix fun isSameAs(unit: TimeDurationUnit): Boolean { return this == unit } @FrameworkDsl infix fun isNotSameAs(unit: TimeDurationUnit): Boolean = isSameAs(unit).isNotTrue() @FrameworkDsl fun toOrdinal(): Int { return ordinal.copyOf() } @FrameworkDsl fun toOrdinalLong(): Long { return toOrdinal().longOf() } @FrameworkDsl @JvmOverloads fun toLowerCase(full: Boolean = true) = if (full.isTrue()) lows else tail }
0
Kotlin
0
2
5fdcab11d7d959efe77d45cc896e3f997310f860
3,389
mercenary-creators-kotlin-util
Apache License 2.0
app/src/main/java/com/erdi/linkhub/data/LinkInfo.kt
ZeynelErdiKarabulut
577,432,109
false
{"Kotlin": 122128}
package com.erdi.linkhub.data data class LinkInfo( val linkTitle: String, val linkSubtitle: String )
0
Kotlin
0
0
2d8fbb222e572a82975581d66d9e5605f4155120
109
LinkHub
MIT License
app/src/main/java/xjunz/tool/mycard/ui/SpreadingRippleDrawable.kt
xjunz
482,685,350
false
{"Kotlin": 352659, "HTML": 8679}
package xjunz.tool.mycard.ui import android.animation.ValueAnimator import android.graphics.* import android.graphics.drawable.Drawable import android.view.animation.LinearInterpolator /** * A drawable with a effect of spreading ripples, which is basically used as a background for an * interactive component, like buttons, indicating that this target requires the user's attention. */ class SpreadingRippleDrawable : Drawable() { var rippleSpreadDuration = 3_600L /** * The total count of ripples to draw. */ var rippleCount = 3 var rippleColor = Color.RED set(value) { paint.color = value field = value } /** * The inset applied to the drawing bounds, positive value to shrink and negative value to expand, * may not expand exceeding its parent bounds. */ var inset = 0 /** * The radius of the preserved circle in center of ripple that will keep drawing a solid * [ripple color][rippleColor], from which the ripple will start spreading. */ var rippleCenterRadius = 0 private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = rippleColor style = Paint.Style.FILL } private var maxRadius = 0F private val rippleFractions = FloatArray(rippleCount) private val animator = ValueAnimator.ofFloat(0F, 1F).apply { var prev = 0F addUpdateListener { val f = it.animatedFraction val delta = if (f < prev) 1 - prev else f - prev for (i in rippleFractions.indices) { rippleFractions[i] = (rippleFractions[i] + delta) % 1 } prev = f if (fadeMultiplier > 0) { fadeMultiplier = (fadeMultiplier - delta).coerceAtLeast(0F) // when it is totally faded out, cancel the animator if (fadeMultiplier == 0F) cancel() } invalidateSelf() } interpolator = LinearInterpolator() duration = rippleSpreadDuration repeatMode = ValueAnimator.RESTART repeatCount = ValueAnimator.INFINITE } private val drawingRect = RectF() override fun draw(canvas: Canvas) { val drawableRadius = maxRadius - rippleCenterRadius var hasDrawn = false for (i in 0..rippleCount) { val f = if (i == rippleCount) 0F else rippleFractions[i] if (f >= 0) { if (f == 0F && i != rippleCount) continue if (i == rippleCount && !hasDrawn) return drawingRect.left = (1 - f) * drawableRadius drawingRect.right = maxRadius + rippleCenterRadius + f * drawableRadius drawingRect.top = drawingRect.left drawingRect.bottom = drawingRect.right if (f == 0F) paint.alpha = 0xFF else paint.alpha = ((1 - f) * initialAlpha).toInt() if (fadeMultiplier >= 0) paint.alpha = (paint.alpha * fadeMultiplier).toInt() drawingRect.offset(inset.toFloat(), inset.toFloat()) canvas.drawOval(drawingRect, paint) hasDrawn = true } } } override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) maxRadius = bounds.width().coerceAtMost(bounds.height()) / 2F - inset } override fun isStateful() = false private var initialAlpha = 0xFF override fun setAlpha(alpha: Int) { initialAlpha = alpha } override fun setColorFilter(colorFilter: ColorFilter?) { paint.colorFilter = colorFilter } @Deprecated( "Deprecated in Java", ReplaceWith("PixelFormat.TRANSLUCENT", "android.graphics.PixelFormat") ) override fun getOpacity() = PixelFormat.TRANSLUCENT fun start() { if (!animator.isStarted) { for (i in rippleFractions.indices) { rippleFractions[i] = -i.toFloat() / rippleCount } fadeMultiplier = -1F animator.start() } } fun pause() { animator.pause() } fun resume() { animator.resume() } fun clear() { if (animator.isStarted) { animator.cancel() for (i in rippleFractions.indices) { rippleFractions[i] = 0F } invalidateSelf() } } private var fadeMultiplier = -1F fun fadeOut() { fadeMultiplier = 1F } }
0
Kotlin
0
3
c7f329739339790393ea9a73c83f5b2c0d8285ff
4,515
MyCard-YGO-Assistant
Apache License 2.0
src/main/kotlin/com/odenizturker/locky/user/model/UserRegistrationModel.kt
odenizturker
845,420,580
false
{"Kotlin": 9176}
package com.odenizturker.locky.user.model data class UserRegistrationModel( val username: String, val password: String, )
0
Kotlin
0
0
c50516d9db232abcf48e09585e5371f92207e9b8
131
locky-service-user
MIT License
test-framework/src/main/kotlin/com/epam/drill/e2e/plugin/Logging.kt
Drill4J
229,633,944
false
null
/** * Copyright 2020 EPAM Systems * * 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.epam.drill.e2e.plugin import com.epam.drill.logger.api.* object SimpleLogging : LoggerFactory { override fun logger(name: String): Logger = name.namedLogger( logLevel = { LogLevel.TRACE }, appender = ::appendLog ) } @Suppress("UNUSED_PARAMETER") internal fun appendLog(name: String, level: LogLevel, t: Throwable?, marker: Marker?, msg: () -> Any?) { println("[$name][${level.name}] ${msg()}") t?.printStackTrace() }
4
null
2
13
f2043e2be04ca7cbfc0d17e3409ee03f11a9917c
1,057
admin
Apache License 2.0
test-framework/src/main/kotlin/com/epam/drill/e2e/plugin/Logging.kt
Drill4J
229,633,944
false
null
/** * Copyright 2020 EPAM Systems * * 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.epam.drill.e2e.plugin import com.epam.drill.logger.api.* object SimpleLogging : LoggerFactory { override fun logger(name: String): Logger = name.namedLogger( logLevel = { LogLevel.TRACE }, appender = ::appendLog ) } @Suppress("UNUSED_PARAMETER") internal fun appendLog(name: String, level: LogLevel, t: Throwable?, marker: Marker?, msg: () -> Any?) { println("[$name][${level.name}] ${msg()}") t?.printStackTrace() }
4
null
2
13
f2043e2be04ca7cbfc0d17e3409ee03f11a9917c
1,057
admin
Apache License 2.0
sample-super-rx-ai-kotlin/src/main/java/com/mateuszkoslacz/moviper/rxsample/viper/view/activity/ListingActivity.kt
mkoslacz
66,210,591
false
null
package com.mateuszkoslacz.moviper.rxsample.viper.view.activity import android.app.Activity import android.content.Intent import android.support.v4.app.ActivityOptionsCompat import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.view.View import android.widget.ImageView import com.mateuszkoslacz.moviper.base.presenter.ViperPresentersList import com.mateuszkoslacz.moviper.base.view.activity.autoinject.passive.ViperAiPassiveActivity import com.mateuszkoslacz.moviper.iface.interactor.CommonViperInteractor import com.mateuszkoslacz.moviper.iface.presenter.ViperPresenter import com.mateuszkoslacz.moviper.iface.routing.CommonViperRouting import com.mateuszkoslacz.moviper.rxsample.R import com.mateuszkoslacz.moviper.rxsample.viper.contract.ListingContract import com.mateuszkoslacz.moviper.rxsample.viper.entity.User import com.mateuszkoslacz.moviper.rxsample.viper.presenter.ListingPresenter import com.mateuszkoslacz.moviper.rxsample.viper.view.adapter.UserAdapter import kotlinx.android.synthetic.main.activity_listing.* import io.reactivex.Observable import io.reactivex.subjects.PublishSubject open class ListingActivity : ViperAiPassiveActivity<ListingContract.View>(), ListingContract.View, UserAdapter.UserClickListener { override val userClicks: Observable<User> get() = mUserClicks internal var mUserClicks = PublishSubject.create<User>() private var mAdapter: UserAdapter? = null override fun setUserList(userList: List<User>) = mAdapter?.setUserList(userList)!! private fun prepareRecyclerView() { mAdapter = UserAdapter(this) recycler_view?.layoutManager = LinearLayoutManager(this) recycler_view?.itemAnimator = DefaultItemAnimator() recycler_view?.adapter = mAdapter } override fun onUserClick(user: User) = mUserClicks.onNext(user) override fun onDestroy() { super.onDestroy() mAdapter = null } override fun showError(throwable: Throwable) { errorView?.visibility = View.VISIBLE loadingView?.visibility = View.INVISIBLE recycler_view?.visibility = View.INVISIBLE errorView?.text = throwable.message } override fun showLoading() { errorView?.visibility = View.INVISIBLE loadingView?.visibility = View.VISIBLE recycler_view.visibility = View.INVISIBLE } override fun showContent() { errorView?.visibility = View.INVISIBLE loadingView?.visibility = View.INVISIBLE recycler_view.visibility = View.VISIBLE } override fun createPresenter(): ViperPresenter<ListingContract.View> = ListingPresenter() override fun injectViews() = prepareRecyclerView() override fun getLayoutId(): Int = R.layout.activity_listing companion object { val PHOTO_URL_EXTRA_STRING = "PHOTO_URL_EXTRA_STRING" fun start(activity: Activity, avatarUrl: String, avatarImageView: ImageView) { val starter = Intent(activity, FullscreenPhotoActivity::class.java) starter.putExtra(PHOTO_URL_EXTRA_STRING, avatarUrl) val optionsCompat = ActivityOptionsCompat .makeSceneTransitionAnimation(activity, avatarImageView, activity.getString(R.string.avatar_transition)) activity.startActivity(starter, optionsCompat.toBundle()) } } }
1
null
10
80
7994cd8824ecc1b376919e047a67afbb6149d58c
3,481
Moviper
Apache License 2.0
shared/src/commonMain/kotlin/features/favorite/domain/GetFavoriteBurgersUseCase.kt
mamadou94Diop
683,034,694
false
{"Kotlin": 48431, "Ruby": 1790, "Swift": 653, "Shell": 228}
package features.favorite.domain import features.common.domain.BaseUseCase import features.favorite.data.FavoriteRepository import features.menu.domain.model.Burger import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import toBurger class GetFavoriteBurgersUseCase(private val favoriteRepository: FavoriteRepository) : BaseUseCase<List<Burger>> { override suspend fun execute(): Flow<Result<List<Burger>>> { return favoriteRepository.getFavoriteBurgers() .map { favorites -> Result.success(favorites.map { it.toBurger() }) } } }
0
Kotlin
0
0
2220f6cdb584d6200f508fa6e102fbadb83e2b0e
609
restaurant-app-compose-multiplatform
Apache License 2.0
app/src/main/java/com/example/todo/MainActivity.kt
yogesh-7
641,281,385
false
{"Kotlin": 75010}
package com.example.todo import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.material.ExperimentalMaterialApi import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.example.todo.navigation.SetupNavigation import com.example.todo.ui.theme.ToDoTheme import com.example.todo.ui.viewmodels.SharedViewModel import dagger.hilt.android.AndroidEntryPoint @ExperimentalAnimationApi @ExperimentalMaterialApi @AndroidEntryPoint class MainActivity : ComponentActivity() { private lateinit var navController: NavHostController private val sharedViewModel: SharedViewModel by viewModels() @ExperimentalMaterialApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ToDoTheme { navController = rememberNavController() SetupNavigation( navController = navController, sharedViewModel = sharedViewModel ) } } } }
0
Kotlin
0
0
f7a4c05dd910b02db1d241cc87de2c16082cae86
1,245
Jetpack-Compose-TODO-App
MIT License
domain/src/test/kotlin/com/mctech/domain/model/AuthRequestTest.kt
MayconCardoso
198,072,780
false
null
package com.mctech.domain.model import com.mctech.domain.TestDataFactory import com.mctech.domain.errors.AuthException import org.assertj.core.api.Assertions import org.junit.Test /** * @author <NAME> on 2019-09-21. */ class AuthRequestTest { @Test fun `should throw when email fail`() { val request = TestDataFactory.createAuthRequest("") Assertions.assertThatThrownBy { request.validateOrThrow() } .isEqualTo( AuthException.InvalidEmailFormatException ) } @Test fun `should validate`() { val request = TestDataFactory.createAuthRequest("<EMAIL>") request.validateOrThrow() } }
0
Kotlin
4
21
7c2d04f56439c42b6bf8bc26807be25111d90dde
679
Modularized-Kotlin-Clean-Architecture-Showcase
Apache License 2.0
src/main/java/com/minus/git/reactive/backend/ProtocolServiceExecutor.kt
minus199
401,333,141
false
null
package com.minus.git.reactive.backend import com.minus.git.reactive.readUpToChar import java.io.InputStream private const val NULL_CHAR = "\u0000" class GitHttpRequest(private val inputStream: InputStream) { val cmd: String val headers: Map<String, String> val protocol: String val query: Map<String, String> val url: String val repoName: String val verb: String val protocolVersion: String init { val rawRequestLines = inputStream.readUpToChar(' ', 1000).split('\n').map { it.trim() } val (_, verb, url, rawQuery, protocol, protocolVersion) = rawRequestLines.matchStatusLine() this.verb = verb this.url = url this.protocol = protocol this.protocolVersion = protocolVersion this.query = rawQuery.parseQuery() this.cmd = this.query["service"]!! this.headers = rawRequestLines.parseHeaders() this.repoName = url.split('/').filter { it.isNotEmpty() }[0] } private fun String.parseQuery() = split('&').fold(mutableMapOf<String, String>()) { acc, s -> val (k, v) = s.split('=') acc.apply { acc[k] = v } }.toMap() private fun List<String>.matchStatusLine() = statusLine.matchEntire(this[0])!!.groupValues private fun List<String>.parseHeaders() = subList(1, size) .fold(mutableMapOf<String, String>()) { acc, rawHeader -> acc.apply { val (_, hName, hValue) = Companion.headerLine.matchEntire(rawHeader)?.groupValues?.toList() ?: Companion.emptyHeader if (hName != null && hValue != null) { this[hName] = hValue } } }.toMap() private operator fun <T> List<T>.component6(): T = get(5) companion object { private val statusLine = """^([A-Z]{3,})\s+(.*)?\?(.*)\s([A-Z]{4,})/(.*)""".toRegex() private val headerLine = """^([A-Za-z\-]+):\s(.*)$""".toRegex() private val emptyHeader = arrayOfNulls<String>(3).toList() } } //class ProtocolServiceExecutor internal constructor(val daemon: Daemon, private val socket: Socket) : Closeable { // val inputStream: BufferedInputStream by lazy { BufferedInputStream(socket.getInputStream()) } // val outputStream: BufferedOutputStream by lazy { BufferedOutputStream(socket.getOutputStream()) } // val remotePeer = socket.remoteSocketAddress // // // @Throws(IOException::class, ServiceNotEnabledException::class, ServiceNotAuthorizedException::class) // internal fun executeService() { // val request = GitHttpRequest(inputStream) // daemon.run { request.cmd.matchService() } // ?.execute(this@ProtocolServiceExecutor, request, null) // } // // override fun close() { // inputStream.runCatching { close() } // outputStream.runCatching { close() } // } //}
0
Kotlin
0
0
ec0152a7b11017892eddb4e92a9494b30f556985
2,879
git-server
Apache License 2.0
app/src/main/java/com/momentolabs/app/security/applocker/ui/security/function/LockedAppListViewStateCreator.kt
iammert
225,160,602
false
null
package com.momentolabs.app.security.applocker.ui.security.function import com.momentolabs.app.security.applocker.data.AppData import com.momentolabs.app.security.applocker.data.database.lockedapps.LockedAppEntity import com.momentolabs.app.security.applocker.ui.security.AppLockItemItemViewState import io.reactivex.Observable import io.reactivex.functions.BiFunction class LockedAppListViewStateCreator : BiFunction<List<AppData>, List<LockedAppEntity>, List<AppLockItemItemViewState>> { override fun apply( installedApps: List<AppData>, lockedApps: List<LockedAppEntity> ): List<AppLockItemItemViewState> { val itemViewStateList: ArrayList<AppLockItemItemViewState> = arrayListOf() installedApps.forEach { installedApp -> val itemViewState = AppLockItemItemViewState(installedApp) lockedApps.forEach { lockedApp -> if (installedApp.packageName == lockedApp.packageName) { itemViewState.isLocked = true } } itemViewStateList.add(itemViewState) } return itemViewStateList } companion object { fun create( appDataListObservable: Observable<List<AppData>>, lockedAppsObservable: Observable<List<LockedAppEntity>> ): Observable<List<AppLockItemItemViewState>> { return Observable.combineLatest( appDataListObservable, lockedAppsObservable, LockedAppListViewStateCreator() ) } } }
10
null
102
433
35dd8d4f120a3db09a690d375a12fab5463ee166
1,575
AppLocker
Apache License 2.0
api-test/src/test/kotlin/ApiTest.kt
VEuPathDB
291,791,738
false
{"Java": 381511, "RAML": 136941, "Kotlin": 4083, "Dockerfile": 2002, "Makefile": 1906}
import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.kotlin.readValue import io.restassured.RestAssured import io.restassured.RestAssured.given import io.restassured.http.ContentType import org.apache.logging.log4j.kotlin.logger import org.junit.jupiter.api.* import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import java.net.URL import java.nio.file.Path import java.util.stream.Stream @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ApiTest { private val AuthToken: String = System.getProperty("AUTH_TOKEN") private val AuthTokenKey: String = "Auth-Key" private val YamlMapper = ObjectMapper(YAMLFactory()).registerModule(KotlinModule.Builder().build()) // Files in the testdata resource directory must follow structure testdata/{dataset-type}/{upload-file} private val TestFilesDir = "testdata" private val TestSuite = testSuite() @BeforeAll internal fun setup() { RestAssured.baseURI = System.getProperty("BASE_URL") RestAssured.port = System.getProperty("SERVICE_PORT").toInt() RestAssured.useRelaxedHTTPSValidation() } @ParameterizedTest @MethodSource("bubbleTestCaseProvider") fun parameterizedBubbleTest(input: BubbleMarkerTestCase) { val overlayValues = given() // Setup request .contentType(ContentType.JSON) .header(AuthTokenKey, AuthToken) .body(input.body) // Execute request .`when`() .post("apps/standalone-map/visualizations/map-markers/bubbles") .then() .statusCode(200) .contentType(ContentType.JSON) .extract() .path<List<Double>>("mapElements.overlayValue") logger().info("Received overlay values: $overlayValues") Assertions.assertEquals(input.expectedMarkerCount, overlayValues.size) } @ParameterizedTest @MethodSource("donutTestCaseProvider") fun parameterizedDonutTest(input: DonutMarkerTestCase) { logger().info("BODY: " + input.body) val overlayValues = given() // Setup request .contentType(ContentType.JSON) .header(AuthTokenKey, AuthToken) .body(input.body) // Execute request .`when`() .post("apps/standalone-map/visualizations/map-markers") .then() .statusCode(200) .contentType(ContentType.JSON) .extract() .path<List<Int>>("mapElements.entityCount") logger().info("Received count values: $overlayValues") } /** * Provide bubble test cases from YAML file. */ private fun bubbleTestCaseProvider(): Stream<BubbleMarkerTestCase> { return TestSuite.bubbles.stream() .map { BubbleMarkerTestCase( expectedMarkerCount = it.expectedMarkerCount, body = it.body ) } } /** * Provide donut test cases. */ private fun donutTestCaseProvider(): Stream<DonutMarkerTestCase> { return TestSuite.donuts.stream() .map { DonutMarkerTestCase( expectedMarkerCount = it.expectedMarkerCount, body = it.body ) } } private fun testSuite(): TestSuite { val loader = Thread.currentThread().contextClassLoader val url: URL = loader.getResource(TestFilesDir)!! val testDataDir: String = url.path val testConfig = Path.of(testDataDir, "test-cases.yaml") return YamlMapper.readValue(testConfig.toFile()) } }
55
Java
0
2
79d1bdc9eb11c0c095d65d61e06c8370e7376959
3,826
EdaDataService
Apache License 2.0
clikt/src/jsMain/kotlin/com/github/ajalt/clikt/output/Editor.kt
ggrell
263,683,978
true
{"Kotlin": 584983, "Shell": 460}
package com.github.ajalt.clikt.output import com.github.ajalt.clikt.core.CliktError import com.github.ajalt.clikt.mpp.readEnvvar private external fun require(mod: String): dynamic private val fs = require("fs") private val crypto = require("crypto") private val childProcess = require("child_process") internal actual class Editor actual constructor( private val editorPath: String?, private val env: Map<String, String>, private val requireSave: Boolean, private val extension: String ) { private fun getEditorPath(): String { return editorPath ?: inferEditorPath { editor -> val options = jsObject( "timeout" to 100, "windowsHide" to true, "stdio" to "ignore" ) childProcess.execSync("${getWhichCommand()} $editor", options) == 0 } } private fun getEditorCommand(): Array<String> { return getEditorPath().trim().split(" ").toTypedArray() } private fun editFileWithEditor(editorCmd: Array<String>, filename: String) { val cmd = editorCmd[0] val args = (editorCmd.drop(1) + filename).toTypedArray() val options = jsObject("stdio" to "inherit", "env" to env.toJsObject()) try { val exitCode = childProcess.spawnSync(cmd, args, options) if (exitCode.status != 0) throw CliktError("$cmd: Editing failed!") } catch (err: CliktError) { throw err } catch (err: Throwable) { throw CliktError("Error staring editor") } } actual fun editFile(filename: String) { editFileWithEditor(getEditorCommand(), filename) } private fun getTmpFileName(extension: String): String { val rand = crypto.randomBytes(8).toString("hex") val dir = readEnvvar("TMP") ?: "." return "$dir/clikt_tmp_$rand.${extension.trimStart { it == '.' }}" } private fun getLastModified(path: String): Int { return (fs.statSync(path).mtimeMs as Number).toInt() } actual fun edit(text: String): String? { val editorCmd = getEditorCommand() val textToEdit = normalizeEditorText(editorCmd[0], text) val tmpFilename = getTmpFileName(extension) try { fs.writeFileSync(tmpFilename, textToEdit) try { val lastModified = getLastModified(tmpFilename) editFileWithEditor(editorCmd, tmpFilename) if (requireSave && getLastModified(tmpFilename) == lastModified) { return null } val readFileSync = fs.readFileSync(tmpFilename, "utf8") return (readFileSync as String?)?.replace("\r\n", "\n") } finally { try { fs.unlinkSync(tmpFilename) } catch (ignored: Throwable) { } } } catch (e: Throwable) { throw CliktError("Error staring editing text: ${e.message}") } } } private fun <K, V> Map<K, V>.toJsObject(): dynamic { val result = js("{}") for ((key, value) in this) { result[key] = value } return result } private fun jsObject(vararg pairs: Pair<Any, Any>): dynamic { return pairs.toMap().toJsObject() }
0
null
0
0
39a0ecaf4275376416ac25d05b71e78b1a6e432b
3,327
clikt
Apache License 2.0
android/DartsScorecard/domain/src/main/java/nl/entreco/domain/setup/settings/StoreSettingsRequest.kt
Entreco
110,022,468
false
null
package nl.entreco.domain.setup.settings /** * Created by entreco on 04/01/2018. */ class StoreSettingsRequest(val sets: Int, val legs: Int, val min: Int, val max: Int, val score: Int)
4
null
1
1
a031a0eeadd0aa21cd587b5008364a16f890b264
187
Darts-Scorecard
Apache License 2.0
workflows/src/test/kotlin/com/r3/corda/lib/accounts/workflows/test/ShareStateWithAccountFlowsTest.kt
corda
170,131,330
false
{"Kotlin": 149237, "Dockerfile": 724}
package com.r3.corda.lib.accounts.workflows.test import com.r3.corda.lib.accounts.contracts.states.AccountInfo import com.r3.corda.lib.accounts.workflows.flows.AllAccounts import com.r3.corda.lib.accounts.workflows.flows.CreateAccount import com.r3.corda.lib.accounts.workflows.flows.ShareStateWithAccount import com.r3.corda.lib.accounts.workflows.internal.accountObservedQueryBy import net.corda.core.node.services.vault.QueryCriteria import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNetworkParameters import net.corda.testing.node.StartedMockNode import net.corda.testing.node.TestCordapp import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test class ShareStateWithAccountFlowsTest { lateinit var network: MockNetwork lateinit var nodeA: StartedMockNode lateinit var nodeB: StartedMockNode @Before fun setup() { network = MockNetwork( MockNetworkParameters( networkParameters = testNetworkParameters(minimumPlatformVersion = 4), cordappsForAllNodes = listOf( TestCordapp.findCordapp("com.r3.corda.lib.accounts.contracts"), TestCordapp.findCordapp("com.r3.corda.lib.accounts.workflows") ) ) ) nodeA = network.createPartyNode() nodeB = network.createPartyNode() network.runNetwork() } @After fun tearDown() { network.stopNodes() } /*This test case check whether a shared state can be viewed by an account to which the state is shared*/ @Test fun `should the shared state be seen by accounts to shared`() { //create an account on node A val testAccountA1 = nodeA.startFlow(CreateAccount("Test_AccountA1")).runAndGet(network) //create an account on node B val testAccountA2 = nodeA.startFlow(CreateAccount("Test_AccountA2")).runAndGet(network) //create another account on node A val testAccountToShare=nodeA.startFlow(CreateAccount("Test_Account_To_Share")).runAndGet(network) //share a state of an account with testAccount1 nodeA.startFlow(ShareStateWithAccount(testAccountA2.state.data, testAccountToShare)).runAndGet(network) //get all state references of testAccount2 val permissionedStatesForA2 = nodeA.transaction { nodeA.services.vaultService.accountObservedQueryBy<AccountInfo>( listOf(testAccountA2.uuid), QueryCriteria.VaultQueryCriteria(contractStateTypes = setOf(AccountInfo::class.java)) ).states }.map { it.ref } //get all state references of testAccount1 val permissionedStatesForA1 = nodeA.transaction { nodeA.services.vaultService.accountObservedQueryBy<AccountInfo>( listOf(testAccountA1.uuid), QueryCriteria.VaultQueryCriteria(contractStateTypes = setOf(AccountInfo::class.java)) ).states }.map { it.ref } //create three accounts on node A nodeA.transaction { //checking reference of testAccountToShare is present in testAccount2 Assert.assertEquals(permissionedStatesForA2, listOf(testAccountToShare.ref)) //checking reference of testAccountToShare is not present in testAccount1 Assert.assertEquals(permissionedStatesForA1.size, 0) } } /* This test case check whether a shared state can be viewed by an account to which the state is shared */ @Test fun `should an account get the actual shared state`() { //create an account on node A val testAccountA1 = nodeA.startFlow(CreateAccount("Test_AccountA1")).runAndGet(network) val testAccountA2 = nodeA.startFlow(CreateAccount("Test_AccountA2")).runAndGet(network) //create an account on node B val testAccountB1 = nodeB.startFlow(CreateAccount("Test_AccountB1")).runAndGet(network) val testAccountB2 = nodeB.startFlow(CreateAccount("Test_AccountB2")).runAndGet(network) //create another account on node A val testAccountToShare = nodeA.startFlow(CreateAccount("Test_Account_To_Share")).runAndGet(network) //share a state of an account with testAccount1 nodeA.startFlow(ShareStateWithAccount(testAccountB1.state.data, testAccountA1)).runAndGet(network) nodeA.startFlow(ShareStateWithAccount(testAccountB1.state.data, testAccountA2 )).runAndGet(network) //get all state references of testAccountB1 val permissionedStatesForB1 = nodeB.transaction { nodeA.services.vaultService.accountObservedQueryBy<AccountInfo>( listOf(testAccountB1.uuid), QueryCriteria.VaultQueryCriteria(contractStateTypes = setOf(AccountInfo::class.java)) ).states }.map { it.ref } //get all state references of testAccountB2 val permissionedStatesForB2 = nodeB.transaction { nodeA.services.vaultService.accountObservedQueryBy<AccountInfo>( listOf(testAccountB2.uuid), QueryCriteria.VaultQueryCriteria(contractStateTypes = setOf(AccountInfo::class.java)) ).states }.map { it.ref } val allAccountInfoA = nodeA.startFlow(AllAccounts()).runAndGet(network) val allAccountInfoB = nodeB.startFlow(AllAccounts()).runAndGet(network) //checking permissioned state for nodeB Assert.assertEquals(allAccountInfoB, listOf(testAccountB1, testAccountB2, testAccountA1, testAccountA2)) //checking permissioned state for testAccountB1 Assert.assertEquals(permissionedStatesForB1, listOf(testAccountA1.ref, testAccountA2.ref)) //checking permissioned state for testAccountB2 Assert.assertEquals(permissionedStatesForB2.size, 0) } }
28
Kotlin
38
35
c2428c28c341d6f9649390e202ff3b02c25cb2f3
5,939
accounts
Apache License 2.0
feature/books/src/main/java/com/githukudenis/comlib/feature/books/BooksRoute.kt
DenisGithuku
707,847,935
false
{"Kotlin": 289725}
package com.githukudenis.comlib.feature.books import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.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.safeDrawingPadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.githukudenis.comlib.core.common.untangle import com.githukudenis.comlib.core.designsystem.ui.components.loadingBrush import com.githukudenis.comlib.feature.books.components.BookComponent @Composable fun BooksRoute( viewModel: BooksViewModel = hiltViewModel(), onOpenBook: (String) -> Unit ) { val state by viewModel.uiState.collectAsStateWithLifecycle() BooksScreen( state = state, onChangeGenre = viewModel::onChangeGenre, onOpenBook = onOpenBook ) } @Composable fun BooksScreen( state: BooksUiState, onChangeGenre: (GenreUiModel) -> Unit, onOpenBook: (String) -> Unit ) { when (state) { is BooksUiState.Loading -> LoadingScreen() is BooksUiState.Success -> { LoadedScreen( genreListUiState = state.genreListUiState, bookListUiState = state.bookListUiState, onChangeGenre = onChangeGenre, onOpenBook = onOpenBook ) } is BooksUiState.Error -> ErrorScreen() } } @Composable private fun LoadingScreen() { Column( modifier = Modifier .fillMaxSize() .safeDrawingPadding(), verticalArrangement = Arrangement.spacedBy(12.dp) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { (0..4).map { Box( modifier = Modifier .height(24.dp) .width(36.dp) .clip(CircleShape) .background(brush = loadingBrush()) ) } } Divider(modifier = Modifier.fillMaxWidth(), color = Color.Black.copy(0.09f)) Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { (0..6).map { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .size(56.dp) .clip(CircleShape) .background(brush = loadingBrush()) ) Spacer(modifier = Modifier.width(16.dp)) Column { Box( modifier = Modifier .height(24.dp) .fillMaxWidth(0.6f) .clip(CircleShape) .background(brush = loadingBrush()) ) Spacer(modifier = Modifier.height(12.dp)) Box( modifier = Modifier .height(24.dp) .fillMaxWidth(0.6f) .clip(CircleShape) .background(brush = loadingBrush()) ) } } } } } } @Composable private fun LoadedScreen( genreListUiState: GenreListUiState, bookListUiState: BookListUiState, onChangeGenre: (GenreUiModel) -> Unit, onOpenBook: (String) -> Unit ) { LazyColumn( modifier = Modifier .fillMaxSize() .safeDrawingPadding(), ) { item { when (genreListUiState) { is GenreListUiState.Error -> { Text( text = genreListUiState.message, style = MaterialTheme.typography.titleMedium ) } GenreListUiState.Loading -> { Row( modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { (0..4).map { Box( modifier = Modifier .height(32.dp) .width(56.dp) .clip(CircleShape) .background(brush = loadingBrush()) ) } } } is GenreListUiState.Success -> { LazyRow( horizontalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues(horizontal = 16.dp) ) { items(items = genreListUiState.genres, key = { it.id }) { genre -> Box(modifier = Modifier .clip(CircleShape) .background( color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.1f) ) .clickable { onChangeGenre(genre) }) { Text( text = genre.name.untangle("-"), modifier = Modifier.padding( horizontal = 16.dp, vertical = 8.dp ), style = MaterialTheme.typography.titleMedium ) } } } } } } item { Divider(modifier = Modifier, color = Color.Black.copy(alpha = 0.1f)) } when (bookListUiState) { is BookListUiState.Error -> { item { Text( text = bookListUiState.message, style = MaterialTheme.typography.titleMedium ) } } BookListUiState.Loading -> { item { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { (0..6).map { Row( modifier = Modifier.fillMaxWidth().padding( vertical = 12.dp, horizontal = 8.dp ), ) { Box( modifier = Modifier .size(56.dp) .clip(CircleShape) .background(brush = loadingBrush()) ) Spacer(modifier = Modifier.width(16.dp)) Column { Box( modifier = Modifier .height(16.dp) .fillMaxWidth(0.6f) .background(brush = loadingBrush()) ) Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier .height(16.dp) .fillMaxWidth(0.4f) .background(brush = loadingBrush()) ) } } } } } } is BookListUiState.Success -> { items(bookListUiState.books) { bookModel -> BookComponent(bookItemUiModel = bookModel, onOpenBookDetails = { bookId -> onOpenBook(bookId) }) } } } } } @Composable private fun ErrorScreen() { }
6
Kotlin
1
0
68beba7ad2a6f36842f75ee81969f61125c5af0f
9,683
comlib-android-client
Apache License 2.0
src/main/kotlin/me/msoucy/gbat/models/KnowledgeModel.kt
msoucy
273,097,310
false
null
package me.msoucy.gbat.models import me.msoucy.gbat.copyOf import me.msoucy.gbat.mutableCopyOf import org.jetbrains.exposed.dao.id.IntIdTable import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction class KnowledgeModel(val db: Database, val constant: Double, val riskModel: RiskModel) { class KnowledgeAcct( var knowledgeAcctId: Int, var authors: List<String>, var authorsStr: String ) object AuthorsTable : IntIdTable("authors", "authorid") { val author = text("author").uniqueIndex("authors_idx") } object KnowledgeAcctsTable : IntIdTable("knowledgeaccts", "knowledgeacctid") { val authors = text("authors").uniqueIndex("knowledgeacctsauthors_idx") } object KnowledgeAuthorsTable : Table("knowedgeaccts_authors") { val knowledgeacctid = integer("knowledgeacctid") val authorid = integer("authorid") override val primaryKey = PrimaryKey(knowledgeacctid, authorid) } object LineKnowledge : Table("lineknowledge") { val linenum = integer("linenum") val knowledgeacctid = integer("knowledgeacctid").references(KnowledgeAuthorsTable.knowledgeacctid) val knowledge = double("knowledge") } init { createTables() } val SAFE_AUTHOR_ID = 1 val SAFE_KNOWLEDGE_ACCT_ID = 1 val KNOWLEDGE_PER_LINE_ADDED = 1000.0 fun apply(changeType: ChangeType, author: String, lineNum: Int) = when (changeType) { ChangeType.Add -> lineAdded(author, lineNum) ChangeType.Change -> lineChanged(author, lineNum) ChangeType.Remove -> lineRemoved(lineNum) } fun lineChanged(author: String, lineNum: Int) { val kCreated = constant * KNOWLEDGE_PER_LINE_ADDED val kAcquired = (1 - constant) * KNOWLEDGE_PER_LINE_ADDED val totLineK = totalLineKnowledge(lineNum) val acquiredPct = if (totLineK != 0.0) { kAcquired / totLineK } else 0.0 redistributeKnowledge(author, lineNum, acquiredPct) val knowledgeAcctId = lookupOrCreateKnowledgeAcct(listOf(author)) adjustKnowledge(knowledgeAcctId, lineNum, kCreated) } fun lineRemoved(lineNum: Int) { allAcctsWithKnowledgeOf(lineNum).forEach { destroyLineKnowledge(it, lineNum) } bumpAllLinesFrom(lineNum, -1) } fun lineAdded(author: String, lineNum: Int) { val knowledgeAcctId = lookupOrCreateKnowledgeAcct(listOf(author)) bumpAllLinesFrom(lineNum - 1, 1) adjustKnowledge(knowledgeAcctId, lineNum, KNOWLEDGE_PER_LINE_ADDED) } fun knowledgeSummary(lineNum: Int) = transaction(db) { LineKnowledge.select { LineKnowledge.linenum eq lineNum }.map { val acct = getKnowledgeAcct(it[LineKnowledge.knowledgeacctid]) Pair(acct.authors, it[LineKnowledge.knowledge]) }.sortedBy { it.first.joinToString("\n") }.copyOf() } private fun bumpAllLinesFrom(lineNum: Int, adjustment: Int) = transaction(db) { LineKnowledge.update({ LineKnowledge.linenum greater lineNum }) { with(SqlExpressionBuilder) { it[LineKnowledge.linenum] = LineKnowledge.linenum + adjustment } } } private fun getKnowledgeAcct(knowledgeAcctId: Int): KnowledgeAcct = transaction(db) { KnowledgeAcctsTable.select { KnowledgeAcctsTable.id eq knowledgeAcctId }.map { KnowledgeAcct( it[KnowledgeAcctsTable.id].value, it[KnowledgeAcctsTable.authors].split("\n"), it[KnowledgeAcctsTable.authors] ) }.firstOrNull() ?: KnowledgeAcct(-1, listOf(), "") } private fun destroyLineKnowledge(knowledgeId: Int, lineNum: Int) = transaction(db) { LineKnowledge.deleteWhere { (LineKnowledge.knowledgeacctid eq knowledgeId) and (LineKnowledge.linenum eq lineNum) } } private fun redistributeKnowledge(author: String, lineNum: Int, redistPct: Double) { if (riskModel.isDeparted(author)) { return } val knowledgeIds = nonSafeAcctsWithKnowledgeOf(lineNum) for (knowledgeId in knowledgeIds) { val knowledgeAcct = getKnowledgeAcct(knowledgeId) if (author !in knowledgeAcct.authors) { val oldKnowledge = knowledgeInAcct(knowledgeAcct.knowledgeAcctId, lineNum) var newAuthors = knowledgeAcct.authors.mutableCopyOf() if (newAuthors.all(riskModel::isDeparted)) { newAuthors = mutableListOf(author) } else { newAuthors.add(author) } newAuthors = newAuthors.sorted().mutableCopyOf() val newKnowledgeId = if (riskModel.jointBusProbBelowThreshold(newAuthors)) { SAFE_KNOWLEDGE_ACCT_ID } else { lookupOrCreateKnowledgeAcct(newAuthors) } val knowledgeToDist = oldKnowledge * redistPct adjustKnowledge(knowledgeId, lineNum, -knowledgeToDist) adjustKnowledge(newKnowledgeId, lineNum, knowledgeToDist) } } } private fun knowledgeInAcct(knowledgeAcctId: Int, lineNum: Int) = transaction(db) { LineKnowledge.select { (LineKnowledge.knowledgeacctid eq knowledgeAcctId) and (LineKnowledge.linenum eq lineNum) }.map { it[LineKnowledge.knowledge] }.first() } private fun nonSafeAcctsWithKnowledgeOf(lineNum: Int) = transaction(db) { LineKnowledge.select { (LineKnowledge.linenum eq lineNum) and (LineKnowledge.knowledgeacctid neq SAFE_KNOWLEDGE_ACCT_ID) }.map { it[LineKnowledge.knowledgeacctid] } } private fun allAcctsWithKnowledgeOf(lineNum: Int) = transaction(db) { LineKnowledge.select { LineKnowledge.linenum eq lineNum }.map { it[LineKnowledge.knowledgeacctid] } } private fun adjustKnowledge(knowledgeAcctId: Int, lineNum: Int, adjustment: Double) = transaction(db) { val lineExists = LineKnowledge.select { (LineKnowledge.knowledgeacctid eq knowledgeAcctId) and (LineKnowledge.linenum eq lineNum) }.count() > 0 if (!lineExists) { LineKnowledge.insert { it[LineKnowledge.knowledgeacctid] = knowledgeAcctId it[LineKnowledge.linenum] = lineNum it[LineKnowledge.knowledge] = 0.0 } } LineKnowledge.update({ (LineKnowledge.knowledgeacctid eq knowledgeAcctId) and (LineKnowledge.linenum eq lineNum) }) { with(SqlExpressionBuilder) { it[LineKnowledge.knowledge] = LineKnowledge.knowledge + adjustment } } } private fun lookupOrCreateKnowledgeAcct(authors: List<String>) = transaction(db) { val authorStr = authors.sorted().joinToString("\n") KnowledgeAcctsTable.select { KnowledgeAcctsTable.authors eq authorStr }.map { it[KnowledgeAcctsTable.id].value }.firstOrNull() ?: run { KnowledgeAcctsTable.insert { it[KnowledgeAcctsTable.authors] = authorStr } val theNewId = KnowledgeAcctsTable.select { KnowledgeAcctsTable.authors eq authorStr }.map { it[KnowledgeAcctsTable.id].value }.first() authors.map(::lookupOrCreateAuthor).forEach { authorId -> KnowledgeAuthorsTable.insert { it[KnowledgeAuthorsTable.knowledgeacctid] = theNewId it[KnowledgeAuthorsTable.authorid] = authorId.value } } theNewId } } private fun lookupOrCreateAuthor(authorName: String) = transaction(db) { AuthorsTable.insertIgnore { it[author] = authorName } AuthorsTable.select { AuthorsTable.author eq authorName }.first().let { it[AuthorsTable.id] } } private fun totalLineKnowledge(linenum: Int) = transaction(db) { LineKnowledge.select { LineKnowledge.linenum eq linenum }.map { it[LineKnowledge.knowledge] }.firstOrNull() ?: 0.0 } private fun createTables() = transaction(db) { SchemaUtils.dropDatabase() SchemaUtils.createMissingTablesAndColumns(AuthorsTable, KnowledgeAcctsTable, KnowledgeAuthorsTable, LineKnowledge) AuthorsTable.insertIgnore { it[author] = "" } KnowledgeAcctsTable.insertIgnore { it[authors] = "" } KnowledgeAuthorsTable.insertIgnore { it[knowledgeacctid] = SAFE_KNOWLEDGE_ACCT_ID it[authorid] = SAFE_AUTHOR_ID } } }
0
Kotlin
0
0
e897278323ff184609c92a2d2851152311a118ca
9,085
git-by-a-truck
MIT License
solar/src/main/java/com/chiksmedina/solar/bold/videoaudiosound/QuitPip.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.bold.videoaudiosound import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.bold.VideoAudioSoundGroup val VideoAudioSoundGroup.QuitPip: ImageVector get() { if (_quitPip != null) { return _quitPip!! } _quitPip = Builder( name = "QuitPip", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(10.0f, 3.0f) horizontalLineTo(14.0f) curveTo(17.7712f, 3.0f, 19.6569f, 3.0f, 20.8284f, 4.1716f) curveTo(21.7775f, 5.1206f, 21.9577f, 6.8663f, 21.992f, 9.4997f) curveTo(22.0042f, 10.4366f, 22.0102f, 10.905f, 21.7166f, 11.2025f) curveTo(21.4229f, 11.5f, 20.9486f, 11.5f, 20.0f, 11.5f) horizontalLineTo(17.5f) curveTo(14.6716f, 11.5f, 13.2574f, 11.5f, 12.3787f, 12.3787f) curveTo(11.5f, 13.2574f, 11.5f, 14.6716f, 11.5f, 17.5f) verticalLineTo(19.5f) curveTo(11.5f, 19.9659f, 11.5f, 20.1989f, 11.4239f, 20.3827f) curveTo(11.3224f, 20.6277f, 11.1277f, 20.8224f, 10.8827f, 20.9239f) curveTo(10.6989f, 21.0f, 10.4659f, 21.0f, 10.0f, 21.0f) curveTo(6.2288f, 21.0f, 4.3432f, 21.0f, 3.1716f, 19.8284f) curveTo(2.0f, 18.6569f, 2.0f, 16.7712f, 2.0f, 13.0f) verticalLineTo(11.0f) curveTo(2.0f, 7.2288f, 2.0f, 5.3432f, 3.1716f, 4.1716f) curveTo(4.3432f, 3.0f, 6.2288f, 3.0f, 10.0f, 3.0f) close() moveTo(10.9697f, 12.0303f) curveTo(11.2626f, 12.3232f, 11.7374f, 12.3232f, 12.0303f, 12.0303f) curveTo(12.3232f, 11.7374f, 12.3232f, 11.2626f, 12.0303f, 10.9697f) lineTo(9.3107f, 8.25f) horizontalLineTo(10.5f) curveTo(10.9142f, 8.25f, 11.25f, 7.9142f, 11.25f, 7.5f) curveTo(11.25f, 7.0858f, 10.9142f, 6.75f, 10.5f, 6.75f) horizontalLineTo(7.5f) curveTo(7.0858f, 6.75f, 6.75f, 7.0858f, 6.75f, 7.5f) verticalLineTo(10.5f) curveTo(6.75f, 10.9142f, 7.0858f, 11.25f, 7.5f, 11.25f) curveTo(7.9142f, 11.25f, 8.25f, 10.9142f, 8.25f, 10.5f) verticalLineTo(9.3107f) lineTo(10.9697f, 12.0303f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(13.5858f, 13.5858f) curveTo(13.0f, 14.1716f, 13.0f, 15.1144f, 13.0f, 17.0f) curveTo(13.0f, 18.8856f, 13.0f, 19.8284f, 13.5858f, 20.4142f) curveTo(14.1716f, 21.0f, 15.1144f, 21.0f, 17.0f, 21.0f) horizontalLineTo(18.0f) curveTo(19.8856f, 21.0f, 20.8284f, 21.0f, 21.4142f, 20.4142f) curveTo(22.0f, 19.8284f, 22.0f, 18.8856f, 22.0f, 17.0f) curveTo(22.0f, 15.1144f, 22.0f, 14.1716f, 21.4142f, 13.5858f) curveTo(20.8284f, 13.0f, 19.8856f, 13.0f, 18.0f, 13.0f) horizontalLineTo(17.0f) curveTo(15.1144f, 13.0f, 14.1716f, 13.0f, 13.5858f, 13.5858f) close() } } .build() return _quitPip!! } private var _quitPip: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
4,378
SolarIconSetAndroid
MIT License
mobile/src/main/java/com/google/samples/apps/iosched/ui/schedule/DayIndicatorAdapter.kt
google
18,347,476
false
null
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.schedule import android.view.LayoutInflater import android.view.ViewGroup import android.widget.TextView import androidx.databinding.BindingAdapter import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.DiffUtil.ItemCallback import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.google.samples.apps.iosched.databinding.ItemScheduleDayIndicatorBinding import com.google.samples.apps.iosched.shared.util.TimeUtils import com.google.samples.apps.iosched.util.executeAfter class DayIndicatorAdapter( private val scheduleViewModel: ScheduleViewModel, private val lifecycleOwner: LifecycleOwner ) : ListAdapter<DayIndicator, DayIndicatorViewHolder>(IndicatorDiff) { init { setHasStableIds(true) } override fun getItemId(position: Int): Long { return getItem(position).day.start.toEpochSecond() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DayIndicatorViewHolder { val binding = ItemScheduleDayIndicatorBinding .inflate(LayoutInflater.from(parent.context), parent, false) return DayIndicatorViewHolder(binding, scheduleViewModel, lifecycleOwner) } override fun onBindViewHolder(holder: DayIndicatorViewHolder, position: Int) { holder.bind(getItem(position)) } } class DayIndicatorViewHolder( private val binding: ItemScheduleDayIndicatorBinding, private val scheduleViewModel: ScheduleViewModel, private val lifecycleOwner: LifecycleOwner ) : ViewHolder(binding.root) { fun bind(item: DayIndicator) { binding.executeAfter { indicator = item viewModel = scheduleViewModel lifecycleOwner = [email protected] } } } object IndicatorDiff : ItemCallback<DayIndicator>() { override fun areItemsTheSame(oldItem: DayIndicator, newItem: DayIndicator) = oldItem == newItem override fun areContentsTheSame(oldItem: DayIndicator, newItem: DayIndicator) = oldItem.areUiContentsTheSame(newItem) } @BindingAdapter("indicatorText", "inConferenceTimeZone", requireAll = true) fun setIndicatorText( view: TextView, dayIndicator: DayIndicator, inConferenceTimeZone: Boolean ) { view.setText(TimeUtils.getShortLabelResForDay(dayIndicator.day, inConferenceTimeZone)) }
77
null
6259
21,755
738e1e008096fad5f36612325275e80c33dbe436
3,030
iosched
Apache License 2.0
app/src/main/java/fr/free/nrw/commons/customselector/ui/adapter/ImageAdapter.kt
commons-app
42,032,884
false
null
package fr.free.nrw.commons.customselector.ui.adapter import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.constraintlayout.widget.Group import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import fr.free.nrw.commons.R import fr.free.nrw.commons.customselector.helper.ImageHelper import fr.free.nrw.commons.customselector.listeners.ImageSelectListener import fr.free.nrw.commons.customselector.model.Image import fr.free.nrw.commons.customselector.ui.selector.ImageLoader /** * Custom selector ImageAdapter. */ class ImageAdapter( /** * Application Context. */ context: Context, /** * Image select listener for click events on image. */ private var imageSelectListener: ImageSelectListener, /** * ImageLoader queries images. */ private var imageLoader: ImageLoader ): RecyclerViewAdapter<ImageAdapter.ImageViewHolder>(context) { /** * ImageSelectedOrUpdated payload class. */ class ImageSelectedOrUpdated /** * ImageUnselected payload class. */ class ImageUnselected /** * Currently selected images. */ private var selectedImages = arrayListOf<Image>() /** * List of all images in adapter. */ private var images: ArrayList<Image> = ArrayList() /** * Create View holder. */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder { val itemView = inflater.inflate(R.layout.item_custom_selector_image, parent, false) return ImageViewHolder(itemView) } /** * Bind View holder, load image, selected view, click listeners. */ override fun onBindViewHolder(holder: ImageViewHolder, position: Int) { val image=images[position] holder.image.setImageDrawable (null) if (context.contentResolver.getType(image.uri) == null) { // Image does not exist anymore, update adapter. holder.itemView.post { val updatedPosition = images.indexOf(image) images.remove(image) notifyItemRemoved(updatedPosition) notifyItemRangeChanged(updatedPosition, images.size) } } else { val selectedIndex = ImageHelper.getIndex(selectedImages, image) val isSelected = selectedIndex != -1 if (isSelected) { holder.itemSelected(selectedIndex + 1) } else { holder.itemUnselected(); } Glide.with(holder.image).load(image.uri).thumbnail(0.3f).into(holder.image) imageLoader.queryAndSetView(holder, image) holder.itemView.setOnClickListener { selectOrRemoveImage(holder, position) } // launch media preview on long click. holder.itemView.setOnLongClickListener { imageSelectListener.onLongPress(image.uri) true } } } /** * Handle click event on an image, update counter on images. */ private fun selectOrRemoveImage(holder: ImageViewHolder, position: Int){ val clickedIndex = ImageHelper.getIndex(selectedImages, images[position]) if (clickedIndex != -1) { selectedImages.removeAt(clickedIndex) notifyItemChanged(position, ImageUnselected()) val indexes = ImageHelper.getIndexList(selectedImages, images) for (index in indexes) { notifyItemChanged(index, ImageSelectedOrUpdated()) } } else { if(holder.isItemUploaded()){ Toast.makeText(context, R.string.custom_selector_already_uploaded_image_text, Toast.LENGTH_SHORT).show() } else { selectedImages.add(images[position]) notifyItemChanged(position, ImageSelectedOrUpdated()) } } imageSelectListener.onSelectedImagesChanged(selectedImages) } /** * Initialize the data set. */ fun init(newImages: List<Image>) { val oldImageList:ArrayList<Image> = images val newImageList:ArrayList<Image> = ArrayList(newImages) val diffResult = DiffUtil.calculateDiff( ImagesDiffCallback(oldImageList, newImageList) ) images = newImageList diffResult.dispatchUpdatesTo(this) } /** * Returns the total number of items in the data set held by the adapter. * * @return The total number of items in this adapter. */ override fun getItemCount(): Int { return images.size } fun getImageIdAt(position: Int): Long { return images.get(position).id } /** * Image view holder. */ class ImageViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { val image: ImageView = itemView.findViewById(R.id.image_thumbnail) private val selectedNumber: TextView = itemView.findViewById(R.id.selected_count) private val uploadedGroup: Group = itemView.findViewById(R.id.uploaded_group) private val selectedGroup: Group = itemView.findViewById(R.id.selected_group) /** * Item selected view. */ fun itemSelected(index: Int) { selectedGroup.visibility = View.VISIBLE selectedNumber.text = index.toString() } /** * Item Unselected view. */ fun itemUnselected() { selectedGroup.visibility = View.GONE } /** * Item Uploaded view. */ fun itemUploaded() { uploadedGroup.visibility = View.VISIBLE } fun isItemUploaded():Boolean { return uploadedGroup.visibility == View.VISIBLE } /** * Item Not Uploaded view. */ fun itemNotUploaded() { uploadedGroup.visibility = View.GONE } } /** * DiffUtilCallback. */ class ImagesDiffCallback( var oldImageList: ArrayList<Image>, var newImageList: ArrayList<Image> ) : DiffUtil.Callback(){ /** * Returns the size of the old list. */ override fun getOldListSize(): Int { return oldImageList.size } /** * Returns the size of the new list. */ override fun getNewListSize(): Int { return newImageList.size } /** * Called by the DiffUtil to decide whether two object represent the same Item. */ override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return newImageList[newItemPosition].id == oldImageList[oldItemPosition].id } /** * Called by the DiffUtil when it wants to check whether two items have the same data. * DiffUtil uses this information to detect if the contents of an item has changed. */ override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldImageList[oldItemPosition].equals(newImageList[newItemPosition]) } } }
557
null
953
730
18a9170691199725254067504bb1f8508f25447d
7,361
apps-android-commons
Apache License 2.0
httpClient/src/commonMain/kotlin/pw/binom/io/httpClient/RequestAsyncChunkedOutput.kt
caffeine-mgn
182,165,415
false
{"C": 13079003, "Kotlin": 1913743, "C++": 200, "Shell": 88}
package pw.binom.io.httpClient import pw.binom.DEFAULT_BUFFER_SIZE import pw.binom.net.URI import pw.binom.io.http.AsyncAsciiChannel import pw.binom.io.http.AsyncChunkedOutput import kotlin.time.Duration import kotlin.time.ExperimentalTime @OptIn(ExperimentalTime::class) class RequestAsyncChunkedOutput constructor( val URI: URI, val client: BaseHttpClient, var keepAlive: Boolean, val channel: AsyncAsciiChannel, val timeout: Duration?, autoFlushBuffer: Int = DEFAULT_BUFFER_SIZE, ) : AsyncHttpRequestOutput, AsyncChunkedOutput( stream = channel.writer, autoFlushBuffer = autoFlushBuffer, closeStream = false ) { override suspend fun getResponse(): HttpResponse { checkClosed() super.asyncClose() return DefaultHttpResponse.read( uri = URI, client = client, keepAlive = keepAlive, channel = channel, timeout = timeout, ) } override suspend fun asyncClose() { getResponse().asyncClose() } }
7
C
2
59
580ff27a233a1384273ef15ea6c63028dc41dc01
1,047
pw.binom.io
Apache License 2.0
Introduction to Objects/Testing/Exercise 2/src/Task.kt
marchdz
633,862,396
false
null
// Testing/Task2.kt package testingExercise2 import atomictest.eq import atomictest.neq fun sum(a: Int, b: Int, c: Int): Int = a + b + c fun main() { sum(4, 3, 7) eq 14 neq 15 sum(2, 5, 8) eq 15 neq 14 sum(1, 6, 10) eq 17 neq 18 sum(1, 1, 1) eq 3 neq 2 sum(10, 10, 10) eq 30 neq 20 }
0
Kotlin
0
0
1efabf8721c4efbb0891b7b9469efc9e7b36f189
295
atomic-kotlin-exercises
MIT License
domain/src/main/java/kr/ohyung/domain/usecase/search/DropSearchHistory.kt
androiddevnotesforks
310,938,493
false
{"Kotlin": 243295}
/* * Created by <NAME> on 2020/09/26. */ package kr.ohyung.domain.usecase.search import io.reactivex.Completable import io.reactivex.Scheduler import kr.ohyung.domain.repository.SearchHistoryRepository import kr.ohyung.domain.usecase.base.CompletableUseCase class DropSearchHistory( private val searchHistoryRepository: SearchHistoryRepository, executorThread: Scheduler, postExecutionThread: Scheduler ) : CompletableUseCase(executorThread, postExecutionThread) { override fun buildUseCaseCompletable(): Completable = searchHistoryRepository.drop() }
0
Kotlin
2
1
c1567d938af59c3ca09c8dc15675358ba1abc63a
572
android-mvi-redux
MIT License
buildSrc/src/main/java/Version.kt
cyrillrx
45,385,110
false
{"Java": 65580, "Kotlin": 27577}
import org.gradle.api.JavaVersion object Version { const val kotlin = "1.6.10" const val compileSdk = 31 const val minSdk = 21 const val targetSdk = 31 const val jvmTarget = "11" }
1
null
1
1
402718426ed0438c1a97e18a256f1eaf4bc85d75
205
android-logger
MIT License
app/src/main/java/com/example/weatherapp/data/mappers/settings/UnitsSystemDomainEntityMapper.kt
t1geryan
635,408,978
false
null
package com.example.weatherapp.data.mappers.settings import com.example.weatherapp.data.pref_datastore.settings_datastore.entities.UnitsSystemEntity import com.example.weatherapp.domain.models.AppUnitsSystem import com.example.weatherapp.utils.BidirectionalMapper import javax.inject.Inject /** * Interface for mapping [AppUnitsSystem] <-> [UnitsSystemEntity] * @see BidirectionalMapper */ interface UnitsSystemDomainEntityMapper : BidirectionalMapper<AppUnitsSystem, UnitsSystemEntity> class UnitsSystemDomainEntityMapperImpl @Inject constructor() : UnitsSystemDomainEntityMapper { /** * Maps from [AppUnitsSystem] to [UnitsSystemEntity] * @throws IllegalArgumentException when [AppUnitsSystem] does not match any enum constant */ override fun map(valueToMap: AppUnitsSystem): UnitsSystemEntity = when (valueToMap) { AppUnitsSystem.METRIC_SYSTEM -> UnitsSystemEntity.METRIC_SYSTEM AppUnitsSystem.IMPERIAL_SYSTEM -> UnitsSystemEntity.IMPERIAL_SYSTEM } /** * Maps from [UnitsSystemEntity] to [AppUnitsSystem] */ override fun reverseMap(valueToMap: UnitsSystemEntity): AppUnitsSystem = when (valueToMap) { UnitsSystemEntity.METRIC_SYSTEM -> AppUnitsSystem.METRIC_SYSTEM UnitsSystemEntity.IMPERIAL_SYSTEM -> AppUnitsSystem.IMPERIAL_SYSTEM } }
0
Kotlin
0
0
95db60e66edddf9b01dd5d2142088eeda1789465
1,328
DSR_Android_Weather_App
Apache License 2.0
app/src/main/java/com/warlock/tmdb/data/db/dao/BaseDao.kt
rahulgothwal5
366,426,179
false
{"Kotlin": 189195, "Java": 19482}
package com.warlock.tmdb.data.db.dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Update interface BaseDao<T> { /** * use to insert T into database * @param obj of T */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(obj: T) /** * use to insert list of T into database * @param obj of T */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(obj: List<T>) /** * use to update T * @param obj of T */ @Update suspend fun update(obj: T) /** * use to delete T from database * @param obj of T */ @Delete suspend fun delete(obj: T) /** * use to delete list of T from database * @param obj of T */ @Delete suspend fun delete(obj: List<T>) }
0
Kotlin
0
0
3264a8cb808f0184ffee394548b670efe7cdd33c
882
TMDB-App
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Refund.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.Refund: ImageVector get() { if (_refund != null) { return _refund!! } _refund = Builder(name = "Refund", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(23.152f, 8.681f) curveToRelative(-0.515f, -0.469f, -1.186f, -0.712f, -1.878f, -0.678f) curveToRelative(-0.697f, 0.032f, -1.339f, 0.334f, -1.794f, 0.835f) lineToRelative(-3.541f, 3.737f) curveToRelative(0.032f, 0.21f, 0.065f, 0.42f, 0.065f, 0.638f) curveToRelative(0.0f, 2.083f, -1.555f, 3.876f, -3.617f, 4.17f) lineToRelative(-4.241f, 0.606f) lineToRelative(-0.283f, -1.979f) lineToRelative(4.241f, -0.606f) curveToRelative(1.084f, -0.155f, 1.9f, -1.097f, 1.9f, -2.191f) curveToRelative(0.0f, -1.22f, -0.993f, -2.213f, -2.213f, -2.213f) lineTo(3.003f, 11.0f) curveTo(1.349f, 11.0f, 0.003f, 12.346f, 0.003f, 14.0f) verticalLineToRelative(7.0f) curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f) horizontalLineToRelative(9.664f) lineToRelative(10.674f, -11.655f) curveToRelative(0.948f, -1.062f, 0.862f, -2.707f, -0.189f, -3.665f) close() moveTo(10.962f, 0.0f) curveToRelative(0.0f, 1.657f, -1.343f, 3.0f, -3.0f, 3.0f) reflectiveCurveToRelative(-3.0f, -1.343f, -3.0f, -3.0f) horizontalLineToRelative(-2.962f) verticalLineToRelative(9.0f) horizontalLineToRelative(12.0f) lineTo(14.0f, 0.0f) horizontalLineToRelative(-3.038f) close() moveTo(5.5f, 7.0f) curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f) reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f) close() moveTo(10.5f, 7.0f) curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f) reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f) close() } } .build() return _refund!! } private var _refund: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,481
icons
MIT License
app/src/main/java/com/minnu/instagramjetpackcompose/NavigationBarItem.kt
Minnu13
683,026,613
false
null
package com.minnu.instagramjetpackcompose data class BottomNavItem( val title: String, val icon: Int, val route: String ) enum class BottomNavRoutes(val route: String) { HOME("home"), SEARCH("search"), REELS("reels"), NOTIFICATIONS("notification"), PROFILE("profile") }
0
Kotlin
0
0
09e22a592fa3eed07af004f6125f1c31b02e52e7
281
jepack_compose
Apache License 2.0
src/main/kotlin/at/cath/simpletabs/gui/TabButton.kt
otcathatsya
495,090,255
false
null
package at.cath.simpletabs.gui import at.cath.simpletabs.mixins.MixinSuggestorAccessor import at.cath.simpletabs.mixins.MixinSuggestorState import at.cath.simpletabs.tabs.CONTROL_ELEMENT import at.cath.simpletabs.tabs.ChatTab import at.cath.simpletabs.utility.SimpleColour import net.minecraft.client.MinecraftClient import net.minecraft.client.gui.DrawableHelper import net.minecraft.client.gui.screen.ChatScreen import net.minecraft.client.util.math.MatrixStack import net.minecraft.text.Text class TabButton( x: Int, y: Int, width: Int, height: Int, message: Text, private val tab: ChatTab? = null, clickCallback: MouseActionCallback = object : MouseActionCallback {} ) : SimpleButton( x, y, width, height, message, tab?.theme?.backgroundColour ?: CONTROL_ELEMENT.backgroundColour, tab?.theme?.outlineColour ?: CONTROL_ELEMENT.outlineColour, tab?.theme?.textColour ?: CONTROL_ELEMENT.textColour, clickCallback ), TabGUIComponent { override fun renderButton(matrices: MatrixStack, mouseX: Int, mouseY: Int, delta: Float) { val minecraftClient = MinecraftClient.getInstance() val screen = minecraftClient.currentScreen if (screen is ChatScreen) { if (((screen as MixinSuggestorAccessor).commandSuggestor as MixinSuggestorState).suggestionWindow == null) { super.renderButton(matrices, mouseX, mouseY, delta) val textRenderer = minecraftClient.textRenderer if (tab != null) { if (tab.unreadCount > 0) { val startX = x + width - 4 val startY = y + 4 DrawableHelper.fill( matrices, startX, startY, startX + 6, startY - 6, SimpleColour.RED.packedRgb ) val startXScaled = startX / 0.5 val startYScaled = startY / 0.5 matrices.push() matrices.scale(0.5f, 0.5f, 1.0f) DrawableHelper.drawCenteredText( matrices, textRenderer, Text.of("${tab.unreadCount}"), startXScaled.toInt() + 6, startYScaled.toInt() - 9, SimpleColour.WHITE.packedRgb ) matrices.pop() } } } } } }
0
Kotlin
1
6
0f7a981f77b2e345ea9145a69df6b4c7095f822e
2,742
simple-tabs
MIT License
src/app/src/main/java/com/billboard/movies/model/rest/base/ServiceGenerator.kt
sergio83
160,894,777
false
null
package com.billboard.movies.model.rest.base import com.billboard.movies.BuildConfig import com.billboard.movies.model.controller.AppPreferences import com.facebook.stetho.okhttp3.StethoInterceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.* class ServiceGenerator { companion object { private val mLogging = HttpLoggingInterceptor() private var mGsonFactory: GsonConverterFactory? = null private val mHttpClient: OkHttpClient.Builder = OkHttpClient.Builder() private var mBuilder: Retrofit.Builder? = null fun <S> createService(serviceClass: Class<S>): S { mHttpClient.let { if (BuildConfig.DEBUG) { mLogging.level = HttpLoggingInterceptor.Level.BODY mHttpClient.addInterceptor(mLogging) mHttpClient.addNetworkInterceptor(StethoInterceptor()) } mHttpClient.addInterceptor { chain -> //val language = AppPreferences.language ?: "en" val language = Locale.getDefault().language val url = chain.request().url().newBuilder() .addQueryParameter("api_key", BuildConfig.API_KEY) .addQueryParameter("language", language) .build() val request = chain.request().newBuilder() .addHeader("Accept", "application/json") .addHeader("Content-type", "application/json") .url(url) .build() chain.proceed(request) } } if (mGsonFactory == null) { mGsonFactory = GsonConverterFactory.create() } mBuilder = Retrofit.Builder() .baseUrl(BuildConfig.HOST) .addCallAdapterFactory(LiveDataCallAdapterFactory()) .addConverterFactory(mGsonFactory!!) val client = mHttpClient.build() val retrofit = mBuilder!!.client(client).build() return retrofit.create(serviceClass) } } }
0
Kotlin
0
0
cea8027b9d8676649843d76e31313cd2a94dd5c3
2,298
MovieTrends
Apache License 2.0
buildSrc/src/main/java/Coordinates.kt
CostaFot
376,393,535
false
null
object AppCoordinates { const val APP_ID = "com.feelsokman.androidtemplate" const val APP_VERSION_NAME = "1.0.0" const val APP_VERSION_CODE = 1 } object Sdk { const val MIN_SDK_VERSION = 23 const val TARGET_SDK_VERSION = 30 const val COMPILE_SDK_VERSION = 30 }
0
Kotlin
0
0
f1ead067a2936caf41dcb59a980ac3174fd76347
288
android-template-compose
Apache License 2.0
applications/iot-event-dashboard/src/main/kotlin/com/github/ggreen/iot/event/dashboard/processor/controllers/SensorConditionSummariesSseController.kt
ggreen
509,500,435
false
null
package com.github.ggreen.iot.event.dashboard.controllers import com.github.ggreen.iot.event.dashboard.domains.analytics.ConditionSummaries import com.github.ggreen.iot.event.dashboard.repositories.ConditionSummaryRepository import org.springframework.http.codec.ServerSentEvent import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Flux import java.time.Duration /** * @author <NAME> */ @RestController class SensorConditionSummariesSseController(private val repository: ConditionSummaryRepository) { @GetMapping("/summaries-sse") fun summaries(): Flux<ServerSentEvent<ConditionSummaries>>? { return Flux.interval(Duration.ofSeconds(1)) .map<ServerSentEvent<ConditionSummaries>> { sequence: Long -> val builder = ServerSentEvent.builder<ConditionSummaries>() builder.id(sequence.toString()) builder.data(repository.findTotalConditionSummaries()) builder.build() } } @GetMapping("/summariesGroupBy-sse") fun summariesGroupBy(): Flux<ServerSentEvent<Iterable<ConditionSummaries>>>? { return Flux.interval(Duration.ofSeconds(2)) .map<ServerSentEvent<Iterable<ConditionSummaries>>> { sequence: Long -> val builder = ServerSentEvent.builder<Iterable<ConditionSummaries>>() builder.id(sequence.toString()) builder.data(repository.findConditionSummariesGroupNyName()) builder.build() } } }
0
Kotlin
0
0
73c49136d66a8684353ba3add7d4dbf4cff9a2b1
1,603
iot-sensor-events-showcase
Apache License 2.0
src/com/visualdust/deliveryBackYard/infoManagement/Extension.kt
nekumiya
232,745,537
false
{"Kotlin": 53909, "Java": 20629, "Roff": 1}
package com.visualdust.deliveryBackYard.infoManagement import com.visualdust.deliveryBackYard.common.EventRW import java.lang.Exception /** * @author VisualDust * @since 0.0.0.1 * last update on 20200105 */ class Extension<K, T> : ITagManage<K, T> { var map: MutableMap<K, T> = HashMap<K, T>() /** *<p>Will be transformed into addTag(key: K, value: T):Unit *</p> * @see addTag */ public override fun addTag(tag: Tag<K, T>): T? = addTag(tag.key, tag.value) public fun addTag(key: K, value: T) = map.put(key, value) public override fun removeTag(tagKey: K) { if (map.remove(tagKey) == null) EventRW.Write(Exception("$this : exception occurred when removing $tagKey, cause key not found")) } /** * <p> will be transform into setValueOfKey(key: String, value: String):Unit * </p> * @see setValueOfKey */ public fun setValueOf(tag: Tag<K, T>) = setValueOfKey(tag.key, tag.value) public override fun setValueOfKey(key: K, value: T) { if (map.get(key) == null) map.put(key, value) else map.set(key, value) } public override fun checkIfThereIs(key: K): Boolean = map.get(key) != null public override fun getValueOf(key: K): T? { if (checkIfThereIs(key)) return map.getValue(key) else return null } }
0
null
0
0
3c8b36d2327bfff2dbecade3104fc62c3f9c6b6a
1,396
IoTBackYard
MIT License
app/src/androidTest/java/io/demars/stellarwallet/encryption/KeyStoreWrapperTest.kt
DEMARS-MU
169,842,814
false
null
package io.demars.stellarwallet.encryption import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class KeyStoreWrapperTest { private val aliases = arrayOf("1234", "5678", "0987") @Test fun clear_aliases() { val context = InstrumentationRegistry.getInstrumentation().context val keyStoreWrapper = KeyStoreWrapper(context) aliases.forEach { keyStoreWrapper.createAndroidKeyStoreAsymmetricKey(it) } aliases.forEach { assert(keyStoreWrapper.getAndroidKeyStoreAsymmetricKeyPair(it) != null) } keyStoreWrapper.clear() aliases.forEach { assert(keyStoreWrapper.getAndroidKeyStoreAsymmetricKeyPair(it) == null) } } }
0
Kotlin
0
2
33d586d8f9a0c213d299ed28398ada42e26ca8da
880
DMC-Stellar-Android-Wallet
MIT License
src/main/kotlin/ac/github/oa/internal/core/attribute/Abstract.kt
Man297
542,411,142
false
null
package ac.github.oa.internal.core.attribute annotation class Abstract()
0
Kotlin
0
0
e2dac46ab0680dd1fc4eebdfce4e7680302364f0
74
OriginAttributes_Test
Creative Commons Zero v1.0 Universal
src/test/kotlin/RosieBreadthFirstSearchTest.kt
jimandreas
377,843,697
false
null
@file:Suppress( "UNUSED_VARIABLE", "MemberVisibilityCanBePrivate", "UNUSED_PARAMETER", "unused", "ReplaceManualRangeWithIndicesCalls" ) import algorithms.RosalindSearch import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import kotlin.collections.set import kotlin.test.assertEquals /** * * Breadth First Search * rosalind: http://rosalind.info/problems/bfs/ * Note: not part of the stepik cirriculum. */ internal class RosieBreadthFirstSearchTest { lateinit var rbfs: RosalindSearch @BeforeEach fun setUp() { rbfs = RosalindSearch() } // example from: // hhttp://rosalind.info/problems/bfs/ @Test @DisplayName("Rosalind Breadth First sample test") fun rosalindBreadthFirstSampleTest() { val sampleInput = """ 6 6 4 6 6 5 4 3 3 5 2 1 1 4 """.trimIndent() val expectedOutputString = """ 0 -1 2 1 3 2 """.trimIndent() val input = sampleInput.reader().readLines().toMutableList() val numNodes = input[0].split(" ").first().toInt() input.removeFirst() val m = parseGraphInput(numNodes, input) val expectedResultIntegerList = expectedOutputString.reader().readLines()[0].split(" ") .map { it.toInt() } // note that node numbers start at 1 val result = rbfs.doSearches(numNodes, m) assertEquals(expectedResultIntegerList, result) } // example from: // hhttp://rosalind.info/problems/bfs/ @Test @DisplayName("Rosalind Breadth First cyclic graph test") fun rosalindBreadthFirstCyclicGraphTest() { val sampleInput = """ 6 6 4 6 6 5 4 3 3 5 3 1 1 4 """.trimIndent() val expectedOutputString = """ 0 -1 2 1 3 2 """.trimIndent() val input = sampleInput.reader().readLines().toMutableList() val numNodes = input[0].split(" ").first().toInt() input.removeFirst() val m = parseGraphInput(numNodes, input) val expectedResultIntegerList = expectedOutputString.reader().readLines()[0].split(" ") .map { it.toInt() } // note that node numbers start at 1 val result = rbfs.doSearches(numNodes, m) assertEquals(expectedResultIntegerList, result) } /** * take the list of edges (from to) and convert to a map of the base node to the list of connected * nodes. */ private fun parseGraphInput(numNodes: Int, lines: List<String>): HashMap<Int, MutableList<Int>> { val map: HashMap<Int, MutableList<Int>> = hashMapOf() // make sure all nodes have a list for (i in 0 until numNodes + 1) { map[i] = mutableListOf() } for (l in lines) { val p = l.split(" ").map { it.toInt() } map[p[0]]!!.add(p[1]) } return map } // example from: // hhttp://rosalind.info/problems/bfs/ @Test @DisplayName("Rosalind Breadth First cyclic quiz test") fun rosalindBreadthFirstQuizGraphTest() { val sampleInput = """ 839 2874 506 568 716 782 33 629 96 536 407 169 182 1 728 420 133 579 44 469 525 557 177 252 681 700 403 504 190 415 562 348 736 663 735 380 278 152 120 700 725 310 191 51 800 408 508 488 715 192 181 437 208 654 319 618 675 741 218 238 643 396 492 78 166 732 174 187 552 737 622 640 58 807 592 435 81 36 559 716 121 304 68 806 342 333 700 457 403 187 646 478 8 94 264 40 525 381 546 25 785 205 168 418 276 493 78 49 769 206 338 281 356 200 356 517 655 675 180 600 236 837 807 702 383 13 424 445 482 536 671 181 594 700 15 108 185 659 367 569 208 265 373 119 452 55 663 418 755 694 596 740 381 104 734 227 33 838 11 390 503 794 678 81 147 59 537 726 517 477 187 534 757 494 832 118 446 448 671 178 450 584 90 149 809 23 368 146 740 44 282 708 250 237 329 679 412 574 682 101 576 736 313 510 759 113 545 368 730 361 272 22 276 808 557 30 188 711 445 122 818 756 375 178 213 142 450 720 436 761 453 549 682 753 185 498 424 598 479 549 72 432 746 815 468 489 325 416 1 679 2 330 577 20 55 756 122 782 583 655 801 748 549 70 74 38 478 90 115 229 794 456 339 515 156 512 606 455 593 5 208 464 651 222 107 451 493 647 243 246 500 719 763 668 360 442 693 408 233 519 198 531 826 59 39 520 616 140 122 777 141 519 199 127 474 81 826 170 646 556 564 538 746 389 429 303 712 269 659 262 646 831 771 545 95 79 353 420 188 725 411 4 716 380 238 573 78 625 706 166 286 803 202 522 220 725 354 159 69 232 579 262 1 685 818 179 838 570 200 409 449 827 780 742 86 302 275 139 72 30 255 790 309 735 832 414 405 236 131 757 337 238 255 638 449 121 231 67 551 623 560 130 136 223 193 648 325 411 372 204 737 75 627 788 591 826 44 744 245 724 100 700 391 32 569 293 71 493 491 572 274 529 518 739 78 417 650 110 230 781 194 162 361 517 380 153 290 196 92 659 493 150 115 105 777 308 727 779 506 822 488 298 696 184 131 838 762 528 727 760 158 685 822 25 695 261 22 820 117 636 298 166 322 288 624 608 89 833 177 429 576 136 82 10 446 140 357 132 105 833 142 645 76 748 700 105 629 445 298 472 155 522 163 401 715 684 37 125 330 386 645 807 65 364 429 78 430 420 808 735 271 193 407 635 747 691 516 713 193 293 522 71 781 389 655 801 776 592 210 788 266 514 447 412 621 652 803 396 490 737 201 660 3 353 264 478 214 488 548 472 309 529 455 93 538 428 710 808 61 806 408 382 616 632 338 3 301 141 608 102 621 430 696 710 414 706 805 525 815 118 614 578 831 216 392 722 671 84 304 14 196 116 473 380 456 260 494 757 9 693 215 169 437 159 100 705 361 282 495 835 47 427 105 336 251 145 363 443 491 213 652 725 616 384 448 757 334 604 771 180 20 382 79 422 264 808 797 66 508 826 686 671 586 566 251 817 555 16 41 109 666 53 64 136 423 800 616 2 545 26 468 703 272 705 659 217 742 507 181 170 749 694 255 61 661 282 439 785 776 779 615 781 622 193 474 324 628 680 98 772 389 5 514 201 240 552 205 327 427 512 636 84 67 124 328 656 402 84 367 209 740 490 352 31 603 463 620 545 429 638 665 672 338 306 818 437 485 439 269 800 587 331 274 301 148 140 539 347 242 395 368 123 530 122 197 601 552 19 165 410 419 595 807 503 350 467 407 461 173 21 191 769 602 664 701 425 641 199 813 453 69 719 352 258 637 370 605 702 56 240 353 485 81 152 206 634 193 156 285 676 471 594 312 404 166 818 445 625 834 415 449 525 394 723 604 342 569 748 804 176 272 353 793 590 115 771 425 255 63 547 797 260 25 218 327 221 74 107 55 586 334 804 578 94 502 467 106 792 70 156 630 673 280 597 447 422 824 583 150 404 146 408 601 596 94 55 668 309 523 337 547 262 123 581 366 189 370 631 116 119 335 791 191 50 525 782 320 413 54 624 255 191 340 341 395 499 324 427 53 174 109 833 768 152 628 121 369 73 573 712 835 372 671 456 585 700 674 810 711 36 694 100 159 822 257 359 131 48 78 201 238 134 282 172 407 562 393 314 158 748 144 266 648 747 422 746 498 529 319 443 291 174 452 88 290 773 607 704 80 433 354 176 411 756 280 606 255 272 420 827 478 586 390 45 679 579 559 724 248 70 264 207 455 37 39 159 374 593 122 281 260 406 568 691 132 402 427 771 157 438 30 188 625 204 370 331 116 720 49 59 395 382 90 439 36 786 292 356 718 391 535 215 131 62 424 52 23 500 80 726 506 779 456 613 111 730 93 827 593 242 650 255 132 71 173 312 155 567 249 50 40 556 513 366 474 642 799 829 168 541 426 545 597 817 747 108 14 470 49 795 42 593 389 135 746 812 339 142 358 820 752 571 624 320 53 298 296 239 662 573 771 720 421 321 612 31 795 92 634 236 155 374 154 754 269 450 162 284 405 825 536 454 772 495 572 22 620 94 41 119 437 498 768 323 759 836 408 638 61 412 145 27 191 167 412 381 514 725 198 330 292 208 256 785 810 661 579 541 485 599 624 327 734 443 129 341 55 670 352 725 49 556 171 574 9 487 407 136 740 1 87 41 732 290 571 177 771 476 193 4 810 33 264 688 229 718 203 456 149 705 331 546 336 669 787 43 598 179 394 398 108 401 53 69 729 177 98 299 537 345 833 296 445 759 636 155 231 156 358 620 108 284 695 515 739 130 334 16 104 54 251 825 124 41 457 48 222 447 765 229 387 499 826 404 683 5 773 838 300 748 724 638 489 240 625 377 661 139 680 310 222 279 24 239 244 800 562 351 63 54 270 771 734 825 110 119 241 689 644 747 577 213 389 106 230 294 291 619 543 768 95 205 78 576 779 782 744 124 452 574 548 427 273 165 248 774 231 146 242 626 424 337 722 830 173 277 339 85 799 60 105 269 802 445 179 457 271 34 3 234 745 234 218 528 770 264 831 30 106 495 100 732 471 509 239 458 831 694 523 148 836 792 230 59 33 384 786 139 30 379 663 254 385 515 48 335 50 544 13 421 735 415 433 666 274 454 69 321 481 266 303 620 514 688 515 761 432 182 479 526 338 113 11 224 31 603 178 189 766 564 357 611 80 338 46 305 505 478 694 365 453 812 568 826 610 815 232 402 84 530 303 644 234 669 217 273 499 818 794 795 485 81 532 139 112 73 39 389 816 500 817 336 124 358 622 587 769 600 86 303 835 116 658 432 14 794 421 737 115 266 833 587 580 702 501 344 193 31 485 388 17 139 771 82 499 366 741 211 742 745 69 501 620 497 383 149 365 394 55 775 124 398 98 7 722 512 284 43 624 574 695 727 149 542 24 750 764 772 723 44 580 483 28 32 377 53 46 450 696 10 132 457 244 504 615 780 229 364 820 427 288 268 270 347 569 363 316 685 479 163 30 500 835 155 837 163 251 650 31 141 376 285 293 316 719 623 703 810 753 683 296 383 666 354 27 804 449 135 275 72 149 180 649 705 525 110 504 38 251 530 739 435 575 66 118 491 301 95 417 85 509 711 436 593 504 260 638 171 290 131 754 767 828 90 519 374 371 651 483 325 319 614 107 574 808 22 826 477 510 158 154 380 318 17 525 103 551 566 682 252 292 683 795 567 78 689 63 733 815 119 229 523 375 29 199 754 554 434 648 766 663 366 187 145 741 21 579 797 653 574 126 824 272 497 24 370 754 384 750 603 164 791 491 833 553 222 39 540 244 722 461 116 351 725 306 470 751 802 735 489 210 561 192 401 447 635 526 449 711 368 821 208 52 584 695 332 39 232 24 191 408 756 484 508 527 98 459 444 291 714 384 775 578 800 371 665 655 407 836 248 656 270 824 736 641 510 474 146 525 409 765 746 463 70 400 790 811 398 562 158 343 254 588 244 664 626 294 422 446 310 116 453 657 504 159 205 292 85 772 386 439 390 404 164 315 323 124 772 266 305 235 165 737 366 60 726 540 680 562 765 190 650 818 156 130 772 481 419 85 400 395 639 481 408 269 549 308 395 132 246 776 306 613 640 264 781 564 527 781 63 696 160 239 376 370 505 388 805 321 334 413 736 432 156 509 560 133 506 725 749 302 662 88 83 86 482 700 829 682 208 689 130 9 605 391 62 582 664 146 21 611 347 774 517 370 42 836 838 216 700 472 550 365 46 392 335 238 582 21 745 527 238 509 336 398 822 516 775 3 281 497 6 795 174 619 41 732 437 567 482 455 750 354 376 139 531 546 177 303 305 322 647 458 266 573 94 685 207 374 238 412 463 72 18 91 648 258 46 332 233 780 820 638 399 463 257 625 645 330 518 149 808 711 444 270 585 548 496 661 225 610 250 205 705 68 723 805 25 799 612 344 124 548 113 454 387 554 462 521 414 831 185 233 748 515 527 143 342 826 283 332 603 480 302 522 589 604 48 427 316 68 109 270 282 693 680 6 12 511 468 98 110 138 127 638 257 143 441 538 3 760 143 78 742 727 178 268 491 343 801 804 309 327 61 132 61 395 112 117 84 7 469 248 285 569 403 823 87 769 772 129 562 98 246 302 621 444 283 265 82 159 650 274 160 150 534 583 50 272 736 810 474 794 432 601 183 136 741 451 335 676 487 438 491 268 548 306 713 92 218 148 687 512 432 460 35 595 744 83 543 121 139 237 248 285 136 754 452 59 205 519 452 727 762 671 153 233 338 825 809 313 432 365 494 417 47 271 363 554 117 24 258 646 429 800 616 564 46 69 648 179 19 363 359 164 41 538 378 760 454 336 643 572 533 178 816 17 547 397 18 609 362 691 251 479 353 480 674 502 217 397 728 272 265 458 781 459 476 313 441 204 627 667 77 564 585 480 71 485 256 140 784 161 800 329 627 455 578 637 339 322 424 80 53 705 476 137 639 86 416 604 51 623 635 637 799 3 355 260 773 530 474 678 247 594 392 13 76 324 60 471 362 772 434 132 452 439 712 214 691 11 58 609 250 438 479 296 282 412 797 234 813 698 534 826 425 810 303 351 502 8 296 192 517 89 221 157 675 787 723 511 764 447 787 90 617 72 212 821 734 73 5 654 811 489 13 252 575 680 418 774 779 314 224 142 783 80 645 823 287 599 798 715 415 646 544 207 732 433 695 604 807 733 581 314 719 137 263 760 40 688 330 82 628 160 787 124 92 343 584 698 226 486 114 303 634 667 251 17 82 291 527 626 13 37 31 421 432 80 766 83 689 63 304 302 141 819 728 828 84 364 318 78 727 366 217 762 89 201 649 643 192 55 630 342 614 657 449 564 9 378 36 33 28 311 568 593 527 151 740 8 334 285 681 327 487 511 813 262 440 83 694 123 585 566 384 325 360 18 234 219 416 22 791 207 674 281 210 154 832 211 218 46 775 675 619 715 282 91 593 129 6 651 734 557 393 280 331 83 404 411 413 158 364 364 475 424 630 386 213 78 519 183 167 139 311 128 516 373 468 164 516 430 464 451 374 735 368 684 229 299 724 366 109 449 700 837 513 824 416 713 536 733 592 5 191 587 579 141 720 62 824 491 832 184 53 187 459 540 398 563 788 821 537 348 126 370 175 210 558 484 752 729 250 415 822 587 244 553 593 703 287 529 469 606 35 795 124 184 379 388 397 506 772 34 175 437 462 136 333 250 544 162 75 825 761 560 98 317 344 542 190 100 661 737 728 362 529 153 498 281 165 726 528 503 290 694 339 629 459 483 676 728 383 601 247 253 216 436 408 49 533 837 143 214 423 646 325 615 14 323 662 125 286 586 784 91 89 598 41 424 649 296 606 535 230 227 531 798 389 138 759 472 544 471 231 326 229 127 577 222 449 99 780 574 165 706 402 333 729 86 538 819 356 810 115 287 785 534 130 295 266 464 238 7 150 544 104 620 323 606 250 678 167 274 665 763 380 578 414 724 353 290 397 581 115 68 791 272 640 285 496 623 809 310 395 345 479 184 282 371 623 427 193 654 117 692 168 308 689 826 76 94 589 576 47 693 87 549 269 321 388 353 137 636 135 601 483 658 353 821 750 127 171 20 684 419 716 355 129 466 161 272 469 807 138 538 359 408 29 145 16 266 610 729 61 610 735 534 22 795 627 667 806 634 319 267 750 92 423 167 783 332 456 116 45 209 72 341 571 487 646 489 803 588 678 579 403 228 67 839 424 54 451 739 236 718 588 119 700 360 82 432 727 608 43 84 589 58 651 150 235 480 670 63 480 33 258 414 129 788 601 634 170 668 361 744 458 338 26 530 701 766 605 508 91 437 299 457 421 114 254 22 223 388 448 317 486 134 740 818 483 486 381 734 122 773 376 223 305 223 135 317 87 105 95 30 804 551 616 1 449 821 686 313 752 775 661 280 125 738 793 620 423 353 135 711 807 271 252 717 796 409 594 284 121 103 674 217 599 192 141 636 342 89 571 164 406 827 580 80 17 287 754 473 415 165 12 349 490 704 588 835 668 513 423 73 504 133 109 735 586 150 665 814 266 444 625 78 218 785 587 146 113 148 704 738 32 668 238 227 102 533 723 236 770 522 742 186 596 172 615 87 835 435 601 60 506 523 57 790 411 684 12 473 41 821 715 384 227 352 354 556 547 463 539 529 583 640 590 423 275 79 102 135 415 364 216 456 367 383 225 516 413 702 338 834 447 28 727 359 376 309 457 3 499 11 537 84 750 217 29 97 365 722 814 209 318 671 538 157 54 362 795 117 360 385 651 498 788 621 237 451 524 206 229 289 343 309 417 402 411 3 363 521 156 106 124 636 526 352 773 182 682 437 13 413 237 632 307 226 166 484 593 107 105 696 5 507 691 286 648 57 26 779 533 63 84 11 505 451 187 749 587 649 725 383 132 29 245 529 308 681 241 573 366 75 116 796 198 119 114 168 107 393 541 637 55 450 131 468 230 471 204 322 426 77 341 244 506 762 789 746 465 127 421 473 774 6 665 578 310 759 160 669 109 724 563 162 808 107 396 69 169 487 377 471 387 642 621 310 466 425 837 102 16 671 266 305 242 144 550 181 431 199 64 759 733 547 594 335 15 48 737 567 111 117 394 311 230 66 506 573 698 832 636 297 701 816 411 566 311 137 87 433 132 647 576 282 609 781 590 799 115 692 95 654 658 567 520 398 166 112 310 130 397 793 763 467 52 503 818 382 161 292 137 258 489 28 214 174 173 414 522 201 702 717 264 667 395 78 695 355 603 238 330 490 145 312 131 6 510 600 67 546 3 692 38 306 242 254 260 127 200 475 835 539 445 246 514 743 320 229 389 467 390 361 21 70 801 769 657 185 474 386 173 675 369 32 733 732 467 12 142 329 378 457 832 521 161 498 505 81 39 155 824 445 137 355 426 598 815 31 559 495 655 252 373 309 580 534 7 826 708 186 298 48 341 728 63 268 533 568 680 810 557 463 1 598 147 701 113 505 379 509 323 454 251 368 120 630 703 668 69 119 190 784 484 736 253 489 117 818 692 497 85 410 778 748 605 732 679 737 130 666 142 561 476 588 710 19 322 111 253 442 420 190 825 46 727 160 642 657 399 1 86 39 449 5 652 405 759 85 712 235 308 19 544 613 730 702 146 560 114 689 708 7 809 389 766 49 40 324 691 777 582 98 426 449 330 319 429 376 674 767 404 566 379 496 753 468 533 417 763 756 391 663 757 626 705 544 676 564 754 378 262 359 247 440 819 718 127 578 415 410 419 414 753 436 329 93 824 8 112 245 621 584 462 31 725 238 580 539 409 44 115 527 232 33 201 568 503 579 599 492 797 114 577 62 481 598 279 431 180 787 17 310 272 441 26 813 391 45 594 623 817 595 807 349 786 686 222 547 715 87 130 452 176 4 694 355 273 433 591 451 168 34 176 14 529 643 492 442 759 422 508 372 414 769 263 415 728 821 581 718 803 575 576 591 545 304 787 476 510 615 451 583 640 419 756 367 351 111 167 4 432 557 326 504 717 543 669 217 764 533 711 662 789 665 650 813 780 751 469 248 722 194 530 174 115 568 570 594 19 744 113 137 101 429 95 442 609 385 677 228 305 362 501 727 130 12 741 592 212 386 527 439 827 775 264 707 110 601 759 147 666 189 608 171 157 545 392 447 365 255 318 419 113 772 254 738 369 320 213 746 772 285 830 405 525 221 214 339 688 261 687 389 437 193 829 621 628 307 724 550 270 638 80 648 205 665 817 408 551 118 347 28 572 17 482 695 558 510 383 682 468 481 765 811 713 675 696 655 315 624 272 257 314 813 346 281 428 264 468 428 325 733 254 640 298 53 267 630 543 121 376 408 703 742 681 528 656 18 37 583 483 368 418 439 777 24 167 64 233 64 517 211 163 768 200 22 532 46 482 118 694 121 709 270 237 112 507 369 601 27 456 794 146 730 716 23 228 491 74 73 571 270 124 168 769 153 56 829 498 800 364 587 632 180 348 220 480 276 676 817 114 12 123 454 171 454 380 690 6 621 211 34 239 362 672 401 379 666 47 83 211 391 833 197 754 218 649 827 557 419 520 573 1 98 483 530 8 265 146 105 339 674 55 694 714 277 437 758 182 244 501 281 728 122 163 690 772 603 109 18 477 825 27 608 389 77 307 793 194 192 549 705 96 374 574 437 782 235 785 240 105 410 266 523 54 335 764 301 113 433 502 179 259 179 246 28 72 477 570 369 784 103 314 803 663 436 257 283 440 317 2 290 592 488 806 40 462 45 270 273 119 542 371 699 330 665 385 651 569 323 718 272 368 594 121 422 156 598 5 497 707 126 479 399 201 700 621 20 146 455 358 578 113 561 15 27 800 376 382 583 303 435 519 679 792 95 154 280 580 723 216 523 410 414 537 399 837 404 822 259 600 561 794 685 364 686 496 744 535 489 195 255 538 112 161 157 791 336 570 35 389 715 359 813 153 594 258 799 762 484 337 674 599 660 444 273 409 555 245 403 384 467 602 557 84 776 624 816 82 619 525 712 590 620 756 566 279 752 170 823 330 533 27 475 504 256 610 31 260 105 190 30 560 200 326 716 23 497 335 618 171 375 26 675 621 584 609 388 103 772 782 222 828 337 153 743 330 30 281 409 593 770 263 312 94 735 742 115 92 335 244 686 836 268 326 453 153 221 290 39 426 131 669 461 702 671 799 471 751 343 702 291 451 240 351 628 344 612 207 261 743 30 398 546 599 514 396 360 538 572 807 330 722 770 636 64 385 780 463 673 131 675 739 158 341 645 25 681 278 277 648 38 745 488 732 583 92 264 356 348 563 628 304 221 230 54 322 199 330 335 729 229 561 657 107 17 91 641 721 398 6 636 236 14 651 435 63 53 530 765 374 216 142 36 483 662 299 25 483 689 772 392 537 384 600 491 389 717 313 700 343 475 633 136 137 505 33 362 506 429 724 604 715 741 585 460 783 30 483 52 351 552 213 254 669 19 760 494 236 703 407 739 650 294 344 70 147 771 417 542 161 503 578 804 90 808 755 588 804 19 108 628 262 517 352 500 452 65 254 323 664 209 827 738 131 250 225 445 691 93 371 663 374 372 540 124 1 70 77 759 363 141 492 776 79 170 290 725 633 554 21 512 687 345 325 76 550 114 583 501 133 393 772 488 134 490 99 589 725 455 803 69 338 683 8 169 766 648 210 259 134 704 324 371 704 200 221 483 282 249 617 499 839 260 175 353 539 541 298 190 808 708 411 262 64 710 569 552 679 149 812 758 725 569 676 399 692 127 787 684 51 380 512 795 80 381 359 269 510 142 425 734 71 594 682 39 724 459 615 780 283 51 186 108 441 654 209 491 150 792 600 153 372 430 290 361 678 57 744 682 741 4 838 410 328 151 220 409 485 190 105 266 501 12 211 808 257 452 343 330 660 402 466 719 691 353 128 315 585 15 247 180 200 132 49 618 248 653 28 671 461 820 454 325 544 697 194 642 709 240 248 191 222 115 83 832 65 360 279 698 630 221 821 274 369 517 307 579 380 28 256 43 649 456 61 789 628 521 206 157 628 301 623 360 53 821 771 346 677 310 402 590 143 41 337 134 145 140 536 66 379 194 164 104 399 33 575 152 473 164 38 510 373 517 427 258 63 703 558 117 663 808 787 675 201 416 650 550 45 553 351 534 235 661 74 65 802 86 663 199 219 312 336 406 595 796 788 64 837 175 329 802 79 330 162 591 635 425 654 768 614 380 745 243 793 705 553 631 26 745 658 174 713 12 105 693 589 839 628 398 476 398 785 3 374 521 367 830 483 98 680 700 256 389 690 411 134 231 313 434 464 622 698 366 597 58 266 441 386 632 288 339 507 281 233 751 724 535 523 130 469 115 657 295 504 98 321 463 540 209 661 122 331 123 603 244 279 635 468 51 592 427 277 256 71 301 478 172 752 327 585 308 525 226 146 122 483 468 798 752 796 771 60 257 105 701 504 761 597 298 317 580 692 88 818 801 450 587 497 806 93 661 379 510 803 277 284 443 601 137 55 231 560 444 826 164 277 386 827 353 308 462 139 500 567 193 291 733 20 833 709 282 574 100 793 220 504 720 305 494 60 386 93 152 317 774 205 706 530 301 334 801 475 87 738 98 44 276 425 379 422 34 285 486 494 363 656 644 457 476 542 704 595 669 479 619 509 196 346 658 691 492 331 681 722 97 267 616 175 708 138 139 234 752 778 20 148 721 1 212 670 154 40 597 772 193 582 39 41 123 624 577 133 358 732 162 638 472 453 551 519 789 397 440 697 647 112 425 817 108 739 240 299 59 404 520 130 684 251 567 574 355 34 610 737 776 471 551 118 595 234 23 621 140 535 102 563 287 253 108 385 202 263 425 646 349 84 81 734 742 222 444 723 1 317 630 704 742 356 66 572 381 287 793 583 184 257 150 690 392 434 780 144 450 152 270 834 552 250 455 547 591 517 209 295 17 447 734 348 106 814 40 445 646 205 480 164 557 542 638 735 725 7 323 558 110 299 608 672 401 358 761 792 562 676 177 536 397 754 70 408 76 713 244 256 421 834 189 709 703 234 781 23 674 51 508 464 609 443 704 401 151 483 787 385 474 339 398 648 721 133 333 172 373 288 290 496 241 190 696 378 515 734 206 320 762 7 10 96 156 652 657 558 454 425 440 317 833 38 191 48 358 414 512 401 142 52 258 465 649 280 192 247 836 253 328 279 551 300 5 205 311 599 49 419 736 355 310 266 292 734 376 114 125 767 589 698 399 191 337 690 558 399 389 501 447 756 588 113 801 256 234 604 1 639 756 12 269 187 703 35 807 548 330 455 349 297 574 361 426 774 134 32 523 534 600 281 376 558 68 343 51 313 53 331 739 721 596 731 193 88 30 480 548 168 254 201 179 448 666 322 479 684 600 567 122 464 270 258 454 559 92 147 438 387 791 222 814 37 413 223 217 364 183 579 777 63 672 264 411 348 747 147 379 342 830 48 201 800 272 784 789 346 439 209 238 307 426 142 708 270 304 567 505 410 398 128 238 14 368 25 595 715 355 814 223 103 530 195 677 741 201 719 39 392 699 178 221 95 189 768 650 274 632 185 660 772 20 561 331 784 198 426 677 453 41 381 834 761 639 693 52 302 257 419 276 505 171 741 264 171 47 629 545 814 196 176 270 268 402 329 756 581 478 228 300 406 447 449 605 242 146 505 667 108 333 613 669 566 584 573 141 520 694 550 93 324 612 454 45 172 129 620 324 562 552 203 272 456 510 328 368 23 497 543 481 744 28 576 359 828 69 545 271 655 277 692 345 115 812 686 512 246 501 150 47 30 654 242 124 246 749 336 418 192 59 734 336 628 45 585 181 332 9 627 105 140 767 316 218 494 149 449 225 827 634 99 320 306 428 632 325 559 641 422 346 420 603 99 571 37 538 806 777 268 373 366 488 664 285 765 162 585 133 82 810 332 393 830 320 615 802 194 714 800 490 93 678 207 330 668 528 513 501 469 637 603 14 55 485 684 490 275 787 142 728 401 477 55 615 753 323 347 252 83 805 286 716 181 22 77 297 15 208 606 779 578 180 103 34 801 687 592 263 724 253 711 269 749 438 172 593 267 805 524 245 777 376 163 837 506 17 343 324 754 358 208 533 727 27 538 496 65 4 250 717 247 546 271 235 371 490 745 494 703 65 826 393 808 429 79 103 583 567 723 668 653 355 666 144 710 307 329 515 355 598 271 259 234 317 501 392 383 339 549 605 505 110 3 292 98 794 236 116 656 270 702 570 829 94 66 44 837 192 421 836 67 838 347 688 757 839 765 207 414 721 562 352 257 351 29 172 494 106 102 792 417 500 786 636 359 93 683 250 396 639 234 235 653 35 376 453 612 5 230 79 99 812 839 373 791 355 308 268 792 285 150 52 135 733 482 20 627 55 780 337 100 233 320 715 552 39 280 497 417 632 740 743 772 425 507 821 721 382 498 475 188 695 249 836 710 48 767 255 816 273 97 60 367 206 608 482 610 763 168 122 16 433 411 839 23 435 245 757 791 494 287 498 473 298 10 706 328 282 317 174 369 801 548 573 295 202 59 658 561 738 659 100 500 287 358 697 305 653 561 442 832 629 663 166 743 502 595 361 747 654 815 170 738 206 619 617 666 184 442 228 748 708 568 321 598 709 418 152 260 744 200 552 527 519 803 205 652 538 558 675 118 136 652 28 490 47 446 801 379 768 39 700 623 679 645 237 635 540 333 360 175 184 775 760 486 328 726 616 778 234 334 555 440 96 716 479 608 390 211 232 750 384 339 827 249 594 804 616 595 672 325 641 381 790 736 311 370 810 575 585 122 290 660 320 693 605 703 143 223 77 220 776 626 689 791 816 665 84 370 654 2 583 104 418 743 609 643 187 635 762 438 565 744 470 691 31 243 336 563 """.trimIndent() val expectedOutputString = """ 0 2 3 6 5 5 5 6 8 5 -1 5 5 4 6 4 4 5 5 5 5 5 5 -1 3 5 6 5 4 4 5 4 5 5 5 4 4 5 6 6 3 6 5 6 5 6 4 4 6 4 4 5 6 5 4 5 7 -1 6 4 5 5 5 4 5 4 4 -1 4 6 4 6 5 6 4 6 6 5 5 5 5 4 6 4 4 1 2 6 6 5 5 4 4 4 4 6 6 5 4 5 6 6 3 4 3 6 6 5 4 3 5 6 5 3 5 4 6 5 4 6 2 5 6 3 5 7 5 5 4 3 4 6 3 5 2 5 5 4 3 4 3 4 6 5 5 5 5 6 6 3 -1 6 4 5 4 6 6 6 5 5 5 3 4 5 5 5 6 5 5 4 5 6 4 7 5 5 7 7 6 7 7 6 6 8 5 5 4 4 4 4 5 4 6 5 6 5 -1 7 -1 6 4 -1 6 5 5 7 2 5 6 5 4 6 4 6 6 3 4 4 -1 7 7 5 6 5 5 5 5 6 5 5 -1 5 5 2 4 4 4 4 6 6 6 4 6 6 5 4 4 5 3 4 5 6 5 3 4 3 5 5 7 4 7 3 6 6 6 5 5 6 4 6 7 5 5 4 5 -1 5 6 5 6 4 5 5 4 4 6 4 5 -1 4 7 -1 7 6 5 5 -1 4 4 5 5 2 2 3 3 6 5 5 4 4 4 5 5 4 6 6 1 3 4 5 5 6 4 5 4 4 6 5 6 2 5 5 5 3 5 4 4 5 4 -1 5 4 3 2 5 4 5 6 -1 -1 6 6 4 6 4 6 -1 4 3 5 4 6 4 2 6 3 5 5 4 5 5 4 6 3 -1 3 6 3 5 3 3 4 5 4 5 3 5 5 5 5 4 5 4 7 5 5 4 4 4 5 5 5 3 4 -1 5 5 3 3 6 5 6 6 3 3 2 3 3 6 5 4 6 4 6 5 5 5 3 5 4 8 5 6 5 5 -1 4 7 5 4 6 6 5 4 6 5 5 6 1 5 6 5 4 4 3 6 3 7 5 -1 6 5 5 5 6 5 4 5 3 5 -1 5 5 5 3 5 6 6 4 5 6 2 4 6 4 2 6 7 5 6 6 4 5 3 5 5 4 4 4 5 2 7 4 4 5 4 5 7 8 5 -1 4 6 5 5 6 5 3 4 4 -1 4 6 7 2 5 4 5 5 5 4 6 6 4 5 3 4 2 5 5 3 4 5 5 4 6 4 4 5 6 4 5 7 -1 -1 7 3 3 5 5 5 5 5 7 -1 4 4 5 6 5 6 5 4 4 5 6 4 4 2 3 5 5 4 4 4 5 5 6 3 5 7 5 4 4 6 6 4 6 3 3 5 5 5 3 6 6 -1 5 5 3 -1 5 6 5 6 5 4 5 7 3 3 -1 3 6 5 5 6 4 5 5 6 4 4 3 4 5 -1 4 1 5 -1 6 5 3 2 6 6 5 5 3 5 4 4 6 5 5 6 5 4 3 5 3 2 5 4 5 -1 3 3 5 7 5 6 3 6 5 5 5 1 3 5 5 5 5 1 6 5 5 6 4 5 4 2 6 6 7 5 4 -1 2 6 4 4 6 6 4 5 6 3 6 5 5 7 7 4 6 5 5 5 4 5 3 5 5 4 5 6 4 6 6 7 3 5 6 4 6 4 3 4 5 6 5 4 7 4 6 4 5 5 4 -1 6 4 5 5 4 3 -1 5 6 6 7 4 5 5 6 5 5 6 5 6 4 5 6 5 -1 6 6 5 4 6 3 5 5 4 5 4 5 4 5 4 2 4 5 6 6 3 4 8 5 4 6 4 4 6 3 3 4 4 4 7 5 3 4 4 5 4 5 5 5 8 4 -1 5 5 5 2 4 3 4 7 4 4 5 3 6 5 5 5 """.trimIndent() val input = sampleInput.reader().readLines().toMutableList() val numNodes = input[0].split(" ").first().toInt() input.removeFirst() val m = parseGraphInput(numNodes, input) val expectedResultIntegerList = expectedOutputString.reader().readLines()[0].split(" ") .map { it.toInt() } // note that node numbers start at 1 val result = rbfs.doSearches(numNodes, m) //println(result.joinToString(" ")) assertEquals(expectedResultIntegerList, result) } }
0
Kotlin
0
0
371f10bf537a604f031b3fe4b91203e07ea0e2c6
27,944
stepikBioinformaticsCourse
Apache License 2.0
app/src/main/java/com/workbook/liuwb/workbook/actions/viewdemo/menu/MenuDemoActivity.kt
bobo-lwenb
224,773,966
false
null
package com.workbook.liuwb.workbook.actions.viewdemo.menu import android.os.Bundle import android.view.* import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import com.workbook.liuwb.workbook.R import com.workbook.liuwb.workbook.databinding.ActivityMenuDemoBinding class MenuDemoActivity : AppCompatActivity(), View.OnClickListener, View.OnLongClickListener { private var actionMode: ActionMode? = null private val binding: ActivityMenuDemoBinding by lazy { ActivityMenuDemoBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) setSupportActionBar(binding.menuToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.menuChange.setOnClickListener(this) registerForContextMenu(binding.menuContext) binding.singleContext.setOnLongClickListener(this) } override fun onClick(v: View?) = when (v?.id) { R.id.menu_change -> { invalidateOptionsMenu() } else -> { } } override fun onLongClick(v: View?): Boolean = when (v?.id) { R.id.single_context -> { if (actionMode != null) { false } else { actionMode = startActionMode(callback) v.isSelected = true true } } else -> { false } } /** * 创建toolbar选项菜单 */ override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_demo, menu) val searchItem = menu?.findItem(R.id.menu_main_search) val searchView = searchItem?.actionView as SearchView /** * actionView展开收起监听 */ val expandListener = object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem?): Boolean { return true } override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { return true } } searchItem.setOnActionExpandListener(expandListener) return true } /** * 动态修改选项菜单 * * 在 Android 2.3.x 及更低版本中,每当用户打开选项菜单时(按“菜单”按钮),系统均会调用 onPrepareOptionsMenu()。 * 在 Android 3.0 及更高版本中,当菜单项显示在应用栏中时,选项菜单被视为始终处于打开状态。 发生事件时,如果您要执行菜单更新,则必须调用 invalidateOptionsMenu() 来请求系统调用 onPrepareOptionsMenu()。 * * 然而有些手机不管版本是多少,每当打开选项菜单式都会调用 onPrepareOptionsMenu()。 */ override fun onPrepareOptionsMenu(menu: Menu?): Boolean { menu?.removeItem(R.id.menu_demo_other) menu?.add(0, R.id.menu_demo_other, 0, "other") return super.onPrepareOptionsMenu(menu) } /** * toolbar选项菜单点击 */ override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item?.itemId) { R.id.menu_main_add -> { true } R.id.menu_main_setting -> { true } R.id.menu_main_about -> { true } else -> { super.onOptionsItemSelected(item) } } /** * 创建上下文浮动菜单 */ override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) { super.onCreateContextMenu(menu, v, menuInfo) menuInflater.inflate(R.menu.menu_demo_context, menu) } /** * 上下文浮动菜单点击事件 */ override fun onContextItemSelected(item: MenuItem): Boolean = when (item?.itemId) { R.id.context_about -> { true } R.id.context_setting -> { true } R.id.context_share -> { true } else -> { super.onContextItemSelected(item) } } /** * 为单个视图创建上下文操作模式回调 */ private val callback: ActionMode.Callback = object : ActionMode.Callback { override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean { return false } override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean { mode?.menuInflater?.inflate(R.menu.menu_demo_context, menu) supportActionBar?.hide() return true } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { return false } override fun onDestroyActionMode(mode: ActionMode?) { actionMode = null supportActionBar?.show() } } }
0
Kotlin
0
0
0f5a4da165de6795a8cd3ca073eeb453dab0d646
4,573
WorkBook
Apache License 2.0
src/main/kotlin/com/jscisco/lom/extensions/EntityExtensions.kt
jscisco3
168,425,969
false
null
package com.jscisco.lom.extensions import AnyGameEntity import com.jscisco.lom.attributes.EntityActions import com.jscisco.lom.attributes.EntityPosition import com.jscisco.lom.attributes.EntityTile import com.jscisco.lom.attributes.flags.BlockOccupier import com.jscisco.lom.attributes.flags.VisionBlocker import com.jscisco.lom.attributes.types.Player import com.jscisco.lom.dungeon.GameContext import org.hexworks.amethyst.api.Attribute import org.hexworks.amethyst.api.Consumed import org.hexworks.amethyst.api.Pass import org.hexworks.amethyst.api.Response import org.hexworks.cobalt.datatypes.extensions.map import org.hexworks.cobalt.datatypes.extensions.orElseThrow import org.hexworks.zircon.api.data.Tile inline fun <reified T : Attribute> AnyGameEntity.findAttribute(): T = findAttribute(T::class).orElseThrow { NoSuchElementException("Entity '$this' has no property with type '${T::class.simpleName}'.") } inline fun <reified T : Attribute> AnyGameEntity.hasAttribute() = findAttribute(T::class).isPresent inline fun <reified T : Attribute> AnyGameEntity.whenHasAttribute(crossinline fn: (T) -> Unit) = findAttribute(T::class).map(fn) fun AnyGameEntity.tryActionsOn(context: GameContext, target: AnyGameEntity): Response { findAttribute<EntityActions>() .createActionsFor(context, this, target) .forEach { action -> if (target.executeCommand(action) is Consumed) { return Consumed } } return Pass } var AnyGameEntity.position get() = findAttribute(EntityPosition::class).orElseThrow { IllegalArgumentException("This Entity has no EntityPosition") }.position set(value) { findAttribute(EntityPosition::class).map { it.position = value } } val AnyGameEntity.tile: Tile get() = this.findAttribute<EntityTile>().tile val AnyGameEntity.occupiesBlock: Boolean get() = hasAttribute<BlockOccupier>() val AnyGameEntity.blocksVision: Boolean get() = hasAttribute<VisionBlocker>() val AnyGameEntity.isPlayer: Boolean get() = this.type == Player
0
Kotlin
0
1
e4d3ffa25ae096ee5757fad7929ad2d9175fc806
2,122
lords-of-mysterium
Apache License 2.0
app/src/main/java/com/xdja/app/mvp/model/TestModel.kt
yuan9034
280,068,333
false
null
package com.xdja.app.mvp.model import com.xdja.app.mvp.contract.TestContract import com.xdja.easymvp.integration.IRepositoryManager import com.xdja.easymvp.mvp.BaseModel /** * 描述: * Create by yuanwanli * Date 2020/07/15 */ class TestModel(repositoryManager: IRepositoryManager) : BaseModel(repositoryManager), TestContract.Model { }
0
Kotlin
0
1
85290317abc7dc62de12c73a6b8e195a8323b45b
344
EasyMvp
Apache License 2.0
app/src/main/java/io/github/tatakinov/treegrove/nostr/Bech32.kt
Tatakinov
704,510,443
false
{"Kotlin": 289348}
package io.github.tatakinov.treegrove.nostr import android.util.Log object Bech32 { private val hexToBech32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" private val bech32ToHex = mapOf<String, Byte>( "q" to 0x00, "p" to 0x01, "z" to 0x02, "r" to 0x03, "y" to 0x04, "9" to 0x05, "x" to 0x06, "8" to 0x07, "g" to 0x08, "f" to 0x09, "2" to 0x0a, "t" to 0x0b, "v" to 0x0c, "d" to 0x0d, "w" to 0x0e, "0" to 0x0f, "s" to 0x10, "3" to 0x11, "j" to 0x12, "n" to 0x13, "5" to 0x14, "4" to 0x15, "k" to 0x16, "h" to 0x17, "c" to 0x18, "e" to 0x19, "6" to 0x1a, "m" to 0x1b, "u" to 0x1c, "a" to 0x1d, "7" to 0x1e, "l" to 0x1f ) fun encode(prefix: String, data: ByteArray): String { val hrp = prefix.toByteArray() val checksum = checksum(hrp, data) var result = prefix + "1" for (v in data + checksum) { result += hexToBech32[v.toInt()] } return result } fun decode(bech32: String): Triple<Boolean, String, ByteArray> { val pos = bech32.indexOfLast { it.code == 0x31 } if (pos < 1 || pos > 83) { Log.d("Bech32.decode", "failed to indexOfLast") return Triple(false, "", ByteArray(0)) } val hrp = bech32.substring(0, pos) val remain = bech32.substring(pos + 1) val data = ByteArray(remain.length) for (i in remain.indices) { data[i] = bech32ToHex[remain.substring(i, i + 1)]?.toByte() ?: return Triple(false, "", ByteArray(0)) } if ( ! verify(hrp.toByteArray(), data)) { Log.d("Bech32.decode", "failed to verify") return Triple(false, "", ByteArray(0)) } val bytes = ByteArray(data.size - 6) for (i in 0 .. data.size - 7) { bytes[i] = data[i] } return Triple(true, hrp, bytes) } private fun expand(prefix : ByteArray) : ByteArray { val result = ByteArray(prefix.size * 2 + 1) for (i in prefix.indices) { result[i] = (prefix[i].toInt() shr 5).toByte() result[i + prefix.size + 1] = (prefix[i].toInt() and 0x1f).toByte() } result[prefix.size] = 0 return result } private fun polymod(data : ByteArray) : Int { val gen = listOf(0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3) var chk = 1 for (v in data) { val n = v.toInt() val b = (chk shr 25) chk = ((chk and 0x1ffffff) shl 5) xor n for (i in 0 .. 4) { if (((b shr i) and 1) > 0) { chk = chk xor (gen[i]) } } } return chk } private fun verify(prefix : ByteArray, data : ByteArray) : Boolean { return polymod(expand(prefix) + data) == 1 } private fun checksum(hrp : ByteArray, data : ByteArray) : ByteArray { val values = expand(hrp) + data val buffer : ByteArray = byteArrayOf(0x00, 0x00, 0x00, 0x00, 0x00, 0x00) val polymod = polymod(values + buffer) xor 1 val result = ByteArray(6) for (i in 0 .. 5) { result[i] = ((polymod shr (5 * (5 - i))) and 0x1f).toByte() } return result } }
0
Kotlin
0
2
59d6f716bde1729972b22d735c319c2d36de5b7e
3,331
TreeGrove
MIT License
kommons-mvvm/src/main/java/cz/seznam/kommons/mvvm/IBindableView.kt
seznam
141,697,690
false
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 2, "Proguard": 5, "XML": 13, "Kotlin": 45, "Java": 3}
package cz.seznam.kommons.mvvm import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.LifecycleOwner /** Base interface for implementing view by MVVM pattern. * * @author <NAME> */ interface IBindableView<in T : IViewModel, in A : IViewActions> { /** Creates view. * * Prepare your view. It's called before bind(). * * @param inflater inflater you can use to create your view * @param parent parent viewgroup for your view * * @return your view */ fun createView( inflater: LayoutInflater, viewLifecycleOwner: LifecycleOwner, parent: ViewGroup?, viewState: Bundle? = null ): View /** Called when view is destroyed. * * Your chance to clean up view stuff. It's called after unbind. */ fun destroyView() { } /** Saves the view state for later. * * @param state bundle when you can save your state */ fun saveViewState(state: Bundle) {} /** Binds model to your view. * * It's called when view and model is ready for use together, typically in some onViewCreated phase, * after createView() is called. * * @param viewModel model for your view * @param viewActions actions your view can invoke * @param lifecycleOwner lifecycle owner you can use for observing livedata from your model */ fun bind( viewModel: T, viewActions: A?, lifecycleOwner: LifecycleOwner ) /** Unbinds model from your view. * * Here you can unbind your model from view, for example when using DataBinding. * Typically called in onDestroyView phase. * * @param lifecycleOwner lifecycle owner used to bind your view and viewmodel */ fun unbind(lifecycleOwner: LifecycleOwner) }
1
null
1
1
502cf2ec058196d2d2fbf11e715014115543a0b3
1,778
Kommons
Apache License 2.0
library/src/commonMain/kotlin/com/befrvnk/knotion/objects/other/Owner.kt
befrvnk
672,042,674
false
null
package com.befrvnk.knotion.objects.other import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed class Owner @Serializable @SerialName("workspace") object WorkspaceOwner : Owner() @Serializable @SerialName("user") object UserOwner : Owner()
1
Kotlin
0
0
6271d06fc965de19f5449804b7a8e33648eec7f2
293
knotion
MIT License
library_android_q/src/main/java/ando/file/androidq/BaseMediaColumnsData.kt
df13954
330,521,541
true
{"Kotlin": 320773, "Java": 49263}
package ando.file.androidq import android.net.Uri import java.util.* /** * BaseMediaColumnsData * <p> * Description: android.provider.MediaStore.MediaColumns 映射数据类 , 包含常用的字段 * </p> * @author javakam * @date 2020/5/28 14:31 */ open class BaseMediaColumnsData { open var id: Long = -1L open var uri: Uri? = null open var displayName: String? = null open var size: Long? = 0L open var title: String? = null open var mimeType: String? = null open var relativePath: String? = null open var isPending: Int? = 0 open var volumeName: String? = null open var dateAdded: Date? = null open var dateModified: Long? = 0L open var dateTaken: Long? = 0L }
0
null
0
0
dea36f5c130ad368316ca0f047a1ca5a842dd57f
700
FileOperator
Apache License 2.0
src/main/java/com/metriql/warehouse/mysql/BaseMySQLFilters.kt
metriql
370,169,788
false
null
package com.metriql.warehouse.mysql import com.metriql.warehouse.spi.bridge.WarehouseMetriqlBridge import com.metriql.warehouse.spi.filter.ANSISQLFilters import com.metriql.warehouse.spi.filter.ArrayOperatorType import com.metriql.warehouse.spi.filter.WarehouseFilterValue import com.metriql.warehouse.spi.filter.WarehouseFilters.Companion.validateFilterValue open class BaseMySQLFilters(override val bridge: () -> WarehouseMetriqlBridge) : ANSISQLFilters(bridge) { override val arrayOperators: Map<ArrayOperatorType, WarehouseFilterValue> = mapOf( ArrayOperatorType.INCLUDES to { dimension: String, value: Any?, _ -> val validatedValue = validateFilterValue(value, List::class.java) "FIND_IN_SET($dimension, '${validatedValue.joinToString(",") { it.toString() }}') > 1" }, ArrayOperatorType.NOT_INCLUDES to { dimension: String, value: Any?, _ -> val validatedValue = validateFilterValue(value, List::class.java) "FIND_IN_SET($dimension, '${validatedValue.joinToString(",") { it.toString() }}') == 0" } ) }
30
Kotlin
19
253
10fa42434c19d1dbfb9a3d04becea679bb82d0f1
1,098
metriql
Apache License 2.0
theme-css/src/commonMain/kotlin/tz/co/asoft/CSSTheme.kt
cybernetics
348,603,077
true
{"Kotlin": 10625, "JavaScript": 348}
package tz.co.asoft typealias CSSTheme = Theme<Typography>
0
null
0
0
8ce9f7b1e76cad29a49959339ce04d23c5e94abd
59
theme
MIT License
sykepenger-model/src/main/kotlin/no/nav/helse/hendelser/Foreldrepermisjon.kt
navikt
193,907,367
false
null
package no.nav.helse.hendelser import no.nav.helse.person.Aktivitetslogg class Foreldrepermisjon( private val foreldrepengeytelse: Periode?, private val svangerskapsytelse: Periode?, private val aktivitetslogg: Aktivitetslogg ) { internal fun overlapper(sykdomsperiode: Periode): Boolean { if (foreldrepengeytelse == null && svangerskapsytelse == null) { aktivitetslogg.info("Bruker har ingen foreldrepenge- eller svangerskapsytelser") return false } return listOfNotNull(foreldrepengeytelse, svangerskapsytelse) .any { ytelse -> ytelse.overlapperMed(sykdomsperiode) } } }
1
Kotlin
5
5
a1d4ace847a123e6bf09754ea0640116caf6ceb7
661
helse-spleis
MIT License
ask-api/src/main/kotlin/com/fluxtah/ask/api/printers/AskResponsePrinter.kt
fluxtah
794,032,032
false
{"Kotlin": 180140, "Shell": 387}
/* * Copyright (c) 2024 <NAME> * Released under the MIT license * https://opensource.org/licenses/MIT */ package com.fluxtah.ask.api.printers interface AskResponsePrinter { fun println(message: String? = null) fun print(message: String) fun flush() }
4
Kotlin
0
8
c59cfeee7b7034e08b64a0bf31d770b0b123f875
268
ask
MIT License
app/shared/state-machine/ui/public/src/commonMain/kotlin/build/wallet/statemachine/send/fee/FeeSelectionUiStateMachine.kt
proto-at-block
761,306,853
false
{"C": 10474259, "Kotlin": 7954899, "Rust": 2637832, "Swift": 864356, "HCL": 349275, "Python": 338898, "Shell": 136166, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.statemachine.send.fee import build.wallet.bitcoin.address.BitcoinAddress import build.wallet.bitcoin.fees.Fee import build.wallet.bitcoin.transactions.BitcoinTransactionSendAmount import build.wallet.bitcoin.transactions.EstimatedTransactionPriority import build.wallet.money.exchange.ExchangeRate import build.wallet.statemachine.core.BodyModel import build.wallet.statemachine.core.StateMachine import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.ImmutableMap interface FeeSelectionUiStateMachine : StateMachine<FeeSelectionUiProps, BodyModel> /** * @property fiatCurrency: The fiat currency to convert BTC amounts to and from. */ data class FeeSelectionUiProps( val recipientAddress: BitcoinAddress, val sendAmount: BitcoinTransactionSendAmount, val exchangeRates: ImmutableList<ExchangeRate>?, val onBack: () -> Unit, val onContinue: ( EstimatedTransactionPriority, ImmutableMap<EstimatedTransactionPriority, Fee>, ) -> Unit, )
3
C
16
113
694c152387c1fdb2b6be01ba35e0a9c092a81879
1,014
bitkey
MIT License
imageChooser/src/main/java/com/irisoftmex/imagechooser/provider/BaseProvider.kt
israis007
414,095,974
false
null
package com.irisoftmex.imagechooser.provider import android.content.ContextWrapper import android.os.Bundle import android.os.Environment import com.irisoftmex.imagechooser.ImagePickerActivity import java.io.File abstract class BaseProvider(protected val activity: ImagePickerActivity) : ContextWrapper(activity) { fun getFileDir(path: String?): File { return if (path != null) File(path) else getExternalFilesDir(Environment.DIRECTORY_DCIM) ?: activity.filesDir } /** * Cancel operation and Set Error Message * * @param error Error Message */ protected fun setError(error: String) { onFailure() activity.setError(error) } /** * Cancel operation and Set Error Message * * @param errorRes Error Message */ protected fun setError(errorRes: Int) { setError(getString(errorRes)) } /** * Call this method when task is cancel in between the operation. * E.g. user hit back-press */ protected fun setResultCancel() { onFailure() activity.setResultCancel() } /** * This method will be Call on Error, It can be used for clean up Tasks */ protected open fun onFailure() { } /** * Save all appropriate provider state. */ open fun onSaveInstanceState(outState: Bundle) { } /** * Restores the saved state for all Providers. * * @param savedInstanceState the Bundle returned by {@link #onSaveInstanceState()} * @see #onSaveInstanceState() */ open fun onRestoreInstanceState(savedInstanceState: Bundle?) { } }
0
Kotlin
0
0
71c35f687d00170a539b97a825b964511d901a6e
1,643
Prueba-Marvel
Apache License 2.0
admin/src/main/java/com/bookstore/admin/model/formatted/user/SignInResponse.kt
ezralazuardy
271,148,211
false
null
package com.bookstore.admin.model.formatted.user import com.bookstore.admin.constant.RetrofitStatus data class SignInResponse( val status: RetrofitStatus = RetrofitStatus.UNKNOWN )
0
Kotlin
0
7
d2f7dce513588e1797fa379bf43b70ec87759f29
186
bookstore
MIT License
plugins/drill-coverage-plugin/src/adminPartMain/kotlin/Test.kt
IgorKey
191,016,353
true
{"Kotlin": 463665, "C": 18447, "HTML": 16984, "Less": 8583, "Batchfile": 713, "Shell": 532, "Dockerfile": 61}
package com.epam.drill.plugins.coverage data class Test( val id: String? = null, val testName: String? = null, val testType: Int? = null, val data: List<ClassData>? = null )
0
Kotlin
0
2
e6e287fb9a23a7a8438372587714f2be0c757943
190
Drill4J
Apache License 2.0
app/src/main/java/com/steve_md/smartmkulima/ui/fragments/auth/PhoneVerificationFragment.kt
MuindiStephen
559,873,955
false
{"Kotlin": 161111}
package com.steve_md.smartmkulima.ui.fragments.auth import android.os.Bundle import android.os.CountDownTimer import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import com.steve_md.smartmkulima.R import com.steve_md.smartmkulima.databinding.FragmentPhoneVerificationBinding import com.steve_md.smartmkulima.utils.Resource import com.steve_md.smartmkulima.utils.toast import com.steve_md.smartmkulima.viewmodel.AuthenticationViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest @AndroidEntryPoint class PhoneVerificationFragment : Fragment() { private lateinit var binding: FragmentPhoneVerificationBinding private lateinit var navController: NavController private val phoneOTPViewModel: AuthenticationViewModel by viewModels() private val args:PhoneVerificationFragmentArgs by navArgs() private var phone = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding = FragmentPhoneVerificationBinding.inflate(layoutInflater, container, false) binding.emailVerificationCodeText.setOnClickListener { findNavController().navigate(R.id.action_verificationFragment_to_emailVerificationFragment) } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (activity as AppCompatActivity).supportActionBar?.hide() navController = findNavController() val appBarConfiguration = AppBarConfiguration(navController.graph) binding.mainAuthsToolbar.setupWithNavController(navController, appBarConfiguration) binding.mainAuthsToolbar.title = null phone = args.phone binding.phoneSendVerificationCode.text = phone object : CountDownTimer(30000, 1000) { // Callback function, fired on regular interval override fun onTick(millisUntilFinished: Long) { binding.textView15.setText("0." + millisUntilFinished / 1000) binding.textView18.setText("1."+millisUntilFinished / 500) } // Callback function, fired // when the time is up override fun onFinish() { binding.textView15.setText("done!") binding.textView18.setText("Time exceeded") } }.start() binding.buttonVerifyPhoneOTP.setOnClickListener { val code:String = binding.pinView.text.toString() phoneOTPViewModel.confirmPhoneOTP(code) } observeViewModelOtp() } private fun observeViewModelOtp() { lifecycleScope.launchWhenResumed { phoneOTPViewModel.otpRes.collectLatest { when (it) { Resource.Loading -> { toast("Loading") } is Resource.Error -> { //toast("") navigateToLoginPage() } is Resource.Success -> { toast("Authenticated Successfully") navigateToLoginPage() } null -> {} } } } } private fun navigateToLoginPage() { findNavController().navigate(R.id.action_verificationFragment_to_signInDetailsFragment) } }
3
Kotlin
1
4
83df8835dd9621cd8131db67b06b927423179f54
4,001
Shamba-App
MIT License
src/test/kotlin/util/TestCoordinate2d.kt
Stenz123
779,628,245
false
{"Kotlin": 3782}
package util import kotlin.test.Test import kotlin.test.assertEquals class TestCoordinate2dTest { @Test fun testGet8Neighbours() { val coordinate = Coordinate2d(3, 4) val expectedNeighbors = listOf( Coordinate2d(3, 3), Coordinate2d(3, 5), Coordinate2d(4, 4), Coordinate2d(2, 4), Coordinate2d(2, 3), Coordinate2d(4, 3), Coordinate2d(2, 5), Coordinate2d(4, 5) ) assertEquals(expectedNeighbors, coordinate.get8Neighbours()) } @Test fun testGet4Neighbours() { val coordinate = Coordinate2d(3, 4) val expectedNeighbors = listOf( Coordinate2d(3, 3), Coordinate2d(3, 5), Coordinate2d(4, 4), Coordinate2d(2, 4) ) assertEquals(expectedNeighbors, coordinate.get4Neighbours()) } @Test fun testTop() { val coordinate = Coordinate2d(3, 4) val expectedTop = Coordinate2d(3, 3) assertEquals(expectedTop, coordinate.top()) } @Test fun testBottom() { val coordinate = Coordinate2d(3, 4) val expectedBottom = Coordinate2d(3, 5) assertEquals(expectedBottom, coordinate.bottom()) } @Test fun testLeft() { val coordinate = Coordinate2d(3, 4) val expectedLeft = Coordinate2d(2, 4) assertEquals(expectedLeft, coordinate.left()) } @Test fun testRight() { val coordinate = Coordinate2d(3, 4) val expectedRight = Coordinate2d(4, 4) assertEquals(expectedRight, coordinate.right()) } @Test fun testTopRight() { val coordinate = Coordinate2d(3, 4) val expectedTopRight = Coordinate2d(4, 3) assertEquals(expectedTopRight, coordinate.topRight()) } @Test fun testBottomLeft() { val coordinate = Coordinate2d(3, 4) val expectedBottomLeft = Coordinate2d(2, 5) assertEquals(expectedBottomLeft, coordinate.bottomLeft()) } @Test fun testTopLeft() { val coordinate = Coordinate2d(3, 4) val expectedTopLeft = Coordinate2d(2, 3) assertEquals(expectedTopLeft, coordinate.topLeft()) } @Test fun testBottomRight() { val coordinate = Coordinate2d(3, 4) val expectedBottomRight = Coordinate2d(4, 5) assertEquals(expectedBottomRight, coordinate.bottomRight()) } }
0
Kotlin
0
0
299ff9825f7b38c415ecd2ebc096302e71c3c870
2,378
algorithms
The Unlicense
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/item/widget/use/QuickUseWidgetRsp.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.item.widget.use import org.anime_game_servers.core.base.Version.GI_1_1_0 import org.anime_game_servers.core.base.Version.GI_2_6_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.RemovedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.OneOf import org.anime_game_servers.core.base.annotations.proto.OneOfEntry import org.anime_game_servers.core.base.annotations.proto.OneOfType import org.anime_game_servers.core.base.annotations.proto.ProtoCommand import org.anime_game_servers.multi_proto.gi.data.general.Retcode import org.anime_game_servers.multi_proto.gi.data.item.widget.ClientCollectorData import org.anime_game_servers.multi_proto.gi.data.item.widget.one_of_gather_point_detector.OneOfGatherPointDetectorData import org.anime_game_servers.multi_proto.gi.data.item.widget.sky_cristal_detector.SkyCrystalDetectorQuickUseResult @AddedIn(GI_1_1_0) @ProtoCommand(RESPONSE) internal interface QuickUseWidgetRsp { var retcode: Retcode @RemovedIn(GI_2_6_0) var clientCollectorData: ClientCollectorData @RemovedIn(GI_2_6_0) var detectorData: OneOfGatherPointDetectorData var materialId: Int @AddedIn(GI_2_6_0) @OneOf( types = [ OneOfEntry(ClientCollectorData::class, "client_collector_data"), OneOfEntry(OneOfGatherPointDetectorData::class, "detector_data"), OneOfEntry(SkyCrystalDetectorQuickUseResult::class, "sky_crystal_detector_quick_use_result"), ] ) var param: OneOfType }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
1,676
anime-game-multi-proto
MIT License
platform/feedback/src/com/intellij/feedback/demo/dialog/DemoFeedbackDialog.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.feedback.demo.dialog import com.intellij.feedback.common.DEFAULT_FEEDBACK_CONSENT_ID import com.intellij.feedback.common.FeedbackRequestDataWithDetailedAnswer import com.intellij.feedback.common.FeedbackRequestType import com.intellij.feedback.common.dialog.BaseFeedbackDialog import com.intellij.feedback.common.dialog.COMMON_FEEDBACK_SYSTEM_INFO_VERSION import com.intellij.feedback.common.dialog.CommonFeedbackSystemInfoData import com.intellij.feedback.common.dialog.showFeedbackSystemInfoDialog import com.intellij.feedback.common.dialog.uiBlocks.* import com.intellij.feedback.common.submitFeedback import com.intellij.feedback.demo.bundle.DemoFeedbackBundle import com.intellij.feedback.new_ui.CancelFeedbackNotification import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.project.Project import com.intellij.ui.LicensingFacade import com.intellij.ui.dsl.builder.panel import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBUI import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import javax.swing.Action import javax.swing.JComponent class DemoFeedbackDialog( project: Project?, private val forTest: Boolean, ) : BaseFeedbackDialog(project) { /** Increase the additional number when feedback format is changed */ override val feedbackJsonVersion: Int = COMMON_FEEDBACK_SYSTEM_INFO_VERSION + 1 override val feedbackReportId: String = "demo_feedback" private val TICKET_TITLE_ZENDESK = "Demo in-IDE Feedback" private val FEEDBACK_TYPE_ZENDESK = "Demo in-IDE Feedback" private val systemInfoData: CommonFeedbackSystemInfoData = CommonFeedbackSystemInfoData.getCurrentData() private val propertyGraph = PropertyGraph() private val textFieldEmailProperty = propertyGraph.lazyProperty { LicensingFacade.INSTANCE?.getLicenseeEmail().orEmpty() } private val jsonConverter = Json { prettyPrint = true } private val blocks: List<BaseFeedbackBlock> = listOf( TopLabelBlock(DemoFeedbackBundle.message("dialog.title")), TextAreaBlock(propertyGraph.property(""), DemoFeedbackBundle.message("dialog.textarea.label")), SegmentedButtonBlock(propertyGraph.property(0), DemoFeedbackBundle.message("dialog.segmentedButton.label"), (1..9).toList(), { it.toString() }, DemoFeedbackBundle.message("dialog.segmentedButton.leftHint"), DemoFeedbackBundle.message("dialog.segmentedButton.middleHint"), DemoFeedbackBundle.message("dialog.segmentedButton.rightHint")), EmailBlock(textFieldEmailProperty, myProject) { showFeedbackSystemInfoDialog(myProject, systemInfoData) } ) init { init() title = DemoFeedbackBundle.message("dialog.top.title") } override fun doOKAction() { super.doOKAction() val feedbackData = FeedbackRequestDataWithDetailedAnswer(feedbackReportId, TICKET_TITLE_ZENDESK, createRequestDescription(), DEFAULT_FEEDBACK_CONSENT_ID, FEEDBACK_TYPE_ZENDESK, createCollectedDataJsonObject()) submitFeedback(myProject, feedbackData, { }, { }, if (forTest) FeedbackRequestType.TEST_REQUEST else FeedbackRequestType.PRODUCTION_REQUEST) } override fun doCancelAction() { super.doCancelAction() CancelFeedbackNotification().notify(myProject) } private fun createRequestDescription(): String { return buildString { // TODO: FIX IT //appendLine(DemoFeedbackBundle.message("dialog.zendesk.title")) //appendLine(DemoFeedbackBundle.message("dialog.zendesk.description")) //appendLine() //appendLine(DemoFeedbackBundle.message("dialog.zendesk.rating.label")) //appendLine(" ${ratingProperty.get()}") //appendLine() //appendLine(DemoFeedbackBundle.message("dialog.zendesk.like_most.textarea.label")) //appendLine(textAreaLikeMostFeedbackProperty.get()) //appendLine() //appendLine(DemoFeedbackBundle.message("dialog.zendesk.dislike.textarea.label")) //appendLine(textAreaDislikeFeedbackProperty.get()) //appendLine() //appendLine() //appendLine(newUISystemInfoData.value.toString()) } } private fun createCollectedDataJsonObject(): JsonObject { val collectedData = buildJsonObject { // TODO: FIX IT //put(FEEDBACK_REPORT_ID_KEY, FEEDBACK_REPORT_ID_VALUE) //put("format_version", FEEDBACK_JSON_VERSION) //put("rating", ratingProperty.get()) //put("like_most", textAreaLikeMostFeedbackProperty.get()) //put("dislike", textAreaDislikeFeedbackProperty.get()) //put("system_info", jsonConverter.encodeToJsonElement(newUISystemInfoData.value)) } return collectedData } override fun createCenterPanel(): JComponent { val mainPanel = panel { for (block in blocks) { block.addToPanel(this) } }.also { dialog -> dialog.border = JBEmptyBorder(JBUI.scale(15), JBUI.scale(10), JBUI.scale(0), JBUI.scale(10)) } return mainPanel } override fun createActions(): Array<Action> { return arrayOf(cancelAction, okAction) } override fun getOKAction(): Action { return object : OkAction() { init { putValue(NAME, DemoFeedbackBundle.message("dialog.ok.label")) } } } override fun getCancelAction(): Action { val cancelAction = super.getCancelAction() cancelAction.putValue(Action.NAME, DemoFeedbackBundle.message("dialog.cancel.label")) return cancelAction } }
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
5,861
intellij-community
Apache License 2.0
server-logic/src/test/kotlin/com/github/vatbub/matchmaking/server/logic/roomproviders/data/ObservableRoomTest.kt
vatbub
162,929,659
false
null
/*- * #%L * matchmaking.server * %% * Copyright (C) 2016 - 2019 <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. * #L% */ package com.github.vatbub.matchmaking.server.logic.roomproviders.data import com.github.vatbub.matchmaking.common.data.GameData import com.github.vatbub.matchmaking.common.data.Room import com.github.vatbub.matchmaking.common.data.User import com.github.vatbub.matchmaking.testutils.KotlinTestSuperclass import com.github.vatbub.matchmaking.testutils.TestUtils import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class ObservableRoomTest : KotlinTestSuperclass<ObservableRoom>() { override fun getCloneOf(instance: ObservableRoom) = ObservableRoom(instance.toRoom(), instance.onGameStartedChange) override fun newObjectUnderTest() = ObservableRoom(Room(TestUtils.getRandomHexString(), TestUtils.defaultConnectionId)) @Test fun copyTest() { val room = Room( TestUtils.getRandomHexString(), TestUtils.defaultConnectionId, listOf("vatbub", "heykey"), listOf("leoll"), 2, 5 ) room.connectedUsers.add(User(TestUtils.defaultConnectionId, "vatbub")) room.gameState["someKey"] = "someValue" room.gameStarted = true val dataToHost = GameData(room.hostUserConnectionId) dataToHost["anotherKey"] = "anotherValue" room.dataToBeSentToTheHost.add(dataToHost) val observableRoom = ObservableRoom(room) Assertions.assertEquals(room.id, observableRoom.id) Assertions.assertEquals(room.hostUserConnectionId, observableRoom.hostUserConnectionId) Assertions.assertEquals(room.whitelist, observableRoom.whitelist) Assertions.assertEquals(room.blacklist, observableRoom.blacklist) Assertions.assertEquals(room.minRoomSize, observableRoom.minRoomSize) Assertions.assertEquals(room.maxRoomSize, observableRoom.maxRoomSize) Assertions.assertEquals(room.connectedUsers, observableRoom.connectedUsers) Assertions.assertEquals(ObservableGameData(room.gameState), observableRoom.gameState) Assertions.assertEquals(room.gameStarted, observableRoom.gameStarted) Assertions.assertEquals(room.dataToBeSentToTheHost, observableRoom.dataToBeSentToTheHost) } @Test fun toRoomTest() { val room = Room( TestUtils.getRandomHexString(), TestUtils.defaultConnectionId, listOf("vatbub", "heykey"), listOf("leoll"), 2, 5 ) room.connectedUsers.add(User(TestUtils.defaultConnectionId, "vatbub")) room.gameState["someKey"] = "someValue" room.gameStarted = true val dataToHost = GameData(room.hostUserConnectionId) dataToHost["anotherKey"] = "anotherValue" room.dataToBeSentToTheHost.add(dataToHost) val observableRoom = ObservableRoom(room) Assertions.assertEquals(room, observableRoom.toRoom()) Assertions.assertNotSame(room, observableRoom.toRoom()) } @Test fun onGameStartedChangeTest() { val room = Room(TestUtils.getRandomHexString(), TestUtils.defaultConnectionId) val expectedNewValue = true var listenerCalled = false val observableRoom = ObservableRoom(room) { newValue -> Assertions.assertEquals(expectedNewValue, newValue) listenerCalled = true } observableRoom.gameStarted = true Assertions.assertTrue(listenerCalled) } @Test override fun notEqualsTest() { val object1 = newObjectUnderTest() val object2 = ObservableRoom(Room(TestUtils.getRandomHexString(object1.id), TestUtils.getRandomHexString())) Assertions.assertNotEquals(object1, object2) } }
11
Kotlin
5
32
7ece6b79c6ea15dcf636851a61fde6dc6615188d
4,537
matchmaking
Apache License 2.0
crypto-currency-app/app/src/main/java/com/bkarakoca/cryptocurrencyapp/domain/login/LoginUseCase.kt
kkocaburak
448,974,871
false
{"Kotlin": 84154}
package com.bkarakoca.cryptocurrencyapp.domain.login import com.bkarakoca.cryptocurrencyapp.data.remote.model.datastore.AuthResponse import com.bkarakoca.cryptocurrencyapp.data.repository.AuthRepository import com.bkarakoca.cryptocurrencyapp.internal.util.flow.FlowUseCase import kotlinx.coroutines.flow.Flow import javax.inject.Inject class LoginUseCase @Inject constructor( private val authRepository: AuthRepository ) : FlowUseCase<LoginUseCase.Params, AuthResponse>() { data class Params( val emailText: String, val passwordText: String ) override suspend fun execute(params: Params): Flow<AuthResponse> = authRepository.postLogin(params.emailText, params.passwordText) }
0
Kotlin
0
1
66615b00611d3c440baca2f4c49f8fd87b9734a3
720
crypto-currency-mvvm-android
Apache License 2.0
wallet-sdk/src/main/kotlin/org/stellar/walletsdk/customer/Data.kt
stellar
523,604,257
false
{"Kotlin": 199953}
package org.stellar.walletsdk.customer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AddCustomerResponse( @SerialName("id") var id: String, ) enum class Sep12Status(val status: String) { @SerialName("NEEDS_INFO") NEEDS_INFO("NEEDS_INFO"), @SerialName("ACCEPTED") ACCEPTED("ACCEPTED"), @SerialName("PROCESSING") PROCESSING("PROCESSING"), @SerialName("REJECTED") REJECTED("REJECTED"), @SerialName("VERIFICATION_REQUIRED") VERIFICATION_REQUIRED("VERIFICATION_REQUIRED") } @Serializable data class Field( var type: Type? = null, var description: String? = null, var choices: List<String>? = null, var optional: Boolean? = null, ) { enum class Type(val status: String) { @SerialName("string") STRING("string"), @SerialName("binary") BINARY("binary"), @SerialName("number") NUMBER("number"), @SerialName("date") DATE("date") } } @Serializable data class ProvidedField( var type: Field.Type? = null, var description: String? = null, var choices: List<String>? = null, var optional: Boolean? = null, var status: Sep12Status? = null, var error: String? = null, ) @Serializable data class GetCustomerResponse( var id: String? = null, var status: Sep12Status? = null, var fields: Map<String?, Field?>? = null, @SerialName("provided_fields") var providedFields: Map<String, ProvidedField>? = null, var message: String? = null, )
1
Kotlin
8
5
15be5994da787f59c0e724f241035f6095b5fb3a
1,446
kotlin-wallet-sdk
Apache License 2.0
app/src/main/java/com/immortalweeds/pedometer/model/gps/Waypoint.kt
Weedlly
523,343,757
false
{"Kotlin": 65187}
package com.immortalweeds.pedometer.model.gps data class Waypoint( val distance: Double, val location: List<Double>, val name: String )
0
Kotlin
0
7
411c6fcf45a7a9aa34214148264297b345211ed7
148
Pedometer
Apache License 2.0
app/src/main/java/com/example/android/architecture/mockmvvmtesting/todoapp/data/source/local/ToDatabase.kt
bhola143143
578,958,924
false
null
package com.example.android.architecture.mockmvvmtesting.todoapp.data.source.local import androidx.room.Database import androidx.room.RoomDatabase import com.example.android.architecture.mockmvvmtesting.todoapp.data.Task @Database(entities = [Task::class], version = 1, exportSchema = false) abstract class ToDatabase : RoomDatabase() { abstract fun taskDao(): TasksDao }
0
Kotlin
0
0
ca4489ebdb3ed90c025c1fa4a6444e5ec3cdf8da
380
mock
Apache License 2.0
spark-screenshot-testing/src/test/kotlin/com/adevinta/spark/PaparazziUtils.kt
adevinta
598,741,849
false
{"Kotlin": 2093965}
/* * Copyright (c) 2023 Adevinta * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.adevinta.spark import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalInspectionMode import app.cash.paparazzi.Paparazzi import app.cash.paparazzi.detectEnvironment internal fun Paparazzi.sparkSnapshot( name: String? = null, drawBackground: Boolean = true, composable: @Composable () -> Unit, ): Unit = snapshot(name) { // Behave like in Android Studio Preview renderer CompositionLocalProvider(LocalInspectionMode provides true) { SparkTheme(useLegacyStyle = false) { // The first box acts as a shield from ComposeView which forces the first layout node // to match it's size. This allows the content below to wrap as needed. Box { // The second box adds a border and background so we can easily see layout bounds in screenshots Box( Modifier.background(if (drawBackground) SparkTheme.colors.surface else Color.Transparent), ) { composable() } } } } } /** * Lower the current Paparazzi Environment from API level 34 to 33 to work around new resource conflicts: * * ``` * SEVERE: resources.format: Hexadecimal color expected, found Color State List for @android:color/system_bar_background_semi_transparent * java.lang.NumberFormatException: Color value '/usr/local/lib/android/sdk/platforms/android-34/data/res/color/system_bar_background_semi_transparent.xml' has wrong size. Format is either#AARRGGBB, #RRGGBB, #RGB, or #ARGB * ``` * * GitHub issue: https://github.com/cashapp/paparazzi/issues/1025 */ internal fun patchedEnvironment() = with(detectEnvironment()) { copy(compileSdkVersion = 33, platformDir = platformDir.replace("34", "33")) } internal const val MaxPercentDifference: Double = 0.01 internal const val PaparazziTheme: String = "android:Theme.MaterialComponent.Light.NoActionBar"
50
Kotlin
18
42
ef56659dd940e0a32e397822f6c3c43a3d75f5e4
3,288
spark-android
MIT License
ktor-demo/src/Application.kt
ozkanpakdil
288,530,857
false
{"HTML": 3, "Maven POM": 10, "Shell": 1, "Text": 1, "Ignore List": 6, "Markdown": 4, "JSON": 15, "Kotlin": 1, "INI": 8, "XML": 7, "Java": 23, "YAML": 9, "C#": 6, "Java Properties": 2, "EditorConfig": 1, "AsciiDoc": 1}
package com.mascix import com.fasterxml.jackson.core.util.DefaultIndenter import com.fasterxml.jackson.core.util.DefaultPrettyPrinter import com.fasterxml.jackson.databind.SerializationFeature import io.ktor.client.engine.* import io.ktor.serialization.jackson.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.plugins.contentnegotiation.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.util.* import java.time.LocalDate import java.util.* val props = Properties() fun main() { props.load(ClassLoader.getSystemResourceAsStream("app.properties")) embeddedServer(Netty, port = 8080, host = "0.0.0.0") { mainModule() }.start(wait = true) } data class ApplicationInfo( val name: String, val releaseYear: Int ) @OptIn(InternalAPI::class) fun Application.mainModule() { println("kotlin version:${KotlinVersion.CURRENT} ktor:${props["ktor_version"]}") install(ContentNegotiation) { jackson { configure(SerializationFeature.INDENT_OUTPUT, true) setDefaultPrettyPrinter(DefaultPrettyPrinter().apply { indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance) indentObjectsWith(DefaultIndenter(" ", "\n")) }) } } routing { get("/hello") { call.respond(ApplicationInfo("ktor", LocalDate.now().getYear())) } } }
5
Java
4
9
035e144dbcfa4d13d338f827413200daf97ab2f2
1,480
test-microservice-frameworks
Apache License 2.0
app/src/main/java/com/simform/ssfurnicraftar/ui/download/navigation/DownloadNavigation.kt
SimformSolutionsPvtLtd
771,436,960
false
{"Kotlin": 173195}
package com.simform.ssfurnicraftar.ui.download.navigation import android.content.Intent import androidx.lifecycle.SavedStateHandle import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navDeepLink import com.simform.ssfurnicraftar.ui.arview.ColorState import com.simform.ssfurnicraftar.ui.download.DownloadRoute import com.simform.ssfurnicraftar.utils.constant.Urls import java.nio.file.Path private const val DOWNLOAD_ROUTE_BASE = "download_route" private const val PRODUCT_ID_ARG = "productId" private const val MODEL_COLOR_ARG = "modelColor" private const val DOWNLOAD_ROUTE = "$DOWNLOAD_ROUTE_BASE/{$PRODUCT_ID_ARG}?$MODEL_COLOR_ARG={$MODEL_COLOR_ARG}" private const val DOWNLOAD_URL_PATTERN = "${Urls.MODEL}/{$PRODUCT_ID_ARG}?$MODEL_COLOR_ARG={$MODEL_COLOR_ARG}" fun NavController.navigateToDownload(productId: String) { navigate("$DOWNLOAD_ROUTE_BASE/$productId") } fun NavGraphBuilder.downloadScreen( onDownloadComplete: (String, Path, ColorState) -> Unit ) { composable( route = DOWNLOAD_ROUTE, arguments = listOf( navArgument(PRODUCT_ID_ARG) { type = NavType.StringType } ), deepLinks = listOf( navDeepLink { uriPattern = DOWNLOAD_URL_PATTERN action = Intent.ACTION_VIEW } ) ) { DownloadRoute(onDownloadComplete = onDownloadComplete) } } internal data class DownloadArgs( val productId: String, val modelColor: ColorState ) { constructor(savedStateHandle: SavedStateHandle) : this( productId = requireNotNull(savedStateHandle[PRODUCT_ID_ARG]), modelColor = ColorState.parseFrom(savedStateHandle.get<String>(MODEL_COLOR_ARG)) ) }
0
Kotlin
0
33
78a676b0a18b1fc3a5e02b0e40f32c10321f1a9f
1,896
SSCompose-FurniCraftAR
MIT License
step8/PrimaryConstructor4.kt
shilpasayura
400,781,913
false
null
// Primary constructor with init block. class Personq(pName: String, pAge: Int, pHeight : Double ) { var name : String var age : Int var height : Double init { name = pName age = pAge height = pHeight require(name.trim().isNotEmpty()) {"Name should not empty"} require(age > 0 ) {"Age is not correct"} require(height > 0) {"Height is not correct"} print("Hello") } } fun main(args: Array<String>) { val person = Personq("Ama",17,5.5) println("Name ${person.name}, Age ${person.age} Height ${person.height}") val person1 = Personq("Bima",0,0.0) }
0
Kotlin
0
0
d0898fef7231adc9c6661ab6f75f9020696d0600
641
kotlin
MIT License
app/src/main/java/com/example/woodinvoicetest/MainActivity.kt
MaherDeeb
270,105,871
false
null
package com.example.woodinvoicetest import android.content.DialogInterface import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import java.text.DateFormat import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) getAndShowDate() enterMaterialProductButton.setOnClickListener { goToWoodProductsScreen() } showInvoicesButton.setOnClickListener { goToShowInvoices() } exitProgramButton.setOnClickListener { exitApp() } } private fun goToWoodProductsScreen() { val intent = Intent(this, WoodProducts::class.java) ordersInvoice = InvoiceObjectClass() orderedProduct = OrderedProduct() startActivity(intent) } override fun onBackPressed() { exitApp() } private fun exitApp() { showYesNoDialog() } private fun showYesNoDialog() { lateinit var dialog: AlertDialog val builder = AlertDialog.Builder(this) builder.setTitle(getString(R.string.finishTheAppTitle)) builder.setMessage(getString(R.string.messageDoYouWantToFinishTheApp)) val dialogClickListener = DialogInterface.OnClickListener { _, which -> when (which) { DialogInterface.BUTTON_POSITIVE -> this.finishAffinity() DialogInterface.BUTTON_NEGATIVE -> doNothing() } } builder.setPositiveButton(getString(R.string.yesAnswer), dialogClickListener) builder.setNegativeButton(getString(R.string.noAnswer), dialogClickListener) dialog = builder.create() dialog.show() } private fun goToShowInvoices() { val intent = Intent(this, ShowInvoices::class.java) startActivity(intent) } private fun getAndShowDate() { val calender = Calendar.getInstance().time val formatter = SimpleDateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN) actualDate.text = formatter.format(calender) } }
0
Kotlin
4
43
63bdf72166f5a0bcd50d90ea569880aea91d3e83
2,301
take_orders_app
Apache License 2.0
app/src/main/java/com/ulearn/ms_ulearn_mobile_app_kotlin/ModelCoursesRow.kt
U-Learn-Repository
259,471,839
false
null
package com.ulearn.ms_ulearn_mobile_app_kotlin class ModelCoursesRow (val title:String, val img: Int) { }
0
Kotlin
0
0
4bc5458baad8a585d3db706e6a9e956219b53047
106
ms-ulearn-mobile-app-kotlin
MIT License
app/src/main/java/com/saliktariq/archelon/ui/login/RegisterNewUser.kt
saliktariq
376,143,999
false
null
package com.saliktariq.archelon.ui.login import android.os.Bundle import android.os.Handler import android.util.Log import android.view.Gravity import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.findNavController import com.saliktariq.archelon.databinding.RegisterNewUserFragmentBinding import com.saliktariq.archelon.helper.AuxiliaryFunctions import com.saliktariq.archelon.helper.MyToasts import kotlinx.android.synthetic.main.register_new_user_fragment.* import kotlinx.coroutines.launch class RegisterNewUser : Fragment() { private var binding: RegisterNewUserFragmentBinding? = null private val viewBinding get() = binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { //Getting reference to the binding object and inflating the fragment binding = RegisterNewUserFragmentBinding.inflate(inflater, container, false) // Creating instance of ViewModel Factory val viewModelFactory = RegisterNewUserViewModelFactory() // Get a reference to the ViewModel associated with RegisterNewUser fragment val registerNewUserViewModel = ViewModelProvider(this, viewModelFactory).get(RegisterNewUserViewModel::class.java) // Set onClickListener on the back button viewBinding.backArrowRegPage.setOnClickListener { viewBinding.root.findNavController() .navigate(RegisterNewUserDirections.actionGlobalLoginFragment()) } // Set onClickListener on the login link viewBinding.loginLinkRegPage.setOnClickListener { viewBinding.root.findNavController() .navigate(RegisterNewUserDirections.actionGlobalLoginFragment()) } // Set onClickListener to Signup button viewBinding.btnSignUp.setOnClickListener { //Assigning user entered data to view model variables registerNewUserViewModel.firstName = firstName.text.toString() registerNewUserViewModel.email = emailAddress.text.toString() registerNewUserViewModel.username = newUsername.text.toString() registerNewUserViewModel.pwd = <PASSWORD>.text.toString() //Generating new authentication code registerNewUserViewModel.authCode = AuxiliaryFunctions.generateAuthCode( registerNewUserViewModel.username, registerNewUserViewModel.pwd, registerNewUserViewModel.email, registerNewUserViewModel.firstName ) //Starting coroutine with application lifecycle scope viewLifecycleOwner.lifecycleScope.launch { //Checking if the registration data entered is not already in the system val fetchData = viewLifecycleOwner.lifecycleScope.launch { registerNewUserViewModel.getUserData(registerNewUserViewModel.username) } //Query database to see if the dataset (username or email address) already exists //Waiting for the coroutine to complete query fetchData.join() //Checking if email already exist in the system if (registerNewUserViewModel.emailAlreadyExists) { MyToasts.showToastWithGravity( "Email address already exist.", context, Gravity.TOP ) } //Checking if email field is empty or inval else if (registerNewUserViewModel.email.length < 3) { val toastHandler = Handler() toastHandler.postDelayed({ MyToasts.showToastWithGravity( "Enter a valid email address", context, Gravity.TOP ) }, 2000) } //Checking if username field is empty or invalid else if (registerNewUserViewModel.username.length < 5) { val toastHandler = Handler() toastHandler.postDelayed({ MyToasts.showToastWithGravity( "Minimum username length is 5 characters", context, Gravity.TOP ) }, 2000) } else if (registerNewUserViewModel.userAlreadyExists) { /*Using handler to display second toast right after the first error toast to avoid second toast override first toast message. */ val toastHandler = Handler() toastHandler.postDelayed({ MyToasts.showToastWithGravity( "Username already exist.", context, Gravity.TOP ) }, 2000) //Adding delay to avoid toasts overlapping in case of multiple errors } //Checking if password field is 5 characters or more else if (registerNewUserViewModel.pwd.length < 5) { val toastHandler = Handler() toastHandler.postDelayed({ MyToasts.showToastWithGravity( "Minimum password length is 5 characters", context, Gravity.BOTTOM ) }, 2000) //Adding delay to avoid toasts overlapping in case of multiple errors } else { val signup = viewLifecycleOwner.lifecycleScope.launch { registerNewUserViewModel.signUpUser() } //Waiting for signup query to complete signup.join() MyToasts.showToastWithGravity( "Success! User account created", context, Gravity.TOP ) viewModelStore.clear() //Clearing viewModel viewBinding.root.findNavController() .navigate(RegisterNewUserDirections.actionGlobalLoginFragment()) } registerNewUserViewModel.emailAlreadyExists = false registerNewUserViewModel.userAlreadyExists = false } } //Returning view return viewBinding.root } override fun onDestroyView() { super.onDestroyView() //Destroying the viewBinding object binding = null } }
0
Kotlin
0
0
ffc9c8ed0e9d5009a88f1d1d499f82a2a08cdad9
7,019
Archelon-Android-Application
MIT License
file/src/main/kotlin/me/gegenbauer/catspy/file/Size.kt
Gegenbauer
609,809,576
false
{"Kotlin": 652879}
package me.gegenbauer.catspy.file const val KB = 1024L const val MB = 1024 * KB const val GB = 1024 * MB const val TB = 1024 * GB
0
Kotlin
1
7
70d905761d3cb0cb2e5ee9b80ceec72fca46ee52
130
CatSpy
Apache License 2.0
apina-core/src/main/kotlin/fi/evident/apina/output/swift/SwiftGenerator.kt
javier-vilares
219,011,076
true
{"Kotlin": 200630, "TypeScript": 9315, "Java": 4642}
package fi.evident.apina.output.swift import fi.evident.apina.model.ApiDefinition import fi.evident.apina.model.settings.TranslationSettings import fi.evident.apina.model.type.ApiType class SwiftGenerator(val api: ApiDefinition, val settings: TranslationSettings) { private val out = SwiftWriter() val output: String get() = out.output fun writeApi() { out.writeLine("// Automatically generated from server-side definitions by Apina (https://apina.evident.fi)") out.writeLine("import Foundation") out.writeLine() writeTypes() } private fun writeTypes() { check(settings.imports.isEmpty()) { "Imports are not yet supported for Swift" } if (api.typeAliases.isNotEmpty()) { for ((alias, target) in api.typeAliases) out.writeLine("typealias ${alias.name} = ${target.toSwift()};") out.writeLine() } if (api.enumDefinitions.isNotEmpty()) { for (enum in api.enumDefinitions) { out.writeBlock("enum ${enum.type.name}: String, Codable") { for (constant in enum.constants) out.writeLine("case $constant") } } out.writeLine() } if (api.classDefinitions.isNotEmpty()) { for (classDefinition in api.classDefinitions) { out.writeStruct(classDefinition.type.name, ": Codable") { for (property in classDefinition.properties) { val nullable = property.type is ApiType.Nullable val init = if (nullable) " = nil" else "" out.writeLine("var ${property.name}: ${property.type.toSwift()}$init") } } } out.writeLine() } check(api.discriminatedUnionDefinitions.isEmpty()) { "Discriminated unions are not yet supported for Swift" } } }
0
Kotlin
1
1
6e048b6d2ebfaa57c783e4b4cd2b12a8168876f0
1,985
apina
MIT License
core/model/src/commonMain/kotlin/io/github/droidkaigi/confsched/model/ColoredImageBase64.kt
DroidKaigi
776,354,672
false
{"Kotlin": 1119401, "Swift": 211686, "Shell": 2954, "Makefile": 1314, "Ruby": 386}
package io.github.droidkaigi.confsched.model import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.IntSize expect fun generateColoredImageBase64( color: Color = Color.White, size: IntSize = IntSize(400, 400), ): String
49
Kotlin
201
438
57c38a76beb5b75edc9220833162e1257f40ac06
249
conference-app-2024
Apache License 2.0
faucet/src/main/kotlin/org/basinmc/faucet/internal/warn/Unrecommended.kt
BasinMC
59,916,990
false
null
/* * Copyright 2017 Hex <<EMAIL>> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.basinmc.faucet.internal.warn /** * Denotes an API method, class, or constructor whose use is not recommended. This should be used to * produce warnings at compile-time or at loading time. */ @MustBeDocumented @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CONSTRUCTOR) annotation class Unrecommended( /** * An explanation for why this API is not recommended. */ val value: String = "")
1
null
1
12
151c6a1897d80d2808387f46925cb470f2292537
1,253
Basin
Apache License 2.0
src/main/kotlin/com/realworld/springmongo/user/User.kt
a-mountain
396,700,282
false
null
package com.realworld.springmongo.user import com.realworld.springmongo.article.Article import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.core.mapping.Field @Document class User( @Id val id: String, var username: String, var encodedPassword: String, var email: String, var bio: String? = null, var image: String? = null, @Field("followingIds") private val _followingIds: MutableList<String> = ArrayList(), @Field("favoriteArticlesIds") private val _favoriteArticlesIds: MutableList<String> = ArrayList(), ) { val followingIds: MutableList<String> get() = _followingIds val favoriteArticlesIds: List<String> get() = _favoriteArticlesIds fun follow(followerId: String) { _followingIds.add(followerId) } fun follow(follower: User) { follow(follower.id) } fun unfollow(userId: String) { _followingIds.remove(userId) } fun unfollow(user: User) { unfollow(user.id) } fun favorite(article: Article) { article.incrementFavoritesCount() _favoriteArticlesIds.add(article.id) } fun unfavorite(article: Article) { article.decrementFavoritesCount() _favoriteArticlesIds.remove(article.id) } fun isFollowing(user: User) = _followingIds.contains(user.id) fun isFollower(user: User) = user.isFollowing(this) fun isFavoriteArticle(article: Article): Boolean = _favoriteArticlesIds.contains(article.id) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as User if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } override fun toString(): String { return "User(id='$id', username='$username', encodedPassword='$<PASSWORD>', email='$email', bio='$bio', image='$image', _followingIds=$_followingIds, _favoriteArticlesIds=$_favoriteArticlesIds)" } }
0
Kotlin
4
9
318a7c72d4fd9d5aea4f92e68c24233fd143dbb6
2,117
realworld-spring-webflux-kt
MIT License
src/main/kotlin/testee/it/e2e/core/pages/Number.kt
hibissscus
318,316,878
false
{"Kotlin": 76082, "JavaScript": 1388}
package testee.it.e2e.core.pages import org.openqa.selenium.By import org.openqa.selenium.WebElement import org.openqa.selenium.support.ui.ExpectedConditions interface Number : Driver { /** * Checking [number] of [WebElement]s with given [locator] */ fun numberOfElementsToBe(locator: By, number: Int): List<WebElement> { return wait().until(ExpectedConditions.numberOfElementsToBe(locator, number)) } /** * Checking [number] of [WebElement]s with given [locator] to be more than */ fun numberOfElementsToBeMoreThan(locator: By, number: Int): List<WebElement> { return wait().until(ExpectedConditions.numberOfElementsToBeMoreThan(locator, number)) } /** * Checking [number] of [WebElement]s with given [locator] to be less than */ fun numberOfElementsToBeLessThan(locator: By, number: Int): List<WebElement> { return wait().until(ExpectedConditions.numberOfElementsToBeLessThan(locator, number)) } }
1
Kotlin
0
2
9277975eeab90c929ec159472135a359df1469ed
999
testee
Apache License 2.0
app/src/main/java/br/com/mathsemilio/simpleapodbrowser/infrastructure/network/response/ApodResponse.kt
mttwmenezes
794,356,939
false
{"Kotlin": 175149}
/* 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 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 br.com.mathsemilio.simpleapodbrowser.infrastructure.network.response import com.google.gson.annotations.SerializedName data class ApodResponse( @SerializedName("concept_tags") val conceptTags: Boolean, val title: String, val url: String, val date: String, @SerializedName("media_type") val mediaType: String, val explanation: String, @SerializedName("thumbnail_url") val thumbnailUrl: String?, val concepts: List<String>, val copyright: String? )
1
Kotlin
0
0
cfbf5ef872fee2b4250a8c7d24f787cf6924112e
1,059
simple-apod-browser-android
Apache License 2.0
src/main/kotlin/br/com/lucascm/mangaeasy/micro_api_monolito/features/mangas/repositories/MangaDetailsRepository.kt
manga-easy
627,169,031
false
{"Kotlin": 158887, "Dockerfile": 912}
package br.com.lucascm.mangaeasy.micro_api_monolito.features.mangas.repositories import br.com.lucascm.mangaeasy.micro_api_monolito.core.configs.RedisRepository import br.com.lucascm.mangaeasy.micro_api_monolito.features.mangas.entities.MandaDetailsEntity import org.springframework.stereotype.Repository @Repository interface MangaDetailsRepository : RedisRepository<MandaDetailsEntity, String> { fun findByOrderByCreatAtDesc(): List<MandaDetailsEntity> }
0
Kotlin
1
2
499fb4d6c332b0bd41a234dbf8fe1b2c20293e36
462
manga_easy_micro_api_monolito
MIT License
kotlin-node/src/jsMain/generated/node/crypto/GenerateKeySyncOptions.kt
JetBrains
93,250,841
false
{"Kotlin": 12159121, "JavaScript": 330528}
// Generated by Karakum - do not modify it manually! package node.crypto sealed external interface GenerateKeySyncOptions { var length: Double }
40
Kotlin
165
1,319
a8a1947d73e3ed26426f1e27b641bff427dfd6a0
152
kotlin-wrappers
Apache License 2.0
src/main/kotlin/com/kurovale/models/MessageSection.kt
kuro-vale
496,013,008
false
{"Kotlin": 22732, "FreeMarker": 15657, "CSS": 1244, "JavaScript": 593}
package com.kurovale.models enum class MessageSection { GENERAL_US, GENERAL_ES, GAMES, MOVIES, BOOKS }
0
Kotlin
0
6
548ac5ad05a2e7f2461b7eb7fbeca8d425c9e8b9
107
kuro-chat-ktor
MIT License
app/src/main/java/com/jiangkang/ktools/CrashInfoActivity.kt
Androidwl
317,710,299
true
{"Kotlin": 2368794, "JavaScript": 136056, "Java": 30535, "C++": 5737, "HTML": 5095, "CMake": 2645, "CSS": 2570, "Shell": 429}
package com.jiangkang.ktools import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.jiangkang.tools.extend.startActivity import kotlinx.android.synthetic.main.activity_crash_info.* import kotlinx.coroutines.MainScope class CrashInfoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_crash_info) val crashInfo = intent.getStringExtra("crash_info") crashInfo?.let { tv_crash_info.text = it } btn_crash_restart.setOnClickListener { [email protected]<MainActivity>() finish() } } }
0
null
0
0
03967b9324dc0c700ea9fca19e912cd4da18cf0d
733
KTools
MIT License
app/src/main/java/com/herdal/dummyshoppingcenter/ui/home/adapter/categories/CategoryViewHolder.kt
herdal06
574,877,371
false
{"Kotlin": 79242}
package com.herdal.dummyshoppingcenter.ui.home.adapter.categories import androidx.recyclerview.widget.RecyclerView import com.herdal.dummyshoppingcenter.databinding.ItemCategoryBinding import com.herdal.dummyshoppingcenter.ui.home.CategoryItemUiState import com.herdal.dummyshoppingcenter.utils.ext.executeWithAction class CategoryViewHolder( private val binding: ItemCategoryBinding, ) : RecyclerView.ViewHolder(binding.root) { fun bind(uiState: CategoryItemUiState) = binding.apply { binding.executeWithAction { this.uiState = uiState } } }
0
Kotlin
0
1
a4275cb6ff10c6bd3dc7fee2d4bb2f0dfabbd829
584
DummyShoppingCenter
Apache License 2.0