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
src/main/kotlin/net/rossharper/koin/main.kt
rossharper
107,672,515
false
null
package net.rossharper.koin import net.rossharper.koin.usecases.createBitcoinWalletGenerator class Koin { companion object { @JvmStatic fun main(args: Array<String>) { // TODO: put some proper CLI around this (this is temp to try it out) if (args.size != 2) { print("koin <passphrase> <salt>") return } val passphrase = args[0] val salt = args[1] println("Generating Bitcoin wallet with passphrase '$passphrase' and salt '$salt'...") val wallet = createBitcoinWalletGenerator().generate(passphrase, salt) println("Private key: ${wallet.privateKey}") println("Address: ${wallet.publicKey}") } } }
0
Kotlin
0
0
546360c44541f9f56c1023c9c0bdcdfa95fe86a7
762
koin
Apache License 2.0
ts-core/ts-proxy/src/main/kotlin/cn/tursom/proxy/Proxy.kt
tursom
213,611,087
false
null
package cn.tursom.proxy import cn.tursom.core.uncheckedCast interface Proxy<out T : ProxyMethod> : Iterable<T> { data class Result<out R>( val result: R, val success: Boolean = false, ) companion object { val failed: Result<*> = Result<Any?>(null, false) fun <R> of(): Result<R?> { return of(null) } /** * 返回一个临时使用的 Result 对象 * 因为是临时对象,所以不要把这个对象放到任何当前函数堆栈以外的地方 * 如果要长期储存对象请 new Result */ fun <R> of(result: R): Result<R> { return Result(result, true) } fun <R> failed(): Result<R> { return failed.uncheckedCast() } } } inline fun <T : ProxyMethod> Proxy<T>.forEachProxy(action: (T) -> Unit) { for (t in this) { action(t) } } inline fun <R, T : ProxyMethod> Proxy<T>.forFirstProxy(action: (T) -> Proxy.Result<R>?): Proxy.Result<R> { for (t in this) { val result = action(t) if (result != null && result.success) { return result } } return Proxy.failed() }
0
Kotlin
2
4
40801d52fbe5031bc5461635911d31efb52a76b4
979
TursomServer
MIT License
src/main/java/dev/mikchan/mcnp/motd/user/creator/UserManagerCreator.kt
MikChanNoPlugins
723,544,621
false
{"Kotlin": 22072}
package dev.mikchan.mcnp.motd.user.creator import dev.mikchan.mcnp.motd.MOTDPlugin import dev.mikchan.mcnp.motd.user.manager.IUserManager import dev.mikchan.mcnp.motd.user.manager.UserManager internal class UserManagerCreator : IUserManagerCreator { override fun build(plugin: MOTDPlugin): IUserManager { return UserManager(plugin) } }
0
Kotlin
0
0
d8abc26d9863ecb3c460446301ee3efc7f4bfdf4
354
MOTD
MIT License
src/ii_collections/n16FlatMap.kt
gokhanaliccii
124,394,310
true
{"Kotlin": 69758, "Java": 4952}
package ii_collections import java.util.* fun example() { val result = listOf("abc", "12").flatMap { it.toList() } result == listOf('a', 'b', 'c', '1', '2') } val Customer.orderedProducts: Set<Product> get() { val flatMap = this.orders.flatMap { it.products } return flatMap.toSet() } val Shop.allOrderedProducts: Set<Product> get() { return this.customers.flatMap { it.orders } .flatMap { it.products }.toSet() }
0
Kotlin
0
0
afc7a4e95af680859b0c512397b7a9d718d5fcb7
484
kotlin-koans
MIT License
plugins/kotlin/idea/tests/testData/resolve/referenceInLib/toLocalFun.kt
ingokegel
72,937,917
true
null
import inlibrary.test.* val tl = <caret>topLevel() // CONTEXT: return <ref-caret>local() // WITH_LIBRARY: inLibrarySource // REF: (in inlibrary.test.topLevel).local()
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
169
intellij-community
Apache License 2.0
src/main/kotlin/me/ste/stevesseries/base/ChatInputListener.kt
SteveTheEngineer
243,009,646
false
{"Gradle Kotlin DSL": 4, "Markdown": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Kotlin": 74, "INI": 1, "Java": 5}
package me.ste.stevesseries.base import me.ste.stevesseries.base.BaseAPIImpl import me.ste.stevesseries.base.api.event.EventManager import org.bukkit.event.Listener import org.bukkit.event.player.AsyncPlayerChatEvent import org.bukkit.event.player.PlayerCommandPreprocessEvent class ChatInputListener( private val impl: BaseAPIImpl ) : Listener { fun onPlayerChat(event: AsyncPlayerChatEvent) { if (this.impl.consumeChatInput(event.player, event.message)) { event.isCancelled = true } } fun onPlayerCommand(event: PlayerCommandPreprocessEvent) { if (this.impl.consumeChatInput(event.player, event.message)) { event.isCancelled = true } } fun register(manager: EventManager) { manager.listen(listener = this::onPlayerChat) manager.listen(listener = this::onPlayerCommand) } }
0
Kotlin
0
0
d8dc71fed6a5531e0ea8717fd965932a71030f65
878
SS-Core-Base
MIT License
program/src/main/kotlin/de/heilsen/ganzhornfest/program/GetStagesUseCase.kt
sebokopter
38,719,010
false
{"Kotlin": 315068, "Assembly": 1280}
package de.heilsen.ganzhornfest.program import de.heilsen.ganzhornfest.poi.PoiRepository import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toPersistentList import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class GetStagesUseCase @Inject constructor(private val poiRepository: PoiRepository) { operator fun invoke( ): Flow<ImmutableList<String>> = poiRepository.getStages() .map { it.toPersistentList() } }
0
Kotlin
0
2
52ad2fdffa6e35bd9f07039d141b3659e66722b5
522
ganzhornfest
MIT License
db-api/src/main/kotlin/repositories/DbDictionary.kt
crowdproj
543,982,440
false
{"Kotlin": 639694, "JavaScript": 83472, "HTML": 31654, "FreeMarker": 27019, "Batchfile": 876, "Shell": 842, "Dockerfile": 361}
package com.gitlab.sszuev.flashcards.repositories data class DbDictionary( val dictionaryId: String, val userId: String, val name: String, val sourceLang: DbLang, val targetLang: DbLang, val details: Map<String, Any>, ) { companion object { val NULL = DbDictionary( dictionaryId = "", userId = "", name = "", sourceLang = DbLang.NULL, targetLang = DbLang.NULL, details = emptyMap(), ) } }
3
Kotlin
0
2
dae3969737a2df47dcd3c1c5c1d3717450839b8a
509
opentutor
Apache License 2.0
backend/src/main/kotlin/com/github/davinkevin/podcastserver/cover/CoverRepository.kt
davinkevin
13,350,152
false
null
package com.github.davinkevin.podcastserver.cover import com.github.davinkevin.podcastserver.cover.DeleteCoverInformation.Item import com.github.davinkevin.podcastserver.cover.DeleteCoverInformation.Podcast import com.github.davinkevin.podcastserver.database.Tables.ITEM import com.github.davinkevin.podcastserver.database.Tables.PODCAST import com.github.davinkevin.podcastserver.database.tables.Cover.COVER import com.github.davinkevin.podcastserver.tag.Tag import org.jooq.DSLContext import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.core.scheduler.Schedulers import reactor.kotlin.core.publisher.toMono import java.net.URI import java.sql.Timestamp import java.time.OffsetDateTime import java.util.* class CoverRepository(private val query: DSLContext) { fun save(cover: CoverForCreation): Mono<Cover> = Mono.defer{ val id = UUID.randomUUID() query.insertInto(COVER) .set(COVER.ID, id) .set(COVER.WIDTH, cover.width) .set(COVER.HEIGHT, cover.height) .set(COVER.URL, cover.url.toASCIIString()) .toMono() .map { Cover(id, cover.url, cover.height, cover.width) } } .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()) fun findCoverOlderThan(date: OffsetDateTime): Flux<DeleteCoverInformation> = Flux.defer { Flux.from( query .select( PODCAST.ID, PODCAST.TITLE, ITEM.ID, ITEM.TITLE, COVER.ID, COVER.URL ) .from(COVER .innerJoin(ITEM).on(COVER.ID.eq(ITEM.COVER_ID)) .innerJoin(PODCAST).on(ITEM.PODCAST_ID.eq(PODCAST.ID)) ) .where(ITEM.CREATION_DATE.lessOrEqual(date)) .orderBy(COVER.ID.asc()) ) .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()) .map { (podcastId, podcastTitle, itemId, itemTitle, coverId, coverUrl) -> DeleteCoverInformation( id = coverId, extension = coverUrl.substringAfterLast("."), item = Item(itemId, itemTitle), podcast = Podcast(podcastId, podcastTitle) ) } } } data class CoverForCreation(val width: Int, val height: Int, val url: URI) data class DeleteCoverInformation(val id: UUID, val extension: String, val item: Item, val podcast: Podcast) { data class Item(val id: UUID, val title: String) data class Podcast(val id: UUID, val title: String) }
1
HTML
39
165
97b1793dc96a56e2e70cb4bd96e2bebe18cd13de
2,972
Podcast-Server
Apache License 2.0
ReSift/app/src/main/java/edu/uw/minh2804/resift/models/Author.kt
tomn2804
462,968,863
false
null
package edu.uw.minh2804.resift.models data class Author( val name: String, )
0
Kotlin
0
0
dcb2199e76105479bf22d7db83576e105b25f3e0
79
ReSift
MIT License
src/lang/clojure-psi-stubs.kt
zhanghuabin
73,789,401
true
{"Kotlin": 240392, "Lex": 4977, "Clojure": 853, "HTML": 245}
/* * Copyright 2016-present <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.intellij.clojure.psi.stubs import com.intellij.lang.ASTNode import com.intellij.lang.Language import com.intellij.psi.PsiFile import com.intellij.psi.stubs.* import com.intellij.psi.tree.IStubFileElementType import org.intellij.clojure.ClojureConstants import org.intellij.clojure.ClojureConstants.NS_USER import org.intellij.clojure.lang.ClojureLanguage import org.intellij.clojure.parser.ClojureTokens import org.intellij.clojure.psi.* import org.intellij.clojure.psi.impl.CDefImpl import org.intellij.clojure.psi.impl.CKeywordImpl import org.intellij.clojure.psi.impl.CMDefImpl /** * @author gregsh */ private val VERSION: Int = 5 private val NS_VERSION: Int = 1 private val DEF_VERSION: Int = 1 private val KEYWORD_VERSION: Int = 1 val NS_INDEX_KEY: StubIndexKey<String, ClojureFile> = StubIndexKey.createIndexKey("clj.namespaces") val DEF_INDEX_KEY: StubIndexKey<String, CDef> = StubIndexKey.createIndexKey("clj.definitions") val KEYWORD_INDEX_KEY: StubIndexKey<String, CKeyword> = StubIndexKey.createIndexKey("clj.keywords") class ClojureNSIndex : StringStubIndexExtension<ClojureFile>() { override fun getKey() = NS_INDEX_KEY override fun getVersion() = NS_VERSION } class ClojureDefsIndex : StringStubIndexExtension<CDef>() { override fun getKey() = DEF_INDEX_KEY override fun getVersion() = DEF_VERSION } class ClojureKeywordIndex : StringStubIndexExtension<CKeyword>() { override fun getKey() = KEYWORD_INDEX_KEY override fun getVersion() = KEYWORD_VERSION } class CKeywordStub(override val name: String, override val namespace: String, stub: StubElement<*>?) : StubBase<CKeyword>(stub, ClojureTypes.C_KEYWORD as IStubElementType<out StubElement<*>, *>), DefInfo { override val type = "keyword" } class CListStub(override val type: String, override val name: String, override val namespace: String, stub: StubElement<*>?) : StubBase<CList>(stub, ClojureTypes.C_LIST as IStubElementType<out StubElement<*>, *>), DefInfo { } class CFileStub private constructor(val namespace: String, file: ClojureFile?) : PsiFileStubImpl<ClojureFile>(file) { constructor(file: ClojureFile) : this(file.namespace, file) constructor(namespace: String) : this(namespace, null) override fun getType() = ClojureTokens.CLJ_FILE_TYPE } class ClojureFileElementType(name: String, language: Language) : IStubFileElementType<CFileStub>(name, language) { override fun getExternalId() = "${language.id.toLowerCase()}.FILE" override fun getStubVersion() = super.getStubVersion() + VERSION override fun getBuilder() = object: DefaultStubBuilder() { override fun createStubForFile(file: PsiFile): StubElement<*> { return CFileStub(file as ClojureFile) } } override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?): CFileStub = CFileStub(dataStream.readName()?.string?: NS_USER) override fun serialize(stub: CFileStub, dataStream: StubOutputStream) { dataStream.writeName(stub.namespace) } override fun indexStub(stub: PsiFileStub<*>, sink: IndexSink) { val o = stub as? CFileStub ?: return sink.occurrence(NS_INDEX_KEY, o.namespace) } } class CListElementType(name: String) : IStubElementType<CListStub, CDef>(name, ClojureLanguage), ClojureElementType { override fun getExternalId(): String = "clj." + super.toString() override fun createPsi(stub: CListStub) = if (stub.type == ClojureConstants.TYPE_PROTOCOL_METHOD) CMDefImpl(stub) else CDefImpl(stub) override fun createStub(psi: CDef, parentStub: StubElement<*>?): CListStub { val def = psi.def return CListStub(def.type, def.name, def.namespace, parentStub) } override fun serialize(stub: CListStub, dataStream: StubOutputStream) { dataStream.writeName(stub.type) dataStream.writeName(stub.name) dataStream.writeName(stub.namespace) } override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = CListStub( dataStream.readName()?.string ?: "", dataStream.readName()?.string ?: "", dataStream.readName()?.string ?: "", parentStub) override fun indexStub(stub: CListStub, sink: IndexSink) { sink.occurrence(DEF_INDEX_KEY, stub.name) } override fun shouldCreateStub(node: ASTNode?): Boolean { val psi = node?.psi ?: return false return psi is CDef && psi.firstChild.node.elementType == ClojureTypes.C_PAREN1 } } class CKeywordElementType(name: String) : IStubElementType<CKeywordStub, CKeyword>(name, ClojureLanguage), ClojureElementType { override fun getExternalId(): String = "clj." + super.toString() override fun createPsi(stub: CKeywordStub) = CKeywordImpl(stub) override fun createStub(psi: CKeyword, parentStub: StubElement<*>?) = CKeywordStub(psi.name, psi.namespace, parentStub) override fun serialize(stub: CKeywordStub, dataStream: StubOutputStream) { dataStream.writeName(stub.name) dataStream.writeName(stub.namespace) } override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = CKeywordStub(dataStream.readName()?.string ?: "", dataStream.readName()?.string ?: "", parentStub) override fun indexStub(stub: CKeywordStub, sink: IndexSink) = sink.occurrence(KEYWORD_INDEX_KEY, stub.name) }
0
Kotlin
0
0
64ae80286d4e20e9d91da43d21e349cfbb3629a0
5,888
Clojure-Kit
Apache License 2.0
app/src/main/java/com/habitude/habit/ui/fragment/MyHabitsFragment.kt
vickatGit
663,121,210
false
{"Kotlin": 482474, "Java": 4691}
package com.example.habit.ui.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.navigation.fragment.findNavController import com.example.habit.R import com.example.habit.databinding.FragmentMyHabitsBinding import com.example.habit.ui.fragment.Habits.HabitsFragment class MyHabitsFragment : Fragment() { private var _binding: FragmentMyHabitsBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding=FragmentMyHabitsBinding.inflate(inflater,container,false) binding.newHabitContainer.setOnClickListener { findNavController().navigate(R.id.action_myHabitsFragment_to_addHabitFragment) } binding.habits.setOnClickListener { findNavController().navigate(R.id.action_myHabitsFragment_to_habitsFragment,Bundle().apply { putBoolean(HabitsFragment.IS_COMPLETED_HABITS,false) }) } binding.groupHabitsCont.setOnClickListener { findNavController().navigate(R.id.action_myHabitsFragment_to_groupsFragment,Bundle().apply { putBoolean(HabitsFragment.IS_COMPLETED_HABITS,true) }) } binding.completedHabits.setOnClickListener { findNavController().navigate(R.id.action_myHabitsFragment_to_habitsFragment,Bundle().apply { putBoolean(HabitsFragment.IS_COMPLETED_HABITS,true) }) } binding.back.setOnClickListener { findNavController().popBackStack() } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding=null } }
0
Kotlin
0
0
67559162f6501881b4fbd9ff807e6e13023fc087
1,907
HB
MIT License
src/Builder_Pattern_3/Pepsi.kt
estand25
119,630,165
false
null
package Builder_Pattern_3 import Builder_Pattern_3.Abstract.ColdDrink class Pepsi: ColdDrink() { override fun price(): Float? = 35.0f override fun name(): String? = "Pepsi" }
0
Kotlin
0
0
52de8a1993e3043fc5bfe36cc1fb1ca09e80b7d3
185
JavaDesignPattern
The Unlicense
app/src/main/java/xyz/teamgravity/retrofitfileupload/presentation/screen/ImageUploadScreen.kt
gohil-rahul-tft
553,570,011
false
{"Kotlin": 16229}
package xyz.teamgravity.retrofitfileupload.presentation.screen import androidx.annotation.StringRes import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import xyz.teamgravity.retrofitfileupload.R import xyz.teamgravity.retrofitfileupload.presentation.viewmodel.ImageUploadViewModel @Composable fun ImageUploadScreen(viewModel: ImageUploadViewModel = hiltViewModel()) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { FileUploadWithProgress( progress = viewModel.imageProgressState.value, isProgressing = viewModel.isImageProgressing.value, buttonTag = R.string.upload_image ) { viewModel.onUploadImage() } FileUploadWithProgress( progress = viewModel.pdfProgressState.value, isProgressing = viewModel.isPDFProgressing.value, buttonTag = R.string.upload_pdf ) { viewModel.onUploadPDF() } } } @Composable fun FileUploadWithProgress( progress: Int = 10, @StringRes buttonTag: Int = -1, isProgressing: Boolean = false, onClick: () -> Unit, ) { Column { Button(onClick = onClick) { Text(text = stringResource(id = buttonTag)) } if (isProgressing) { LinearProgressIndicator( progress = (progress.toFloat() / 100), // color = Color.Red, ) } } } @Composable @Preview(showBackground = true) fun ImageUploadWithProgressPreview() { FileUploadWithProgress() {} }
0
Kotlin
0
0
b88ba460f3add7d7e0c416507e59bb8077e564c6
2,167
File-Upload-With-Progress
Apache License 2.0
app/src/main/java/com/datamate/mycomposebottomnav/navigation/BottomNavItem.kt
Garycoco
614,863,318
false
null
package com.datamate.mycomposebottomnav.navigation import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Phone import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.Phone import androidx.compose.material.icons.outlined.Settings import androidx.compose.ui.graphics.vector.ImageVector data class BottomNavItem( val name: String, val route: String, val icon: ImageVector, val selectedIcons: ImageVector ) val bottomNabBarItems = listOf( BottomNavItem( name = "Home", route = Home.route, icon = Icons.Outlined.Home, selectedIcons = Icons.Filled.Home ), BottomNavItem( name = "Settings", route = Settings.route, icon = Icons.Outlined.Settings, selectedIcons = Icons.Filled.Settings ), BottomNavItem( name = "Contacts", route = Contacts.route, icon = Icons.Outlined.Phone, selectedIcons = Icons.Filled.Phone ) )
0
Kotlin
0
0
cdcbb49d60dcd93fa56eaaf877a546ebd8c1b3d4
1,135
ComposeBottomNav
Apache License 2.0
android/quest/src/main/java/org/smartregister/fhircore/quest/ui/patient/details/QuestPatientDetailActivity.kt
opensrp
339,242,809
false
null
/* * Copyright 2021 Ona Systems, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.smartregister.fhircore.quest.ui.patient.details import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.annotation.StringRes import ca.uhn.fhir.context.FhirContext import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject import org.hl7.fhir.r4.model.QuestionnaireResponse import org.hl7.fhir.r4.model.ResourceType import org.smartregister.fhircore.engine.configuration.ConfigurationRegistry import org.smartregister.fhircore.engine.configuration.view.ConfigurableComposableView import org.smartregister.fhircore.engine.configuration.view.NavigationOption import org.smartregister.fhircore.engine.configuration.view.RegisterViewConfiguration import org.smartregister.fhircore.engine.ui.base.AlertDialogue import org.smartregister.fhircore.engine.ui.base.BaseMultiLanguageActivity import org.smartregister.fhircore.engine.ui.questionnaire.QuestionnaireActivity import org.smartregister.fhircore.engine.ui.questionnaire.QuestionnaireActivity.Companion.QUESTIONNAIRE_RESPONSE import org.smartregister.fhircore.engine.ui.questionnaire.QuestionnaireConfig import org.smartregister.fhircore.engine.ui.questionnaire.QuestionnaireType import org.smartregister.fhircore.engine.ui.theme.AppTheme import org.smartregister.fhircore.engine.util.extension.decodeResourceFromString import org.smartregister.fhircore.engine.util.extension.getEncounterId import org.smartregister.fhircore.quest.R import org.smartregister.fhircore.quest.configuration.view.DataDetailsListViewConfiguration import org.smartregister.fhircore.quest.configuration.view.QuestionnaireNavigationAction import org.smartregister.fhircore.quest.configuration.view.ResultDetailsNavigationConfiguration import org.smartregister.fhircore.quest.configuration.view.TestDetailsNavigationAction import org.smartregister.fhircore.quest.data.patient.model.QuestResultItem import org.smartregister.fhircore.quest.ui.patient.details.SimpleDetailsActivity.Companion.RECORD_ID_ARG import org.smartregister.fhircore.quest.util.QuestConfigClassification import org.smartregister.fhircore.quest.util.QuestJsonSpecificationProvider @AndroidEntryPoint class QuestPatientDetailActivity : BaseMultiLanguageActivity(), ConfigurableComposableView<DataDetailsListViewConfiguration> { var patientResourcesList: ArrayList<String> = arrayListOf() private lateinit var patientDetailConfig: DataDetailsListViewConfiguration private lateinit var patientId: String val patientViewModel by viewModels<ListDataDetailViewModel>() @Inject lateinit var configurationRegistry: ConfigurationRegistry @Inject lateinit var questJsonSpecificationProvider: QuestJsonSpecificationProvider override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) patientId = intent.extras?.getString(QuestionnaireActivity.QUESTIONNAIRE_ARG_PATIENT_KEY)!! patientViewModel.apply { val detailActivity = this@QuestPatientDetailActivity onBackPressClicked.observe(detailActivity) { backPressed -> if (backPressed) detailActivity.finish() } fetchPatientResources(patientId) .observe(detailActivity, detailActivity::handlePatientResources) onMenuItemClicked.observe(detailActivity, detailActivity::launchTestResults) onFormItemClicked.observe(detailActivity, detailActivity::launchQuestionnaireForm) onFormTestResultClicked.observe(detailActivity, detailActivity::onTestResultItemClickListener) } patientDetailConfig = configurationRegistry.retrieveConfiguration( configClassification = QuestConfigClassification.PATIENT_DETAILS_VIEW, questJsonSpecificationProvider.getJson() ) if (configurationRegistry.isAppIdInitialized()) { configureViews(patientDetailConfig) } loadData() setContent { AppTheme { QuestPatientDetailScreen(patientViewModel) } } } private fun handlePatientResources(resourceList: ArrayList<String>) { if (resourceList.isNotEmpty()) patientResourcesList.addAll(resourceList) } override fun onResume() { super.onResume() loadData() } fun loadData() { patientViewModel.run { getDemographicsWithAdditionalData(patientId, patientDetailConfig) getAllResults( patientId, ResourceType.Patient, patientDetailConfig.questionnaireFilter!!, patientDetailConfig ) getAllForms(patientDetailConfig.questionnaireFilter!!) } } private fun launchTestResults(@StringRes id: Int) { when (id) { R.string.edit_patient_info -> { startActivity( Intent(this, QuestionnaireActivity::class.java) .putExtras( QuestionnaireActivity.intentArgs( clientIdentifier = patientId, formName = getRegistrationForm(), questionnaireType = QuestionnaireType.EDIT ) ) .apply { if (patientResourcesList.isNotEmpty()) { this.putStringArrayListExtra( QuestionnaireActivity.QUESTIONNAIRE_POPULATION_RESOURCES, patientResourcesList ) } } ) } } } fun getRegistrationForm(): String { return configurationRegistry.retrieveConfiguration<RegisterViewConfiguration>( configClassification = QuestConfigClassification.PATIENT_REGISTER, questJsonSpecificationProvider.getJson() ) .registrationForm } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) getResultDetailsNavigationOptions().navigationOptions.forEach { when (it.action) { is TestDetailsNavigationAction -> { data?.getStringExtra(QUESTIONNAIRE_RESPONSE)?.let { val response = FhirContext.forR4Cached().newJsonParser().parseResource(it) as QuestionnaireResponse response.getEncounterId()?.let { startActivity( Intent(this, SimpleDetailsActivity::class.java).apply { putExtra(RECORD_ID_ARG, it.replace("#", "")) } ) } } } is QuestionnaireNavigationAction -> {} } } } private fun launchQuestionnaireForm(questionnaireConfig: QuestionnaireConfig?) { if (questionnaireConfig != null) { startActivityForResult( Intent(this, QuestionnaireActivity::class.java).apply { putExtras( QuestionnaireActivity.intentArgs( clientIdentifier = patientId, formName = questionnaireConfig.identifier ) ) }, 0 ) } } private fun onTestResultItemClickListener(resultItem: QuestResultItem?) { getResultDetailsNavigationOptions().navigationOptions.forEach { handleNavigationOptions(it, resultItem, patientId) } } private fun handleNavigationOptions( navigationOption: NavigationOption, resultItem: QuestResultItem?, patientId: String ) { when (navigationOption.action) { is QuestionnaireNavigationAction -> { resultItem?.let { when { resultItem.source.second.logicalId.isNullOrBlank() -> { AlertDialogue.showErrorAlert(this, R.string.invalid_form_id) } else -> { startActivity( Intent(this@QuestPatientDetailActivity, QuestionnaireActivity::class.java) .putExtras( QuestionnaireActivity.intentArgs( clientIdentifier = patientId, formName = resultItem.source.second.logicalId!!, questionnaireType = QuestionnaireType.READ_ONLY, questionnaireResponse = resultItem.source.first.questionnaireResponseString .decodeResourceFromString() ) ) ) } } } } is TestDetailsNavigationAction -> { resultItem?.source?.first?.encounterId?.let { startActivity( Intent(this@QuestPatientDetailActivity, SimpleDetailsActivity::class.java).apply { putExtra(RECORD_ID_ARG, it) } ) } } } } fun getResultDetailsNavigationOptions() = configurationRegistry.retrieveConfiguration<ResultDetailsNavigationConfiguration>( configClassification = QuestConfigClassification.RESULT_DETAILS_NAVIGATION, questJsonSpecificationProvider.getJson() ) override fun configureViews(viewConfiguration: DataDetailsListViewConfiguration) { patientViewModel.updateViewConfigurations(viewConfiguration) } }
158
Kotlin
7
18
9d7044a12ef2726705a3019cb26ab03bc48bc28c
9,603
fhircore
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress1010018.kt
pointillion
428,683,199
true
{"Kotlin": 1212476, "HTML": 26704, "CSS": 26127, "JavaScript": 1640}
package xyz.qwewqa.relive.simulator.core.presets.dress.generated import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType import xyz.qwewqa.relive.simulator.stage.character.Character import xyz.qwewqa.relive.simulator.stage.character.DamageType import xyz.qwewqa.relive.simulator.stage.character.Position val dress1010018 = PartialDressBlueprint( id = 1010018, name = "明智光秀", baseRarity = 4, character = Character.Karen, attribute = Attribute.Cloud, damageType = DamageType.Normal, position = Position.Middle, positionValue = 25050, stats = StatData( hp = 1282, actPower = 243, normalDefense = 131, specialDefense = 87, agility = 217, dexterity = 5, critical = 50, accuracy = 0, evasion = 0, ), growthStats = StatData( hp = 42240, actPower = 4010, normalDefense = 2160, specialDefense = 1440, agility = 3580, ), actParameters = mapOf( ActType.Act1 to listOf( ActParameters( values = listOf(165, 173, 181, 189, 198), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(20, 22, 24, 27, 30), times = listOf(3, 3, 3, 3, 3), ), ActParameters( values = listOf(20, 22, 24, 27, 30), times = listOf(3, 3, 3, 3, 3), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.Act2 to listOf( ActParameters( values = listOf(165, 173, 181, 189, 198), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(3, 3, 3, 3, 3), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.Act3 to listOf( ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(100, 100, 100, 100, 100), times = listOf(3, 3, 3, 3, 3), ), ActParameters( values = listOf(165, 173, 181, 189, 198), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.ClimaxAct to listOf( ActParameters( values = listOf(200, 210, 220, 230, 240), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(1, 1, 1, 1, 1), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ), autoSkillRanks = listOf(1, 4, 9, null), autoSkillPanels = listOf(0, 0, 5, 0), rankPanels = listOf( listOf( StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.SpecialDefense, 1), ), listOf( StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.Agility, 7), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 3), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 3), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Hp, 3), StatBoost(StatBoostType.ActPower, 3), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Hp, 4), ), listOf( StatBoost(StatBoostType.SpecialDefense, 3), StatBoost(StatBoostType.NormalDefense, 7), StatBoost(StatBoostType.NormalDefense, 3), StatBoost(StatBoostType.Agility, 8), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 4), StatBoost(StatBoostType.Hp, 4), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 4), StatBoost(StatBoostType.Act1Level, 0), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.SpecialDefense, 8), StatBoost(StatBoostType.ActPower, 5), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Hp, 5), ), listOf( StatBoost(StatBoostType.Hp, 5), StatBoost(StatBoostType.NormalDefense, 8), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Agility, 9), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 5), StatBoost(StatBoostType.NormalDefense, 8), StatBoost(StatBoostType.NormalDefense, 4), ), listOf( StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.Agility, 11), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.SpecialDefense, 6), ), listOf( StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.NormalDefense, 6), ), ), friendshipPanels = listOf( StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.SpecialDefense, 1), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.SpecialDefense, 1), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), ), remakeParameters = listOf( StatData( hp = 9900, actPower = 240, normalDefense = 690, specialDefense = 150, agility = 180, ), StatData( hp = 16500, actPower = 400, normalDefense = 1150, specialDefense = 250, agility = 300, ), StatData( hp = 26400, actPower = 640, normalDefense = 1840, specialDefense = 400, agility = 480, ), StatData( hp = 33000, actPower = 800, normalDefense = 2300, specialDefense = 500, agility = 600, ), ), )
0
Kotlin
0
0
53479fe3d1f4a067682509376afd87bdd205d19d
10,050
relive-simulator
MIT License
src/org/mrr/selectors/puppeteer/SelectorsFactory.kt
mw1980
266,480,832
false
null
package org.mrr.selectors.puppeteer import org.mrr.selectors.core.SelectorProviderFactory private val puppeteerHtmlIdSelector = fun (htmlId: String): String = "[id=\"$htmlId\"]" private val puppeteerCssSelector = fun (css: String): String = "[css=\"$css\"]" private val puppeteerXPathSelector = fun (xPath: String): String = "[xpath=\"$xPath\"]" private val puppeteerDataTestIdSelector = fun (dataTestId: String): String = "[data-testid==\"$dataTestId\"]" class PuppeteerSelectorProviderFactory : SelectorProviderFactory { override fun htmlIdSelectorProvider(): (String) -> String { return puppeteerHtmlIdSelector } override fun cssSelectorProvider(): (String) -> String { return puppeteerCssSelector } override fun xPathSelectorProvider(): (String) -> String { return puppeteerXPathSelector } override fun dataTestIdSelectorProvider(): (String) -> String { return puppeteerDataTestIdSelector } }
0
Kotlin
0
0
2d49091e6fce862bab88da3277c5478d18440e9d
970
twinkie
MIT License
ui/common/src/main/java/ly/david/ui/common/paging/IPagedList.kt
lydavid
458,021,427
false
null
package ly.david.ui.common.paging import androidx.paging.PagingData import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import ly.david.data.domain.listitem.ListItemModel interface IPagedList<LI : ListItemModel> { data class ViewModelState( val resourceId: String = "", val query: String = "", val isRemote: Boolean = true ) val resourceId: MutableStateFlow<String> val query: MutableStateFlow<String> val isRemote: MutableStateFlow<Boolean> fun loadPagedResources(resourceId: String) { this.resourceId.value = resourceId } fun updateQuery(query: String) { this.query.value = query } fun setRemote(isRemote: Boolean) { this.isRemote.value = isRemote } val pagedResources: Flow<PagingData<LI>> }
54
Kotlin
0
4
052613fefaeb5a687ee36d0f3889d9a120224994
830
MusicSearch
Apache License 2.0
src/com/jdiazcano/kota/model/address.kt
jdiazcano
181,292,926
false
null
package com.jdiazcano.kota.model import com.jdiazcano.kota.utils.ADDRESS_LENGTH_WITHOUT_CHECKSUM import com.jdiazcano.kota.utils.ADDRESS_LENGTH_WITH_CHECKSUM typealias Address = String fun String.toAddress(): Seed = if (isValidAddress(this)) this else throw IllegalArgumentException("Address must be valid: $this") private fun isValidAddress(address: String): Boolean { return when (address.length) { ADDRESS_LENGTH_WITH_CHECKSUM -> address.isTrytes(ADDRESS_LENGTH_WITH_CHECKSUM) ADDRESS_LENGTH_WITHOUT_CHECKSUM -> address.isTrytes(ADDRESS_LENGTH_WITHOUT_CHECKSUM) else -> false } } fun Address.removeChecksum(): Address = if (length == ADDRESS_LENGTH_WITHOUT_CHECKSUM) { this } else { substring(0, ADDRESS_LENGTH_WITHOUT_CHECKSUM) }
1
null
1
1
a3a5b5bd71110b61286a274334f8c5be2326c4da
818
iota-kotlin
Apache License 2.0
src/main/kotlin/com/theo/plugins/openapi/OpenApiPluginExtension.kt
theochiu2010
521,088,018
false
{"Kotlin": 14544}
package com.theo.plugins.openapi import org.gradle.api.provider.ListProperty interface OpenApiPluginExtension { val producers: ListProperty<String> val consumers: ListProperty<String> }
0
Kotlin
0
0
200375063b86c201a2e08a7b7ede4a5228b6f600
195
OpenApiGradlePlugin
MIT License
app/src/main/java/com/hoy/ecommercecompose/data/source/remote/model/response/GetProductDetailResponse.kt
yusufaltunoymak
835,617,146
false
{"Kotlin": 389192}
package com.hoy.ecommercecompose.data.source.remote.model.response import com.google.gson.annotations.SerializedName import com.hoy.ecommercecompose.data.source.remote.model.ProductDto data class GetProductDetailResponse( @SerializedName("product") val productDto: ProductDto? ) : BaseResponse()
0
Kotlin
1
0
e02d0f14d89442f1195cde84f7783cda4a468009
306
ECommerceCompose
MIT License
mulighetsrommet-api/src/test/kotlin/no/nav/mulighetsrommet/api/repositories/DeltakerRepositoryTest.kt
navikt
435,813,834
false
{"Kotlin": 1627414, "TypeScript": 1445375, "SCSS": 41073, "JavaScript": 27458, "PLpgSQL": 14591, "Handlebars": 3189, "HTML": 2263, "Dockerfile": 1423, "CSS": 1145, "Shell": 396}
package no.nav.mulighetsrommet.api.repositories import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.collections.shouldContainExactly import no.nav.mulighetsrommet.api.createDatabaseTestConfig import no.nav.mulighetsrommet.api.domain.dbo.DeltakerDbo import no.nav.mulighetsrommet.api.fixtures.MulighetsrommetTestDomain import no.nav.mulighetsrommet.api.fixtures.TiltaksgjennomforingFixtures import no.nav.mulighetsrommet.database.kotest.extensions.FlywayDatabaseTestListener import no.nav.mulighetsrommet.domain.dto.DeltakerStatus import java.time.LocalDateTime import java.util.* class DeltakerRepositoryTest : FunSpec({ val database = extension(FlywayDatabaseTestListener(createDatabaseTestConfig())) val domain = MulighetsrommetTestDomain( gjennomforinger = listOf(TiltaksgjennomforingFixtures.Oppfolging1, TiltaksgjennomforingFixtures.Oppfolging2), ) beforeEach { domain.initialize(database.db) } context("consume deltakere") { val deltakere = DeltakerRepository(database.db) val registrertTidspunkt = LocalDateTime.of(2023, 3, 1, 0, 0, 0) val deltaker1 = DeltakerDbo( id = UUID.randomUUID(), gjennomforingId = TiltaksgjennomforingFixtures.Oppfolging1.id, startDato = null, sluttDato = null, registrertTidspunkt = registrertTidspunkt, endretTidspunkt = registrertTidspunkt, stillingsprosent = 100.0, status = DeltakerStatus( DeltakerStatus.Type.VENTER_PA_OPPSTART, aarsak = null, opprettetDato = registrertTidspunkt, ), ) val deltaker2 = deltaker1.copy( id = UUID.randomUUID(), gjennomforingId = TiltaksgjennomforingFixtures.Oppfolging2.id, ) test("CRUD") { deltakere.upsert(deltaker1) deltakere.upsert(deltaker2) deltakere.getAll().shouldContainExactly(deltaker1, deltaker2) val avsluttetDeltaker2 = deltaker2.copy( status = DeltakerStatus( DeltakerStatus.Type.HAR_SLUTTET, aarsak = null, opprettetDato = LocalDateTime.of(2023, 3, 2, 0, 0, 0), ), ) deltakere.upsert(avsluttetDeltaker2) deltakere.getAll().shouldContainExactly(deltaker1, avsluttetDeltaker2) deltakere.delete(deltaker1.id) deltakere.getAll().shouldContainExactly(avsluttetDeltaker2) } test("get by tiltaksgjennomforing") { deltakere.upsert(deltaker1) deltakere.upsert(deltaker2) deltakere .getAll(tiltaksgjennomforingId = TiltaksgjennomforingFixtures.Oppfolging1.id) .shouldContainExactly(deltaker1) deltakere .getAll(tiltaksgjennomforingId = TiltaksgjennomforingFixtures.Oppfolging2.id) .shouldContainExactly(deltaker2) } } })
2
Kotlin
2
7
ee39b300c4f1d01462fc37851fc039ba9d16531b
3,045
mulighetsrommet
MIT License
src/main/kotlin/com/dataxow/ui/window/MainWindow.kt
paulocoutinhox
763,882,755
false
{"Kotlin": 94338, "Vue": 12412, "JavaScript": 1759, "HTML": 1023, "SCSS": 154}
package com.dataxow.ui.window import androidx.compose.foundation.layout.Column import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Scaffold import androidx.compose.material.Tab import androidx.compose.material.TabRow import androidx.compose.material.TabRowDefaults.Indicator import androidx.compose.material.TabRowDefaults.tabIndicatorOffset import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.ApplicationScope import androidx.compose.ui.window.Window import androidx.compose.ui.window.WindowState import com.dataxow.enum.MainTab import com.dataxow.ui.components.loadingDialog import com.dataxow.ui.content.* @Composable fun mainWindow( applicationScope: ApplicationScope, projectPath: String, setProjectPath: (String) -> Unit, isLoading: Boolean, setForceUpdateWindowState: () -> Unit, imagePath: String?, setImagePath: (String?) -> Unit, videoPath: String?, setVideoPath: (String?) -> Unit, playerWindowOpen: Boolean, setPlayerWindowOpen: (Boolean) -> Unit, ips: List<String>, serverHost: String, setServerHost: (String) -> Unit, serverPort: String, setServerPort: (String) -> Unit, qrCodeBitmap: ImageBitmap?, setQrCodeBitmap: (ImageBitmap?) -> Unit, serverStatus: Boolean, setServerStatus: (Boolean) -> Unit, startServer: (String, Int) -> Unit, stopServer: () -> Unit, reload: () -> Unit, ) { val windowState by remember { mutableStateOf(WindowState()) } windowState.size = DpSize(1024.dp, 768.dp) val imageListListState = rememberLazyListState() val imageListGridState = rememberLazyGridState() var imageListIsGrid by remember { mutableStateOf(false) } val videoListListState = rememberLazyListState() val textListSearchResultsListState = rememberLazyListState() val textListPreviewListState = rememberLazyListState() val textListContentSelectedListState = rememberLazyListState() val textListContentSelectedPreviewListState = rememberLazyListState() Window( onCloseRequest = applicationScope::exitApplication, state = windowState, title = "DataXow", ) { Scaffold { Column { var selectedTab by remember { mutableStateOf(MainTab.Home) } TabRow( selectedTabIndex = selectedTab.ordinal, indicator = { tabPositions -> Indicator( Modifier.tabIndicatorOffset(tabPositions[selectedTab.ordinal]), color = Color(0xFFC5CAE9), height = 3.dp ) } ) { MainTab.entries.forEach { tab -> Tab( text = { if (selectedTab == tab) { Text("• ${tab.title}") } else { Text(tab.title) } }, selected = selectedTab == tab, onClick = { selectedTab = tab }, ) } } when (selectedTab) { MainTab.Home -> homeContent( applicationScope = applicationScope, projectPath = projectPath, setProjectPath = { setProjectPath(it) }, setForceUpdateWindowState = { setForceUpdateWindowState() }, reload = { reload() } ) MainTab.Images -> imageListContent( applicationScope = applicationScope, projectPath = projectPath, imagePath = imagePath, setImagePath = { setImagePath(it) }, setPlayerWindowOpen = { setPlayerWindowOpen(it) }, isGrid = imageListIsGrid, setIsGrid = { imageListIsGrid = it }, listState = imageListListState, gridState = imageListGridState, reload = { reload() } ) MainTab.Videos -> videoListContent( applicationScope = applicationScope, projectPath = projectPath, videoPath = videoPath, setVideoPath = { setVideoPath(it) }, setPlayerWindowOpen = { setPlayerWindowOpen(it) }, listState = videoListListState, reload = { reload() } ) MainTab.Text -> textContent( applicationScope = applicationScope, projectPath = projectPath, setPlayerWindowOpen = { setPlayerWindowOpen(it) }, searchResultsListState = textListSearchResultsListState, previewListState = textListPreviewListState, contentSelectedListState = textListContentSelectedListState, contentSelectedPreviewListState = textListContentSelectedPreviewListState, ) MainTab.Remote -> remoteContent( applicationScope = applicationScope, projectPath = projectPath, ips = ips, serverHost = serverHost, setServerHost = { setServerHost(it) }, serverPort = serverPort, setServerPort = { setServerPort(it) }, qrCodeBitmap = qrCodeBitmap, setQrCodeBitmap = { setQrCodeBitmap(it) }, serverStatus = serverStatus, setServerStatus = { setServerStatus(it) }, startServer = { host, port -> startServer(host, port) }, stopServer = { stopServer() } ) } } loadingDialog(isLoading) } } }
0
Kotlin
0
1
0c5d679e45680e37fb477d585e719a0aa516aec7
7,542
dataxow
MIT License
features/report/src/main/java/com/yuriikonovalov/report/framework/ui/common/AccountFilterAdapter.kt
yuriikonovalov
563,974,428
false
{"Kotlin": 872022}
package com.yuriikonovalov.report.framework.ui.common import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.yuriikonovalov.common.application.entities.account.Account import com.yuriikonovalov.common.presentation.model.AccountUi import com.yuriikonovalov.report.databinding.ItemAccountFilterAdapterBinding import com.yuriikonovalov.report.presentation.model.AccountItem class AccountFilterAdapter(private val onItemClick: (account: Account) -> Unit) : ListAdapter<AccountItem, AccountFilterAdapter.AccountViewHolder>(DiffCallback) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AccountViewHolder { return AccountViewHolder.from(parent, onItemClick = { position -> onItemClick(currentList[position].account) }) } override fun onBindViewHolder(holder: AccountViewHolder, position: Int) { holder.bind(getItem(position)) } class AccountViewHolder private constructor( private val binding: ItemAccountFilterAdapterBinding, private val onItemClick: (position: Int) -> Unit ) : RecyclerView.ViewHolder(binding.root) { init { binding.root.setOnClickListener { onItemClick(bindingAdapterPosition) } } fun bind(item: AccountItem) { val ui = AccountUi.from(item.account) binding.name.text = ui.name binding.checkbox.isChecked = item.checked } companion object { fun from( parent: ViewGroup, onItemClick: (position: Int) -> Unit ): AccountViewHolder { val binding = ItemAccountFilterAdapterBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return AccountViewHolder(binding, onItemClick) } } } private object DiffCallback : DiffUtil.ItemCallback<AccountItem>() { override fun areItemsTheSame(oldItem: AccountItem, newItem: AccountItem): Boolean { return oldItem.account.id == newItem.account.id } override fun areContentsTheSame(oldItem: AccountItem, newItem: AccountItem): Boolean { return oldItem == newItem } } }
0
Kotlin
0
0
8063508f836512fc8f8a0ba18f794bb895ee2449
2,465
budgethub
MIT License
pixelgrid/filter/jhlabs/src/main/kotlin/com/deflatedpickle/rawky/pixelgrid/filter/jhlabs/colours/Grayscale.kt
DeflatedPickle
197,672,095
false
null
/* Copyright (c) 2023 DeflatedPickle under the MIT license */ package com.deflatedpickle.rawky.pixelgrid.filter.jhlabs.colours import com.deflatedpickle.rawky.api.FilterCollection import com.jhlabs.image.GrayscaleFilter import java.awt.image.BufferedImage object Grayscale : FilterCollection.Filter() { override val name = "Grayscale" override val category = "Colour" override val comment = "Converts to grayscale" override fun filter( source: BufferedImage, ): BufferedImage = GrayscaleFilter().filter(source, null) }
7
Kotlin
6
27
6ee77e8f054571823d2448688f38ece858c2c2c4
551
Rawky
MIT License
domain/src/test/java/ru/cherryperry/amiami/domain/model/PriceTest.kt
CherryPerry
83,009,764
false
null
package ru.cherryperry.amiami.domain.model import org.junit.Assert import org.junit.Test class PriceTest { @Test fun testToStringDefault() { val price = Price(1.0) // should be without separator Assert.assertTrue(price.toString().matches(Regex("\\d+ ${ExchangeRates.DEFAULT}"))) } @Test fun testToStringOther() { val price = Price(1.0, "RUB") // should be with separator Assert.assertTrue(price.toString().matches(Regex("\\d+[,.]\\d+ RUB"))) } }
6
Kotlin
2
13
6cda5f48d33a31ab0d23814ad36fa525601892f1
522
Amiami-android-app
Apache License 2.0
src/test/kotlin/androidstudio/tools/missed/features/input/domain/usecase/sendevent/SendEventUseCaseImplTest.kt
rasoulmiri
668,869,188
false
null
package androidstudio.tools.missed.features.input.domain.usecase.sendevent import androidstudio.tools.missed.manager.adb.command.AdbCommand import androidstudio.tools.missed.manager.device.DeviceManager import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import io.mockk.unmockkAll import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.single import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class SendEventUseCaseImplTest { private val mockDeviceManager = mockk<DeviceManager>() private lateinit var useCase: SendEventUseCase @Before fun setUp() { useCase = SendEventUseCaseImpl(mockDeviceManager) } @After fun cleanup() { unmockkAll() } @Test fun `invoke() should emit success result when shell command succeeds`() = runTest { // Arrange val event = "KEYCODE_A" val expectedResult = Result.success(Unit) coEvery { mockDeviceManager.executeShellCommand(any()) } coAnswers { if (args.first() is AdbCommand.InputEvent) { Result.success("") } else { error("Unexpected command") } } // Act val result = useCase.invoke(event).single() // Assert assertEquals(expectedResult, result) coVerify { mockDeviceManager.executeShellCommand(match { it is AdbCommand.InputEvent && it.event == event }) } coVerify(exactly = 1) { mockDeviceManager.executeShellCommand(any()) } } @Test fun `invoke() should emit failure result when shell command fails`() = runTest { val event = "KEYCODE_B" val errorText = "Command failed" val exception = RuntimeException(errorText) val expectedResult = Result.failure<Unit>(exception) coEvery { mockDeviceManager.executeShellCommand(any()) } coAnswers { if (args.first() is AdbCommand.InputEvent) { Result.failure<String>(exception) } else { error("Unexpected command") } } // Act val result = useCase.invoke(event).single() // Assert assertEquals(expectedResult, result) coVerify { mockDeviceManager.executeShellCommand(match { it is AdbCommand.InputEvent && it.event == event }) } coVerify(exactly = 1) { mockDeviceManager.executeShellCommand(any()) } } }
0
null
0
2
fb33080fef3289880a4efdaf92bb9826c322cfc4
2,606
AndroidStudioToolsMissed
Apache License 2.0
SpinnerDatePickerLib/src/main/java/com/tsongkha/spinnerdatepicker/CustomTimePickerDialog.kt
datnguyencr
399,779,986
false
null
package com.tsongkha.spinnerdatepicker import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.AppCompatTextView import androidx.fragment.app.DialogFragment import java.text.DateFormat import java.text.DecimalFormat import java.text.NumberFormat import java.util.* class CustomTimePickerDialog constructor( var mainColor: Int, var blackColor: Int, private val mCallBack: OnTimeSetListener?, private val mOnCancel: OnTimeCancelListener?, var isDayShown: Boolean, var isTitleShown: Boolean, var customTitle: String?, var defaultHour: Int = 0, var defaultMinute: Int = 0 ) : DialogFragment(), OnTimeChangedListener { private var mPicker: TimePicker? = null private var mTitleDateFormat: DateFormat? = null private var mIsDayShown = true private var mIsTitleShown = true private var mCustomTitle: String? = "" private var vTitle: AppCompatTextView? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.date_picker_dialog_container, null, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dialog?.setCanceledOnTouchOutside(true) dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) mTitleDateFormat = DateFormat.getDateInstance(DateFormat.LONG, Locale.JAPAN) mIsDayShown = isDayShown mIsTitleShown = isTitleShown mCustomTitle = customTitle updateTitle(defaultHour, defaultMinute) val container = view.findViewById<ViewGroup>(R.id.datePickerContainer) vTitle = view.findViewById(R.id.vTitle) vTitle?.setTextColor(blackColor) val btnCancel = view.findViewById(R.id.vCancel) as AppCompatTextView btnCancel.setTextColor(blackColor) btnCancel.setOnClickListener { if (mOnCancel != null) { mPicker?.clearFocus() mOnCancel.onCancelled(mPicker) } dismiss() } val btnOk = view.findViewById(R.id.vOk) as AppCompatTextView btnOk.setTextColor(mainColor) btnOk.setOnClickListener { if (mCallBack != null) { mPicker?.clearFocus() mCallBack.onTimeSet( mPicker, mPicker?.mCurrentHour ?: 0, mPicker?.mCurrentMinute ?: 0 ) } dismiss() } mPicker = TimePicker(container, mainColor, blackColor) mPicker?.init( hour = defaultHour, minute = defaultMinute, isDayShown, this ) } interface OnTimeSetListener { fun onTimeSet(view: TimePicker?, hour: Int, minute: Int) } interface OnTimeCancelListener { fun onCancelled(view: TimePicker?) } private fun setTitle(title: String?) { if (vTitle != null) { vTitle?.text = title } } override fun onTimeChanged(view: TimePicker?, hour: Int, minute: Int) { updateTitle(hour, minute) } private fun updateTitle(hour: Int, minute: Int) { if (mIsTitleShown && mCustomTitle != null && !mCustomTitle!!.isEmpty()) { setTitle(mCustomTitle) } else if (mIsTitleShown) { val formatter: NumberFormat = DecimalFormat("00") val value = "${formatter.format(hour)}:${formatter.format(minute)}" setTitle(value) } else { setTitle(" ") } } }
1
null
1
1
625fa040d661ed098aa61e4788e4bd8f798f2dbc
3,814
spinnerdatepicker
Apache License 2.0
src/main/kotlin/no/nav/helse/AktoerId.kt
navikt
247,679,008
false
null
package no.nav.helse data class AktoerId(val id: String)
1
Kotlin
0
0
4a6bd25cc20ff2b446324b2162d572cac8d98968
57
omsorgspengerutbetalingsoknad-mottak
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/Billiard.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.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.rounded.Icons public val Icons.Filled.Billiard: ImageVector get() { if (_billiard != null) { return _billiard!! } _billiard = Builder(name = "Billiard", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(12.0f, 6.0f) arcToRelative(6.0f, 6.0f, 0.0f, true, false, 6.0f, 6.0f) arcToRelative(6.006f, 6.006f, 0.0f, false, false, -6.0f, -6.0f) close() moveTo(14.857f, 10.515f) lineTo(11.857f, 15.515f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, -1.714f, -1.03f) lineToRelative(2.091f, -3.485f) horizontalLineToRelative(-2.234f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f) horizontalLineToRelative(4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.857f, 1.515f) close() moveTo(12.0f, -0.0f) arcToRelative(12.0f, 12.0f, 0.0f, true, false, 12.0f, 12.0f) arcToRelative(12.013f, 12.013f, 0.0f, false, false, -12.0f, -12.0f) close() moveTo(12.0f, 20.0f) arcToRelative(8.0f, 8.0f, 0.0f, true, true, 8.0f, -8.0f) arcToRelative(8.009f, 8.009f, 0.0f, false, true, -8.0f, 8.0f) close() } } .build() return _billiard!! } private var _billiard: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,342
icons
MIT License
app/src/main/java/app/simple/peri/glide/tags/Tag.kt
Hamza417
667,998,169
false
{"Kotlin": 611273, "Java": 43136}
package app.simple.peri.glide.tags import android.content.Context class Tag( val tag: app.simple.peri.models.Tag?, val context: Context ) { override fun equals(other: Any?): Boolean { if (other is Tag) { return tag == other.tag } return false } override fun hashCode(): Int { return tag.hashCode() } }
9
Kotlin
6
245
97650c02d98ab7baab0ae9ba723173e55bd35a6d
381
Peristyle
Apache License 2.0
src/main/kotlin/day9.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2021.day09 import nerok.aoc.utils.Input import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun clusterBaisins(map: MutableList<List<Int>>, basinLimits: Set<Pair<Int,Int>>): Map<Int, Set<Pair<Int,Int>>> { var nextCluster = 0 val clusterMap = mutableMapOf<Int, Set<Pair<Int,Int>>>() val clusterIndex = mutableMapOf<Pair<Int,Int>, Int>() map.forEachIndexed { rowIndex, row -> row.forEachIndexed { index, point -> if (point == 9) return@forEachIndexed val columnNeighbours = when (rowIndex) { 0 -> { listOf(rowIndex+1 to index to clusterIndex.getOrDefault(rowIndex+1 to index, -1)) } map.size - 1 -> { listOf(rowIndex-1 to index to clusterIndex.getOrDefault(rowIndex-1 to index, -1)) } else -> { listOf( rowIndex-1 to index to clusterIndex.getOrDefault(rowIndex-1 to index, -1), rowIndex+1 to index to clusterIndex.getOrDefault(rowIndex+1 to index, -1) ) } } val rowNeighbours = when(index) { 0 -> { listOf(rowIndex to index + 1 to clusterIndex.getOrDefault(rowIndex to index + 1, -1)) } row.size - 1 -> { listOf(rowIndex to index - 1 to clusterIndex.getOrDefault(rowIndex to index - 1, -1)) } else -> { listOf( rowIndex to index-1 to clusterIndex.getOrDefault(rowIndex to index-1, -1), rowIndex to index+1 to clusterIndex.getOrDefault(rowIndex to index+1, -1) ) } } val neighbours = columnNeighbours + rowNeighbours if (neighbours.none { it.second != -1 }) { val neighbourhood = (neighbours.map { it.first } + (rowIndex to index)) .filter { map[it.first][it.second] != 9 } .toSet() clusterMap[nextCluster] = neighbourhood neighbourhood.forEach { clusterIndex[it] = nextCluster } nextCluster = nextCluster.inc() } else { val neighbourhood = (neighbours.map { it.first } + (rowIndex to index)) .filter { map[it.first][it.second] != 9 } .toMutableSet() var cluster = -1 neighbourhood.map { if (cluster == -1) { cluster = clusterIndex.getOrDefault(it, -1) } else { val neighbourIndex = clusterIndex[it] if (neighbourIndex != null && cluster != neighbourIndex) { val newCluster = minOf(cluster, neighbourIndex) val neighbourhood1 = clusterMap.getOrDefault(neighbourIndex, emptySet()) clusterMap.remove(neighbourIndex) val neighbourhood2 = clusterMap.getOrDefault(cluster, emptySet()) clusterMap.remove(cluster) val newNeighbourhood = neighbourhood1 + neighbourhood2 newNeighbourhood.forEach { clusterIndex[it] = newCluster } clusterMap[newCluster] = newNeighbourhood } } } neighbourhood.forEach { clusterIndex[it] = cluster } clusterMap[cluster]?.let { neighbourhood.addAll(it) } clusterMap[cluster] = neighbourhood } } } return clusterMap } fun findBasinLimits(map: MutableList<List<Int>>): Set<Pair<Int,Int>> { val limits = mutableSetOf<Pair<Int,Int>>() map.forEachIndexed { rowIndex, row -> row.forEachIndexed { index, point -> if (point == 9) limits.add(rowIndex to index) } } return limits } fun findLocalMinimas(map: MutableList<List<Int>>): List<Pair<Int,Int>> { val minimas = mutableListOf<Pair<Int,Int>>() map.forEachIndexed { rowIndex, row -> row.forEachIndexed { index, point -> val possibleMinima = when (index) { 0 -> { point < row[index+1] } row.size-1 -> { point < row[index-1] } else -> { (point < row[index-1]) && (point < row[index+1]) } } //println("Row $rowIndex, column $index: $possibleMinima") if (!possibleMinima) { return@forEachIndexed } val localMinima = when (rowIndex) { 0 -> { point < map[rowIndex+1][index] } map.size-1 -> { point < map[rowIndex-1][index] } else -> { (point < map[rowIndex-1][index]) && (point < map[rowIndex+1][index]) } } if (localMinima) { minimas.add(rowIndex to index) } } } return minimas } fun part1(input: List<String>): Long { val coordinates = mutableListOf<List<Int>>() input.mapIndexed { index, line -> line.split("") .filterNot { it == "" } .map { it.toInt() } .let { coordinates.add(index, it) } } return findLocalMinimas(coordinates).sumOf { coordinates[it.first][it.second]+1 }.toLong() } fun part2(input: List<String>): Long { val coordinates = mutableListOf<List<Int>>() input.mapIndexed { index, line -> line.split("") .filterNot { it == "" } .map { it.toInt() } .let { coordinates.add(index, it) } } val limits = findBasinLimits(coordinates) return clusterBaisins(coordinates, limits) .map { it.value.size } .sorted() .takeLast(3) .reduce { acc: Int, i: Int -> acc * i }.toLong() } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day09_test") check(part1(testInput) == 15L) check(part2(testInput) == 1134L) val input = Input.readInput("Day09") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
7,353
Advent-of-code-2021
MIT License
science/src/main/java/com/kylecorry/sol/science/astronomy/eclipse/Eclipse.kt
kylecorry31
294,668,785
false
null
package com.kylecorry.sol.science.astronomy.eclipse import java.time.Duration import java.time.Instant data class Eclipse(val start: Instant, val end: Instant, val magnitude: Float) { val duration: Duration = Duration.between(start, end) val maximum: Instant = start.plus(duration.dividedBy(2)) }
12
Kotlin
3
6
6698b78bb41f6de462932d64df0d5078c8b57363
307
sol
MIT License
android/src/main/java/com/theoplayer/ads/AdEventAdapter.kt
THEOplayer
500,366,784
false
{"TypeScript": 269097, "Swift": 260168, "Kotlin": 179499, "CSS": 168106, "Objective-C": 14356, "Java": 8332, "JavaScript": 5981, "Ruby": 3504, "HTML": 851, "Shell": 613, "Starlark": 602, "C": 208}
package com.theoplayer.ads import com.facebook.react.bridge.Arguments import com.theoplayer.android.api.ads.wrapper.AdsApiWrapper import com.facebook.react.bridge.WritableMap import com.theoplayer.android.api.ads.Ad import com.theoplayer.android.api.ads.AdBreak import com.theoplayer.android.api.ads.ima.GoogleImaAdEventType import com.theoplayer.android.api.ads.wrapper.AdEventListener import com.theoplayer.android.api.event.EventType import com.theoplayer.android.api.event.ads.AdEvent import java.util.* private const val EVENT_PROP_AD = "ad" private const val EVENT_PROP_TYPE = "type" private val ALL_AD_EVENTS = arrayOf( GoogleImaAdEventType.LOADED, GoogleImaAdEventType.AD_BREAK_STARTED, GoogleImaAdEventType.STARTED, GoogleImaAdEventType.FIRST_QUARTILE, GoogleImaAdEventType.MIDPOINT, GoogleImaAdEventType.THIRD_QUARTILE, GoogleImaAdEventType.COMPLETED, GoogleImaAdEventType.AD_BREAK_ENDED, GoogleImaAdEventType.SKIPPED, GoogleImaAdEventType.AD_ERROR, GoogleImaAdEventType.AD_BUFFERING, GoogleImaAdEventType.AD_BREAK_FETCH_ERROR ) class AdEventAdapter(private val adsApi: AdsApiWrapper, eventEmitter: AdEventEmitter) { private val eventListener: AdEventListener interface AdEventEmitter { fun emit(payload: WritableMap?) } init { eventListener = object : AdEventListener { override fun <E : AdEvent<*>?> onAdEvent(type: EventType<E>?, ad: Ad?) { val payload = Arguments.createMap() if (type != null) { payload.putString(EVENT_PROP_TYPE, mapAdType(type)) } if (ad != null) { payload.putMap(EVENT_PROP_AD, AdAdapter.fromAd(ad)) } eventEmitter.emit(payload) } override fun <E : AdEvent<*>?> onAdBreakEvent(type: EventType<E>?, adBreak: AdBreak?) { val payload = Arguments.createMap() if (type != null) { payload.putString(EVENT_PROP_TYPE, mapAdType(type)) } if (adBreak != null) { payload.putMap(EVENT_PROP_AD, AdAdapter.fromAdBreak(adBreak)) } eventEmitter.emit(payload) } } for (eventType in ALL_AD_EVENTS) { adsApi.addEventListener(eventType, eventListener) } } private fun mapAdType(eventType: EventType<*>): String { return when (eventType as GoogleImaAdEventType) { GoogleImaAdEventType.LOADED -> "adloaded" GoogleImaAdEventType.STARTED -> "adbegin" GoogleImaAdEventType.FIRST_QUARTILE -> "adfirstquartile" GoogleImaAdEventType.MIDPOINT -> "admidpoint" GoogleImaAdEventType.THIRD_QUARTILE -> "adthirdquartile" GoogleImaAdEventType.COMPLETED -> "adend" GoogleImaAdEventType.SKIPPED -> "adskip" GoogleImaAdEventType.AD_ERROR -> "aderror" GoogleImaAdEventType.AD_BUFFERING -> "adbuffering" GoogleImaAdEventType.AD_BREAK_STARTED -> "adbreakbegin" GoogleImaAdEventType.AD_BREAK_ENDED -> "adbreakend" GoogleImaAdEventType.AD_BREAK_FETCH_ERROR -> "aderror" else -> eventType.getName().lowercase(Locale.getDefault()) } } fun destroy() { for (eventType in ALL_AD_EVENTS) { adsApi.removeEventListener(eventType, eventListener) } } }
8
TypeScript
18
44
5492f6be55d4838460279127db99903704403bf9
3,170
react-native-theoplayer
MIT License
ByteIoFramer/Api/src/test/kotlin/org/elkoserver/foundation/byteioframer/ReadAsciiLineTest.kt
jstuyts
213,739,601
false
null
package org.elkoserver.foundation.byteioframer import org.junit.jupiter.api.assertThrows import java.io.ByteArrayInputStream import java.io.IOException import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull class ReadAsciiLineTest { @Test fun eofResultsInNull() { val input = ByteArrayInputStream(byteArrayOf()) val result = readAsciiLine { input.read() } assertNull(result) } @Test fun lfResultsInEmptyString() { val input = ByteArrayInputStream(byteArrayOf(LF)) val result = readAsciiLine { input.read() } assertEquals("", result) } @Test fun charLfResultsInChar() { val input = ByteArrayInputStream(byteArrayOf(A, LF)) val result = readAsciiLine { input.read() } assertEquals("a", result) } @Test fun crLfResultsInEmptyString() { val input = ByteArrayInputStream(byteArrayOf(CR, LF)) val result = readAsciiLine { input.read() } assertEquals("", result) } @Test fun nulLfResultsInEmptyString() { val input = ByteArrayInputStream(byteArrayOf(0, LF)) val result = readAsciiLine { input.read() } assertEquals("", result) } @Test fun nonAsciiResultsInError() { assertThrows<IOException> { val input = ByteArrayInputStream(byteArrayOf(NON_ASCII_BYTE, LF)) readAsciiLine { input.read() } } } // FIXME: Is this the correct behavior? @Test fun charEofResultsInError() { assertThrows<IOException> { val input = ByteArrayInputStream(byteArrayOf(SOME_ASCII_BYTE)) readAsciiLine { input.read() } } } }
5
null
1
1
d18864aaa29914c50edcb9ccfbd074a45d3d0498
1,731
Elko
MIT License
sdk/src/main/kotlin/org/ocast/sdk/core/models/Settings.kt
Orange-OpenSource
182,258,816
false
null
/* * Copyright 2019 Orange * * 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.ocast.sdk.core.models import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonValue import com.fasterxml.jackson.databind.annotation.JsonSerialize import org.ocast.sdk.core.utils.BitflagsSerializer import java.io.Serializable import java.util.EnumSet //region Messages /** * Represents a public settings input message. * * @param T The type of params. * @param data The data layer conveyed by the public settings input message. * @constructor Creates an instance of [InputMessage]. */ class InputMessage<T>(data: OCastDataLayer<T>) : OCastApplicationLayer<T>(SettingsService.INPUT, data) /** * Represents a public settings device message. * * @param T The type of params. * @param data The data layer conveyed by the public settings device message. * @constructor Creates an instance of [DeviceMessage]. */ class DeviceMessage<T>(data: OCastDataLayer<T>) : OCastApplicationLayer<T>(SettingsService.DEVICE, data) //endregion //region Commands /** * Represents the parameters of a `getUpdateStatus` command. * * @constructor Creates an instance of [GetUpdateStatusCommandParams]. */ class GetUpdateStatusCommandParams : OCastCommandParams("getUpdateStatus") /** * Represents the parameters of a `getDeviceID` command. * * @constructor Creates an instance of [GetDeviceIDCommandParams]. */ class GetDeviceIDCommandParams : OCastCommandParams("getDeviceID") /** * Represents the parameters of a `setVolume` command. * * @property level The system sound level. * @property mute The system sound mute status. * @constructor Creates an instance of [SetVolumeCommandParams]. */ class SetVolumeCommandParams( @JsonProperty("level") val level: Int, @JsonProperty("mute") val mute: Boolean ) : OCastCommandParams("setVolume") /** * Represents the parameters of a `getVolume` command. * * @constructor Creates an instance of [GetVolumeCommandParams]. */ class GetVolumeCommandParams : OCastCommandParams("getVolume") /** * Represents the parameters of a `keyPressed` command. * * @property key The key attribute value corresponding to the key pressed. Possible supported keys are defined by the [W3C UI events KeyboardEvent interface](https://www.w3.org/TR/uievents-code/). * @property code A string that identifies the physical key being pressed. * @property ctrl Indicates if the `Control` key is pressed. * @property alt Indicates if the `Alt` key is pressed. * @property shift Indicates if the `Shift` key is pressed. * @property meta Indicates if the `Meta` key (OS specific) is pressed. * @property location The location of the key on the keyboard. This is used to disambiguate between key values that can be generated by different physical keys on the keyboard, for example, the left and right `Shift` key. * @constructor Creates an instance of [SendKeyEventCommandParams]. */ class SendKeyEventCommandParams( @JsonProperty("key") val key: String, @JsonProperty("code") val code: String, @JsonProperty("ctrl") val ctrl: Boolean, @JsonProperty("alt") val alt: Boolean, @JsonProperty("shift") val shift: Boolean, @JsonProperty("meta") val meta: Boolean, @JsonProperty("location") val location: DOMKeyLocation ) : OCastCommandParams("keyPressed") { /** * Represents the location of a key on the keyboard. * * @property value The raw key location value. */ enum class DOMKeyLocation(private val value: Int) { /** * The key activation MUST NOT be distinguished as the left or right version of the key, * and (other than the `NumLock` key) did not originate from the numeric keypad. */ STANDARD(0), /** * The key activated originated from the left key location * (when there is more than one possible location for this key). */ LEFT(1), /** * The key activation originated from the right key location * (when there is more than one possible location for this key). */ RIGHT(2), /** * The key activation originated on the numeric keypad or with a virtual key corresponding to the numeric keypad * (when there is more than one possible location for this key). * Note that the NumLock key should always be encoded with a location of `STANDARD`. */ NUMPAD(3); /** * Returns the raw key location value. */ @JsonValue fun toValue() = value } } /** * Represents the parameters of a `mouseEvent` command. * * @property x The horizontal coordinate at which the event occurred relative to the origin of the screen coordinate system. * @property y The vertical coordinate at which the event occurred relative to the origin of the screen coordinate system. * @property buttons The combination of mouse buttons clicked. * @constructor Creates an instance of [SendMouseEventCommandParams]. */ class SendMouseEventCommandParams( @JsonProperty("x") val x: Int, @JsonProperty("y") val y: Int, @JsonSerialize(using = BitflagsSerializer::class) @JsonProperty("buttons") val buttons: EnumSet<Button> ) : OCastCommandParams("mouseEvent") { /** * Represents a mouse button. */ enum class Button(override val bit: Int) : Bitflag { /** The primary / left button. */ PRIMARY(0), /** The secondary / right button. */ RIGHT(1), /** The auxiliary / middle button. */ MIDDLE(2); /** * Returns the raw button value. */ @JsonValue fun toValue() = bit } } /** * Represents the parameters of a `gamepadEvent` command. * * @property axes The axes of the gamepad. * @property buttons The combination of gamepad buttons pressed. * @constructor Creates an instance of [SendGamepadEventCommandParams]. */ class SendGamepadEventCommandParams( @JsonProperty("axes") val axes: List<Axis>, @JsonSerialize(using = BitflagsSerializer::class) @JsonProperty("buttons") val buttons: EnumSet<Button> ) : OCastCommandParams("gamepadEvent") { /** * Represents a gamepad axis. * * @property x The horizontal axis value, ranging from -1.0 (left) to 1.0 (right). * @property y The vertical axis value, ranging from -1.0 (up) to 1.0 (down). * @property type The axis type. */ class Axis( @JsonProperty("x") val x: Double, @JsonProperty("y") val y: Double, @JsonProperty("num") val type: Type ) { /** * Represents a type of axis. * * @property value The raw axis type value. */ enum class Type(private val value: Int) { /** The horizontal axis of the left stick. */ LEFT_STICK_HORIZONTAL(0), /** The vertical axis of the left stick. */ LEFT_STICK_VERTICAL(1), /** The horizontal axis of the right stick. */ RIGHT_STICK_HORIZONTAL(2), /** The vertical axis of the right stick. */ RIGHT_STICK_VERTICAL(3); /** * Returns the raw axis type value. */ @JsonValue fun toValue() = value } } /** * Represents a gamepad button. */ enum class Button(override val bit: Int) : Bitflag { /** The bottom button in the right cluster. */ RIGHT_CLUSTER_BOTTOM(0), /** The right button in the right cluster. */ RIGHT_CLUSTER_RIGHT(1), /** The left button in the right cluster. */ RIGHT_CLUSTER_LEFT(2), /** The top button in the right cluster. */ RIGHT_CLUSTER_TOP(3), /** The top left front button. */ TOP_LEFT_FRONT(4), /** The top right front button. */ TOP_RIGHT_FRONT(5), /** The bottom left front button. */ BOTTOM_LEFT_FRONT(6), /** The bottom right front button. */ BOTTOM_RIGHT_FRONT(7), /** The left button in the center cluster. */ CENTER_CLUSTER_LEFT(8), /** The right button in the center cluster. */ CENTER_CLUSTER_RIGHT(9), /** The left stick pressed button. */ LEFT_STICK_PRESSED(10), /** The right stick pressed button. */ RIGHT_STICK_PRESSED(11), /** The top button in the left cluster. */ LEFT_CLUSTER_TOP(12), /** The bottom button in the left cluster. */ LEFT_CLUSTER_BOTTOM(13), /** The left button in the left cluster. */ LEFT_CLUSTER_LEFT(14), /** The right button in the left cluster. */ LEFT_CLUSTER_RIGHT(15), /** The middle button in the center cluster. */ CENTER_CLUSTER_MIDDLE(16); /** * Returns the raw button value. */ @JsonValue fun toValue() = bit } } //endregion //region Replies and events /** * Represents the firmware update status of a device. * * @property state The firmware update state. * @property version The version of the firmware to update. * @property progress The download progress. Only available if state equals `DOWNLOADING`. * @constructor Creates an instance of [UpdateStatus]. */ class UpdateStatus( @JsonProperty("state") val state: State, @JsonProperty("version") val version: String, @JsonProperty("progress") val progress: Int ) : Serializable { /** * Represents the state of a firmware update. * * @property value The raw state value. */ enum class State(private val value: String) { /** The firmware was successfully updated. */ SUCCESS("success"), /** There was an error while updating the firmware. */ ERROR("error"), /** The firmware update status has not been checked yet. */ NOT_CHECKED("notChecked"), /** The firmware is up to date. */ UP_TO_DATE("upToDate"), /** A firmware update is available. */ NEW_VERSION_FOUND("newVersionFound"), /** The firmware update is being downloaded. */ DOWNLOADING("downloading"), /** The firmware update is downloaded and ready to be installed. */ NEW_VERSION_READY("newVersionReady"); /** * Returns the raw firmware update state value. */ @JsonValue fun toValue() = value } } /** * Represents the device identifier. * * @property id The device identifier. * @constructor Creates an instance of [DeviceID]. */ class DeviceID( @JsonProperty("id") val id: String ) /** * Represents the volume. * * @property level The system volume level. * @property mute The system mute state. * @constructor Creates an instance of [Volume]. */ class Volume( @JsonProperty("level") val level: Int, @JsonProperty("mute") val mute: Boolean ) //endregion
1
null
3
6
e15aec7cdf29787c6d019a81d8cf34b63fbf88d8
11,493
OCast-JVM
Apache License 2.0
src/main/kotlin/modules/personality_pokemon/InnerHPFactor.kt
saber71
845,560,398
false
{"Kotlin": 60715}
package heraclius.modules.personality_pokemon //生命值 class InnerHPFactor(value: Float) : PokemonInnerPersonalityComponent(value) { }
0
Kotlin
0
0
43f2268cab076b3e87fa46047cec0a3bef75ce66
133
whispers-of-warlocks
MIT License
src/com/price_of_command/fleet_interaction/pc_FleetInteractionEveryFrame.kt
atlanticaccent
409,181,802
false
null
package com.price_of_command.fleet_interaction import com.fs.starfarer.api.EveryFrameScript import com.fs.starfarer.api.Global import com.fs.starfarer.api.campaign.OptionPanelAPI import com.fs.starfarer.api.impl.campaign.FleetInteractionDialogPluginImpl import com.price_of_command.pc_CampaignEventListener object pc_FleetInteractionEveryFrame : EveryFrameScript { var fleetInteractionWasOpen = false private val vanillaIDs = listOf( FIDPIoption.LEAVE, FIDPIoption.ENGAGE, FIDPIoption.OPEN_COMM, FIDPIoption.PURSUE, FIDPIoption.CONTINUE_INTO_BATTLE, FIDPIoption.CONTINUE_ONGOING_BATTLE, FIDPIoption.INITIATE_BATTLE, FIDPIoption.ATTEMPT_TO_DISENGAGE, FIDPIoption.AUTORESOLVE_PURSUE, FIDPIoption.CRASH_MOTHBALL ) private fun shouldAppendOption(optionPanel: OptionPanelAPI): Boolean { return !optionPanel.hasOption(pc_AutoClosingOptionDelegate.OPTION_ID) && vanillaIDs.any { optionPanel.hasOption(it) } } override fun isDone(): Boolean = false override fun runWhilePaused(): Boolean = true override fun advance(amount: Float) { val dialog = Global.getSector().campaignUI.currentInteractionDialog if (dialog != null && dialog.plugin is FleetInteractionDialogPluginImpl && shouldAppendOption(dialog.optionPanel)) { val options = dialog.optionPanel dialog.optionPanel.addOption( "Reassign captains", pc_AutoClosingOptionDelegate.OPTION_ID, "Last minute reassignment of captains to ships" ) options.addOptionConfirmation( pc_AutoClosingOptionDelegate.OPTION_ID, pc_ReassignOfficerOptionDelegate(dialog) ) dialog.setOptionOnEscape("foo", pc_AutoClosingOptionDelegate.OPTION_ID) fleetInteractionWasOpen = true } if (dialog == null && fleetInteractionWasOpen) { fleetInteractionWasOpen = false pc_CampaignEventListener.tryRestoreFleetAssignments() } } } typealias FIDPIoption = FleetInteractionDialogPluginImpl.OptionId
0
Kotlin
0
1
ca781787185b4167c7f27899431ae16e13f3c287
2,177
price-of-command
The Unlicense
sample/src/main/java/me/xiaopan/assemblyadaptersample/itemfactory/GameItemFactory.kt
wavefar
107,957,471
true
{"Java Properties": 3, "Text": 2, "Gradle": 4, "Shell": 1, "Markdown": 10, "Batchfile": 1, "Ignore List": 3, "Proguard": 2, "XML": 27, "Java": 32, "Kotlin": 42}
package me.xiaopan.assemblyadaptersample.itemfactory import android.content.Context import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import me.xiaopan.assemblyadapter.AssemblyItem import me.xiaopan.assemblyadapter.AssemblyItemFactory import me.xiaopan.assemblyadaptersample.R import me.xiaopan.assemblyadaptersample.bean.Game import me.xiaopan.ssvt.bindView class GameItemFactory(context: Context) : AssemblyItemFactory<GameItemFactory.GameItem>() { private val eventListener: EventListener init { this.eventListener = EventProcessor(context) } override fun isTarget(data: Any): Boolean { return data is Game } override fun createAssemblyItem(parent: ViewGroup): GameItem { return GameItem(R.layout.list_item_game, parent) } interface EventListener { fun onClickIcon(position: Int, user: Game) fun onClickName(position: Int, user: Game) fun onClickLike(position: Int, user: Game) } private class EventProcessor(private val context: Context) : EventListener { override fun onClickIcon(position: Int, game: Game) { Toast.makeText(context, "瞅这游戏这臭逼样!", Toast.LENGTH_SHORT).show() } override fun onClickName(position: Int, game: Game) { Toast.makeText(context, "原来你叫" + game.name + "啊!", Toast.LENGTH_SHORT).show() } override fun onClickLike(position: Int, game: Game) { Toast.makeText(context, "我也" + game.like + "这游戏!", Toast.LENGTH_SHORT).show() } } inner class GameItem(itemLayoutId: Int, parent: ViewGroup) : AssemblyItem<Game>(itemLayoutId, parent) { val iconImageView: ImageView by bindView(R.id.image_gameListItem_icon) val nameTextView: TextView by bindView(R.id.text_gameListItem_name) val likeTextView: TextView by bindView(R.id.text_gameListItem_like) override fun onConfigViews(context: Context) { iconImageView.setOnClickListener { eventListener.onClickIcon(position, data) } nameTextView.setOnClickListener { eventListener.onClickName(position, data) } likeTextView.setOnClickListener { eventListener.onClickLike(position, data) } } override fun onSetData(position: Int, game: Game) { iconImageView.setImageResource(game.iconResId) nameTextView.text = game.name likeTextView.text = game.like } } }
0
Java
0
0
be330aa2439fc593d3df1bc9ccf27665cc9b63c6
2,511
AssemblyAdapter
Apache License 2.0
app/src/main/java/com/guru/cocktails/ui/bar/myingredients/MyIngredientListFragment.kt
morristech
143,734,527
false
null
package com.guru.cocktails.ui.bar.myingredients import android.os.Bundle import android.support.v4.util.Pair import android.support.v7.widget.GridLayoutManager import android.view.View import android.widget.Toast import com.guru.cocktails.App import com.guru.cocktails.R import com.guru.cocktails.domain.model.ingredient.MyIngredient import com.guru.cocktails.platform.extensions.ifAdded import com.guru.cocktails.platform.extensions.lazyFast import com.guru.cocktails.ui.bar.myingredients.MyIngredientListContract.Presenter import com.guru.cocktails.ui.bar.myingredients.di.DaggerMyIngredientListComponent import com.guru.cocktails.ui.bar.myingredients.di.MyIngredientListModule import com.guru.cocktails.ui.base.BaseFragment import com.guru.cocktails.ui.ingredientdetail.IngredientDetailActivity import kotlinx.android.synthetic.main.recycler_view.* import javax.inject.Inject class MyIngredientListFragment : BaseFragment(), MyIngredientListContract.View { private lateinit var myIngredientListType: MyIngredientListType @Inject lateinit var presenter: Presenter private val adapter by lazyFast { MyIngredientListAdapter(this, picasso) } override fun layoutId() = R.layout.recycler_view override fun inject() { DaggerMyIngredientListComponent.builder() .applicationComponent(App.instance.appComponent()) .myIngredientListModule(MyIngredientListModule(myIngredientListType)) .build() .inject(this) } @Inject override fun attachPresenter(presenter: Presenter) { this.presenter.attachView(this) } override fun extractArguments() { arguments?.let { it.getString(ARGS_TYPE)?.let { myIngredientListType = when (it) { TYPE_MY_BAR -> MyIngredientListType.MyBar() TYPE_SHOPPING_LIST -> MyIngredientListType.ShoppingList() else -> throw IllegalStateException("Unknown type passed via bundle : $it") } } ?: throw IllegalStateException("Type was not passed in via Bundle") } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) rv_rv.adapter = adapter rv_rv.layoutManager = GridLayoutManager(activity, 2) rv_srl.isEnabled = false presenter.start() } override fun onDestroy() { presenter.stop() super.onDestroy() } override fun onClick(item: MyIngredient, sharedElements: List<Pair<View, String>>?) { ifAdded { abc -> //TODO picasso.subscribeToData(item.imageUrl).fetch() prefetch large image navigator.navigate( source = abc, target = IngredientDetailActivity::class.java, // sharedElements = sharedElements, bundle = IngredientDetailActivity.createBundle(item.ingredientId) ) } } override fun startLoading() { rv_srl.isRefreshing = true } override fun stopLoading() { rv_srl.isRefreshing = false } override fun onNewData(list: List<MyIngredient>) { adapter.updateData(list) } override fun onError(error: Throwable) { ifAdded { Toast.makeText(activity, """Error :$error""", Toast.LENGTH_LONG).show() } } companion object { fun newInstance(bundle: Bundle) = MyIngredientListFragment().apply { arguments = bundle } fun createBundle(ingredientListType: MyIngredientListType) = Bundle().apply { val typeString = when (ingredientListType) { is MyIngredientListType.MyBar -> TYPE_MY_BAR is MyIngredientListType.ShoppingList -> TYPE_SHOPPING_LIST } putString(ARGS_TYPE, typeString) } private const val TYPE_MY_BAR = "TYPE_MY_BAR" private const val TYPE_SHOPPING_LIST = "TYPE_SHOPPING_LIST" private const val ARGS_TYPE = "ARGS_TYPE" } }
0
Kotlin
0
0
f3feac05ebb51a7a30c2d37ccf76f4269da92f07
4,083
client-android
MIT License
src/main/kotlin/xyz/chlamydomonos/catridge/loaders/MenuLoader.kt
Chlamydomonos
840,962,255
false
{"Kotlin": 27405, "Java": 2841}
package xyz.chlamydomonos.catridge.loaders import net.minecraft.core.registries.Registries import net.minecraft.network.RegistryFriendlyByteBuf import net.minecraft.world.entity.player.Inventory import net.minecraft.world.inventory.AbstractContainerMenu import net.minecraft.world.inventory.MenuType import net.neoforged.bus.api.IEventBus import net.neoforged.fml.common.EventBusSubscriber import net.neoforged.neoforge.common.extensions.IMenuTypeExtension import net.neoforged.neoforge.network.IContainerFactory import net.neoforged.neoforge.registries.DeferredHolder import net.neoforged.neoforge.registries.DeferredRegister import thedarkcolour.kotlinforforge.neoforge.forge.getValue import xyz.chlamydomonos.catridge.Catridge import xyz.chlamydomonos.catridge.gui.menu.CatridgeSurgeryTableMenu object MenuLoader { private val MENU_TYPES = DeferredRegister.create(Registries.MENU, Catridge.MODID) private fun <T : AbstractContainerMenu> register( name: String, menu: (Int, Inventory, RegistryFriendlyByteBuf) -> T ): DeferredHolder<MenuType<*>, MenuType<T>> { return MENU_TYPES.register(name) { -> IMenuTypeExtension.create(IContainerFactory(menu)) } } fun register(bus: IEventBus) { MENU_TYPES.register(bus) } val CATRIDGE_SURGERY_TABLE by register("catridge_surgery_table", ::CatridgeSurgeryTableMenu) }
0
Kotlin
0
0
26477c4a6107025aceb060d17e7f1a48aa5f4c96
1,373
Catridge
MIT License
app/src/main/java/android/team/clandestine/posip/fragment/SignInFragment.kt
ukayaj620
303,674,196
false
null
package android.team.clandestine.posip.fragment import android.os.Bundle import android.team.clandestine.posip.R import android.team.clandestine.posip.databinding.FragmentSigninBinding import android.team.clandestine.posip.sharedpreferences.PosipSharedPreferences import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController class SignInFragment : Fragment() { private lateinit var binding: FragmentSigninBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate( inflater, R.layout.fragment_signin, container, false ) (activity as AppCompatActivity).supportActionBar!!.title = "" (activity as AppCompatActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(true) (activity as AppCompatActivity).supportActionBar!!.setDisplayShowHomeEnabled(true) binding.signInButton.setOnClickListener { if (validateInputs()) { findNavController().navigate(R.id.action_signInFragment_to_homeFragment) } } return binding.root } private fun validateInputs(): Boolean { var validated = true if (binding.usernameEditText.text.toString() == "studentisi" && binding.passwordEditText.text.toString() == "studentisi") { PosipSharedPreferences.setLogin(3, context!!) return true } if (binding.usernameEditText.text.toString() == "tutorisi" && binding.passwordEditText.text.toString() == "tutorisi") { PosipSharedPreferences.setLogin(4, context!!) return true } binding.passwordInputLayout.error = null binding.usernameInputLayout.error = null if (binding.passwordEditText.text.isNullOrEmpty()) { binding.passwordInputLayout.error = "Can't be empty" validated = false } if (binding.usernameEditText.text.isNullOrEmpty()) { binding.usernameInputLayout.error = "Can't be empty" validated = false } if (validated && !PosipSharedPreferences.signIn( binding.usernameEditText.text.toString(), binding.passwordEditText.text.toString(), context!! )) { binding.usernameInputLayout.error = "Wrong credentials" validated = false } return validated } }
0
Kotlin
0
0
504cbcac08e3654c325d575b3120ea758b480ecb
2,761
posip
Apache License 2.0
config/src/commonMain/kotlin/raven/CreditWarningConfiguration.kt
aSoft-Ltd
849,606,763
false
{"Kotlin": 80259, "HTML": 24145}
package raven fun <P> AgentConfiguration<P>.toCreditWarning( agent: String, message: (count: Int) -> String ): CreditWarning { val to = params["warning_recipients"] ?: throw IllegalArgumentException("`warning_recipients` is missing: One or more recipients must be set when using the $agent agent") val recipients = to.split(",") if (recipients.isEmpty()) throw IllegalArgumentException("Recipients must have at least one warning recipient") val limit = params["warning_limit"]?.toIntOrNull() ?: throw IllegalArgumentException("`warning_limit` is missing: A warning limit must be set using the $agent agent") return CreditWarning(recipients, limit, message) }
0
Kotlin
0
0
aacd62464c6d381d5e9a13483c1ea1fb23aabf34
687
raven
MIT License
app/src/main/java/com/qhy040404/libraryonetap/utils/extensions/DoubleExtensions.kt
qhy040404
484,416,715
false
null
package com.qhy040404.libraryonetap.utils.extensions import java.math.BigDecimal import java.math.RoundingMode @Suppress("unused") object DoubleExtensions { /** * Keep two decimal places after rounding * * @return Double with two decimal */ fun Double.to2Decimal() = BigDecimal.valueOf(this).setScale(2, RoundingMode.HALF_UP).toDouble() }
4
Kotlin
0
9
54403f5cd7876c24237313daf12835e73b7e6572
369
Library-One-Tap-Android
Apache License 2.0
core/src/commonMain/kotlin/de/frederikbertling/kosc/core/spec/args/OSCTimeTag.kt
Burtan
796,396,999
false
{"Kotlin": 26257}
package de.frederikbertling.kosc.core.spec.args /** * Time tags are represented by a 64-bit fixed point number. The first 32 bits specify the number of seconds since * midnight on January 1, 1900, and the last 32 bits specify fractional parts of a second to a precision of about 200 * picoseconds. This is the representation used by Internet NTP timestamps. The time tag value consisting of 63 zero * bits followed by a one in the least significant bit is a special case meaning “immediately.” */ data class OSCTimeTag( val value: Long ) : OSCArgument
1
Kotlin
0
1
c7720825a4704eb50768c81222f84aa11d818e68
562
kOSC
Apache License 2.0
library/src/main/java/com/lzf/easyfloat/interfaces/PermissionRequester.kt
kongxiaojun
718,896,030
false
{"Kotlin": 160098, "Java": 26139}
package com.lzf.easyfloat.interfaces /** * @author kongxiaojun * @date 2023/11/17 * @description 权限申请器 */ interface PermissionRequester { fun requestPermission(resultCallback: OnPermissionResult) }
5
Kotlin
3
34
8cb46335c09c9913adc820a5a0b6afce5a0ce52d
208
EasyFloat
Apache License 2.0
solar/src/main/java/com/chiksmedina/solar/broken/foodkitchen/WineglassTriangle.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.broken.foodkitchen 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.Round 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.broken.FoodKitchenGroup val FoodKitchenGroup.WineglassTriangle: ImageVector get() { if (_wineglassTriangle != null) { return _wineglassTriangle!! } _wineglassTriangle = Builder( name = "WineglassTriangle", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(12.0f, 14.5714f) lineTo(20.5162f, 5.8638f) curveTo(21.5624f, 4.7941f, 20.7999f, 3.0f, 19.2991f, 3.0f) horizontalLineTo(14.0f) moveTo(12.0f, 14.5714f) lineTo(3.4838f, 5.8638f) curveTo(2.4376f, 4.7941f, 3.2001f, 3.0f, 4.701f, 3.0f) horizontalLineTo(10.0f) moveTo(12.0f, 14.5714f) verticalLineTo(21.0f) moveTo(12.0f, 21.0f) horizontalLineTo(16.2439f) moveTo(12.0f, 21.0f) horizontalLineTo(7.7561f) moveTo(7.4732f, 9.75f) horizontalLineTo(16.5268f) } } .build() return _wineglassTriangle!! } private var _wineglassTriangle: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
2,071
SolarIconSetAndroid
MIT License
app/src/main/kotlin/com/fibelatti/pinboard/core/extension/View.kt
fibelatti
165,537,939
false
null
package com.fibelatti.pinboard.core.extension import android.animation.ObjectAnimator import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import android.widget.FrameLayout import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.unit.dp import com.fibelatti.core.android.extension.getContentView import com.fibelatti.pinboard.R import com.fibelatti.ui.foundation.topSystemBarsPaddingCompat import com.fibelatti.ui.preview.ThemePreviews import com.fibelatti.ui.theme.ExtendedTheme import com.google.android.material.bottomappbar.BottomAppBar import com.google.android.material.floatingactionbutton.FloatingActionButton fun BottomAppBar.show() { animate() .translationY(0f) .setDuration(resources.getInteger(R.integer.anim_time_default).toLong()) .start() } fun FloatingActionButton.blink(onHidden: () -> Unit = {}) { hide( object : FloatingActionButton.OnVisibilityChangedListener() { override fun onHidden(fab: FloatingActionButton?) { super.onHidden(fab) onHidden() show() } }, ) } fun View.smoothScrollY(scrollBy: Int) { ObjectAnimator.ofInt(this, "scrollY", scrollBy) .apply { interpolator = AccelerateDecelerateInterpolator() } .setDuration(resources.getInteger(R.integer.anim_time_long).toLong()) .start() } fun View.showBanner(message: String) { val banner = ComposeView(context).apply { alpha = 0F setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setThemedContent { Banner(message = message) } } val contentView = getContentView() contentView.addView( banner, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL, ), ) banner.animate() .alphaBy(1F) .setDuration(500) .setInterpolator(DecelerateInterpolator()) .withEndAction { banner.animate() .alpha(0F) .setDuration(500) .setStartDelay(1_500) .setInterpolator(AccelerateInterpolator()) .withEndAction { contentView.removeView(banner) } .start() } .start() } @Composable private fun Banner( message: String, ) { Surface( modifier = Modifier .padding(all = 24.dp) .topSystemBarsPaddingCompat(), shape = RoundedCornerShape(8.dp), color = MaterialTheme.colorScheme.inverseSurface, shadowElevation = 8.dp, ) { Text( text = message, modifier = Modifier.padding(all = 16.dp), color = MaterialTheme.colorScheme.inverseOnSurface, style = MaterialTheme.typography.bodyMedium, ) } } @Composable @ThemePreviews private fun BannerPreview() { ExtendedTheme { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter, ) { Banner(message = "Sample message") } } }
5
null
13
95
c6ff28fea78b4785ea02eace40f5811c83e8e14a
3,923
pinboard-kotlin
Apache License 2.0
generator/src/main/kotlin/at/yawk/javabrowser/generator/db/DirectTransaction.kt
yawkat
135,326,421
false
null
package at.yawk.javabrowser.generator.db import at.yawk.javabrowser.BindingId import at.yawk.javabrowser.BindingRefType import at.yawk.javabrowser.Realm import at.yawk.javabrowser.TsVector import org.jdbi.v3.core.Handle class DirectTransaction( private val conn: Handle ) : Transaction { private val refBatch = conn.prepareBatch("insert into binding_reference (realm, target, type, source_artifact_id, source_file_id, source_file_line, source_file_ref_id) VALUES (?, ?, ?, ?, ?, ?, ?)") // TODO private val declBatch = conn.prepareBatch("insert into binding (realm, artifact_id, binding_id, binding, source_file_id, include_in_type_search, description, modifiers, parent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)") override suspend fun insertArtifact(id: Long, stringId: String, compilerVersion: Int, metaBytes: ByteArray) { conn.createUpdate("insert into artifact (artifact_id, string_id, last_compile_version, metadata) values (?, ?, ?, ?)") .bind(0, id) .bind(1, stringId) .bind(2, compilerVersion) .bind(3, metaBytes) .execute() } override suspend fun insertDependency(from: Long, to: String) { conn.createUpdate("insert into dependency (from_artifact, to_artifact) values (?, ?)") .bind(0, from) .bind(1, to) .execute() } override suspend fun insertAlias(from: Long, alias: String) { conn.createUpdate("insert into artifact_alias (artifact_id, alias) values (?, ?)") .bind(0, from) .bind(1, alias) .execute() } override suspend fun insertSourceFile( realm: Realm, artifactId: Long, sourceFileId: Long, hash: Long, path: String, textBytes: ByteArray, annotationBytes: ByteArray ) { conn.createUpdate( "insert into source_file (realm, artifact_id, source_file_id, hash, path, text, annotations) values (?, ?, ?, ?, ?, ?, ?)") .bind(0, realm.id) .bind(1, artifactId) .bind(2, sourceFileId) .bind(3, hash) .bind(4, path) .bind(5, textBytes) .bind(6, annotationBytes) .execute() } override suspend fun insertRef( realm: Realm, binding: BindingId, type: BindingRefType, artifactId: Long, sourceFileId: Long, line: Int, idInSourceFile: Int ) { refBatch.add( realm.id, binding.hash, type.id, artifactId, sourceFileId, line, idInSourceFile ) if (refBatch.size() >= 100) refBatch.execute() } override suspend fun insertDecl( realm: Realm, artifactId: Long, bindingId: BindingId, binding: String, sourceFileId: Long?, includeInTypeSearch: Boolean, descBytes: ByteArray, modifiers: Int, parent: BindingId? ) { declBatch.add( realm.id, artifactId, bindingId.hash, binding, sourceFileId, includeInTypeSearch, descBytes, modifiers, parent?.hash ) if (declBatch.size() >= 100) declBatch.execute() } override suspend fun insertLexemes( set: Transaction.FullTextSearchSet, realm: Realm, artifactId: Long, sourceFileId: Long, lexemes: TsVector, starts: IntArray, lengths: IntArray ) { conn.createUpdate( "insert into ${set.table} (realm, artifact_id, source_file_id, lexemes, starts, lengths) values (?, ?, ?, ?::tsvector, ?, ?)") .bind(0, realm.id) .bind(1, artifactId) .bind(2, sourceFileId) .bind(3, lexemes.toSql()) .bind(4, starts) .bind(5, lengths) .execute() } fun deleteArtifact(artifactStringId: String) { conn.createUpdate("delete from artifact where string_id = ?") .bind(0, artifactStringId) .execute() } fun flush() { refBatch.execute() declBatch.execute() } }
17
null
3
35
b9233824bf594bacffaee2efbf12ab9ea941763e
4,464
java-browser
Apache License 2.0
p2m-core/src/main/java/com/p2m/core/event/BackgroundLiveEvent.kt
wangdaqi77
367,279,479
false
null
package com.p2m.core.event import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import com.p2m.annotation.module.api.* import com.p2m.core.internal.event.InternalBackgroundLiveEvent import com.p2m.core.internal.event.InternalLiveEvent import com.p2m.core.internal.event.InternalMediatorBackgroundLiveEvent import kotlin.reflect.KProperty /** * Defined a common interface for background event holder class. * * See [live-event library](https://github.com/wangdaqi77/live-event) * * @see EventOn.BACKGROUND - gen by KAPT. * @see BackgroundObserver - can specified thread to receive event. */ interface BackgroundLiveEvent<T> { companion object { fun <T> delegate(): Lazy<BackgroundLiveEvent<T>> = lazy { InternalBackgroundLiveEvent() } fun <T> delegateMutable(): Lazy<MutableBackgroundLiveEvent<T>> = lazy { InternalBackgroundLiveEvent() } fun <T> toMutable(real: BackgroundLiveEvent<T>): Lazy<MutableBackgroundLiveEvent<T>> = lazy(LazyThreadSafetyMode.NONE) { real as MutableBackgroundLiveEvent } } fun observe(owner: LifecycleOwner, observer: BackgroundObserver<in T>) fun observeForever(observer: BackgroundObserver<in T>) fun observeNoSticky(owner: LifecycleOwner, observer: BackgroundObserver<in T>) fun observeForeverNoSticky(observer: BackgroundObserver<in T>) fun observeNoLoss(owner: LifecycleOwner, observer: BackgroundObserver<in T>) fun observeForeverNoLoss(observer: BackgroundObserver<in T>) fun observeNoStickyNoLoss(owner: LifecycleOwner, observer: BackgroundObserver<in T>) fun observeForeverNoStickyNoLoss(observer: BackgroundObserver<in T>) fun removeObservers(owner: LifecycleOwner) fun removeObserver(observer: BackgroundObserver<in T>) fun hasActiveObservers(): Boolean fun hasObservers(): Boolean fun getValue(): T? fun asLiveData(): LiveData<out T> } interface MutableBackgroundLiveEvent<T> : BackgroundLiveEvent<T> { fun postValue(value: T) fun setValue(value: T) } interface MediatorBackgroundLiveEvent<T> : MutableBackgroundLiveEvent<T>, MediatorEvent { fun <T> delegate(): Lazy<BackgroundLiveEvent<T>> = lazy { InternalMediatorBackgroundLiveEvent() } fun <T> delegateMutable(): Lazy<MediatorBackgroundLiveEvent<T>> = lazy { InternalMediatorBackgroundLiveEvent() } fun <T> toMutable(real: BackgroundLiveEvent<T>): Lazy<MediatorBackgroundLiveEvent<T>> = lazy(LazyThreadSafetyMode.NONE) { real as MediatorBackgroundLiveEvent } } enum class EventDispatcher { DEFAULT, // Receiving event in default thread, not recommended time-consuming work. BACKGROUND, // Receiving event in background thread, not recommended time-consuming work. ASYNC, // Receiving event in thread pool. MAIN // Receiving event in main thread, not recommended time-consuming work. } class BackgroundObserver<T>(eventDispatcher: EventDispatcher, observer: Observer<T>) : wang.lifecycle.BackgroundObserver<T>( dispatcher = when (eventDispatcher) { EventDispatcher.DEFAULT -> wang.lifecycle.EventDispatcher.DEFAULT EventDispatcher.BACKGROUND -> wang.lifecycle.EventDispatcher.BACKGROUND EventDispatcher.ASYNC -> wang.lifecycle.EventDispatcher.ASYNC EventDispatcher.MAIN -> wang.lifecycle.EventDispatcher.MAIN }, observer = observer ) /** * A simple callback that can specified thread to receive event from [BackgroundLiveEvent]. */ fun <T> BackgroundObserver(eventDispatcher: EventDispatcher = EventDispatcher.DEFAULT, onChanged: (T) -> Unit): BackgroundObserver<T> { return BackgroundObserver(eventDispatcher, Observer { onChanged(it) }) }
0
null
6
34
6263c1c5a2dedda773eb7c6745b86ac2ff8f00d9
3,843
P2M
Apache License 2.0
ShadhinMusicLibrary/src/main/java/com/myrobi/shadhinmusiclibrary/data/model/lastfm/Similar.kt
shadhin-music
589,150,241
false
null
package com.myrobi.shadhinmusiclibrary.data.model.lastfm import androidx.annotation.Keep import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName @Keep internal class Similar { @SerializedName("artist") @Expose var artist: List<LastFmArtistModel>? = null }
0
Kotlin
0
0
99e11cc3a68fd68607401fca71e32003b638025c
305
MyRobiShadhinSDK
MIT License
simplechat/src/main/java/com/ln/simplechat/ui/bubble/BubbleActivity.kt
longnghia
490,517,031
false
{"Kotlin": 599604, "Shell": 367}
package com.ln.simplechat.ui.bubble import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.commitNow import com.ln.simplechat.R import com.ln.simplechat.databinding.ActivitySimpleChatBinding import com.ln.simplechat.ui.chat.ChatFragment import com.ln.simplechat.ui.viewBindings import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class BubbleActivity : AppCompatActivity(R.layout.activity_simple_chat) { private val binding by viewBindings(ActivitySimpleChatBinding::bind) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val channelID = intent.data?.lastPathSegment ?: return if (savedInstanceState == null) { supportFragmentManager.commitNow { setCustomAnimations(R.anim.ps_anim_fade_in, R.anim.ps_anim_fade_out) replace(R.id.container, ChatFragment.newInstance(channelID, isBubble = true)) } } } }
0
Kotlin
1
3
2fce27c406981cac795c8dce80ffac832abf14e3
1,001
E-Commerce-Application
MIT License
protocol/src/main/kotlin/io/kaxis/dtls/extensions/HelloExtensions.kt
barudisshu
806,368,620
false
{"Kotlin": 1248420, "Java": 451145, "Shell": 28440, "Dockerfile": 956}
/* * COPYRIGHT Cplier 2024 * * The copyright to the computer program(s) herein is the property of * Cplier Inc. The programs may be used and/or copied only with written * permission from Cplier Inc. or in accordance with the terms and * conditions stipulated in the agreement/contract under which the * program(s) have been supplied. */ package io.kaxis.dtls.extensions import io.kaxis.dtls.message.AlertMessage import io.kaxis.exception.HandshakeException import io.kaxis.util.DatagramReader import io.kaxis.util.DatagramWriter import io.kaxis.util.Utility import java.util.* /** * A container for one or more [HelloExtension]s. */ class HelloExtensions { companion object { const val OVERALL_LENGTH_BITS = 16 /** * Create and read extensions. * @param reader the serialized extension * @return create extensions * @throws HandshakeException if the (supported) extension could not be de-serialized, e.g. due to * erroneous encoding etc. Or an extension type occurs more than once. */ @Throws(HandshakeException::class) fun fromReader(reader: DatagramReader): HelloExtensions { val extensions = HelloExtensions() extensions.readFrom(reader) return extensions } } /** * The list of extensions. */ private val extensions = arrayListOf<HelloExtension>() /** * Checks if this container actually holds any extensions. * @return `true`, if there are no extensions */ fun isEmpty(): Boolean = extensions.isEmpty() /** * Calculate the lengths of the whole extension fragment. Includes the two bytes to encode the [extensionsLength] itself. [RFC 5246, 7.4.1.2](https://tools.ietf.org/html/rfc5246#section-7.4.1.2). * * ``` * select (extensions_present) { * case false: * struct {}; * case true: * Extension extensions<0..2^16-1>; * }; * ``` * * @return the length of the whole extension fragment. 0, if no extensions are used. */ val length: Int get() { return if (extensions.isEmpty()) { 0 } else { extensionsLength + (OVERALL_LENGTH_BITS / Byte.SIZE_BITS) } } /** * Calculate the length of all extensions. */ val extensionsLength: Int get() { var length = 0 extensions.forEach { extension -> length += extension.length } return length } operator fun <T : HelloExtension> get(type: HelloExtension.ExtensionType?): T? { return getExtension(type) } /** * Gets a hello extension of a particular type. * @param type the type of extension or replacement type * @return the extension, or `null`, if no extension of the given type nor replacement type is present * @throws NullPointerException if type is `null` */ @Suppress("UNCHECKED_CAST", "kotlin:S6531") fun <T : HelloExtension> getExtension(type: HelloExtension.ExtensionType?): T? { requireNotNull(type) { "Extension type must not be null!" } var replacement: HelloExtension? = null extensions.forEach { ext -> if (type == ext.type) { return ext as T } else if (type == ext.type.replacement) { replacement = ext } } return replacement as? T } /** * Add hello extension. * @param extension hello extension to add */ fun addExtension(extension: HelloExtension?) { if (extension != null) { if (getExtension(extension.type) as HelloExtension? == null) { this.extensions += (extension) } else { throw IllegalArgumentException("Hello Extension of type ${extension.type} already added!") } } } operator fun plus(extension: HelloExtension?) = addExtension(extension) /** * Gets the textual presentation of this message. * @param indent line indentation * @return textual presentation */ fun toString(indent: Int): String { return StringBuilder().apply sb@{ val indentation = Utility.indentation(indent) [email protected](indentation).append("Extensions Length: ").append(extensionsLength).append(" bytes") .append(Utility.LINE_SEPARATOR) extensions.forEach { ext -> [email protected](ext.toString(indent + 1)) } }.toString() } override fun toString(): String { return toString(0) } /** * Write extensions. * @param writer writer to write extensions to. */ fun writeTo(writer: DatagramWriter) { if (extensions.isNotEmpty()) { writer.write(extensionsLength, OVERALL_LENGTH_BITS) extensions.forEach { extension -> extension.writeTo(writer) } } } /** * Read extensions from reader. * @param reader the serialized extensions * @throws HandshakeException if the (supported) extension could not be de-serialized, e.g. due to * erroneous encoding etc. Or a extension type occurs more than once. */ @Throws(HandshakeException::class) fun readFrom(reader: DatagramReader) { if (reader.bytesAvailable()) { try { val length = reader.read(OVERALL_LENGTH_BITS) val rangeReader = reader.createRangeReader(length) while (rangeReader.bytesAvailable()) { val extension = HelloExtension.readFrom(rangeReader) if (extension != null) { if (getExtension(extension.type) as HelloExtension? == null) { addExtension(extension) } else { throw HandshakeException( AlertMessage(AlertMessage.AlertLevel.FATAL, AlertMessage.AlertDescription.DECODE_ERROR), "Hello message contains extension ${extension.type} more than once!", ) } } } } catch (ex: IllegalArgumentException) { throw HandshakeException( AlertMessage( AlertMessage.AlertLevel.FATAL, AlertMessage.AlertDescription.DECODE_ERROR, ), "Hello message contained malformed extensions, ${ex.message}", ) } } } }
0
Kotlin
0
0
f18e39e826792f145468f33d8751decc79769c07
6,004
kaxis
MIT License
app/src/main/java/com/hazz/kotlinmvp/base/BaseFragment.kt
PsKs
276,854,013
true
{"Kotlin": 253634, "Java": 17322}
package com.hazz.kotlinmvp.base import android.os.Bundle import android.support.annotation.LayoutRes import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.classic.common.MultipleStatusView import com.hazz.kotlinmvp.MyApplication import io.reactivex.annotations.NonNull import pub.devrel.easypermissions.AppSettingsDialog import pub.devrel.easypermissions.EasyPermissions /** * @author Xuhao * created: 2017/10/25 * desc: */ abstract class BaseFragment: Fragment(),EasyPermissions.PermissionCallbacks{ /** * Is the view loaded */ private var isViewPrepare = false /** * Has the data been loaded */ private var hasLoadData = false /** * Switching of views in multiple states */ protected var mLayoutStatusView: MultipleStatusView? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(getLayoutId(),null) } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) if (isVisibleToUser) { lazyLoadDataIfPrepared() } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) isViewPrepare = true initView() lazyLoadDataIfPrepared() // Views with multiple state switching retry click events mLayoutStatusView?.setOnClickListener(mRetryClickListener) } private fun lazyLoadDataIfPrepared() { if (userVisibleHint && isViewPrepare && !hasLoadData) { lazyLoad() hasLoadData = true } } open val mRetryClickListener: View.OnClickListener = View.OnClickListener { lazyLoad() } /** * Load layout */ @LayoutRes abstract fun getLayoutId():Int /** * Initialize View */ abstract fun initView() /** * Lazy loading */ abstract fun lazyLoad() override fun onDestroy() { super.onDestroy() activity?.let { MyApplication.getRefWatcher(it)?.watch(activity) } } /** * Rewrite the onRequestPermissionsResult() method of the Activity or Fragment that you want to apply for permissions, * Call EasyPermissions.onRequestPermissionsResult() inside to implement the callback. * * @param requestCode Identification code of permission request * @param permissions Requested permissions * @param grantResults Authorization result */ override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this) } /** * Execute callback when permission is successfully applied * * @param requestCode Identification code of permission request * @param perms The name of the requested permission */ override fun onPermissionsGranted(requestCode: Int, perms: List<String>) { Log.i("EasyPermissions", "获取成功的权限$perms") } /** * Callback executed when permission application fails * * @param requestCode Identification code of permission request * @param perms The name of the requested permission */ override fun onPermissionsDenied(requestCode: Int, perms: List<String>) { // Processing authority name string val sb = StringBuffer() for (str in perms) { sb.append(str) sb.append("\n") } sb.replace(sb.length - 2, sb.length, "") // The user clicks to reject and is not called when asked if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { Toast.makeText(activity, "Permission denied" + sb + "And don't ask again", Toast.LENGTH_SHORT).show() AppSettingsDialog.Builder(this) .setRationale("This feature requires" + sb + "Permission, otherwise it cannot be used normally, whether to open the settings") .setPositiveButton("OK") .setNegativeButton("NO") .build() .show() } } }
0
Kotlin
0
0
ccea4ab16e0b9db5cd21dedb4c1c23af45fd4ee3
4,502
KotlinMvp
Apache License 2.0
app/src/main/java/com/bsuir/bsuirschedule/domain/usecase/schedule/WidgetManagerUseCase.kt
Saydullin
526,953,048
false
{"Kotlin": 678273, "HTML": 7301}
package com.bsuir.bsuirschedule.domain.usecase.schedule import com.bsuir.bsuirschedule.domain.models.WidgetSettings import com.bsuir.bsuirschedule.domain.repository.WidgetSettingsRepository class WidgetManagerUseCase ( private val widgetSettingsRepository: WidgetSettingsRepository ) { fun getWidgetSettings(widgetId: Int): WidgetSettings? { return widgetSettingsRepository.getWidgetSettings(widgetId) } fun saveWidgetSettings(widgetSettings: WidgetSettings) { widgetSettingsRepository.saveWidgetSettings(widgetSettings) } fun deleteWidgetSettings(widgetId: Int) { widgetSettingsRepository.deleteWidgetSettings(widgetId) } }
0
Kotlin
0
4
989325e764d14430d5d124efd063f7190b075f4a
685
BSUIR_Schedule
Creative Commons Zero v1.0 Universal
api/src/main/kotlin/org/kryptonmc/api/block/meta/SlabType.kt
KryptonMC
255,582,002
false
null
/* * This file is part of the Krypton project, licensed under the Apache License v2.0 * * Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kryptonmc.api.block.meta /** * Indicates the type of slab that a block this property is applied to * represents. * * Slabs are different from a lot of other blocks, in that two of them can be * placed in the same block space. However, for uniformity, this is all an * illusion, and this property is used to differentiate "half slabs", those * that occupy half of a block from "full slabs", those that occupy a full * block, when two slabs are placed in the same block. */ public enum class SlabType { /** * The slab occupies the top half of a block. */ TOP, /** * The slab occupies the bottom half of a block. */ BOTTOM, /** * The slab occupies both halves of a block. This happens when two slabs * are placed in the same block. */ DOUBLE }
27
Kotlin
11
233
a9eff5463328f34072cdaf37aae3e77b14fcac93
1,558
Krypton
Apache License 2.0
api/src/main/kotlin/org/kryptonmc/api/block/meta/SlabType.kt
KryptonMC
255,582,002
false
null
/* * This file is part of the Krypton project, licensed under the Apache License v2.0 * * Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kryptonmc.api.block.meta /** * Indicates the type of slab that a block this property is applied to * represents. * * Slabs are different from a lot of other blocks, in that two of them can be * placed in the same block space. However, for uniformity, this is all an * illusion, and this property is used to differentiate "half slabs", those * that occupy half of a block from "full slabs", those that occupy a full * block, when two slabs are placed in the same block. */ public enum class SlabType { /** * The slab occupies the top half of a block. */ TOP, /** * The slab occupies the bottom half of a block. */ BOTTOM, /** * The slab occupies both halves of a block. This happens when two slabs * are placed in the same block. */ DOUBLE }
27
Kotlin
11
233
a9eff5463328f34072cdaf37aae3e77b14fcac93
1,558
Krypton
Apache License 2.0
demos/comida-app/src/main/kotlin/dev/tonycode/composed/comida/ui/ComidaAppActivity.kt
tonycode
734,835,138
false
{"Kotlin": 13282}
package dev.tonycode.composed.comida.ui import android.content.Context import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import dev.tonycode.composed.comida.ui.components.BottomNav import dev.tonycode.composed.comida.ui.screens.main.MainScreen import dev.tonycode.composed.comida.ui.theme.ComidaAppTheme class ComidaAppActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComidaApp() } } companion object { fun launch(context: Context) { context.startActivity( Intent(context, ComidaAppActivity::class.java) ) } } } val screenHorizontalPadding = 24.dp @Composable private fun ComidaApp() { ComidaAppTheme { Surface( color = MaterialTheme.colorScheme.background, modifier = Modifier.fillMaxSize(), ) { Box(modifier = Modifier.fillMaxSize()) { MainScreen() BottomNav( modifier = Modifier .fillMaxWidth() .padding(horizontal = screenHorizontalPadding, vertical = 24.dp) .align(Alignment.BottomCenter), ) } } } } @Preview @Composable private fun PreviewComposedApp() { ComidaApp() }
0
Kotlin
0
0
e22da7ca35a21f853b0b96d72af5e737970ef9c9
1,993
composed
MIT License
core/domain/src/main/java/com/github/smmousavi/domain/search/DefaultSearchCharacterUseCase.kt
smmousavi8872
824,171,857
false
{"Kotlin": 99042}
package com.github.smmousavi.domain.search import androidx.paging.PagingData import com.github.smmousavi.model.Character import com.github.smmousavi.repository.searchedcharacter.SearchCharacterRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class DefaultSearchCharacterUseCase @Inject constructor(private val charactersRepository: SearchCharacterRepository) : SearchCharactersUseCase { override suspend operator fun invoke( query: String, pageSize: Int, ): Flow<PagingData<Character>> = charactersRepository.searchCharacter(query, pageSize) }
1
Kotlin
0
0
b9bfc62f7b03c7148d5d60ad2d606ddfe9be3bfb
599
StarWars
Apache License 2.0
phone/src/main/java/com/schloesser/masterthesis/data/repository/SettingsRepository.kt
johnny-bytes
284,705,654
false
{"Java": 2838845, "Kotlin": 84783}
package com.schloesser.masterthesis.data.repository import android.content.Context import androidx.preference.PreferenceManager import com.schloesser.masterthesis.data.base.SingletonHolder class SettingsRepository private constructor(context: Context) { companion object : SingletonHolder<SettingsRepository, Context>(::SettingsRepository) private val sharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) } val sendFrameIntervalSeconds: Int @Synchronized get() = sharedPreferences.getString( "sendFrameIntervalSeconds", "15" )!!.toInt() val offlineModeEnabled: Boolean @Synchronized get() = sharedPreferences.getBoolean("offlineModeEnabled", false) }
1
null
1
1
8a065b1b2145a39051846742f3e639b5308557d0
762
ai-glasses
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/sagemaker/CfnModelCardModelOverviewPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.sagemaker import cloudshift.awscdk.common.CdkDslMarker import kotlin.Number import kotlin.String import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.sagemaker.CfnModelCard /** * An overview about the model. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.sagemaker.*; * ModelOverviewProperty modelOverviewProperty = ModelOverviewProperty.builder() * .algorithmType("algorithmType") * .inferenceEnvironment(InferenceEnvironmentProperty.builder() * .containerImage(List.of("containerImage")) * .build()) * .modelArtifact(List.of("modelArtifact")) * .modelCreator("modelCreator") * .modelDescription("modelDescription") * .modelId("modelId") * .modelName("modelName") * .modelOwner("modelOwner") * .modelVersion(123) * .problemType("problemType") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sagemaker-modelcard-modeloverview.html) */ @CdkDslMarker public class CfnModelCardModelOverviewPropertyDsl { private val cdkBuilder: CfnModelCard.ModelOverviewProperty.Builder = CfnModelCard.ModelOverviewProperty.builder() private val _modelArtifact: MutableList<String> = mutableListOf() /** * @param algorithmType The algorithm used to solve the problem. */ public fun algorithmType(algorithmType: String) { cdkBuilder.algorithmType(algorithmType) } /** * @param inferenceEnvironment An overview about model inference. */ public fun inferenceEnvironment(inferenceEnvironment: IResolvable) { cdkBuilder.inferenceEnvironment(inferenceEnvironment) } /** * @param inferenceEnvironment An overview about model inference. */ public fun inferenceEnvironment(inferenceEnvironment: CfnModelCard.InferenceEnvironmentProperty) { cdkBuilder.inferenceEnvironment(inferenceEnvironment) } /** * @param modelArtifact The location of the model artifact. */ public fun modelArtifact(vararg modelArtifact: String) { _modelArtifact.addAll(listOf(*modelArtifact)) } /** * @param modelArtifact The location of the model artifact. */ public fun modelArtifact(modelArtifact: Collection<String>) { _modelArtifact.addAll(modelArtifact) } /** * @param modelCreator The creator of the model. */ public fun modelCreator(modelCreator: String) { cdkBuilder.modelCreator(modelCreator) } /** * @param modelDescription A description of the model. */ public fun modelDescription(modelDescription: String) { cdkBuilder.modelDescription(modelDescription) } /** * @param modelId The SageMaker Model ARN or non- SageMaker Model ID. */ public fun modelId(modelId: String) { cdkBuilder.modelId(modelId) } /** * @param modelName The name of the model. */ public fun modelName(modelName: String) { cdkBuilder.modelName(modelName) } /** * @param modelOwner The owner of the model. */ public fun modelOwner(modelOwner: String) { cdkBuilder.modelOwner(modelOwner) } /** * @param modelVersion The version of the model. */ public fun modelVersion(modelVersion: Number) { cdkBuilder.modelVersion(modelVersion) } /** * @param problemType The problem being solved with the model. */ public fun problemType(problemType: String) { cdkBuilder.problemType(problemType) } public fun build(): CfnModelCard.ModelOverviewProperty { if(_modelArtifact.isNotEmpty()) cdkBuilder.modelArtifact(_modelArtifact) return cdkBuilder.build() } }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
3,949
awscdk-dsl-kotlin
Apache License 2.0
commons/src/main/kotlin/com/itangcent/common/utils/ThreadPoolUtils.kt
Earth-1610
178,314,657
false
{"Kotlin": 1216463, "Java": 35079, "Shell": 3153}
package com.itangcent.common.utils import com.itangcent.common.logger.Log import org.apache.commons.lang3.concurrent.BasicThreadFactory import java.util.concurrent.* /** * Helpers for [ExecutorService] */ object ThreadPoolUtils : Log() { fun setPoolSize(threadPool: ExecutorService, poolSize: Int?) { if (threadPool is ThreadPoolExecutor) { threadPool.maximumPoolSize = poolSize!! threadPool.corePoolSize = poolSize } } fun createPool(poolSize: Int, clazz: Class<*>): ExecutorService { return createPool(poolSize, clazz.simpleName) } fun createPool(poolSize: Int, name: String): ExecutorService { return createPool(poolSize, poolSize, name) } fun createPool(poolSize: Int, maximumPoolSize: Int, clazz: Class<*>): ExecutorService { return createPool(poolSize, maximumPoolSize, clazz.simpleName) } fun createPool(poolSize: Int, maximumPoolSize: Int, name: String): ExecutorService { return ThreadPoolExecutor( poolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS, LinkedBlockingQueue(), BasicThreadFactory.Builder().daemon(true) .namingPattern("$name-%d").build(), ThreadPoolExecutor.AbortPolicy() ) } fun createSinglePool(clazz: Class<*>): ExecutorService { return createPool(1, clazz) } fun createSinglePool(name: String): ExecutorService { return createPool(1, name) } fun newCachedThreadPool(): ExecutorService { return ThreadPoolExecutor( 0, Int.MAX_VALUE, 20L, TimeUnit.SECONDS, SynchronousQueue() ) } fun newCachedThreadPool(threadFactory: ThreadFactory): ExecutorService { return ThreadPoolExecutor( 0, Int.MAX_VALUE, 20L, TimeUnit.SECONDS, SynchronousQueue(), threadFactory ) } }
0
Kotlin
5
8
a6ebeab31b2cfc62f7ae83a2f4b50ae92782d0c3
1,972
intellij-kotlin
Apache License 2.0
src/main/kotlin/io/kraftsman/tables/Passwords.kt
shengyou
430,960,477
false
{"Kotlin": 5722}
package io.kraftsman.tables import org.jetbrains.exposed.dao.id.IntIdTable object Passwords: IntIdTable(name = "passwords") { val password = varchar("password", 255) }
0
Kotlin
0
0
f5823f90a0594efe13535e7bb61f78f227d4a80b
174
password-checker
MIT License
app/src/main/java/com/example/androiddevchallenge/DetailActivity.kt
HugoMatilla
342,671,717
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.data.Dog import com.example.androiddevchallenge.data.dogs import com.example.androiddevchallenge.data.findByName import com.example.androiddevchallenge.ui.common.Chips import com.example.androiddevchallenge.ui.common.DetailMessage import com.example.androiddevchallenge.ui.common.DetailNotice import com.example.androiddevchallenge.ui.common.DetailSubtitle import com.example.androiddevchallenge.ui.common.DetailTitle import com.example.androiddevchallenge.ui.theme.AppTheme class DetailActivity : AppCompatActivity() { companion object { const val NAME = "Name" fun start(caller: Activity, name: String) { val intent = Intent(caller, this::class.java.declaringClass) intent.putExtra(NAME, name) caller.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppTheme() { Detail() } } } // Start building your app here! @Composable fun Detail() { val dog = dogs.findByName(intent.getStringExtra(NAME) ?: "") if (dog != null) Scaffold(content = { DetailContent(dog) }) else Column(verticalArrangement = Arrangement.Center) { Text(text = "No dogs with this name") } } @Composable fun DetailContent(dog: Dog) { Box(Modifier.fillMaxHeight()) { Column( verticalArrangement = Arrangement.Top, modifier = Modifier.fillMaxHeight() ) { HeaderImage(dog) Column( modifier = Modifier .padding(12.dp) .fillMaxHeight(), verticalArrangement = Arrangement.SpaceBetween ) { DetailTitle(title = dog.name) DetailSubtitle(title = dog.breed) DetailMessage(title = dog.message) Chips(dog.tops) DetailNotice(title = "A house is not a home until there’s a dog in it. \nAdopt a shelter dog.") Button( onClick = { onButtonClick() }, modifier = Modifier.fillMaxWidth(), content = { Text("Adopt ${dog.name}") } ) } } } } private fun onButtonClick() { Toast.makeText(this, "❤️ Thank you! 🐶", Toast.LENGTH_SHORT).show() } @Composable fun HeaderImage(dog: Dog) { Image( painter = painterResource(dog.imageId), contentDescription = null, modifier = Modifier .fillMaxWidth() .clip( shape = RoundedCornerShape( topStartPercent = 0, topEndPercent = 0, bottomStartPercent = 20, bottomEndPercent = 20, ) ), contentScale = ContentScale.Crop ) } @Preview("Light Theme", widthDp = 360, heightDp = 640) @Composable fun LightPreview() { AppTheme { Detail() } } }
0
Kotlin
0
0
2cb2820e43e93c1be5e5c1fefb43438f0144a3d3
5,037
android-dev-challenge-compose-puppies
Apache License 2.0
network/src/main/java/com/quxianggif/network/model/FetchVCode.kt
guolindev
167,902,491
false
null
/* * Copyright (C) guolin, Suzhou Quxiang Inc. Open source codes for study only. * Do not use for commercial purpose. * * 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.quxianggif.network.model import com.quxianggif.network.request.FetchVCodeRequest /** * 获取短信验证码请求的实体类封装。 * * @author guolin * @since 19/1/7 */ class FetchVCode : Response() { /** * companion object 修饰为伴生对象,伴生对象在类中只能存在一个, * 类似于java中的静态方法 Java 中使用类访问静态成员,静态方法。 * https://www.jianshu.com/p/14db81e1576a */ companion object { fun getResponse(number: String, callback: Callback) { FetchVCodeRequest().number(number).listen(callback) } } }
30
null
692
3,448
26227595483a8f2508f23d947b3fe99721346e0f
1,196
giffun
Apache License 2.0
network/src/main/java/com/quxianggif/network/model/FetchVCode.kt
guolindev
167,902,491
false
null
/* * Copyright (C) guolin, Suzhou Quxiang Inc. Open source codes for study only. * Do not use for commercial purpose. * * 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.quxianggif.network.model import com.quxianggif.network.request.FetchVCodeRequest /** * 获取短信验证码请求的实体类封装。 * * @author guolin * @since 19/1/7 */ class FetchVCode : Response() { /** * companion object 修饰为伴生对象,伴生对象在类中只能存在一个, * 类似于java中的静态方法 Java 中使用类访问静态成员,静态方法。 * https://www.jianshu.com/p/14db81e1576a */ companion object { fun getResponse(number: String, callback: Callback) { FetchVCodeRequest().number(number).listen(callback) } } }
30
null
692
3,448
26227595483a8f2508f23d947b3fe99721346e0f
1,196
giffun
Apache License 2.0
feature/stocks/src/main/kotlin/br/com/stonks/feature/stocks/domain/mapper/StockAlertModelToUiMapper.kt
jonathanarodr
792,544,529
false
{"Kotlin": 189661, "Shell": 832}
package br.com.stonks.feature.stocks.domain.mapper import br.com.stonks.common.mapper.Mapper import br.com.stonks.feature.stocks.domain.model.StockAlertModel import br.com.stonks.feature.stocks.ui.model.AlertUiModel import br.com.stonks.feature.stocks.ui.model.StockAlertUiModel import br.com.stonks.feature.stocks.utils.getColor import br.com.stonks.feature.stocks.utils.getIcon internal class StockAlertModelToUiMapper : Mapper<List<StockAlertModel>, StockAlertUiModel> { override fun mapper(input: List<StockAlertModel>) = StockAlertUiModel( totalAssets = input.sumOf { it.alertValue }, stockAlerts = input.map(::mapperStockAlert), ) private fun mapperStockAlert(input: StockAlertModel) = AlertUiModel( id = input.id, ticket = input.ticket, alertValue = input.alertValue, status = input.status, alert = input.notificationTrigger, alertColor = input.notificationTrigger.getColor(), alertIcon = input.notificationTrigger.getIcon(), tagColor = input.status.getColor(), ) }
0
Kotlin
0
0
3303211e4ad5bde4dd4f2a00685884568a5eaeec
1,073
stonks
MIT License
sample/simple/feature/root/implementation/src/main/kotlin/com/freeletics/khonshu/sample/feature/root/RootNavigator.kt
freeletics
375,363,637
false
{"Kotlin": 500333, "Shell": 1814}
package com.freeletics.khonshu.sample.feature.root import com.freeletics.khonshu.navigation.NavEventNavigator import com.freeletics.khonshu.sample.feature.bottomsheet.nav.BottomSheetRoute import com.freeletics.khonshu.sample.feature.dialog.nav.DialogRoute import com.freeletics.khonshu.sample.feature.root.nav.RootRoute import com.freeletics.khonshu.sample.feature.screen.nav.ScreenRoute import com.squareup.anvil.annotations.ContributesBinding import com.squareup.anvil.annotations.optional.ForScope import com.squareup.anvil.annotations.optional.SingleIn import javax.inject.Inject @ForScope(RootRoute::class) @SingleIn(RootRoute::class) @ContributesBinding(RootRoute::class, NavEventNavigator::class) class RootNavigator @Inject constructor() : NavEventNavigator() { fun navigateToScreen() { navigateTo(ScreenRoute(1)) } fun navigateToDialog() { navigateTo(DialogRoute) } fun navigateToBottomSheet() { navigateTo(BottomSheetRoute) } }
6
Kotlin
9
95
eb5bc576d058ba24f6eb8f64c6d42066c664094e
990
khonshu
Apache License 2.0
kodein-di/src/commonMain/kotlin/org/kodein/di/internal/DIBuilderImpl.kt
kosi-libs
34,046,231
false
{"Kotlin": 666847, "Java": 16368}
@file:Suppress("FunctionName") package org.kodein.di.internal import org.kodein.di.Copy import org.kodein.di.DI import org.kodein.di.DirectDI import org.kodein.di.bindings.ArgSetBinding import org.kodein.di.bindings.BaseMultiBinding import org.kodein.di.bindings.ContextTranslator import org.kodein.di.bindings.DIBinding import org.kodein.di.bindings.ExternalSource import org.kodein.di.bindings.InstanceBinding import org.kodein.di.bindings.NoScope import org.kodein.di.bindings.Provider import org.kodein.di.bindings.Scope import org.kodein.di.bindings.SetBinding import org.kodein.type.TypeToken import org.kodein.type.erasedComp internal open class DIBuilderImpl internal constructor( private val moduleName: String?, private val prefix: String, internal val importedModules: MutableSet<String>, override val containerBuilder: DIContainerBuilderImpl ) : DI.Builder { override val contextType = TypeToken.Any override val scope: Scope<Any?> get() = NoScope() // Recreating a new NoScope every-time *on purpose*! override val explicitContext: Boolean get() = false inner class TypeBinder<T : Any> internal constructor( val type: TypeToken<out T>, val tag: Any?, val overrides: Boolean? ) : DI.Builder.TypeBinder<T> { internal val containerBuilder get() = [email protected] override infix fun <C : Any, A> with(binding: DIBinding<in C, in A, out T>) = containerBuilder.bind( DI.Key(binding.contextType, binding.argType, type, tag), binding, moduleName, overrides ) } /** * @see [DI.Builder.DelegateBinder] */ inner class DelegateBinder<T : Any> internal constructor( private val builder: DI.Builder, private val bindType: TypeToken<out T>, private val bindTag: Any? = null, private val overrides: Boolean? = null ) : DI.Builder.DelegateBinder<T>() { /** * @see [DI.Builder.DelegateBinder.To] */ override fun <A : T> To(type: TypeToken<A>, tag: Any?) { builder.Bind(bindTag, overrides, Provider(builder.contextType, bindType) { Instance(type, tag) }) } } inner class DirectBinder internal constructor(private val _tag: Any?, private val _overrides: Boolean?) : DI.Builder.DirectBinder inner class ConstantBinder internal constructor(private val _tag: Any, private val _overrides: Boolean?) : DI.Builder.ConstantBinder { override fun <T : Any> With(valueType: TypeToken<out T>, value: T) = Bind(tag = _tag, overrides = _overrides, binding = InstanceBinding(valueType, value)) } @Suppress("unchecked_cast") inner class SetBinder<T : Any> internal constructor( private val setBindingTag: Any? = null, private val setBindingType: TypeToken<out T>, setBindingOverrides: Boolean? = null, addSetBindingToContainer: Boolean = true, ) : DI.Builder.SetBinder<T> { private val setBinding: BaseMultiBinding<*, *, T> by lazy { val setType = erasedComp(Set::class, setBindingType) as TypeToken<Set<T>> val setKey = DI.Key(TypeToken.Any, TypeToken.Unit, setType, setBindingTag) val setBinding = containerBuilder.bindingsMap[setKey]?.first() ?: throw IllegalStateException("No set binding to $setKey") setBinding.binding as? BaseMultiBinding<*, *, T> ?: throw IllegalStateException("$setKey is associated to a ${setBinding.binding.factoryName()} while it should be associated with bindingSet") } init { if (addSetBindingToContainer) { Bind( tag = setBindingTag, overrides = setBindingOverrides, binding = SetBinding( contextType = TypeToken.Any, _elementType = setBindingType, createdType = erasedComp(Set::class, setBindingType) as TypeToken<Set<T>> ) ) } } override fun add(createBinding: () -> DIBinding<*, *, out T>) { val binding = createBinding() (setBinding.set as MutableSet<DIBinding<*, *, *>>).add(binding) } override fun bind(tag: Any?, overrides: Boolean?, createBinding: () -> DIBinding<*, *, out T>) { val binding = createBinding() (setBinding.set as MutableSet<DIBinding<*, *, *>>).add(binding) Bind(tag = tag, overrides = overrides, binding = binding) } } @Suppress("unchecked_cast") inner class ArgSetBinder<A : Any, T : Any>( private val setBindingTag: Any? = null, setBindingOverrides: Boolean? = null, private val setBindingArgType: TypeToken<in A>, private val setBindingType: TypeToken<out T>, addSetBindingToContainer: Boolean = true, ) : DI.Builder.ArgSetBinder<A, T> { private val setBinding: BaseMultiBinding<*, in A, out T> by lazy { val setType = erasedComp(Set::class, setBindingType) as TypeToken<Set<T>> val setKey = DI.Key(TypeToken.Any, setBindingArgType, setType, setBindingTag) val setBinding = containerBuilder.bindingsMap[setKey]?.first() ?: throw IllegalStateException("No set binding to $setKey") setBinding.binding as? BaseMultiBinding<*, A, T> ?: throw IllegalStateException("$setKey is associated to a ${setBinding.binding.factoryName()} while it should be associated with bindingSet") } init { if (addSetBindingToContainer) { Bind( tag = setBindingTag, overrides = setBindingOverrides, binding = ArgSetBinding( TypeToken.Any, setBindingArgType, setBindingType, erasedComp(Set::class, setBindingType) as TypeToken<Set<T>> ) ) } } override fun add(createBinding: () -> DIBinding<*, in A, out T>) { val binding = createBinding() (setBinding.set as MutableSet<DIBinding<*, *, *>>).add(binding) } override fun bind(tag: Any?, overrides: Boolean?, createBinding: () -> DIBinding<*, in A, out T>) { val binding = createBinding() (setBinding.set as MutableSet<DIBinding<*, *, *>>).add(binding) Bind(tag = tag, overrides = overrides, binding = binding) } } @Suppress("FunctionName") override fun <T : Any> Bind( type: TypeToken<out T>, tag: Any?, overrides: Boolean? ) = TypeBinder(type, tag, overrides) @Suppress("FunctionName") override fun <T : Any> Bind( tag: Any?, overrides: Boolean?, binding: DIBinding<*, *, T> ) { containerBuilder.bind( key = DI.Key(binding.contextType, binding.argType, binding.createdType, tag = tag), binding = binding, fromModule = moduleName, overrides = overrides, ) } override fun <T : Any> BindInSet( tag: Any?, overrides: Boolean?, type: TypeToken<out T>, creator: DI.Builder.SetBinder<T>.() -> Unit ) = creator(SetBinder(tag, type, overrides)) override fun <T : Any> InBindSet( tag: Any?, overrides: Boolean?, type: TypeToken<out T>, creator: DI.Builder.SetBinder<T>.() -> Unit ) = creator( SetBinder( setBindingTag = tag, setBindingType = type, setBindingOverrides = overrides, addSetBindingToContainer = false ) ) override fun <A : Any, T : Any> BindInArgSet( tag: Any?, overrides: Boolean?, argType: TypeToken<in A>, type: TypeToken<out T>, creator: DI.Builder.ArgSetBinder<A, T>.() -> Unit ) = creator( ArgSetBinder( setBindingTag = tag, setBindingOverrides = overrides, setBindingArgType = argType, setBindingType = type ) ) override fun <A : Any, T : Any> InBindArgSet( tag: Any?, overrides: Boolean?, argType: TypeToken<in A>, type: TypeToken<out T>, creator: DI.Builder.ArgSetBinder<A, T>.() -> Unit ) = creator( ArgSetBinder( setBindingTag = tag, setBindingOverrides = overrides, setBindingArgType = argType, setBindingType = type, addSetBindingToContainer = false ) ) @Deprecated("Use inBindSet { add { BINDING } } instead.") @Suppress("deprecation") override fun <T : Any> BindSet( tag: Any?, overrides: Boolean?, binding: DIBinding<*, *, T>, ) = AddBindInSet(tag = tag, overrides = overrides, binding = binding) @Suppress("unchecked_cast") @Deprecated("Use inBindSet { add { BINDING } } instead.") override fun <T : Any> AddBindInSet( tag: Any?, overrides: Boolean?, binding: DIBinding<*, *, T>, ) { val setType = erasedComp(Set::class, binding.createdType) as TypeToken<Set<T>> val setKey = DI.Key(binding.contextType, binding.argType, setType, tag) val setBinding = containerBuilder.bindingsMap[setKey]?.first() ?: throw IllegalStateException("No set binding to $setKey") val multipleBinding = setBinding.binding as? BaseMultiBinding<*, *, T> ?: throw IllegalStateException("$setKey is associated to a ${setBinding.binding.factoryName()} while it should be associated with bindingSet") (multipleBinding.set as MutableSet<DIBinding<*, *, *>>).add(binding) } @Deprecated("This is not used, it will be removed") override fun Bind(tag: Any?, overrides: Boolean?): DirectBinder = DirectBinder(tag, overrides) override fun constant(tag: Any, overrides: Boolean?) = ConstantBinder(tag, overrides) override fun <T : Any> Delegate( type: TypeToken<out T>, tag: Any?, overrides: Boolean?, ): DelegateBinder<T> = DelegateBinder(this, type, tag, overrides) override fun import(module: DI.Module, allowOverride: Boolean) { val moduleName = prefix + module.name if (moduleName.isNotEmpty() && moduleName in importedModules) { throw IllegalStateException("Module \"$moduleName\" has already been imported!") } importedModules += moduleName DIBuilderImpl( moduleName, prefix + module.prefix, importedModules, containerBuilder.subBuilder(allowOverride, module.allowSilentOverride) ).apply(module.init) } override fun importAll(modules: Iterable<DI.Module>, allowOverride: Boolean) = modules.forEach { import(it, allowOverride) } override fun importAll(vararg modules: DI.Module, allowOverride: Boolean) = modules.forEach { import(it, allowOverride) } override fun importOnce(module: DI.Module, allowOverride: Boolean) { if (module.name.isEmpty()) throw IllegalStateException("importOnce must be given a named module.") if (module.name !in importedModules) import(module, allowOverride) } override fun onReady(cb: DirectDI.() -> Unit) = containerBuilder.onReady(cb) override fun RegisterContextTranslator(translator: ContextTranslator<*, *>) = containerBuilder.registerContextTranslator(translator) } internal open class DIMainBuilderImpl(allowSilentOverride: Boolean) : DIBuilderImpl( null, "", HashSet(), DIContainerBuilderImpl(true, allowSilentOverride, HashMap(), ArrayList(), ArrayList()) ), DI.MainBuilder { override val externalSources: MutableList<ExternalSource> = ArrayList() override var fullDescriptionOnError: Boolean = DI.defaultFullDescriptionOnError override var fullContainerTreeOnError: Boolean = DI.defaultFullContainerTreeOnError override fun extend(di: DI, allowOverride: Boolean, copy: Copy) { val keys = copy.keySet(di.container.tree) containerBuilder.extend(di.container, allowOverride, keys) externalSources += di.container.tree.externalSources importedModules.addAll( containerBuilder.bindingsMap .flatMap { it.value.map { it.fromModule } } .filterNotNull() ) } override fun extend(directDI: DirectDI, allowOverride: Boolean, copy: Copy) { val keys = copy.keySet(directDI.container.tree) containerBuilder.extend(directDI.container, allowOverride, keys) externalSources += directDI.container.tree.externalSources importedModules.addAll( containerBuilder.bindingsMap .flatMap { it.value.map { it.fromModule } } .filterNotNull() ) } }
6
Kotlin
174
3,189
573b264a3f6f5f7145583081efc318c4303fc4d2
13,080
Kodein
MIT License
shared/src/androidMain/kotlin/com/hypeapps/lifelinked/MainActivity.kt
ntietje1
672,375,249
false
{"Kotlin": 447815, "Swift": 839}
package com.hypeapps.lifelinked import BackHandler import LifeLinkedApp import android.graphics.Color import android.os.Build import android.os.Bundle import android.view.View import android.view.Window import android.view.WindowInsets import android.view.WindowInsetsController import androidx.activity.ComponentActivity import androidx.activity.addCallback import androidx.activity.compose.setContent import androidx.compose.foundation.isSystemInDarkTheme import org.koin.android.ext.android.inject class MainActivity : ComponentActivity() { private val backHandler: BackHandler by inject() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.requestWindowFeature(Window.FEATURE_NO_TITLE) val activity: ComponentActivity = this // enableEdgeToEdge() setContent { window.decorView.setBackgroundColor(if (isSystemInDarkTheme()) Color.BLACK else Color.WHITE) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.setDecorFitsSystemWindows(false) window.insetsController?.let { it.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars()) it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } } else { @Suppress("DEPRECATION") window.decorView.systemUiVisibility = ( View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) } // fun generateCallback (): () -> Unit { // return { // println("back button pressed!!") // backHandler.pop() // } // } this.onBackPressedDispatcher.addCallback(this) { println("back button pressed!1") // this.isEnabled = false backHandler.pop() // this.handleOnBackPressed() // this.remove() // onBackPressedDispatcher.addCallback(this@MainActivity) { // generateCallback().invoke() // } } LifeLinkedApp() } } }
5
Kotlin
0
1
921bc15794382f79d0878accecea48c896a8d911
2,604
MTG_Life_Total_App
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Volumemute.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup public val BoldGroup.Volumemute: ImageVector get() { if (_volumemute != null) { return _volumemute!! } _volumemute = Builder(name = "Volumemute", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.52f, 3.7817f) curveTo(16.4f, 3.1617f, 14.97f, 3.3217f, 13.51f, 4.2317f) lineTo(10.59f, 6.0617f) curveTo(10.39f, 6.1817f, 10.16f, 6.2517f, 9.93f, 6.2517f) horizontalLineTo(9.0f) horizontalLineTo(8.5f) curveTo(6.08f, 6.2517f, 4.75f, 7.5817f, 4.75f, 10.0017f) verticalLineTo(14.0017f) curveTo(4.75f, 16.4217f, 6.08f, 17.7517f, 8.5f, 17.7517f) horizontalLineTo(9.0f) horizontalLineTo(9.93f) curveTo(10.16f, 17.7517f, 10.39f, 17.8217f, 10.59f, 17.9417f) lineTo(13.51f, 19.7717f) curveTo(14.39f, 20.3217f, 15.25f, 20.5917f, 16.05f, 20.5917f) curveTo(16.57f, 20.5917f, 17.07f, 20.4717f, 17.52f, 20.2217f) curveTo(18.63f, 19.6017f, 19.25f, 18.3117f, 19.25f, 16.5917f) verticalLineTo(7.4117f) curveTo(19.25f, 5.6917f, 18.63f, 4.4017f, 17.52f, 3.7817f) close() } } .build() return _volumemute!! } private var _volumemute: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
2,310
VuesaxIcons
MIT License
feature/feed/src/main/java/lifetracker/feature/feed/FeedAdapter.kt
kamerok
243,346,801
false
null
package lifetracker.feature.feed import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import lifetracker.feature.feed.databinding.ItemDayDoneBinding import lifetracker.feature.feed.databinding.ItemDayProgressBinding import lifetracker.feature.feed.databinding.ItemSkippedDayBinding import org.threeten.bp.LocalDate class FeedAdapter(private val listener: (LocalDate) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var data: List<FeedItem> = emptyList() override fun getItemViewType(position: Int): Int = when (data[position]) { is SkippedDay -> 0 is TodayProgress.Progress -> 1 is TodayProgress.Done -> 2 } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) { 0 -> SkippedDayViewHolder( LayoutInflater.from(parent.context).inflate( R.layout.item_skipped_day, parent, false ), listener ) 1 -> ProgressViewHolder( LayoutInflater.from(parent.context).inflate( R.layout.item_day_progress, parent, false ), listener ) else -> DoneViewHolder( LayoutInflater.from(parent.context).inflate( R.layout.item_day_done, parent, false ), listener ) } override fun getItemCount(): Int = data.size override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val model = data[position] when { holder is SkippedDayViewHolder && model is SkippedDay -> holder.bind(model) holder is ProgressViewHolder && model is TodayProgress.Progress -> holder.bind(model) holder is DoneViewHolder && model is TodayProgress.Done -> holder.bind(model) } } fun setData(data: List<FeedItem>) { this.data = data notifyDataSetChanged() } class SkippedDayViewHolder(view: View, private val listener: (LocalDate) -> Unit) : RecyclerView.ViewHolder(view) { private val binding = ItemSkippedDayBinding.bind(view) fun bind(model: SkippedDay) = with(binding) { buttonView.setOnClickListener { listener(model.date) } dateView.text = model.date.toString() } } class ProgressViewHolder(view: View, private val listener: (LocalDate) -> Unit) : RecyclerView.ViewHolder(view) { private val binding = ItemDayProgressBinding.bind(view) fun bind(model: TodayProgress.Progress) = with(binding) { buttonView.setOnClickListener { listener(model.date) } textView.text = "${model.date}: ${model.progress} of ${model.total}" progressView.max = model.total progressView.progress = model.progress } } class DoneViewHolder(view: View, private val listener: (LocalDate) -> Unit) : RecyclerView.ViewHolder(view) { private val binding = ItemDayDoneBinding.bind(view) fun bind(model: TodayProgress.Done) = with(binding) { buttonView.setOnClickListener { listener(model.date) } } } }
0
Kotlin
0
0
363d097207a3f5b4ef96c8231842d139cddc67c9
3,426
LifeTracker
Apache License 2.0
app/src/main/java/com/omni/continuoussharedelementtransition_viewpager2/grid/GridFragment.kt
OmneyaOsman
231,263,316
false
null
package com.omni.continuoussharedelementtransition_viewpager2.grid import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.core.app.SharedElementCallback import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.interpolator.view.animation.FastOutSlowInInterpolator import androidx.lifecycle.Observer import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import androidx.transition.Fade import androidx.transition.TransitionSet import com.omni.continuoussharedelementtransition_viewpager2.DataGenerator import com.omni.continuoussharedelementtransition_viewpager2.R import com.omni.continuoussharedelementtransition_viewpager2.SharedViewModel import com.omni.continuoussharedelementtransition_viewpager2.waitForTransition class GridFragment : Fragment() { private lateinit var rootView: View private lateinit var recyclerView: RecyclerView private val viewModel by activityViewModels<SharedViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.grid_fragment, container, false) recyclerView = rootView.findViewById(R.id.grid_recycler_view) return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(recyclerView) { layoutManager = StaggeredGridLayoutManager( 2 ,LinearLayout.VERTICAL) adapter = GridAdapter().apply { submitList(DataGenerator.list) } exitTransition = exitTransition() setExitSharedElementCallback(sharedElementCallback) waitForTransition(this) } } /** It's important to note that this callback will be called while exiting the Fragment * when the fragment-transaction occurs, and while re-entering the Fragment when it's popped out * of the backstack (on back navigation). We will use this behavior to remap * the shared view and adjust the transition to handle cases where the view is changed * after paging the images.*/ private fun exitTransition() = TransitionSet() .addTransition(Fade().addTarget(R.id.card_view)) .apply { duration = 375 startDelay = 25 interpolator = FastOutSlowInInterpolator() } private val sharedElementCallback = object : SharedElementCallback() { override fun onMapSharedElements( names: MutableList<String>, sharedElements: MutableMap<String, View> ) { viewModel.currentPositionLiveData.observe(viewLifecycleOwner, Observer { current -> with(recyclerView) { recyclerView.findViewHolderForAdapterPosition(current) // Map the first shared element name to the child ImageView. ?.let { sharedElements.put( names[0], it.itemView.findViewById(R.id.grid_image_view) ) } post { layoutManager?.scrollToPosition(current) } } }) } } }
0
Kotlin
0
1
8803cfdcc0a4927fcf329993603f448bc152b93d
3,534
ContinuousSharedElementTransition-ViewPager2
MIT License
mobile/SmartOutletIOT/app/src/main/java/com/tekydevelop/android/smartoutletiot/data/model/DeviceRequest.kt
ManolescuSebastian
244,956,856
false
null
package com.tekydevelop.android.smartoutletiot.data.model data class DeviceRequest( private val id: Int, private val uuid: Int, private val name: String, private val type: Int )
0
Kotlin
0
8
5de0ed9f2f4965c2dc54c8b60c08a90d04d00a00
194
SmartOutlet-IOT
Apache License 2.0
src/test/java/ca/mcgill/science/tepid/server/printing/PrintingTest.kt
ctf
138,677,497
false
{"Kotlin": 231277, "TSQL": 17082, "JavaScript": 9042, "Java": 5582, "PLpgSQL": 1931, "Dockerfile": 512}
package ca.mcgill.science.tepid.server.printing import ca.mcgill.science.tepid.models.data.PrintJob import ca.mcgill.science.tepid.models.enums.PrintError import ca.mcgill.science.tepid.server.server.Config import io.mockk.every import io.mockk.mockkObject import io.mockk.unmockkAll import org.apache.logging.log4j.kotlin.Logging import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test class PrintingTest : Logging { @Test fun tooManyPagesTestTooManyEnabled() { every { Config.MAX_PAGES_PER_JOB } returns 10 val p = PrintJob(pages = 1000) val e = Assertions.assertThrows(Printer.PrintException::class.java) { Printer.validateJobSize(p) } Assertions.assertEquals(PrintError.TOO_MANY_PAGES.display, e.message) } @Test fun tooManyPagesTestTooManyDisabled() { every { Config.MAX_PAGES_PER_JOB } returns -1 val p = PrintJob(pages = 1000) Printer.validateJobSize(p) } @Test fun tooManyPagesTestEnoughEnabled() { every { Config.MAX_PAGES_PER_JOB } returns 50 val p = PrintJob(pages = 10) Printer.validateJobSize(p) } companion object { @JvmStatic @BeforeAll fun initTest() { mockkObject(Config) } @JvmStatic @AfterAll fun tearTest() { unmockkAll() } } }
1
Kotlin
2
2
6d7a9a33c7d2c3518d62acb7467c8f3e2c27b9f5
1,466
TEPID-Server
Apache License 2.0
idofront-util/src/main/kotlin/com/mineinabyss/idofront/resourcepacks/MinecraftAssetExtractor.kt
MineInAbyss
234,201,953
false
{"Kotlin": 212498}
package com.mineinabyss.idofront.resourcepacks import com.google.gson.JsonObject import com.google.gson.JsonParser import com.mineinabyss.idofront.messaging.idofrontLogger import org.bukkit.Bukkit import java.io.ByteArrayInputStream import java.io.File import java.io.FileOutputStream import java.net.URI import java.util.zip.ZipEntry import java.util.zip.ZipInputStream object MinecraftAssetExtractor { private const val VERSION_MANIFEST_URL = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json" val assetPath = Bukkit.getPluginsFolder().resolve("Idofront/assetCache/${Bukkit.getMinecraftVersion()}") fun extractLatest() { if (assetPath.exists() && !assetPath.listFiles().isNullOrEmpty()) return idofrontLogger.i("Extracting latest vanilla-assets...") val versionInfo = runCatching { downloadJson(findVersionInfoUrl() ?: return)?.asJsonObject }.getOrNull() ?: return val clientJar = downloadClientJar(versionInfo) extractJarAssets(clientJar, assetPath) idofrontLogger.s("Finished extracting vanilla assets for ${assetPath.name}") } private fun extractJarAssets(clientJar: ByteArray?, assetPath: File) { var entry: ZipEntry ByteArrayInputStream(clientJar).use { inputStream -> ZipInputStream(inputStream).use { zipInputStream -> kotlin.runCatching { while (zipInputStream.nextEntry.also { entry = it } != null) { if (!entry.name.startsWith("assets/")) continue if (entry.name.startsWith("assets/minecraft/shaders")) continue if (entry.name.startsWith("assets/minecraft/particles")) continue val file = checkAndCreateFile(assetPath, entry) if (entry.isDirectory && !file.isDirectory && !file.mkdirs()) error("Failed to create directory ${entry.name}") else { val parent = file.parentFile if (!parent.isDirectory && !parent.mkdirs()) error("Failed to create directory ${parent?.path}") runCatching { zipInputStream.copyTo(FileOutputStream(file)) }.onFailure { error("Failed to extract ${entry.name} from ${parent?.path}") } } } } } } } private fun checkAndCreateFile(assetPath: File, entry: ZipEntry): File { val destFile = assetPath.resolve(entry.name) val dirPath = assetPath.canonicalPath val filePath = destFile.canonicalPath if (!filePath.startsWith(dirPath + File.separator)) error("Entry outside target: ${entry.name}") return destFile } private fun downloadClientJar(versionInfo: JsonObject) = runCatching { val url = versionInfo.getAsJsonObject("downloads").getAsJsonObject("client").get("url").asString URI(url).toURL().readBytes() }.onFailure { it.printStackTrace() }.getOrNull() ?: error("Failed to download client JAR") private fun findVersionInfoUrl(): String? { val version = Bukkit.getMinecraftVersion() if (!assetPath.mkdirs()) { idofrontLogger.i("Latest has already been extracted for $version, skipping...") return null } val manifest = runCatching { downloadJson(VERSION_MANIFEST_URL) }.getOrNull() ?: error("Failed to download version manifest") return manifest.getAsJsonArray("versions").firstOrNull { (it as? JsonObject)?.get("id")?.asString?.equals(version) ?: false }?.asJsonObject?.get("url")?.asString ?: error("Failed to find version inof url for version $version") } private fun downloadJson(url: String) = runCatching { JsonParser.parseString(URI.create(url).toURL().readText()) } .getOrNull()?.takeIf { it.isJsonObject }?.asJsonObject }
3
Kotlin
6
15
ecc9da6ee819ccf907718d4a5288d186981c414c
4,106
Idofront
MIT License
app/src/main/java/com/rerere/iwara4a/model/playlist/PlaylistActionResponse.kt
re-ovo
349,642,808
false
null
package com.rerere.iwara4a.model.playlist import com.google.gson.annotations.SerializedName data class PlaylistActionResponse( @SerializedName("message") val message: String, @SerializedName("status") val status: Int )
6
Kotlin
16
354
571cd02d5455bb636e3544abb8ac4498902ed8eb
237
iwara4a
Apache License 2.0
hand-ins/app/src/main/java/com/example/handins/handin2/hand_in_2.kt
Josef-TL
751,238,665
false
{"Kotlin": 21742}
package com.example.handins.handin2 fun main(){ // Opgave 1 val employeeOne = Employee("Jhon","Smith", 40000.0) val employeeTwo = Employee("Beckie","Mcenzie", 56000.0) println("${employeeOne.firstName}'s monthly salary: ${employeeOne.monthlySalary}") println("${employeeTwo.firstName}'s monthly salary: ${employeeTwo.monthlySalary}") employeeOne.raise(10.0) employeeTwo.raise(10.0) println("${employeeOne.firstName}'s monthly salary after 10% raise: ${employeeOne.monthlySalary}") println("${employeeTwo.firstName}'s monthly salary after 10% raise: ${employeeTwo.monthlySalary}") // Opgave 2 val lap = Laptop("Lenovo","Alpha Fold","absd9876",12000) val phone = SmartPhone("Android","Galaxy S-Omega","Sx102030",8000) // Opgave 3 val prod1 = Shirt("T-shirt",60.0,2) val prd2 = Shoe("Yeezeys", 500.0,1) val prd3 = Product("Missing Books",0.0,10) prod1.identifyProductCategory() prd2.identifyProductCategory() prd3.identifyProductCategory() // Opgave 4 val circle1 = Circle(1,"red",false) println(circle1.calculatePerimiter()) val rect1 = Rectangle(3,4,"blue", true) println(rect1.calculateArea()) val tri1 = Triangle(3,3,3,"green",false) print(tri1.area) }
0
Kotlin
0
0
2cff00eda76ddd6ec98f82fa6189ffa4709c39a4
1,265
app-dev
MIT License
src/exchange/src/main/kotlin/com/exchange/exchange/exception/AppException.kt
exchange-all
727,231,684
false
{"Kotlin": 134558, "Java": 26827, "Smarty": 7288, "Shell": 5516, "TypeScript": 5426, "Lua": 906}
package com.exchange.authservice.exception /** * * @author uuhnaut69 * */ class BadRequestException( override val message: String = "BAD_REQUEST_ERROR", ) : RuntimeException() class UnauthorizedException( override val message: String = "UNAUTHORIZED_ERROR", ) : RuntimeException() class InternalServerErrorException( override val message: String = "INTERNAL_SERVER_ERROR", ) : RuntimeException()
15
Kotlin
0
2
6212e37ea4c6ab8b86e809b1d6427f844e84a489
415
exchange-api
Apache License 2.0
Kosalaam/app/src/main/java/com/kosalaamInc/kosalaam/model/network/api/KosalaamAPI.kt
ko-salaam
385,827,098
false
null
package com.kosalaamInc.kosalaam.model.network.api import com.kosalaamInc.kosalaam.model.data.HostRegisterData import com.kosalaamInc.kosalaam.model.data.UserCertified import com.kosalaamInc.kosalaam.model.data.UserData import com.kosalaamInc.kosalaam.model.data.UserHost import com.kosalaamInc.kosalaam.model.network.response.* import okhttp3.MultipartBody import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Response import retrofit2.http.* interface KosalaamAPI { @GET("/api/user/{uid}") fun getUser(@Header("Authorization") authorization : String ,@Path("uid") uid : String) @POST("/api/auth") fun signIn(@Header("Authorization") authorization : String) @POST("/api/auth/new") suspend fun signUp(@Header("Authorization") authorization : String) :Response<SignInResponse> // restaurant list @GET("/api/restaurant") suspend fun getRestaurantList(@Query("distance") distance : Int , @Query("keyword") keyword : String, @Query("latitude") lat : Double, @Query("longitude") lon : Double, @Query("muslimFreindlies") muslimFriendly : ArrayList<String>?, @Query("pageNum") pageNum : Int, @Query("pageSize") pageSize : Int) : Response<List<RestauarntResponse>> // restaurant info @GET("/api/restaurant/{id}") suspend fun getRestaurantInfo(@Header("Authorization") authorization : String?,@Path("id") id : String?) : Response<RestauarntResponse> @GET("/api/accommodation") suspend fun getHotelList(@Query("distance") distance : Int, @Query("isMuslimFriendly") isMuslimFreindly : Boolean, @Query("keyword") keyword : String, @Query("latitude") lat : Double, @Query("longitude") lon : Double, @Query("pageNum") pageNum : Int, @Query("pageSize") pageSize : Int) : Response<List<HotelResponse>> @GET("/api/accommodation/{id}") suspend fun getHotelInfo(@Header("Authorization") authorization : String?,@Path("id") id : String) : Response<HotelResponse> @GET("/api/prayerroom") suspend fun getPrayerRoomList(@Query("distance") distance : Int , @Query("keyword") keyword : String, @Query("latitude") lat : Double, @Query("longitude") lon : Double, @Query("pageNum") pageNum : Int, @Query("pageSize") pageSize : Int) : Response<List<PrayerRoomResponse>> @GET("/api/prayerroom/{id}") suspend fun getPrayerRoomInfo(@Header("Authorization") authorization : String?,@Path("id") id : String) : Response<PrayerRoomResponse> @GET("/api/common") suspend fun getCommonList(@Query("distance") distance : Int ,@Query("isMuslimFriendly") isMuslimFreindly : Boolean, @Query("keyword") keyword : String, @Query("latitude") lat : Double, @Query("longitude") lon : Double, @Query("pageNum") pageNum : Int, @Query("pageSize") pageSize : Int) : Response<List<CommonResponse>> @GET("/api/common/{id}") suspend fun getCommonInfo(@Path("id") id : String) : Response<CommonResponse> @POST("api/prayerroom/like/{id}") suspend fun prayerLike(@Header("Authorization") authorization : String?, @Path("id") id : String) : Response<BaseResponse> @DELETE("api/prayerroom/like/{id}") suspend fun prayerLikeCancel(@Header("Authorization") authorization : String?, @Path("id") id : String) : Response<BaseResponse> @POST("api/accommodation/like/{id}") suspend fun hotelLike(@Header("Authorization") authorization : String?, @Path("id") id : String) : Response<BaseResponse> @DELETE("api/accommodation/like/{id}") suspend fun hotelLikeCancel(@Header("Authorization") authorization : String?, @Path("id") id : String) : Response<BaseResponse> @POST("api/restaurant/like/{id}") suspend fun restaurantLike(@Header("Authorization") authorization : String?, @Path("id") id : String) : Response<BaseResponse> @DELETE("api/restaurant/like/{id}") suspend fun restaurantLikeCancel(@Header("Authorization") authorization : String?, @Path("id") id : String) : Response<BaseResponse> // @POST("/api/restaurant") suspend fun registerResturant() @GET("/api/auth/me") suspend fun getAuthMe(@Header("Authorization") authorization : String?) : Response<UserResponse> @PUT("/api/auth") suspend fun putAuthMe(@Header("Authorization") authorization : String? , @Body body : UserData) : Response<UserResponse> @PUT("api/prayerroom/{id}") suspend fun registerPlayerRoomData(@Header("Authorization") authorization: String?, @Path("id") id : String, @Body prayerRoomInfo : HostRegisterData) : Response<PrayerRoomResponse> @POST("api/prayerroom") suspend fun registerPrayerRoomTest(@Header("Authorization") authorization: String?, @Body data : HostRegisterData) : Response<PrayerRoomResponse> @Multipart @POST("api/prayerroom") suspend fun registerPlayerRoom(@Header("Authorization") authorization: String? ,@PartMap data : HashMap<String,RequestBody>, @Part images : List<MultipartBody.Part>) : Response<PrayerRoomResponse> //@Headers("content-type: application/json") @PUT("api/auth") suspend fun putUserCertified(@Header("Authorization") authorization: String?, @Body user : UserCertified) : Response<UserResponse> @PUT("api/auth") suspend fun putUserHost(@Header("Authorization") authorization: String?, @Body user : UserHost) : Response<UserResponse> @Multipart @PUT("api/auth") suspend fun editUserInfo(@Header("Authorization") authorization: String?, @Part image : MultipartBody.Part?, @PartMap data : HashMap<String,RequestBody>) : Response<UserResponse> }
8
Kotlin
0
1
aec7d173d06d1a37161b8f55284850c85cd86138
5,550
ko-salaam-android
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/quicksight/CfnTemplatePropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.quicksight import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.quicksight.CfnTemplateProps @Generated public fun buildCfnTemplateProps(initializer: @AwsCdkDsl CfnTemplateProps.Builder.() -> Unit): CfnTemplateProps = CfnTemplateProps.Builder().apply(initializer).build()
1
Kotlin
0
0
451a1e42282de74a9a119a5716bd95b913662e7c
404
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/pavelrekun/rekado/screens/serial_checker_activity/SerialCheckerFragment.kt
MenosGrante
139,457,137
false
null
package com.pavelrekun.rekado.screens.serial_checker_activity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import com.google.zxing.integration.android.IntentIntegrator import com.pavelrekun.rekado.R import com.pavelrekun.rekado.base.BaseFragment import com.pavelrekun.rekado.databinding.FragmentSerialCheckerBinding import com.pavelrekun.rekado.services.Constants import com.pavelrekun.rekado.services.utils.SerialUtils import com.pavelrekun.rekado.services.extensions.getString import com.pavelrekun.rekado.services.extensions.isEmpty import com.pavelrekun.rekado.services.extensions.viewBinding import com.pavelrekun.rekado.services.utils.Utils import de.halfbit.edgetoedge.Edge import de.halfbit.edgetoedge.edgeToEdge class SerialCheckerFragment : BaseFragment(R.layout.fragment_serial_checker) { private val binding by viewBinding(FragmentSerialCheckerBinding::bind) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initScrollingBehaviour(binding.serialCheckerLayoutScroll) initClickListeners() initEdgeToEdge() generateInformation() } private fun initClickListeners() { binding.serialCheckerCheck.setOnClickListener { if (binding.serialCheckerField.length() <= 14) { if (!binding.serialCheckerField.isEmpty()) { try { val text = SerialUtils.defineConsoleStatus(binding.serialCheckerField.getString()) Toast.makeText(activity, text, Toast.LENGTH_SHORT).show() } catch (e: Exception) { Toast.makeText(activity, R.string.serial_checker_status_error, Toast.LENGTH_SHORT).show() } } else { Toast.makeText(activity, R.string.serial_checker_status_empty, Toast.LENGTH_SHORT).show() } } else { Toast.makeText(activity, R.string.serial_checker_status_too_long, Toast.LENGTH_SHORT).show() } } binding.serialCheckerHelp.setOnClickListener { Utils.openLink(requireBaseActivity(), Constants.HELP_SERIAL_CHECKER) } binding.serialCheckerScan.setOnClickListener { IntentIntegrator(activity).apply { setOrientationLocked(false) setBeepEnabled(false) }.initiateScan() } } private fun generateInformation() { val serialsInformation = getString(R.string.serial_checker_information_xaw1) + getString(R.string.serial_checker_information_xaw4) + getString(R.string.serial_checker_information_xaw7) + getString(R.string.serial_checker_information_xaj1) + getString(R.string.serial_checker_information_xaj4) + getString(R.string.serial_checker_information_xaj7) + getString(R.string.serial_checker_information_xaw9) + getString(R.string.serial_checker_information_xak) binding.serialCheckerInformation.text = serialsInformation } private fun initEdgeToEdge() { edgeToEdge { binding.serialCheckerLayoutContainer.fit { Edge.Bottom } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (result.contents != null) { binding.serialCheckerField.setText(result.contents) binding.serialCheckerField.requestFocus() } else { Toast.makeText(activity, R.string.serial_checker_status_scan_failed, Toast.LENGTH_SHORT).show() } } }
11
Kotlin
44
573
2643f63b4978bb33836654f4cfdd95b4c510b92d
3,833
Rekado
Apache License 2.0
flutter_play/flutter_play/android/app/src/main/kotlin/com/mtjin/flutter_play/MainActivity.kt
mtjin
329,812,089
false
{"Dart": 2440, "Swift": 404, "Kotlin": 127, "Objective-C": 38}
package com.mtjin.flutter_play import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
3dede37729f404d490f1512e9eaf6de0cf715586
127
flutter_practice
MIT License
quickedit/src/main/java/com/abizer_r/quickedit/utils/textMode/FontUtils.kt
Abizer-R
776,104,244
false
{"Kotlin": 300120}
package com.abizer_r.quickedit.utils.textMode import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import com.abizer_r.quickedit.R import com.abizer_r.quickedit.ui.textMode.bottomToolbarExtension.fontFamilyOptions.FontItem object FontUtils { val eduVicwantFontFamily = FontFamily( Font(R.font.edu_vicwant_regular, FontWeight.Normal), Font(R.font.edu_vicwant_bold, FontWeight.Bold), ) val greyQoFontFamily = FontFamily( Font(R.font.grey_qo_regular, FontWeight.Normal), ) val matemasieFontFamily = FontFamily( Font(R.font.matemasie_regular, FontWeight.Bold), ) val moderusticFontFamily = FontFamily( Font(R.font.moderustic_regular, FontWeight.Normal), Font(R.font.moderustic_bold, FontWeight.Bold), ) val montserratFontFamily = FontFamily( Font(R.font.montserrat_regular, FontWeight.Normal), Font(R.font.montserrat_italic, FontWeight.Normal, FontStyle.Italic), Font(R.font.montserrat_bold, FontWeight.Bold), Font(R.font.montserrat_bold_italic, FontWeight.Bold, FontStyle.Italic), ) val newAmsterdamFontFamily = FontFamily( Font(R.font.new_amsterdam_regular, FontWeight.Bold), ) val oswaldFontFamily = FontFamily( Font(R.font.oswald_regular, FontWeight.Normal), Font(R.font.oswald_bold, FontWeight.Bold), ) val playwrightFontFamily = FontFamily( Font(R.font.playwrite_regular, FontWeight.Normal), Font(R.font.playwrite_italic, FontWeight.Normal, FontStyle.Italic), ) val poppinsFontFamily = FontFamily( Font(R.font.poppins_regular, FontWeight.Normal), Font(R.font.poppins_italic, FontWeight.Normal, FontStyle.Italic), Font(R.font.poppins_bold, FontWeight.Bold), Font(R.font.poppins_bold_italic, FontWeight.Bold, FontStyle.Italic), ) val robotoFontFamily = FontFamily( Font(R.font.roboto_regular, FontWeight.Normal), Font(R.font.roboto_italic, FontWeight.Normal, FontStyle.Italic), Font(R.font.roboto_bold, FontWeight.Bold), Font(R.font.roboto_bold_italic, FontWeight.Bold, FontStyle.Italic), ) val tekoFontFamily = FontFamily( Font(R.font.teko_regular, FontWeight.Normal), Font(R.font.teko_bold, FontWeight.Bold), ) val DefaultFontFamily = poppinsFontFamily fun getFontItems(): List<FontItem> { val fontSet = arrayListOf( DefaultFontFamily.getFontItem() ) fontSet.add(eduVicwantFontFamily.getFontItem()) fontSet.add(greyQoFontFamily.getFontItem()) fontSet.add(moderusticFontFamily.getFontItem()) fontSet.add(newAmsterdamFontFamily.getFontItem()) // bold doesn't work fontSet.add(oswaldFontFamily.getFontItem()) fontSet.add(matemasieFontFamily.getFontItem()) // bold doesn't work fontSet.add(playwrightFontFamily.getFontItem()) fontSet.add(poppinsFontFamily.getFontItem()) fontSet.add(robotoFontFamily.getFontItem()) fontSet.add(tekoFontFamily.getFontItem()) return fontSet.distinct() } private fun getLabel(fontFamily: FontFamily): String { return when (fontFamily) { eduVicwantFontFamily -> "EduVicwant" greyQoFontFamily -> "greyQo" moderusticFontFamily -> "moderustic" newAmsterdamFontFamily -> "newAmsterdam" oswaldFontFamily -> "oswald" matemasieFontFamily -> "matemasie" playwrightFontFamily -> "playwright" poppinsFontFamily -> "poppins" robotoFontFamily -> "roboto" tekoFontFamily -> "teko" else -> "unknown font" } } private fun FontFamily.getFontItem() = FontItem( fontFamily = this, label = getLabel(this) ) }
0
Kotlin
0
1
6f512d374c7abe379b8d3b5bca30342cc2922bc6
3,973
QuickEdit-Photo-Editor
Apache License 2.0
app/src/main/java/br/com/siecola/androidproject02/productdetail/ProductDetailViewModel.kt
siecola
246,328,556
false
null
package br.com.siecola.androidproject02.productdetail import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import br.com.siecola.androidproject02.network.Product import br.com.siecola.androidproject02.network.SalesApi import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch private const val TAG = "ProductDetailViewModel" class ProductDetailViewModel(private val code: String): ViewModel() { private var viewModelJob = Job() private val coroutineScope = CoroutineScope(viewModelJob + Dispatchers.Main) private val _product = MutableLiveData<Product>() val product: LiveData<Product> get() = _product init { getProduct() } private fun getProduct() { Log.i(TAG, "Preparing to request a product by its code") coroutineScope.launch { var getProductDeferred = SalesApi.retrofitService.getProductByCode(code) try { Log.i(TAG, "Loading product by its code") var productByCode = getProductDeferred.await() Log.i(TAG, "Name of the product ${productByCode.name}") _product.value = productByCode } catch (e: Exception) { Log.i(TAG, "Error: ${e.message}") } } Log.i(TAG, "Product requested by code") } override fun onCleared() { super.onCleared() viewModelJob.cancel() } }
0
Kotlin
0
0
57fc03a1b0a49359132ce63abb4ea8fa59124230
1,574
android_project02
MIT License
app/src/main/java/com/shubhans/socialclone/feature_profile/domain/util/ProfileConstants.kt
shubhanshu24510
740,657,467
false
{"Kotlin": 334993}
package com.shubhans.socialclone.feature_profile.domain.util object ProfileConstants { const val MAX_SELECTED_SKILL_COUNT = 3 val GITHUB_PROFILE_REGEX = "(https://)?(www\\.)?github\\.com/[A-z0-9_-]+/?".toRegex() val INSTAGRAM_PROFILE_REGEX = "(https?://)?(www\\.)?instagram\\.com/[a-z_\\-A-Z0-9]*".toRegex() val LINKED_IN_PROFILE_REGEX = "http(s)?://([\\w]+\\.)?linkedin\\.com/in/[A-z0-9_-]+/?".toRegex() const val SEARCH_DELAY = 700L }
0
Kotlin
0
1
a8741f1fd3a8d72ac9aed612ab4e81b7235df134
460
SocialClone
Apache License 2.0
bot/connector-google-chat/src/main/kotlin/builder/GoogleChatCardMessageBuilders.kt
theopenconversationkit
84,538,053
false
{"Kotlin": 6173880, "TypeScript": 1286450, "HTML": 532576, "Python": 376720, "SCSS": 79512, "CSS": 66318, "Shell": 12085, "JavaScript": 1849}
/* * Copyright (C) 2017/2021 e-voyageurs technologies * * 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 ai.tock.bot.connector.googlechat.builder import ai.tock.bot.connector.googlechat.GoogleChatConnectorCardMessageOut import ai.tock.bot.connector.googlechat.builder.ChatImageStyle.IMAGE import ai.tock.bot.definition.Intent import ai.tock.bot.definition.Parameters import ai.tock.bot.engine.I18nTranslator import com.google.api.services.chat.v1.model.ActionParameter import com.google.api.services.chat.v1.model.Button import com.google.api.services.chat.v1.model.Card import com.google.api.services.chat.v1.model.CardHeader import com.google.api.services.chat.v1.model.FormAction import com.google.api.services.chat.v1.model.Image import com.google.api.services.chat.v1.model.ImageButton import com.google.api.services.chat.v1.model.KeyValue import com.google.api.services.chat.v1.model.Message import com.google.api.services.chat.v1.model.OnClick import com.google.api.services.chat.v1.model.OpenLink import com.google.api.services.chat.v1.model.Section import com.google.api.services.chat.v1.model.TextButton import com.google.api.services.chat.v1.model.TextParagraph import com.google.api.services.chat.v1.model.WidgetMarkup internal const val GOOGLE_CHAT_ACTION_SEND_SENTENCE = "SEND_SENTENCE" internal const val GOOGLE_CHAT_ACTION_SEND_CHOICE = "SEND_CHOICE" internal const val GOOGLE_CHAT_ACTION_TEXT_PARAMETER = "TEXT" internal const val GOOGLE_CHAT_ACTION_INTENT_PARAMETER = "INTENT" @DslMarker annotation class CardElementMarker @CardElementMarker abstract class ChatCardElement(val i18nTranslator: I18nTranslator) : I18nTranslator by i18nTranslator { val children: MutableList<ChatCardElement> = arrayListOf() protected fun <T : ChatCardElement> initElement(element: T, init: T.() -> Unit): T { element.init() children.add(element) return element } fun hasChatButtons(): Boolean = children.any { it is ChatButtons } } fun I18nTranslator.card(init: ChatCard.() -> Unit): GoogleChatConnectorCardMessageOut { val card = ChatCard(this) card.init() return GoogleChatConnectorCardMessageOut(card) } class ChatCard(i18nTranslator: I18nTranslator) : ChatCardElement(i18nTranslator) { fun header( title: CharSequence, subtitle: CharSequence? = null, imageUrl: String? = null, imageStyle: ChatImageStyle = IMAGE ) = initElement( ChatHeader( translate(title), subtitle?.let { translate(it) }, imageUrl, imageStyle, i18nTranslator ), {} ) fun section(header: CharSequence? = null, init: ChatSection.() -> Unit) = initElement( ChatSection( header?.let { translate(it) }, i18nTranslator ), init ) } enum class ChatImageStyle { IMAGE, AVATAR } class ChatHeader( val title: CharSequence, val subtitle: CharSequence?, val imageUrl: String?, val imageStyle: ChatImageStyle, i18nTranslator: I18nTranslator ) : ChatCardElement(i18nTranslator) class ChatSection(val header: CharSequence?, i18nTranslator: I18nTranslator) : ChatCardElement(i18nTranslator) { fun textParagraph(text: CharSequence) = initElement(ChatTextParagraph(translate(text), i18nTranslator), { }) fun keyValue( topLabel: CharSequence? = null, content: CharSequence, bottomLabel: CharSequence? = null, action: (ChatButton.() -> Unit)? = null, contentMultiline: Boolean = false, iconUrl: String? = null, icon: ChatIcon? = null ) = initElement( ChatKeyValue( topLabel?.let { translate(it) }, translate(content), bottomLabel?.let { translate(it) }, action?.let { val button = ChatButton.ChatTextButton("", i18nTranslator) button.action() button.buttonAction }, contentMultiline, iconUrl, icon, i18nTranslator ), { } ) fun image(imageUrl: String, init: ChatButton.ChatIconExternalButton.() -> Unit = {}) = initElement( ChatImage( initElement(ChatButton.ChatIconExternalButton(imageUrl, i18nTranslator), init), i18nTranslator ), {} ) fun buttons(init: ChatButtons.() -> Unit) = initElement(ChatButtons(i18nTranslator), init) } sealed class ChatWidget(i18nTranslator: I18nTranslator) : ChatCardElement(i18nTranslator) class ChatTextParagraph(val text: CharSequence, i18nTranslator: I18nTranslator) : ChatWidget(i18nTranslator) class ChatKeyValue( val topLabel: CharSequence?, val content: CharSequence, val bottomLabel: CharSequence?, val action: ChatButtonAction?, val contentMultiline: Boolean, val iconUrl: String?, val icon: ChatIcon?, i18nTranslator: I18nTranslator ) : ChatButtons(i18nTranslator) class ChatImage(val imageButton: ChatButton.ChatIconExternalButton, i18nTranslator: I18nTranslator) : ChatWidget(i18nTranslator) open class ChatButtons(i18nTranslator: I18nTranslator) : ChatWidget(i18nTranslator) { fun textButton(text: CharSequence, init: ChatButton.() -> Unit) = initElement( ChatButton.ChatTextButton( translate(text), i18nTranslator ), init ) fun nlpTextButton(text: CharSequence) = textButton(text) { nlpAction(text) } fun iconButton(iconUrl: String, init: ChatButton.() -> Unit) = initElement(ChatButton.ChatIconExternalButton(iconUrl, i18nTranslator), init) fun iconButton(icon: ChatIcon, init: ChatButton.() -> Unit) = initElement(ChatButton.ChatIconEmbeddedButton(icon, i18nTranslator), init) } enum class ChatIcon { AIRPLANE, BOOKMARK, BUS, CAR, CLOCK, CONFIRMATION_NUMBER_ICON, DESCRIPTION, DOLLAR, EMAIL, EVENT_SEAT, FLIGHT_ARRIVAL, FLIGHT_DEPARTURE, HOTEL, HOTEL_ROOM_TYPE, INVITE, MAP_PIN, MEMBERSHIP, MULTIPLE_PEOPLE, PERSON, PHONE, RESTAURANT_ICON, SHOPPING_CART, STAR, STORE, TICKET, TRAIN, VIDEO_CAMERA, VIDEO_PLAY } sealed class ChatButton(i18nTranslator: I18nTranslator) : ChatCardElement(i18nTranslator) { lateinit var buttonAction: ChatButtonAction fun link(linkUrl: String) { buttonAction = ChatButtonAction.ChatLink(linkUrl) } fun action(action: String, parameters: Map<String, String> = emptyMap()) { buttonAction = ChatButtonAction.ChatAction(action, parameters) } fun nlpAction(text: CharSequence) = action(GOOGLE_CHAT_ACTION_SEND_SENTENCE, mapOf(GOOGLE_CHAT_ACTION_TEXT_PARAMETER to text.toString())) fun choiceAction(intent: Intent, parameters: Parameters = Parameters.EMPTY) = action( GOOGLE_CHAT_ACTION_SEND_CHOICE, mapOf(GOOGLE_CHAT_ACTION_INTENT_PARAMETER to intent.name) + parameters.toMap() ) class ChatTextButton(val text: CharSequence, i18nTranslator: I18nTranslator) : ChatButton(i18nTranslator) class ChatIconExternalButton(val iconUrl: String, i18nTranslator: I18nTranslator) : ChatButton(i18nTranslator) class ChatIconEmbeddedButton( val icon: ChatIcon, i18nTranslator: I18nTranslator ) : ChatButton(i18nTranslator) } sealed class ChatButtonAction { class ChatLink(val link: String) : ChatButtonAction() class ChatAction(val action: String, val parameters: Map<String, String>) : ChatButtonAction() } fun ChatCard.toCardMessage(): Message = Message().setCards( mutableListOf( Card() .setHeader(children.mapNotNull { it as? ChatHeader }.firstOrNull()?.toCardHeader()) .setSections(children.mapNotNull { it as? ChatSection }.map { it.toSection() }) ) ) private fun ChatHeader.toCardHeader() = CardHeader().setTitle(title.toString()).setSubtitle(subtitle?.toString()).setImageUrl(imageUrl) .setImageStyle(imageStyle.name) private fun ChatSection.toSection(): Section { return Section().setHeader(header?.toString()) .setWidgets(children.mapNotNull { it as? ChatWidget }.map { it.toWidget() }) } private fun ChatWidget.toWidget(): WidgetMarkup { return when (this) { is ChatTextParagraph -> WidgetMarkup().setTextParagraph(TextParagraph().setText(text.toString())) is ChatImage -> WidgetMarkup().setImage( Image().setImageUrl(imageButton.iconUrl).setOnClick(imageButton.buttonAction.toOnClick()) ) is ChatKeyValue -> WidgetMarkup().setKeyValue( KeyValue() .setTopLabel(topLabel?.toString()) .setContent(content.toString()) .setBottomLabel(bottomLabel?.toString()) .setOnClick(action?.toOnClick()) .setContentMultiline(contentMultiline) .setIconUrl(iconUrl) .setIcon(icon?.name) .setButton(children.mapNotNull { it as? ChatButton }.lastOrNull()?.toButton()) ) is ChatButtons -> WidgetMarkup().setButtons(children.mapNotNull { it as? ChatButton }.map { it.toButton() }) } } private fun ChatButton.toButton(): Button = when (this) { is ChatButton.ChatTextButton -> Button().setTextButton( TextButton().setText(text.toString()).setOnClick(buttonAction.toOnClick()) ) is ChatButton.ChatIconExternalButton -> Button().setImageButton( ImageButton().setIconUrl(iconUrl).setOnClick(buttonAction.toOnClick()) ) is ChatButton.ChatIconEmbeddedButton -> Button().setImageButton( ImageButton().setIcon(icon.name).setOnClick(buttonAction.toOnClick()) ) } private fun ChatButtonAction.toOnClick(): OnClick = when (this) { is ChatButtonAction.ChatLink -> OnClick().setOpenLink(OpenLink().setUrl(link)) is ChatButtonAction.ChatAction -> OnClick().setAction( FormAction().setActionMethodName(action) .setParameters(parameters.map { ActionParameter().setKey(it.key).setValue(it.value) }) ) }
163
Kotlin
127
475
890f69960997ae9146747d082d808d92ee407fcb
10,732
tock
Apache License 2.0
core/src/main/java/com/example/core/factory/ViewModelFactory.kt
rakhmukova
716,540,491
false
{"Kotlin": 364537}
package com.example.core.factory import androidx.compose.runtime.Composable import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import javax.inject.Inject import javax.inject.Provider class ViewModelFactory @Inject constructor( private val viewModelProviders: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>> ): ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return viewModelProviders[modelClass]?.get() as T } } @Composable inline fun <reified T : ViewModel> daggerViewModel( key: String? = null, crossinline viewModelInstanceCreator: () -> T ): T = androidx.lifecycle.viewmodel.compose.viewModel( modelClass = T::class.java, key = key, factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return viewModelInstanceCreator() as T } } )
0
Kotlin
0
0
7707ae1fac0dcbf98b79596cda5f5308f5e908ab
997
travel-app
Apache License 2.0
proj.android_studio/ee-x-core/src/main/java/com/ee/core/PluginManager.kt
centy
272,264,438
true
{"C++": 1146733, "Java": 813842, "Objective-C": 228466, "Kotlin": 41975, "Ruby": 25824, "Swift": 22742, "Makefile": 18306, "CMake": 11757, "Objective-C++": 9149, "Shell": 6499, "GLSL": 1123, "HTML": 398}
package com.ee.core import android.app.Activity import android.app.Application import android.app.Application.ActivityLifecycleCallbacks import android.content.Context import android.content.Intent import android.os.Bundle import com.ee.core.internal.Utils.deregisterHandlers import com.ee.core.internal.Utils.registerHandlers import com.google.common.truth.Truth.assertThat import kotlinx.serialization.ImplicitReflectionSerializer import kotlinx.serialization.UnstableDefault import java.lang.reflect.InvocationTargetException /** * Created by Zinge on 6/5/16. */ class PluginManager private constructor() { companion object { private val _logger = Logger(PluginManager::class.java.name) private val _sharedInstance = PluginManager() @JvmStatic fun getInstance(): PluginManager { return _sharedInstance } } private interface PluginExecutor { fun execute(plugin: IPlugin) } private val _bridge: IMessageBridge = MessageBridge.getInstance() private val _plugins: MutableMap<String, IPlugin> private val _classes: MutableMap<String, String> private val _lifecycleCallbacks: ActivityLifecycleCallbacks private var _context: Context? = null private var _activity: Activity? = null private var _activityClassName: String? = null init { _plugins = HashMap() _classes = HashMap() _classes["AdMob"] = "com.ee.admob.AdMob" _classes["AppLovin"] = "com.ee.applovin.AppLovin" _classes["AppsFlyer"] = "com.ee.appsflyer.AppsFlyer" _classes["CampaignReceiver"] = "com.ee.campaignreceiver.CampaignReceiver" _classes["Facebook"] = "com.ee.facebook.Facebook" _classes["FacebookAds"] = "com.ee.facebook.FacebookAds" _classes["FirebaseCore"] = "com.ee.firebase.core.FirebaseCore" _classes["FirebaseCrashlytics"] = "com.ee.firebase.crashlytics.FirebaseCrashlytics" _classes["FirebasePerformance"] = "com.ee.firebase.performance.FirebasePerformance" _classes["GoogleAnalytics"] = "com.ee.google.analytics.GoogleAnalytics" _classes["IronSource"] = "com.ee.ironsource.IronSource" _classes["Notification"] = "com.ee.notification.Notification" _classes["Play"] = "com.ee.play.Play" _classes["Recorder"] = "com.ee.recorder.Recorder" _classes["Store"] = "com.ee.store.Store" _classes["Tenjin"] = "com.ee.tenjin.Tenjin" _classes["UnityAds"] = "com.ee.unityads.UnityAds" _classes["Vungle"] = "com.ee.vungle.Vungle" _lifecycleCallbacks = object : ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { if (activity.javaClass.name == _activityClassName) { if (_activity == null) { if (activity.isTaskRoot) { _activity = activity executePlugins(object : PluginExecutor { override fun execute(plugin: IPlugin) { plugin.onCreate(activity) } }) } else { _logger.warn("onActivityCreated: is not root activity") } } else { _logger.warn("onActivityCreated: invalid activity") } } } override fun onActivityStarted(activity: Activity) { if (activity.javaClass.name == _activityClassName) { if (_activity === activity) { executePlugins(object : PluginExecutor { override fun execute(plugin: IPlugin) { plugin.onStart() } }) } else { _logger.warn("onActivityStarted: invalid activity") } } } override fun onActivityResumed(activity: Activity) { if (activity.javaClass.name == _activityClassName) { if (_activity === activity) { executePlugins(object : PluginExecutor { override fun execute(plugin: IPlugin) { plugin.onResume() } }) } else { _logger.warn("onActivityResumed: invalid activity") } } } override fun onActivityPaused(activity: Activity) { if (activity.javaClass.name === _activityClassName) { if (_activity === activity) { executePlugins(object : PluginExecutor { override fun execute(plugin: IPlugin) { plugin.onPause() } }) } else { _logger.warn("onActivityPaused: invalid activity") } } } override fun onActivityStopped(activity: Activity) { if (activity.javaClass.name == _activityClassName) { if (_activity === activity) { executePlugins(object : PluginExecutor { override fun execute(plugin: IPlugin) { plugin.onStart() } }) } else { _logger.warn("onActivityStopped: invalid activity") } } } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { } override fun onActivityDestroyed(activity: Activity) { if (activity.javaClass.name == _activityClassName) { if (_activity === activity) { _activity = null executePlugins(object : PluginExecutor { override fun execute(plugin: IPlugin) { plugin.onDestroy() } }) } else { _logger.warn("onActivityDestroyed: invalid activity") } } } } } fun getContext(): Context? { return _context } fun getActivity(): Activity? { return _activity } @ImplicitReflectionSerializer @UnstableDefault fun initializePlugins(context: Context) { _context = context // Register lifecycle callbacks. if (context is Application) { context.registerActivityLifecycleCallbacks(_lifecycleCallbacks) } else { assertThat(true).isFalse() } // Find main activity. val packageName = context.packageName val launchIntent = context.packageManager.getLaunchIntentForPackage(packageName) _activityClassName = launchIntent!!.component!!.className assertThat(_activityClassName).isNotNull() registerHandlers(_bridge, context) } fun addPlugin(name: String) { _logger.info("addPlugin: $name") if (_plugins.containsKey(name)) { _logger.error("addPlugin: $name already exists!") return } if (!_classes.containsKey(name)) { _logger.error("addPlugin: $name classes doesn't exist!") return } val className = _classes[name] as String try { val clazz = Class.forName(className) val constructor = clazz.getConstructor(Context::class.java, IMessageBridge::class.java) val plugin = constructor.newInstance(_context, _bridge) _plugins[name] = plugin as IPlugin } catch (ex: ClassNotFoundException) { ex.printStackTrace() } catch (ex: NoSuchMethodException) { ex.printStackTrace() } catch (ex: IllegalAccessException) { ex.printStackTrace() } catch (ex: InstantiationException) { ex.printStackTrace() } catch (ex: InvocationTargetException) { ex.printStackTrace() } } fun removePlugin(pluginName: String) { _logger.info("removePlugin: $pluginName") if (!_plugins.containsKey(pluginName)) { _logger.error("removePlugin: $pluginName doesn't exist!") return } _plugins.remove(pluginName) } fun getPlugin(pluginName: String): IPlugin? { return _plugins[pluginName] } fun destroy() { deregisterHandlers(_bridge) for (entry in _plugins) { entry.value.destroy() } _context = null } /// FIXME: to be removed (used in Recorder plugin). fun onActivityResult(requestCode: Int, responseCode: Int, data: Intent?): Boolean { var result = false for (entry in _plugins) { result = result || entry.value.onActivityResult(requestCode, responseCode, data) } return result } private fun executePlugins(executor: PluginExecutor) { for (entry in _plugins) { executor.execute(entry.value) } } }
0
null
0
0
3ad312378fa600f2801a2031e17b3af6eea0b76a
9,635
ee-x
MIT License
app/src/main/kotlin/io/github/nuhkoca/libbra/di/factory/LibbraFragmentFactory.kt
nuhkoca
252,193,036
false
null
/* * Copyright (C) 2020. <NAME>. 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 io.github.nuhkoca.vivy.di.factory import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import dagger.Binds import dagger.MapKey import dagger.Module import javax.inject.Inject import javax.inject.Provider import kotlin.annotation.AnnotationRetention.RUNTIME import kotlin.annotation.AnnotationTarget.FUNCTION import kotlin.annotation.AnnotationTarget.PROPERTY_GETTER import kotlin.annotation.AnnotationTarget.PROPERTY_SETTER import kotlin.reflect.KClass /** * FragmentFactory which uses Dagger to create the instances. */ @Suppress("TooGenericExceptionCaught", "TooGenericExceptionThrown") class VivyFragmentFactory @Inject constructor( private val creators: Map<Class<out Fragment>, @JvmSuppressWildcards Provider<Fragment>> ) : FragmentFactory() { override fun instantiate(classLoader: ClassLoader, className: String): Fragment { val fragmentClass = loadFragmentClass(classLoader, className) val creator = creators[fragmentClass] ?: return super.instantiate(classLoader, className) return try { creator.get() } catch (e: RuntimeException) { throw RuntimeException(e) } } } @Module internal abstract class FragmentBindingsModule { @Binds internal abstract fun bindFragmentFactory( fragmentFactory: VivyFragmentFactory ): FragmentFactory } @MapKey @Retention(RUNTIME) @Target(FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER) internal annotation class FragmentKey(val value: KClass<out Fragment>)
1
null
3
54
ffc089cba24281a3a8a8a1991bea6d4222456a79
2,152
libbra
Apache License 2.0
core/reflection.jvm/src/kotlin/reflect/full/KTypes.kt
JakeWharton
99,388,807
true
null
/* * 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. */ @file:JvmName("KTypes") package kotlin.reflect import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.isFlexible import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import kotlin.reflect.jvm.internal.KTypeImpl /** * Returns a new type with the same classifier, arguments and annotations as the given type, and with the given nullability. */ @SinceKotlin("1.1") fun KType.withNullability(nullable: Boolean): KType { if (isMarkedNullable) { return if (nullable) this else KTypeImpl(TypeUtils.makeNotNullable((this as KTypeImpl).type)) { javaType } } // If the type is not marked nullable, it's either a non-null type or a platform type. val kotlinType = (this as KTypeImpl).type if (kotlinType.isFlexible()) return KTypeImpl(TypeUtils.makeNullableAsSpecified(kotlinType, nullable)) { javaType } return if (!nullable) this else KTypeImpl(TypeUtils.makeNullable(kotlinType)) { javaType } } /** * Returns `true` if `this` type is the same or is a subtype of [other], `false` otherwise. */ @SinceKotlin("1.1") fun KType.isSubtypeOf(other: KType): Boolean { return (this as KTypeImpl).type.isSubtypeOf((other as KTypeImpl).type) } /** * Returns `true` if `this` type is the same or is a supertype of [other], `false` otherwise. */ @SinceKotlin("1.1") fun KType.isSupertypeOf(other: KType): Boolean { return other.isSubtypeOf(this) }
181
Kotlin
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
2,007
kotlin
Apache License 2.0
jetbrains-core-gui/tst/software/aws/toolkits/jetbrains/fixtures/WelcomeFrameUtils.kt
tbtmuse
224,356,807
false
null
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.fixtures import com.intellij.openapi.util.SystemInfo import com.intellij.testGuiFramework.fixtures.WelcomeFrameFixture import com.intellij.testGuiFramework.impl.actionLink import com.intellij.testGuiFramework.impl.popupMenu fun WelcomeFrameFixture.openSettingsDialog() { actionLink("Configure").click() val prefName = if (SystemInfo.isMac) "Preferences" else "Settings" popupMenu(prefName).clickSearchedItem() }
1
null
1
1
76335cf0b23eda6c24b624409cbd135cfbcc31b8
581
jsinbucket
Apache License 2.0
app/src/main/kotlin/de/developercity/arcanosradio/features/appstate/domain/usecase/AddSideEffect.kt
fibelatti
156,989,942
false
null
package de.developercity.arcanosradio.features.appstate.domain.usecase import de.developercity.arcanosradio.features.appstate.domain.AppState import de.developercity.arcanosradio.features.appstate.domain.AppStateRepository import io.reactivex.Observer import javax.inject.Inject class AddSideEffect @Inject constructor( private val appStateRepository: AppStateRepository ) { operator fun invoke(observer: Observer<AppState>) { appStateRepository.addSideEffect(observer) } }
0
Kotlin
1
1
b594c10821ce08117f04c2811dbe8e900cbd0d6f
497
arcanos-radio-kotlin
MIT License
app/src/main/kotlin/de/developercity/arcanosradio/features/appstate/domain/usecase/AddSideEffect.kt
fibelatti
156,989,942
false
null
package de.developercity.arcanosradio.features.appstate.domain.usecase import de.developercity.arcanosradio.features.appstate.domain.AppState import de.developercity.arcanosradio.features.appstate.domain.AppStateRepository import io.reactivex.Observer import javax.inject.Inject class AddSideEffect @Inject constructor( private val appStateRepository: AppStateRepository ) { operator fun invoke(observer: Observer<AppState>) { appStateRepository.addSideEffect(observer) } }
0
Kotlin
1
1
b594c10821ce08117f04c2811dbe8e900cbd0d6f
497
arcanos-radio-kotlin
MIT License
applvsdklib/src/main/java/com/applivery/applvsdklib/domain/model/DownloadToken.kt
friederbluemle
219,840,236
true
{"Java": 267624, "Kotlin": 85024}
/* * Copyright (c) 2019 Applivery * * 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.applivery.applvsdklib.domain.model data class DownloadToken( val downloadToken: String, val buildId: String, val expiresAt: String ) : BusinessObject<DownloadToken> { override fun getObject(): DownloadToken { return this } }
0
null
0
0
47f6434f484ff0eb6764729b29736d79afb46bc1
846
applivery-android-sdk
Apache License 2.0
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/hints/AbstractKotlinReferenceTypeHintsProviderTest.kt
ingokegel
72,937,917
true
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.hints import com.intellij.codeInsight.hints.presentation.PresentationFactory import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.refactoring.suggested.startOffset import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.utils.inlays.InlayHintsProviderTestCase import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.test.runAll import java.io.File abstract class AbstractKotlinReferenceTypeHintsProviderTest : InlayHintsProviderTestCase() { // Abstract- prefix is just a convention for GenerateTests override fun setUp() { super.setUp() PresentationFactory.customToStringProvider = { element -> val virtualFile = element.containingFile.virtualFile val jarFileSystem = virtualFile.fileSystem as? JarFileSystem val path = jarFileSystem?.let { val root = VfsUtilCore.getRootFile(virtualFile) "${it.protocol}://${root.name}${JarFileSystem.JAR_SEPARATOR}${VfsUtilCore.getRelativeLocation(virtualFile, root)}" } ?: virtualFile.toString() "$path:${if (jarFileSystem != null) "*" else element.startOffset.toString()}" } } override fun tearDown() { runAll( ThrowableRunnable { PresentationFactory.customToStringProvider = null }, ThrowableRunnable { super.tearDown() }, ) } override fun getProjectDescriptor(): LightProjectDescriptor { return KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance() } fun doTest(testPath: String) { // named according to the convention imposed by GenerateTests assertThatActualHintsMatch(testPath) } private fun assertThatActualHintsMatch(fileName: String) { with(KotlinReferencesTypeHintsProvider()) { val fileContents = FileUtil.loadFile(File(fileName), true) val settings = createSettings() with(settings) { when (InTextDirectivesUtils.findStringWithPrefixes(fileContents, "// MODE: ")) { "function_return" -> set(functionReturn = true) "local_variable" -> set(localVariable = true) "parameter" -> set(parameter = true) "property" -> set(property = true) "all" -> set(functionReturn = true, localVariable = true, parameter = true, property = true) else -> set() } } doTestProvider("KotlinReferencesTypeHintsProvider.kt", fileContents, this, settings) } } private fun KotlinReferencesTypeHintsProvider.Settings.set( functionReturn: Boolean = false, localVariable: Boolean = false, parameter: Boolean = false, property: Boolean = false ) { this.functionReturnType = functionReturn this.localVariableType = localVariable this.parameterType = parameter this.propertyType = property } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,394
intellij-community
Apache License 2.0
app/src/main/java/p2pdops/dopsender/zshare_helpers/A2AConnMessagesAdapter.kt
p2pdops
278,171,882
false
{"Gradle": 3, "SVG": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 6, "Proguard": 1, "Kotlin": 73, "XML": 113, "Java": 4}
package p2pdops.dopsender.zshare_helpers import android.app.Activity import android.app.AlertDialog import android.content.Intent import android.content.pm.PackageManager import android.graphics.PorterDuff import android.graphics.Typeface import android.net.Uri import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.content.res.AppCompatResources.getColorStateList import androidx.appcompat.content.res.AppCompatResources.getDrawable import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.core.view.updatePadding import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.item_wconn_receive_file.view.* import kotlinx.android.synthetic.main.item_wconn_send_file.view.* import p2pdops.dopsender.BuildConfig import p2pdops.dopsender.R import p2pdops.dopsender.modals.* import p2pdops.dopsender.utils.ApkInstaller import p2pdops.dopsender.utils.docsColormap import p2pdops.dopsender.utils.dpToPx import p2pdops.dopsender.utils.humanizeBytes import java.io.File open class BaseConnHolder(itemView: View) : RecyclerView.ViewHolder(itemView) class ConnSendHolder(itemView: View) : BaseConnHolder(itemView) { fun setItem(item: ConnSendFileItem) { val itemFile = File(item.filePath) when (item.fileType) { FileType.Compressed -> { itemView.sendFileIcon.setColorFilter( getColorStateList( itemView.context, R.color.c_com ).defaultColor, PorterDuff.Mode.SRC_IN ) itemView.sendFileIcon.setImageDrawable( getDrawable( itemView.context, R.drawable.ic_compressed ) ) } FileType.Documents -> { ContextCompat.getColor( itemView.context!!, docsColormap.getOrElse(itemFile.extension) { R.color.color_pdf }) .apply { itemView.sendFileIcon.setColorFilter(this, PorterDuff.Mode.SRC_IN) itemView.sendFileIcon.setImageDrawable( getDrawable( itemView.context, R.drawable.ic_doc_file ) ) } } FileType.Audios -> { itemView.sendFileIcon.setColorFilter( getColorStateList( itemView.context, R.color.c_aud ).defaultColor, PorterDuff.Mode.SRC_IN ) itemView.sendFileIcon.setImageDrawable( getDrawable( itemView.context, R.drawable.ic_audio_outline ) ) } FileType.Images -> { Glide.with(itemView).load(item.filePath).thumbnail(0.5f).centerCrop() .error(R.drawable.ic_images).into(itemView.sendFileIcon) } FileType.Videos -> Glide.with(itemView) .load(item.filePath).thumbnail(0.2f).centerCrop() .error(R.drawable.ic_images).into(itemView.sendFileIcon) FileType.Apps -> { val pm = itemView.context.packageManager pm?.getPackageArchiveInfo( item.filePath, PackageManager.GET_META_DATA )?.let { it.applicationInfo.sourceDir = item.filePath it.applicationInfo.publicSourceDir = item.filePath Log.d("ConnReceiveHolder", "appInfo: ${it.applicationInfo}") Glide .with(itemView) .load(it.applicationInfo.loadIcon(pm)) .error(R.drawable.ic_apk) .thumbnail(0.2f) .centerCrop() .into(itemView.sendFileIcon) } } } itemView.sendFileName.text = item.fileName itemView.sendFileName.isSelected = true itemView.sendFileType.text = item.fileType.name itemView.sendFileSize.text = humanizeBytes(itemFile.length()) itemView.sendFileStatus.text = when (item.status) { ConnFileStatusTypes.WAITING -> "In queue" ConnFileStatusTypes.LOADING -> { itemView.sendFileStatus.setTypeface( itemView.sendFileStatus.typeface, Typeface.BOLD_ITALIC ) "Sending" } ConnFileStatusTypes.LOADED -> "Sent" } } } class ConnReceiveHolder(itemView: View) : BaseConnHolder(itemView) { fun setItem(item: ConnReceiveFileItem) { val itemFile = File(item.filePath) when (item.fileType) { FileType.Compressed -> { itemView.receiveFileIcon.setColorFilter( getColorStateList( itemView.context, R.color.c_com ).defaultColor, PorterDuff.Mode.SRC_IN ) itemView.receiveFileIcon.setImageDrawable( getDrawable( itemView.context, R.drawable.ic_compressed ) ) } FileType.Documents -> { ContextCompat.getColor( itemView.context!!, docsColormap.getOrElse(itemFile.extension) { R.color.color_pdf }) .apply { itemView.receiveFileIcon.setColorFilter(this, PorterDuff.Mode.SRC_IN) itemView.receiveFileIcon.setImageDrawable( getDrawable( itemView.context, R.drawable.ic_doc_file ) ) } } FileType.Audios -> { itemView.receiveFileIcon.setColorFilter( getColorStateList( itemView.context, R.color.c_aud ).defaultColor, PorterDuff.Mode.SRC_IN ) itemView.receiveFileIcon.setImageDrawable( getDrawable( itemView.context, R.drawable.ic_audio_outline ) ) } FileType.Images -> Glide.with(itemView) .load(item.filePath).thumbnail(0.2f).centerCrop() .error( ContextCompat.getDrawable(itemView.context, R.drawable.ic_images) ) .into(itemView.receiveFileIcon) FileType.Videos -> Glide.with(itemView) .load(item.filePath).thumbnail(0.2f).centerCrop().error( ContextCompat.getDrawable(itemView.context, R.drawable.ic_video) ) .into(itemView.receiveFileIcon) FileType.Apps -> { if (item.status == ConnFileStatusTypes.LOADED) { val pm = itemView.context.packageManager pm?.getPackageArchiveInfo( item.filePath, PackageManager.GET_META_DATA )?.let { it.applicationInfo.sourceDir = item.filePath it.applicationInfo.publicSourceDir = item.filePath Log.d("ConnReceiveHolder", "setItem: ${it.applicationInfo}") Glide .with(itemView) .load(it.applicationInfo.loadIcon(pm)) .error(R.drawable.ic_apk) .thumbnail(0.2f) .centerCrop() .into(itemView.receiveFileIcon) } } else Glide .with(itemView) .load(R.drawable.ic_apk) .thumbnail(0.2f) .centerCrop() .into(itemView.receiveFileIcon) } } itemView.receiveFileName.text = item.fileName itemView.receiveFileName.isSelected = true itemView.receiveFileType.text = item.fileType.name itemView.receiveFileSize.text = humanizeBytes(item.fileSize) itemView.receiveFileStatus.text = when (item.status) { ConnFileStatusTypes.WAITING -> "In queue" ConnFileStatusTypes.LOADING -> { itemView.receiveFileStatus.setTypeface( itemView.receiveFileStatus.typeface, Typeface.BOLD_ITALIC ) "Receiving" } ConnFileStatusTypes.LOADED -> "Received" } if (item.status == ConnFileStatusTypes.LOADED) { val context = itemView.context itemView.setOnClickListener { val alertDialog = AlertDialog.Builder(context).create() alertDialog.setTitle("Do you want to open ${item.fileName}?") alertDialog.setMessage("The on going activity may interrupt.") alertDialog.setButton( AlertDialog.BUTTON_POSITIVE, "No" ) { dialog, which -> dialog.dismiss() } alertDialog.setButton( AlertDialog.BUTTON_NEGATIVE, "Yes" ) { dialog, which -> val file = File(item.filePath) if (item.fileType == FileType.Apps) { ApkInstaller.installApplication(context, file) } else { val uri: Uri = FileProvider.getUriForFile( context, BuildConfig.APPLICATION_ID + ".provider", file ) val intent = Intent(Intent.ACTION_VIEW, uri) intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) context.startActivity(intent) } dialog.dismiss() } alertDialog.show() } } } } class ConnectionMessageAdapter( private val list: ArrayList<ConnectionItem>, private val activity: Activity ) : RecyclerView.Adapter<BaseConnHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseConnHolder { return when (viewType) { ConnectionMessageType.SEND_FILE.ordinal -> ConnSendHolder( LayoutInflater.from(activity) .inflate(R.layout.item_wconn_send_file, parent, false) ) ConnectionMessageType.RECEIVE_FILE.ordinal -> ConnReceiveHolder( LayoutInflater.from(activity) .inflate(R.layout.item_wconn_receive_file, parent, false) ) else -> BaseConnHolder(View(activity)) } } override fun getItemCount(): Int = list.size override fun onBindViewHolder(holder: BaseConnHolder, position: Int) { when (list[position].type) { ConnectionMessageType.SEND_FILE -> { (holder as ConnSendHolder).setItem(list[position] as ConnSendFileItem) if (position > 0 && (list[position - 1] is ConnReceiveFileItem)) { holder.itemView.updatePadding(top = dpToPx(20))//layoutParams = marginParams; } } ConnectionMessageType.RECEIVE_FILE -> { (holder as ConnReceiveHolder).setItem(list[position] as ConnReceiveFileItem) if (position > 0 && (list[position - 1] is ConnSendFileItem)) { holder.itemView.updatePadding(top = dpToPx(20))//layoutParams = marginParams; } } } } override fun getItemViewType(position: Int): Int = list[position].type.ordinal }
1
Kotlin
1
5
b95154746ee642b82634d71732cef27deccab7bc
12,473
DopsenderAndroid
MIT License
topartists/src/main/java/com/stylingandroid/muselee/topartists/view/TopArtistsViewHolder.kt
StylingAndroid
163,316,982
false
null
package com.stylingandroid.muselee.topartists.view import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade import com.stylingandroid.muselee.topartists.R class TopArtistsViewHolder( item: View, private val rankView: TextView = item.findViewById(R.id.rank), private val imageView: ImageView = item.findViewById(R.id.image), private val nameView: TextView = item.findViewById(R.id.name) ) : RecyclerView.ViewHolder(item) { fun bind(rank: String, artistName: String, artistImageUrl: String) { rankView.text = rank nameView.text = artistName Glide.with(imageView) .load(artistImageUrl) .transition(withCrossFade()) .into(imageView) } }
2
Kotlin
9
59
7d7e4096e16057e8667446d8a6a4a87c5742ed5d
921
Muselee
Apache License 2.0
android/src/com/android/tools/idea/res/ResourceUpdateTraceSettings.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.res import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.Service import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil /** Persistent settings for resource update tracing. */ @State(name = "ResourceTrace", storages = [Storage("resourceTrace.xml")]) @Service class ResourceUpdateTraceSettings : PersistentStateComponent<ResourceUpdateTraceSettings> { var enabled: Boolean = false override fun getState(): ResourceUpdateTraceSettings { return this } override fun loadState(state: ResourceUpdateTraceSettings) { XmlSerializerUtil.copyBean(state, this) } companion object { @JvmStatic fun getInstance(): ResourceUpdateTraceSettings { return ApplicationManager.getApplication().getService(ResourceUpdateTraceSettings::class.java) } } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,623
android
Apache License 2.0