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
app/src/main/java/com/task/flicky/adapter/TabsAdapter.kt
akhil0808
332,856,233
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 33, "XML": 21, "Java": 1}
package com.task.flicky.adapter import androidx.annotation.Nullable import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter class TabsAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) { private val mFragmentList = arrayListOf<Fragment>() private val mFragmentTitleList = arrayListOf<String>() override fun getItem(position: Int): Fragment { return mFragmentList[position] } fun addFragment(fragment: Fragment, title: String) { mFragmentList.add(fragment) mFragmentTitleList.add(title) } @Nullable override fun getPageTitle(position: Int): CharSequence? { return mFragmentTitleList[position] } override fun getCount(): Int { return mFragmentList.size } }
1
null
1
1
c1a319fc509263e1e9e1e05fc03af7d2e04d84da
836
FlickyTask
Apache License 2.0
components/filemngr/listing/impl/src/androidMain/kotlin/com/flipperdevices/filemanager/listing/impl/composable/NoListingFeatureComposable.kt
flipperdevices
288,258,832
false
{"Kotlin": 4167715, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.filemanager.listing.impl.composable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun NoListingFeatureComposable(modifier: Modifier = Modifier) { Box(modifier = modifier.fillMaxSize()) { // todo Text("Unsopported") } }
21
Kotlin
174
1,528
8f293e596741a6c97409acbc8de10c7ae6e8d8b0
455
Flipper-Android-App
MIT License
app/src/main/java/com/example/neoticket/view/main/concerts/SectorDialogFragment.kt
rybakova-auca-2021
747,738,666
false
{"Kotlin": 442862}
package com.example.neoticket.view.main.concerts import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.provider.ContactsContract.CommonDataKinds.Identity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.example.neoticket.R import com.example.neoticket.databinding.FragmentSectorDetailBinding import com.example.neoticket.viewModel.concerts.GetSectionDetailViewModel import com.example.neoticket.viewModel.sport.GetSportSectionDetailViewModel import com.example.neoticket.viewModel.theater.TheaterSectionDetailViewModel class SectorDialogFragment : DialogFragment() { private lateinit var binding: FragmentSectorDetailBinding private val viewModel: GetSectionDetailViewModel by viewModels() private val sportViewModel: GetSportSectionDetailViewModel by viewModels() private val theaterViewModel: TheaterSectionDetailViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentSectorDetailBinding.inflate(inflater, container, false) dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val title = arguments?.getString("title") val theaterId = arguments?.getInt("theaterId") val source = arguments?.getString("source") val id = arguments?.getInt("id") if (id != null && source != null) { when(source) { "SportSector" -> setSportData(id) "ConcertSector" -> setConcertData(id) "TheaterSector" -> theaterId?.let { setTheaterData(id, it) } } } } private fun setConcertData(id: Int) { viewModel.getSectionDetail(id) viewModel.sectionLiveData.observe(viewLifecycleOwner) { result -> if (result != null) { binding.sectorTitle.text = result.name binding.ticketPrice.text = result.seats[0].price binding.btnChooseTickets.setOnClickListener { val bundle = Bundle() bundle.putInt("id", result.id) bundle.putInt("showTimeId", result.show_times) findNavController().navigate(R.id.concertChooseTicketFragment, bundle) dismiss() } } } } private fun setSportData(id: Int) { sportViewModel.getSectionDetail(id) sportViewModel.sectionLiveData.observe(viewLifecycleOwner) { result -> if (result != null) { binding.sectorTitle.text = result.name binding.ticketPrice.text = result.sport_seats[0].price binding.btnChooseTickets.setOnClickListener { val bundle = Bundle() bundle.putInt("id", result.id) bundle.putInt("showTimeId", result.show_time) findNavController().navigate(R.id.sportChooseTicketFragment, bundle) dismiss() } } } } private fun setTheaterData(id: Int, theaterId: Int) { theaterViewModel.getSectionDetail(id) theaterViewModel.sectionLiveData.observe(viewLifecycleOwner) { result -> if (result != null) { binding.sectorTitle.text = result.name // binding.ticketPrice.text = result.seats[0].price binding.btnChooseTickets.setOnClickListener { val bundle = Bundle() bundle.putInt("id", result.id) bundle.putInt("theaterId", theaterId) bundle.putInt("showTimeId", result.show_time) findNavController().navigate(R.id.theaterChooseTicketsFragment, bundle) dismiss() } } } } }
0
Kotlin
0
0
7b7a198cc176704e613ee794176463935480b3aa
4,262
NeoTicket
MIT License
onebreath/src/main/kotlin/gabek/onebreath/prefab/test/JointTestPrefab.kt
gabe00122
77,073,648
false
null
package gabek.onebreath.prefab.test import com.badlogic.gdx.physics.box2d.BodyDef import com.github.salomonbrys.kodein.instance import gabek.engine.core.assets.Assets import gabek.engine.core.components.BodyCom import gabek.engine.core.components.common.SizeCom import gabek.engine.core.components.common.TranslationCom import gabek.engine.core.components.graphics.SpriteCom import gabek.engine.core.graphics.PixelRatio import gabek.engine.core.physics.shape.RPolygon import gabek.engine.core.prefab.Prefab /** * @author <NAME> * @date 6/4/2017 */ open class JointTestPrefab: Prefab(){ override fun define() { super.define() val assets: Assets = kodein.instance() val pixelToMeter = kodein.instance<PixelRatio>().pixelToMeters val sprite = assets.getTexture("actors:joint_test") val w = 32 * pixelToMeter val h = 16 * pixelToMeter add<TranslationCom>() add<BodyCom> { body.addFixture(RPolygon(w, h), 2.5f, 1f, 0.2f) body.bodyType = BodyDef.BodyType.DynamicBody } add<SpriteCom> { this.sprite = sprite } add<SizeCom> { width = w height = h } } }
0
Kotlin
0
0
6b76a69cca2baa43b743c7a30822cf4f532a67c6
1,226
GameEngine
MIT License
src/main/kotlin/com/br/app/consolidatedataproviderservice/ConsolidateDataProviderServiceApplication.kt
gustavoarruda
644,688,653
false
null
package com.br.app.consolidatedataproviderservice import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cache.annotation.EnableCaching @SpringBootApplication @EnableCaching class ConsolidateDataProviderServiceApplication fun main(args: Array<String>) { runApplication<ConsolidateDataProviderServiceApplication>(*args) }
0
Kotlin
0
0
7b39d350ce96f3f343d66909314d4119da680f49
412
consolidate-data-provider-service
MIT License
app/src/test/java/com/zhuker/ExampleUnitTest.kt
jpitman1010
321,416,047
true
{"Kotlin": 14499}
package com.zhuker import com.google.gson.Gson import com.google.gson.GsonBuilder import com.zhuker.Model.decode import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.sse.EventSource import okhttp3.sse.EventSourceListener import okhttp3.sse.EventSources import org.junit.Test import org.junit.Assert.* import java.io.File import java.lang.RuntimeException import java.lang.StringBuilder import java.net.Socket import java.util.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ fun ByteArray.drop4(limit: Int? = null): ByteArray = this.sliceArray(IntRange(4, (limit ?: this.size) - 1)) class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } fun base64(str: String): ByteArray = Base64.getEncoder().encode(str.toByteArray()) @Test fun parseGson() { val str = File("src/test/java/com/zhuker/status.json").readText() println(str) val status = Gson().fromJson(str, SwitchStatus::class.java)!! println(status) val str64 = Base64.getEncoder().encode("xx".toByteArray()).decodeToString() println(str64) val query = SwitchStatus(System(null)) val message = GsonBuilder().serializeNulls().create().toJson(query) println(message) println(base64(message).decodeToString()) println(base64("{ \"system\":{ \"get_sysinfo\":null } }").decodeToString()) //val sock = Socket("192.168.1.192", 9999) // sock.getOutputStream().write("") val readBytes = File("/home/zhukov/tmp/xxx").readBytes() val ss = decode(readBytes.drop4()) println(ss) Model.query().subscribe { ss: SwitchStatus -> println(ss) } Model.rxmsg(Base64.getDecoder().decode(Model.payload_on)).subscribe { bytes: ByteArray -> println(decode(bytes.drop4())) } // println(readBytes.map { (it.toInt() xor 171).toByte() } // .toByteArray().decodeToString()) } @Test fun gatesse() { val client = OkHttpClient() val events = Observable.create<GateEvent> { emitter -> val newEventSource = EventSources.createFactory(client) .newEventSource(Request.Builder().url("http://gate:80/events").build(), object : EventSourceListener() { override fun onOpen(eventSource: EventSource, response: Response) { super.onOpen(eventSource, response) println("onOpen") } override fun onClosed(eventSource: EventSource) { super.onClosed(eventSource) println("onClosed") emitter.onComplete() } override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) { super.onEvent(eventSource, id, type, data) println("onEvent '$id' '$type' '$data'") emitter.onNext(GateEvent(id, type, data)) } override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) { super.onFailure(eventSource, t, response) println("onFailure $t $response") emitter.onError(SSEException(t, response)) } }) emitter.setCancellable { newEventSource.cancel() } } events.blockingSubscribe { println(it) } } @Test fun example() { } }
0
Kotlin
0
0
ea0a14a7c7f32e8b1c62ccc80f5288140a9d9579
3,844
glekswitcher
Apache License 2.0
app/src/main/java/app/eluvio/wallet/network/converters/v2/SearchFilterConverter.kt
eluv-io
719,801,077
false
{"Kotlin": 814244, "Java": 29738}
package app.eluvio.wallet.network.converters.v2 import app.eluvio.wallet.data.entities.v2.PropertySearchFiltersEntity import app.eluvio.wallet.data.entities.v2.SearchFilterAttribute import app.eluvio.wallet.network.dto.v2.FilterOptionsDto import app.eluvio.wallet.network.dto.v2.GetFiltersResponse import app.eluvio.wallet.network.dto.v2.SearchFilterAttributeDto import app.eluvio.wallet.network.dto.v2.SearchFiltersDto import app.eluvio.wallet.util.realm.toRealmListOrEmpty import io.realm.kotlin.ext.toRealmDictionary fun GetFiltersResponse.toEntity(propId: String, baseUrl: String): PropertySearchFiltersEntity { val dto = this return PropertySearchFiltersEntity().apply { propertyId = propId tags = dto.tags.toRealmListOrEmpty() val attributeMap = dto.attributes.orEmpty() .mapValues { (_, attr) -> attr.toEntity() } attributes = attributeMap.toRealmDictionary() primaryFilter = primarySearchAttributeEntity( dto.primaryFilter, dto.secondaryFilter, dto.filterOptions, attributeMap, baseUrl ) } } fun SearchFiltersDto.toEntity(tagsAndAttributes: PropertySearchFiltersEntity, baseUrl: String): SearchFilterAttribute? { return primarySearchAttributeEntity( primaryFilter, secondaryFilter, filterOptions, tagsAndAttributes.attributes, baseUrl ) } private fun primarySearchAttributeEntity( primaryFilter: String?, secondaryFilter: String?, filterOptions: List<FilterOptionsDto>?, attributeMap: Map<String, SearchFilterAttribute?>, baseUrl: String ): SearchFilterAttribute? { val secondaryFilterFallback = attributeMap[secondaryFilter] return attributeMap[primaryFilter] ?.copy() ?.applyFilterOptions(filterOptions, secondaryFilterFallback, baseUrl) } private fun SearchFilterAttribute.applyFilterOptions( filterOptions: List<FilterOptionsDto>?, secondaryFilterFallback: SearchFilterAttribute?, baseUrl: String ) = apply { if (filterOptions.isNullOrEmpty()) { // Update nextFilter to global secondary filter values.forEach { it.nextFilterAttribute = secondaryFilterFallback?.id } } else { // Nuke any existing tags. If they don't exist in the filter options, they're don't matter. values = filterOptions.map { option -> SearchFilterAttribute.Value().apply { // Server sends empty string as an "all" filter options value = option.primaryFilterValue.takeIf { it.isNotEmpty() } ?: SearchFilterAttribute.Value.ALL nextFilterAttribute = option.secondaryFilterAttribute?.takeIf { it.isNotEmpty() } imageUrl = option.image?.toUrl(baseUrl) } }.toRealmListOrEmpty() } } private fun SearchFilterAttributeDto.toEntity(): SearchFilterAttribute { val dto = this return SearchFilterAttribute().apply { id = dto.id title = dto.title ?: "" values = dto.values ?.map { SearchFilterAttribute.Value.from(it) } .toRealmListOrEmpty() } }
8
Kotlin
1
0
3bd0cc96ff1d75f870d5ee94f3d3a6a5f491e243
3,180
elv-wallet-android
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/ScrewAlt.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.ScrewAlt: ImageVector get() { if (_screwAlt != null) { return _screwAlt!! } _screwAlt = Builder(name = "ScrewAlt", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(19.0f, 18.5f) curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f) reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) close() moveTo(9.0f, 6.914f) verticalLineToRelative(14.058f) lineToRelative(-3.0f, 3.0f) lineToRelative(-3.0f, -3.0f) lineTo(3.0f, 6.914f) lineTo(0.0f, 3.914f) lineTo(0.0f, 0.0f) horizontalLineToRelative(12.0f) verticalLineToRelative(3.914f) lineToRelative(-3.0f, 3.0f) close() moveTo(5.0f, 16.169f) lineToRelative(2.0f, -2.073f) verticalLineToRelative(-2.682f) lineToRelative(-2.0f, 2.0f) verticalLineToRelative(2.755f) close() moveTo(7.0f, 7.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(3.586f) lineToRelative(2.0f, -2.0f) verticalLineToRelative(-1.586f) close() moveTo(2.0f, 3.086f) lineToRelative(1.914f, 1.914f) horizontalLineToRelative(4.172f) lineToRelative(1.914f, -1.914f) verticalLineToRelative(-1.086f) lineTo(2.0f, 2.0f) verticalLineToRelative(1.086f) close() moveTo(7.0f, 20.144f) verticalLineToRelative(-3.167f) lineToRelative(-2.0f, 2.073f) verticalLineToRelative(1.094f) lineToRelative(1.0f, 1.0f) lineToRelative(1.0f, -1.0f) close() moveTo(23.842f, 18.5f) lineToRelative(-3.175f, 5.5f) horizontalLineToRelative(-6.351f) lineToRelative(-3.175f, -5.5f) lineToRelative(3.175f, -5.5f) horizontalLineToRelative(6.351f) lineToRelative(3.175f, 5.5f) close() moveTo(21.533f, 18.5f) lineToRelative(-2.021f, -3.5f) horizontalLineToRelative(-4.042f) lineToRelative(-2.021f, 3.5f) lineToRelative(2.021f, 3.5f) horizontalLineToRelative(4.042f) lineToRelative(2.021f, -3.5f) close() } } .build() return _screwAlt!! } private var _screwAlt: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,819
icons
MIT License
common/src/test/kotlin/org/jetbrains/teamcity/vault/VaultResolverTest.kt
JetBrains
98,586,359
false
{"Kotlin": 175558, "Java": 102627}
package org.jetbrains.teamcity.vault import assertk.assertions.contains import assertk.assertions.isEmpty import assertk.assertions.isNotEmpty import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import jetbrains.buildServer.BaseTestCase import org.jetbrains.teamcity.vault.VaultResolver.VaultParametersFetcher import org.jetbrains.teamcity.vault.support.VaultTemplate import org.mockito.Mockito import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.vault.support.VaultResponse import org.springframework.web.client.HttpClientErrorException import org.springframework.web.client.HttpStatusCodeException import org.testng.Assert import org.testng.Assert.* import org.testng.annotations.BeforeMethod import org.testng.annotations.Test import java.nio.charset.Charset class VaultResolverTest : BaseTestCase(){ lateinit var vaultTemplate: VaultTemplate lateinit var vaultParametersFetcher: VaultParametersFetcher @BeforeMethod override fun setUp() { super.setUp() vaultTemplate = Mockito.mock(VaultTemplate::class.java) vaultParametersFetcher = VaultParametersFetcher(vaultTemplate) } @Test fun testFetch() { val query = VaultQuery(PATH) val response = VaultResponse() response.data = mapOf(VaultResolver.DATA_KEY to VALUE) Mockito.`when`(vaultTemplate.read(PATH)).thenReturn(response) val (replacements, errors) = vaultParametersFetcher.doFetchAndPrepareReplacements(listOf(query)) assertk.assertThat(errors).isEmpty() assertk.assertThat(replacements).contains("/$PATH" to VALUE) } @Test fun testFetch_WithError() { val query = VaultQuery(PATH) Mockito.`when`(vaultTemplate.read(PATH)).thenThrow(RuntimeException("error")) val (replacements, errors) = vaultParametersFetcher.doFetchAndPrepareReplacements(listOf(query)) assertk.assertThat(errors).isNotEmpty() assertk.assertThat(replacements).isEmpty() } @Test fun testFetch_WithFirstHttpErrorRetries() { val query = VaultQuery(PATH) val response = VaultResponse() response.data = mapOf(VaultResolver.DATA_KEY to VALUE) Mockito.`when`(vaultTemplate.read(PATH)) .thenThrow(HttpClientErrorException.create(HttpStatus.INTERNAL_SERVER_ERROR, "Mock error", HttpHeaders.EMPTY, byteArrayOf(), Charset.defaultCharset())) .thenReturn(response) val (replacements, errors) = vaultParametersFetcher.doFetchAndPrepareReplacements(listOf(query)) assertk.assertThat(errors).isEmpty() assertk.assertThat(replacements).contains("/$PATH" to VALUE) } companion object { const val PATH = "path" const val VALUE = "value" private val objectMapper = jacksonObjectMapper() } }
29
Kotlin
18
28
5c174cbe404547b1bb980766ac45bea40c971006
2,868
teamcity-hashicorp-vault-plugin
Apache License 2.0
components-compose/src/main/java/uk/gov/hmrc/components/compose/organism/card/IconButtonCardView.kt
hmrc
299,591,950
false
{"Kotlin": 559754, "Ruby": 10016, "Shell": 1395}
/* * Copyright 2023 HM Revenue & Customs * * 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 uk.gov.hmrc.components.compose.organism.card import androidx.annotation.DrawableRes import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import uk.gov.hmrc.components.compose.atom.button.IconButton import uk.gov.hmrc.components.compose.organism.HmrcCardView @Composable fun IconButtonCardView( titleText: String, @DrawableRes iconResId: Int, onClick: () -> Unit, modifier: Modifier = Modifier, ) { HmrcCardView(modifier = modifier) { IconButton( text = titleText, iconResId = iconResId, onClick = onClick ) } }
1
Kotlin
3
7
e0cce3b1380fbf103e4a32060ddbfdbdda7eb6dd
1,227
android-components
Apache License 2.0
core/src/main/java/com/aditprayogo/core/utils/state/LoaderState.kt
Aditprayogo
285,653,574
false
null
package com.aditprayogo.core.utils.state sealed class LoaderState { object ShowLoading: LoaderState() object HideLoading: LoaderState() }
0
Kotlin
9
54
d204e320430ef13fd5071eb9445217780291410f
146
GithubUsers
Apache License 2.0
app/src/main/java/com/lindungisesama/ui/main/fragment/home/HomeFragment.kt
ezralazuardy
255,088,592
false
null
package com.lindungisesama.ui.main.fragment.home import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.lindungisesama.R import com.lindungisesama.config.AppConfig.DEFAULT_TIMESTAMP_FORMAT import com.lindungisesama.model.response.RetrofitStatus import com.lindungisesama.ui.guides.GuideDetailActivity import com.lindungisesama.ui.guides.GuideDetailActivity.Companion.GUIDE_DETAIL_DATA import com.lindungisesama.ui.guides.GuideListActivity import com.lindungisesama.ui.main.MainViewModel import com.lindungisesama.ui.main.fragment.home.adapter.GuidesAdapter import com.lindungisesama.ui.main.fragment.home.adapter.GuidesItemClickListener import com.lindungisesama.ui.main.fragment.home.adapter.MythbustersAdapter import com.lindungisesama.ui.main.fragment.home.adapter.MythbustersItemClickListener import com.lindungisesama.ui.mythbusters.MythbusterDetailActivity import com.lindungisesama.ui.mythbusters.MythbusterDetailActivity.Companion.MYTHBUSTER_DETAIL_DATA import com.lindungisesama.ui.mythbusters.MythbusterListActivity import com.lindungisesama.utils.ErrorHandler import com.thefinestartist.finestwebview.FinestWebView import kotlinx.android.synthetic.main.layout_covid_current_cases.* import kotlinx.android.synthetic.main.layout_current_updates.* import kotlinx.android.synthetic.main.layout_guides.* import kotlinx.android.synthetic.main.layout_mythbusters.* import org.koin.android.viewmodel.ext.android.sharedViewModel import java.text.SimpleDateFormat import java.util.* class HomeFragment : Fragment(), GuidesItemClickListener, MythbustersItemClickListener { private val mainViewModel: MainViewModel by sharedViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.fragment_home, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) retainInstance = true showLoadingCurrentCovidCase() showGuidesLoading() showMythbustersLoading() context?.let { context -> card_current_update_1.setOnClickListener { FinestWebView.Builder(context) .show(resources.getString(R.string.link_current_update_1)) } card_current_update_2.setOnClickListener { FinestWebView.Builder(context) .show(resources.getString(R.string.link_current_update_2)) } card_current_update_3.setOnClickListener { FinestWebView.Builder(context) .show(resources.getString(R.string.link_current_update_3)) } card_current_update_4.setOnClickListener { FinestWebView.Builder(context) .show(resources.getString(R.string.link_current_update_4)) } card_current_update_5.setOnClickListener { FinestWebView.Builder(context) .show(resources.getString(R.string.link_current_update_5)) } card_current_update_6.setOnClickListener { FinestWebView.Builder(context) .show(resources.getString(R.string.link_current_update_6)) } button_guides_list.setOnClickListener { startActivity(Intent(context, GuideListActivity::class.java)) } button_mythbusters_list.setOnClickListener { startActivity(Intent(context, MythbusterListActivity::class.java)) } val guidesAdapter = GuidesAdapter(context, this@HomeFragment) val mythbustersAdapter = MythbustersAdapter(context, this@HomeFragment) guides_recycler_view.apply { adapter = guidesAdapter layoutManager = LinearLayoutManager(context) setHasFixedSize(true) } mythbusters_recycler_view.apply { adapter = mythbustersAdapter layoutManager = LinearLayoutManager(context) setHasFixedSize(true) } mainViewModel.currentCaseResponse.observe(viewLifecycleOwner, Observer { when (it.status) { RetrofitStatus.SUCCESS -> it.data?.let { data -> txt_covid_current_confirmed.text = if (data.cases != null) data.cases.toString() else "-" txt_covid_current_recovery.text = if (data.active != null) data.active.toString() else "-" txt_covid_current_recovered.text = if (data.recovered != null) data.recovered.toString() else "-" txt_covid_current_death.text = if (data.deaths != null) data.deaths.toString() else "-" data.updated?.let { timestamp -> txt_covid_current_timestamp.text = getString( R.string.text_current_cases_refreshed_time, convertTimeStampToLocalDate(timestamp) ) txt_covid_current_timestamp.visibility = View.VISIBLE } } else -> { setEmptyCurrentCovidCase() activity?.let { activity -> ErrorHandler.show(activity.supportFragmentManager, it.status) } } } hideLoadingCurrentCovidCase() if (!mainViewModel.guidesIsExecuted && !mainViewModel.guidesLoaded ) mainViewModel.getGuides() }) mainViewModel.guides.observe(viewLifecycleOwner, Observer { when (it.status) { RetrofitStatus.SUCCESS -> it.data?.let { data -> guidesAdapter.setData(data) hideGuidesLoading() } else -> activity?.let { activity -> ErrorHandler.show(activity.supportFragmentManager, it.status) } } if (!mainViewModel.mythbustersIsExecuted && !mainViewModel.mythbustersLoaded ) mainViewModel.getMythbusters() }) mainViewModel.mythbusters.observe(viewLifecycleOwner, Observer { when (it.status) { RetrofitStatus.SUCCESS -> it.data?.let { data -> mythbustersAdapter.setData(data) hideMythbustersLoading() } else -> activity?.let { activity -> ErrorHandler.show(activity.supportFragmentManager, it.status) } } }) mainViewModel.prismicResponse.observe(viewLifecycleOwner, Observer { if (it.status != RetrofitStatus.SUCCESS) activity?.let { activity -> ErrorHandler.show(activity.supportFragmentManager, it.status) } else if (!mainViewModel.currentCaseIsExecuted && !mainViewModel.currentCaseLoaded ) mainViewModel.getCurrentCase() }) } } private fun showLoadingCurrentCovidCase() { txt_covid_current_confirmed.visibility = View.GONE loading_covid_current_confirmed.visibility = View.VISIBLE txt_covid_current_recovery.visibility = View.GONE loading_covid_current_recovery.visibility = View.VISIBLE txt_covid_current_recovered.visibility = View.GONE loading_covid_current_recovered.visibility = View.VISIBLE txt_covid_current_death.visibility = View.GONE loading_covid_current_death.visibility = View.VISIBLE } private fun setEmptyCurrentCovidCase() { txt_covid_current_confirmed.text = "-" txt_covid_current_recovery.text = "-" txt_covid_current_recovered.text = "-" txt_covid_current_death.text = "-" txt_covid_current_timestamp.visibility = View.GONE } private fun hideLoadingCurrentCovidCase() { loading_covid_current_confirmed.visibility = View.GONE txt_covid_current_confirmed.visibility = View.VISIBLE loading_covid_current_recovery.visibility = View.GONE txt_covid_current_recovery.visibility = View.VISIBLE loading_covid_current_recovered.visibility = View.GONE txt_covid_current_recovered.visibility = View.VISIBLE loading_covid_current_death.visibility = View.GONE txt_covid_current_death.visibility = View.VISIBLE } private fun showGuidesLoading() { guides_recycler_view.visibility = View.GONE guides_loading.visibility = View.VISIBLE } private fun hideGuidesLoading() { guides_loading.visibility = View.GONE guides_recycler_view.visibility = View.VISIBLE } private fun showMythbustersLoading() { mythbusters_recycler_view.visibility = View.GONE mythbusters_loading.visibility = View.VISIBLE } private fun hideMythbustersLoading() { mythbusters_loading.visibility = View.GONE mythbusters_recycler_view.visibility = View.VISIBLE } private fun convertTimeStampToLocalDate(timestamp: Long): String = SimpleDateFormat(DEFAULT_TIMESTAMP_FORMAT, Locale.getDefault()).format(Date(timestamp)) override fun onGuidesItemClick(result: com.lindungisesama.model.raw.guides.Result) { startActivity( Intent(activity, GuideDetailActivity::class.java) .putExtra(GUIDE_DETAIL_DATA, result) ) } override fun onMythbustersItemClick(result: com.lindungisesama.model.raw.mythbusters.Result) { startActivity( Intent(activity, MythbusterDetailActivity::class.java) .putExtra(MYTHBUSTER_DETAIL_DATA, result) ) } }
0
Kotlin
0
0
c39d59ac08f80f102135a13e57d33d6e60808094
8,577
lindungisesama
MIT License
SpaceSoccerr/app/src/main/java/aula5/example/spacesoccer/views/PerfilUtilizador.kt
macyuri94
257,707,367
false
null
package aula5.example.spacesoccer.views import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import aula5.example.spacesoccer.R import aula5.example.spacesoccer.helper.VolleyHelper import aula5.example.spacesoccer.models.Utilizador import kotlinx.android.synthetic.main.perfil_utilizador.* import kotlinx.android.synthetic.main.torneios.* import org.json.JSONObject class PerfilUtilizador : AppCompatActivity() { var email: String? = null var listarUtilizador : MutableList<Utilizador> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.perfil_utilizador) val bundle = intent.extras bundle?.let { email = it.getString("Email") } VolleyHelper.instance.getUsersById(this, email.toString()) { response -> response?.let { for (index in 0 until it.length()) { val jsonPlayer = it[index] as JSONObject listarUtilizador.add(Utilizador.parseJson(jsonPlayer)) txtNomeUtilizador_PerfilUtilizador.text = listarUtilizador[index].PrimeiroNome txtultimoNome_PerfilUtilizador.text = listarUtilizador[index].UltimoNome txtPrimeiroNome_PerfilUtilizador.text = listarUtilizador[index].PrimeiroNome txtDataNascimento_PerfilUtilizador.text = listarUtilizador[index].DataNascimento txtEmail_PerfilUtilizador.text = listarUtilizador[index].Email } } } } }
0
Kotlin
0
1
e9f3d461cffe60934ca2980c2d46b5186bae2067
1,713
space_soccer
MIT License
MCron/src/main/kotlin/city/newnan/mcron/MCRon.kt
NewNanCity
467,094,551
false
null
package city.newnan.mcron import co.aikar.commands.PaperCommandManager import city.newnan.violet.config.ConfigManager import city.newnan.violet.config.setListIfNull import city.newnan.violet.i18n.LanguageManager import city.newnan.violet.message.MessageManager import me.lucko.helper.Events import me.lucko.helper.plugin.ExtendedJavaPlugin import org.bukkit.Bukkit import org.bukkit.event.EventPriority import org.bukkit.event.server.PluginDisableEvent import org.bukkit.event.server.PluginEnableEvent import org.bukkit.event.server.ServerLoadEvent import java.util.* class MCron : ExtendedJavaPlugin() { internal val configManager: ConfigManager by lazy { ConfigManager(this) } private val languageManager: LanguageManager by lazy { LanguageManager(this) } internal val messageManager: MessageManager by lazy { MessageManager(this) } internal val cronManager: CronManager by lazy { CronManager() } private val commandManager: PaperCommandManager by lazy { PaperCommandManager(this) } companion object { lateinit var INSTANCE: MCron private set } init { INSTANCE = this } override fun enable() { // 初始化ConfigManager configManager touch "config.yml" // 初始化LanguageManager Locale("config").also { languageManager.register(it, "config.yml") setMajorLanguage it } // 初始化MessageManager messageManager setLanguageProvider languageManager messageManager setPlayerPrefix messageManager.sprintf("\$msg.prefix$") // 初始化CommandManager commandManager.run { usePerIssuerLocale(true, false) registerCommand(CronCommands) locales.loadYamlLanguageFile("config.yml", Locale("config")) } // 运行Cron cronManager.run() Events.subscribe(ServerLoadEvent::class.java, EventPriority.MONITOR) .handler { executeCommandsByConfig("on-server-ready") } .bindWith(this) Events.subscribe(PluginEnableEvent::class.java, EventPriority.MONITOR) .handler { e: PluginEnableEvent -> executeCommandsByConfig("on-plugin-enable", e.plugin.description.name) } .bindWith(this) Events.subscribe(PluginDisableEvent::class.java, EventPriority.MONITOR) .handler { e: PluginDisableEvent -> executeCommandsByConfig("on-plugin-disable", e.plugin.description.name) } .bindWith(this) } override fun disable() { commandManager.unregisterCommands() } fun reload() = cronManager.reload() internal fun executeCommandsByConfig(vararg nodePath: Any?) { Bukkit.getConsoleSender().run { configManager["config.yml"]?.getNode(nodePath)?.setListIfNull() ?.getList { obj: Any -> obj.toString() }?.forEach { command -> messageManager.printf("\$msg.execute$", command) Bukkit.dispatchCommand(this, command) } } } }
0
Kotlin
0
3
0004ffea58328bfcda5ad56e01d54872715c3c2b
3,063
Plugins
MIT License
main/src/main/kotlin/siliconsloth/miniruler/rules/PlanningRules.kt
SiliconSloth
229,996,790
false
{"Gradle Kotlin DSL": 4, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 1, "Java": 77, "INI": 1, "Kotlin": 65}
package siliconsloth.miniruler.rules import siliconsloth.miniruler.* import siliconsloth.miniruler.engine.RuleEngine import siliconsloth.miniruler.planner.Enumeration import siliconsloth.miniruler.planner.PartialOrderPlanner import siliconsloth.miniruler.planner.Planner import kotlin.system.exitProcess fun RuleEngine.planningRules(planner: Planner) { rule { val inv by find<InventoryMemory>() fire { maintain(VariableValue(itemCount(inv.item), inv.lower)) } } rule { val menu by find<MenuOpen>() fire { maintain(VariableValue(MENU, menu.menu)) } } rule { not<MenuOpen>() fire { maintain(VariableValue(MENU, null)) } } rule { val item by find<HeldItem>() fire { maintain(VariableValue(HOLDING, item.item)) } } rule { not<HeldItem>() fire { maintain(VariableValue(HOLDING, null)) } } // If the agent is aware of any instance of an entity existing anywhere in the world, // that counts as "next to". Entity.values().forEach { e -> rule { find<Memory> { entity == e } fire { maintain(VariableValue(nextTo(e), true)) } } rule { not<Memory> { entity == e } fire { maintain(VariableValue(nextTo(e), false)) } } } rule { val varValues by all<VariableValue>() delay = 6 // Allow time for all values to be updated fire { val state = state(varValues.map { it.variable to Enumeration(it.value) }.toMap()) PartialOrderPlanner(planner.goal, planner.actions).run(state) exitProcess(0) val action = planner.chooseAction(state) action.action?.let { maintain(CurrentAction(it)) } action.resourceTargets.forEach { maintain(it) } println(action.action) println(action.cost) println(action.resourceTargets) println(varValues.filter { it.value != 0 && it.value != false }) planner.printPlan(state) } } }
1
null
1
1
2c30a2a9d92385f2015b63f1fadb683e3edcddfc
2,248
MiniRuler
MIT License
schemact-plugin/src/main/kotlin/schemact/gradleplugin/KotlinFunctionClientDependencies.kt
typedpath
839,785,725
false
{"Kotlin": 113843, "Shell": 131}
package schemact.gradleplugin object KotlinFunctionClientDependencies { val ktor_version="2.3.12" val kotlinFunctionClientDependencies = listOf( "io.ktor:ktor-client-core:$ktor_version", "io.ktor:ktor-client-cio:$ktor_version", "io.ktor:ktor-client-content-negotiation:$ktor_version", "io.ktor:ktor-serialization-kotlinx-json:$ktor_version" ) }
0
Kotlin
0
0
c97cd444a4377eb86d871fa7ae8079586a559e6d
390
schemact4
Apache License 2.0
src/main/kotlin/me/dominaezzz/chitchat/ui/PublicRooms.kt
Dominaezzz
342,052,724
false
null
package me.dominaezzz.chitchat.ui import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.* import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Clear import androidx.compose.material.icons.filled.Contacts import androidx.compose.material.icons.filled.Search import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import io.github.matrixkt.api.QueryPublicRooms import io.github.matrixkt.models.PublicRoomsChunk import io.github.matrixkt.utils.rpc import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import me.dominaezzz.chitchat.util.loadIcon import java.net.URI @Composable fun PublicRooms(modifier: Modifier = Modifier) { val appModel = LocalAppModel.current val client = LocalAppModel.current.client val session = LocalAppModel.current.session var searchTerm by remember { mutableStateOf("") } val shouldPaginate = remember { MutableStateFlow(false) } @OptIn(ExperimentalCoroutinesApi::class) val rooms = remember { val batchSize = 40L snapshotFlow { searchTerm } .mapLatest { delay(500); it } .map { QueryPublicRooms.Filter(it) } .flatMapLatest { filter -> val searchFlow = flow { var sinceToken: String? = null do { val request = QueryPublicRooms( QueryPublicRooms.Url(), QueryPublicRooms.Body(limit = batchSize, filter = filter, since = sinceToken) ) val response = client.rpc(request, session.accessToken) emit(response.chunk) sinceToken = response.nextBatch } while (sinceToken != null) } searchFlow.runningReduce { acc, value -> acc + value } .onStart<List<PublicRoomsChunk>?> { emit(null) } .transform { chunk -> emit(chunk) shouldPaginate.first { it } } } }.collectAsState(null).value val joinsInProgress by appModel.joinsInProgress.collectAsState() val joinedRooms by appModel.syncClient.joinedRooms.collectAsState(emptyMap()) Column(modifier.padding(32.dp)) { Text( "Explore Rooms", Modifier.padding(vertical = 8.dp), style = MaterialTheme.typography.h5 ) TextField( value = searchTerm, onValueChange = { searchTerm = it }, modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp), placeholder = { Text("Find a room… (e.g. #example:matrix.org)") }, leadingIcon = { Icon(Icons.Default.Search, null) }, trailingIcon = { IconButton({ searchTerm = "" }, enabled = searchTerm.isNotEmpty()) { Icon(Icons.Default.Clear, null) } } ) if (rooms == null) { Box(Modifier.fillMaxSize(), Alignment.Center) { CircularProgressIndicator() DisposableEffect(Unit) { shouldPaginate.value = true onDispose { shouldPaginate.value = false } } } } else if (rooms.isEmpty()) { Box(Modifier.fillMaxSize(), Alignment.Center) { Text("No rooms were found", style = MaterialTheme.typography.h3) } } else { Box(Modifier.fillMaxWidth(), Alignment.TopStart) { val state = rememberLazyListState() LazyColumn(Modifier.padding(end = 12.dp), state = state) { itemsIndexed(rooms, key = { _, room -> room.roomId }) { idx, room -> if (idx == rooms.lastIndex) { DisposableEffect(room.roomId) { shouldPaginate.value = true onDispose { shouldPaginate.value = false } } } val image = room.avatarUrl?.let { loadIcon(URI(it)) } @OptIn(ExperimentalMaterialApi::class) ListItem( icon = { if (image != null) { Image( image, null, Modifier.size(40.dp).clip(CircleShape), contentScale = ContentScale.Crop ) } }, text = { Text(room.name ?: room.canonicalAlias ?: room.roomId) }, secondaryText = room.topic?.let { { Text(it) } }, singleLineSecondaryText = false, overlineText = { val alias = room.canonicalAlias if (alias != null) { Text(alias) } }, trailing = { Column( modifier = Modifier.fillMaxHeight(), verticalArrangement = Arrangement.SpaceEvenly ) { Row(verticalAlignment = Alignment.CenterVertically) { Icon(Icons.Filled.Contacts, null) Text(room.numJoinedMembers.toString()) } Spacer(Modifier.height(8.dp)) if (room.roomId in joinsInProgress) { CircularProgressIndicator() } else { val hasAlreadyJoined = room.roomId in joinedRooms Button( onClick = { appModel.joinRoom(room.roomId) }, enabled = !hasAlreadyJoined, content = { Text(if (hasAlreadyJoined) "Joined" else "Join") } ) } } } ) Divider() } } VerticalScrollbar( rememberScrollbarAdapter(state), Modifier.align(Alignment.CenterEnd).fillMaxHeight() ) } } } }
0
Kotlin
0
12
23ff3f3a3b17db7514ea45f9a8fea9c8b421545b
5,386
ChitChat
Apache License 2.0
src/main/resources/archetype-resources/src/test/kotlin/driverutil/RemoteAndroidWebDriverFactory.kt
secugrow
423,127,303
false
null
#set( $dollar = '$' ) #set( $curlyOpen = '{' ) #set( $curlyClose = '}' ) #set( $bracketOpen = '(' ) #set( $bracketClose = ')' ) package ${package}.driverutil import io.appium.java_client.android.AndroidDriver import io.appium.java_client.remote.MobileCapabilityType import org.openqa.selenium.WebDriver import java.net.URL class RemoteAndroidWebDriverFactory : RemoteWebDriverFactory() { override fun createDriver(): WebDriver { caps.browserName = "android" caps.setVersion("8.1") caps.setCapability("enableVNC", true) caps.setCapability("enableVideo", false) //caps.setCapability("screenResolution", screenSize) caps.setCapability("sessionTimeout", "15m") caps.setCapability("noReset", false) caps.setCapability(MobileCapabilityType.UDID, System.getProperty("device.id", "emulator-5554"))//"DEFAULT_ANDROID_DEVICE_ID")) caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android") caps.setCapability(MobileCapabilityType.DEVICE_NAME, "Android_Device_Appium") caps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2") caps.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 12000) webDriver = AndroidDriver(URL("$dollar$curlyOpen getRemoteTestingServer$bracketOpen$bracketClose$curlyClose/wd/hub"), caps) return webDriver } }
6
Kotlin
1
2
05fddae340285e75689574d5ffdffb319d16320f
1,379
kotlin-archetype
Apache License 2.0
src/KirchoffThinPlate.kt
danftang
140,095,532
false
{"Kotlin": 42153, "Gnuplot": 90}
class KirchoffThinPlate : MaskedDoubleArray2D { val nu : Double val delta : Double // distance between gridpoints constructor(nu : Double, xLength : Double, mask : Mask2D) : super(mask) { this.nu = nu this.delta = xLength/mask.xSize } constructor( nu : Double, xLength : Double, mask : Mask2D, initialiser : (Int,Int) -> Double) : super(mask, initialiser) { this.nu = nu this.delta = xLength/mask.xSize } fun LaplaceLaplace(i : Int, j : Int) : Double { if(!mask[i,j]) return 0.0 // masked point if(!mask[i-1,j]) { // left hand edge if(!mask[i,j+1]) { // top left corner // TODO } if(!mask[i,j-1]) { // bottom left corner // TODO } return LaplaceV(i+1,j) - (1.0-nu)*(1.0-nu)*d4_dy4(i,j) } if(!mask[i+1,j]) { // right hand edge if(!mask[i,j+1]) { // top right corner // TODO } if(!mask[i,j-1]) { // bottom right corner // TODO } return LaplaceV(i-1,j) - (1.0-nu)*(1.0-nu)*d4_dy4(i,j) } if(!mask[i,j+1]) { // top edge return LaplaceH(i,j-1) - (1.0-nu)*(1.0-nu)*d4_dx4(i,j) } if(!mask[i,j-1]) { // bottom edge return LaplaceH(i,j+1) - (1.0-nu)*(1.0-nu)*d4_dx4(i,j) } return Laplace(i+1,j) + Laplace(i-1,j) + Laplace(i,j+1) + Laplace(i,j-1) - 4.0*Laplace(i,j) } fun Laplace(i : Int, j : Int) : Double { if(!mask[i,j]) return 0.0 // masked point if(!mask[i+1,j] || !mask[i-1,j]) { // left/right hand edge if(!mask[i,j+1] || !mask[i,j-1]) return 0.0; // corner return (1.0 - nu)*(this[i,j-1] - 2.0*this[i,j] + this[i,j+1]) } if(!mask[i,j+1] || !mask[i,j-1]) { // top/bottom edge return(1.0-nu)*(this[i-1,j] - 2.0*this[i,j] + this[i+1,j]) } return this[i+1,j] + this[i-1,j] + this[i,j+1] + this[i,j-1] - 4.0*this[i,j] } fun d2_dx2(i : Int, j : Int) : Double { if(!mask[i-1,j] || !mask[i+1,j]) { // left/right edge if(!mask[i,j-1] || !mask[i,j+1]) return 0.0 // corner return -nu*(this[i,j-1] - 2.0*this[i,j] + this[i,j+1]) } return this[i-1,j] - 2.0*this[i,j] + this[i+1,j] } fun d2_dy2(i : Int, j : Int) : Double { if(!mask[i,j-1] || !mask[i,j+1]) { // top/bottom edge if(!mask[i-1,j] || !mask[i+1,j]) return 0.0 // corner return -nu*(this[i-1,j] - 2.0*this[i,j] + this[i+1,j]) } return this[i,j-1] - 2.0*this[i,j] + this[i,j+1] } fun d4_dy4(i : Int, j : Int) : Double { return d2_dy2(i,j-1) - 2.0*d2_dy2(i,j) + d2_dy2(i,j+1) } fun d4_dx4(i : Int, j : Int) : Double { return d2_dx2(i-1,j) - 2.0*d2_dx2(i,j) + d2_dx2(i+1,j) } // LaplaceV = d2_dx2 + nu*d2_dy2 fun LaplaceV(i : Int, j : Int) : Double { if(!mask[i-1,j] || !mask[i+1,j]) return 0.0 if(!mask[i,j-1] || !mask[i,j+1]) { return (1.0-nu*nu)*(this[i-1,j] - 2.0*this[i,j] + this[i+1,j]) } return this[i-1,j] + this [i+1,j] + nu*(this[i,j+1] + this[i,j-1]) - (2.0+2.0*nu)*this[i,j] } // LaplaceH = nu*d2_dx2 + d2_dy2 fun LaplaceH(i : Int, j : Int) : Double { if(!mask[i,j+1] || !mask[i,j-1]) return 0.0 if(!mask[i-1,j] || !mask[i+1,j]) { return (1.0-nu*nu)*(this[i,j-1] - 2.0*this[i,j] + this[i,j+1]) } return nu*(this[i-1,j] + this [i+1,j]) + this[i,j+1] + this[i,j-1] - (2.0+2.0*nu)*this[i,j] } }
0
Kotlin
0
0
338cf2025a73440b1fa3275428085da8745972b4
3,704
MusicalInstrumentSim
MIT License
src/main/kotlin/composables/SingleLineText.kt
oss-review-toolkit
436,895,138
false
{"Kotlin": 278352}
package org.ossreviewtoolkit.workbench.composables import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.TooltipArea import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.text.style.TextOverflow /** * Display the [text] on a single line using [TextOverflow.Ellipsis] on overflow. The text is also shown in a [Tooltip] * on mouse over. */ @OptIn(ExperimentalFoundationApi::class) @Composable fun SingleLineText(text: String) { TooltipArea(tooltip = { Tooltip(text) }) { Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis) } }
6
Kotlin
4
26
38dd099eb5c6e7656a8bbe2614842bae048a78f1
649
ort-workbench
Apache License 2.0
app/src/main/java/std/aanrstudio/apps/moviesup/ui/fragment/favorite/tv/FavTvAdapter.kt
rnaufal32
215,315,812
false
null
package std.aanrstudio.apps.moviesup.ui.fragment.favorite.tv import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import std.aanrstudio.apps.moviesup.R import std.aanrstudio.apps.moviesup.data.source.model.Movie import std.aanrstudio.apps.moviesup.data.source.model.Tv import std.aanrstudio.apps.moviesup.ui.activity.detail.DetailActivity class FavTvAdapter : PagedListAdapter<Tv, FavTvAdapter.ViewHolder>( DIFF_CALLBACK ) { companion object{ private val DIFF_CALLBACK = object: DiffUtil.ItemCallback<Tv>(){ override fun areContentsTheSame(oldItem: Tv, newItem: Tv): Boolean { return oldItem.id == newItem.id } override fun areItemsTheSame(oldItem: Tv, newItem: Tv): Boolean { return oldItem == newItem } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.items, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val tv = getItem(position) holder.txt_title.text = tv?.title holder.txt_overview.text = tv?.overview Glide.with(holder.itemView) .load(tv?.poster) .into(holder.poster) holder.itemView.setOnClickListener { val intent = Intent(it.context, DetailActivity::class.java) intent.putExtra(DetailActivity.EXTRA_INTENT, "Tv") intent.putExtra(DetailActivity.EXTRA_ID, tv?.id) it.context.startActivity(intent) } } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var poster: ImageView = itemView.findViewById(R.id.poster) var txt_title: TextView = itemView.findViewById(R.id.txt_title) var txt_overview: TextView = itemView.findViewById(R.id.txt_overview) } }
0
Kotlin
0
0
e304239f94aa69f89e18697cd84712502c1531b8
2,260
MoviesUp
MIT License
app/src/main/java/demo/com/retainedcomponent/App.kt
creati8e
158,060,347
false
null
package demo.com.retainedcomponent import dagger.android.AndroidInjector import dagger.android.support.DaggerApplication import demo.com.retainedcomponent.di.DaggerAppComponent class App : DaggerApplication() { override fun applicationInjector(): AndroidInjector<out DaggerApplication> { return DaggerAppComponent.builder().create(this) } }
0
Kotlin
0
0
f564a01cfbe88ca222dff64dba6dfec7d22fb246
360
Dagger-Shared-Component-Sample
Apache License 2.0
sample/android-lib/src/main/kotlin/me/xx2bab/koncat/sample/android/AndroidLibraryAPI.kt
2BAB
433,810,120
false
{"Kotlin": 83292, "Shell": 128}
package me.xx2bab.koncat.sample.android import me.xx2bab.koncat.sample.interfaze.DummyAPI class AndroidLibraryAPI: DummyAPI { override fun onCall(param: String): String { return "AndroidLibraryAPI is running with param $param ..." } }
3
Kotlin
3
57
04e6400fe06fb8d099ed31c8f3ed246f8c805ac6
252
Koncat
Apache License 2.0
netty/src/test/kotlin/org/springframework/samples/petclinic/rest/webflux/r2dbc/coroutine/NettyWebFluxR2dbcCoroutineVisitControllerTest.kt
kotoant
612,221,740
false
{"Kotlin": 230920, "JavaScript": 102019, "Mustache": 10054, "PLpgSQL": 2929, "Shell": 1403, "Dockerfile": 709}
package org.springframework.samples.petclinic.rest.webflux.r2dbc.coroutine class NettyWebFluxR2dbcCoroutineVisitControllerTest : WebFluxR2dbcCoroutineVisitControllerTest()
0
Kotlin
0
2
365b0ce4d9eaacee8c888511915c404f414cbd8c
173
spring-petclinic-rest
Apache License 2.0
PictureComposer/app/src/main/java/com/example/picturecomposer/ResultsActivity.kt
jekkogray
368,608,851
false
null
package com.example.picturecomposer import android.animation.AnimatorInflater import android.animation.AnimatorSet import android.annotation.SuppressLint import android.content.* import android.graphics.Bitmap import android.graphics.ImageDecoder import android.graphics.PointF import android.graphics.RectF import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.view.children import com.example.picturecomposer.CameraActivity.Companion.capturedImage import com.example.picturecomposer.model.PCSubjectDetected import com.example.picturecomposer.util.ImageUtility import com.example.picturecomposer.util.ProcImg import com.example.picturecomposer.util.SubjectBoundingBoxView import com.example.picturecomposer.util.SubjectDotView import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.google.firebase.ktx.Firebase import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.ktx.storage import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.face.FaceDetection import com.google.mlkit.vision.face.FaceDetectorOptions import com.google.mlkit.vision.label.ImageLabeling import com.google.mlkit.vision.label.defaults.ImageLabelerOptions import com.photocomposer.subjectdetection.model.SubjectDetected import com.photocomposer.subjectdetection.subjectdetector.SubjectDetectorLocalizerAPI import org.opencv.android.OpenCVLoader import java.io.IOException import java.util.* import kotlin.system.exitProcess @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS", "DEPRECATION") class ResultsActivity : AppCompatActivity() { companion object { val TAG = ResultsActivity::class.java.simpleName } // UI Components private lateinit var categoryTextView: TextView private lateinit var viewGradesButton: Button private lateinit var revealSubjectsButton: ToggleButton private lateinit var backButton: FloatingActionButton private lateinit var helpButton: FloatingActionButton private lateinit var inputImageView: ImageView private var captureMode: Boolean = false private var uploadMode: Boolean = false private lateinit var storage: FirebaseStorage private lateinit var firebaseDatabase: FirebaseDatabase private lateinit var subjectOverlayViewContainer: ViewGroup private var dotViewSize: Int = 0 private val pickPhotoCode = 1046 private var selectedSubjectLabel = "Unknown" private var selectedSubjectBoundingBox: RectF = RectF() private var selectedSubjectConfidenceScore: Float = 0.0f private val subjectDetector by lazy { SubjectDetectorLocalizerAPI.createDefault(assets) } private lateinit var sharedPreferences: SharedPreferences // Grading private var calcThirds = 0 private var calcFraming = 0 private var calcExposure = 0 private var calcLevel = 0 private var calcBlur = 0 private var calcFinal = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_results) // Initialize UI components viewGradesButton = findViewById(R.id.view_grades_button) backButton = findViewById(R.id.back_button) inputImageView = findViewById(R.id.input_image_view) categoryTextView = findViewById(R.id.category_text_view) revealSubjectsButton = findViewById(R.id.reveal_subjects_button) helpButton = findViewById(R.id.help_button) // Initialize subject detection UI components subjectOverlayViewContainer = findViewById(R.id.subject_overlay_view_container) dotViewSize = resources.getDimensionPixelOffset(R.dimen.subject_image_dot_size) firebaseDatabase = FirebaseDatabase.getInstance() // Determine the source activity captureMode = intent.getBooleanExtra("CAPTURE_MODE", false) uploadMode = intent.getBooleanExtra("UPLOAD_MODE", false) // Initialize appropriate intents for corresponding mode if (captureMode) { backButton.setOnClickListener { val intent = Intent(this.applicationContext, CameraActivity::class.java) capturedImage?.recycle() startActivity(intent) } } if (uploadMode) { backButton.setOnClickListener { val intent = Intent(this.applicationContext, NavigationActivity::class.java) intent.putExtra("CAPTURE_MODE", false).putExtra("UPLOAD_MODE", true) capturedImage?.recycle() startActivity(intent) } } //get shared preferences sharedPreferences = getSharedPreferences("photo-composer", Context.MODE_PRIVATE) // Check OpenCV setup if (!OpenCVLoader.initDebug()) { Log.d(TAG, "OpenCVLoader.initDebug(), not working.") exitProcess(0) } else { Log.d(TAG, "OpenCVLoader.initDebug(), working.") } runSubjectDetection() viewGradesButtonInitializeListener() helpButtonInitializeListener() } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data != null && requestCode == pickPhotoCode) { //get photo Uri first val photoUri = data.data //Uri to bitmap conversion var selectedImage: Bitmap? = null try { // check version of Android on device selectedImage = if (Build.VERSION.SDK_INT >= 29) { //changed from 28 // on newer versions of Android, use the new decodeBitmap method val source = ImageDecoder.createSource(this.contentResolver, photoUri!!) ImageDecoder.decodeBitmap(source) } else { // support older versions of Android by using getBitmap MediaStore.Images.Media.getBitmap(this.contentResolver, photoUri) } } catch (e: IOException) { e.printStackTrace() } //store this photo in global variable capturedImage = selectedImage //head to results activity to display selected photo val intent = Intent( applicationContext, ResultsActivity::class.java ).putExtra("CAPTURE_MODE", false).putExtra("UPLOAD_MODE", true) startActivity(intent) } } override fun onBackPressed() { if (captureMode) { val intent = Intent(this.applicationContext, CameraActivity::class.java) capturedImage?.recycle() startActivity(intent) } if (uploadMode) { val intent = Intent(this.applicationContext, NavigationActivity::class.java) capturedImage?.recycle() startActivity(intent) } } private fun helpButtonInitializeListener() { helpButton.setOnClickListener { val helpDialog = AlertDialog.Builder(this) helpDialog.setMessage("Reveal Subjects Button reveals the selectable subjects in the image.\n\n Tap on the dot in the image to select your subject.\n\n Tap and hold on the dot to reveal related labels.") .setPositiveButton("Ok" ) { dialogInterface, _ -> dialogInterface.dismiss() } helpDialog.create().show() } } /** * Confirms the image for upload, and sends metadata. */ private fun viewGradesButtonInitializeListener() { viewGradesButton.setOnClickListener { // Process img calcThirds = ProcImg().thirds( selectedSubjectBoundingBox.left, selectedSubjectBoundingBox.right, selectedSubjectBoundingBox.top, selectedSubjectBoundingBox.bottom ) calcFraming = ProcImg().framing( selectedSubjectBoundingBox.left, selectedSubjectBoundingBox.right, selectedSubjectBoundingBox.top, selectedSubjectBoundingBox.bottom ) calcExposure = ProcImg().exposure() calcBlur = ProcImg().blur() calcLevel = ProcImg().level() calcFinal = ProcImg().final( calcThirds, calcFraming, calcExposure, calcLevel, calcBlur ) Toast.makeText(applicationContext, "Uploading image...", Toast.LENGTH_LONG).show() storage = Firebase.storage // Create a storage reference from our app val storageRef = storage.reference // Create a reference to image file in a directory named as the UID val currentUserID = FirebaseAuth.getInstance().currentUser!!.uid val imageRef = storageRef.child( "$currentUserID/${ ImageUtility.getImageUriFromBitmap( applicationContext, capturedImage!! ).lastPathSegment }" ) // Create task to upload image Uri val uploadTask = imageRef.putFile(ImageUtility.getImageUriFromBitmap(applicationContext, capturedImage!!)) // If the photo successfully uploads to cloud storage and a downloadUrl was generated for it uploadTask.addOnSuccessListener { imageRef.downloadUrl.addOnSuccessListener { // Toast for the successful upload and URL retrieval Toast.makeText( applicationContext, "Photo uploaded successfully!", Toast.LENGTH_LONG ) .show() // Find where to put the photo in the db val currUserID = FirebaseAuth.getInstance().currentUser!!.uid val currPhotoKeyRef = firebaseDatabase.getReference("UID/$currUserID/currPhotoKey") val idReference = firebaseDatabase.getReference("UID/$currUserID/email") val photoListReference = firebaseDatabase.getReference("UID/$currUserID/photoList") // Create a photo object with all of the photo attributes val newPhoto = Photo( it.toString(), selectedSubjectLabel, selectedSubjectBoundingBox.left, selectedSubjectBoundingBox.top, selectedSubjectBoundingBox.right, selectedSubjectBoundingBox.bottom, calcThirds, calcFraming, calcExposure, calcLevel, calcBlur, calcFinal, "tempKey" ) // If this is the user's first photo, initialize their email in the db idReference.setValue(FirebaseAuth.getInstance().currentUser!!.email!!) // Push the new photo with all of its metadata to the appropriate spot in the db val key = photoListReference.push().key firebaseDatabase.getReference("UID/$currUserID/photoList/$key") .setValue(newPhoto) // have currPhotoKey point to this photo so we know it's the one to display on grading screen firebaseDatabase.getReference("UID/$currUserID/photoList/$key/key") .setValue(key) currPhotoKeyRef.setValue(key) //head to the grading screen now and pass along the subject word val intent = Intent(applicationContext, GradeActivity::class.java) startActivity(intent) } .addOnFailureListener { // Since the image failed to upload we want to enable the button again. Toast.makeText( applicationContext, "Unable to upload image please try again.", Toast.LENGTH_SHORT ).show() } } } categoryTextView.addTextChangedListener(object: TextWatcher { override fun afterTextChanged(p0: Editable?) { if (categoryTextView.text.toString() != ""){ viewGradesButton.isEnabled = true } } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { if (categoryTextView.text.toString() == ""){ viewGradesButton.isEnabled = false } } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { if (categoryTextView.text.toString() != ""){ viewGradesButton.isEnabled = true } } }) } /** * Runs subject detection on the provided image from CameraActivity */ private fun runSubjectDetection() { capturedImage?.let { // Required format for images is ARGB_8888, otherwise will throw Config#Hardware getPixels error. val image = it.copy( Bitmap.Config.ARGB_8888, true ) inputImageView.setImageBitmap(image) val detectedSubjectsList = image.let { inputImage -> subjectDetector.detectSubjects(inputImage) } selectedSubjectBoundingBox = detectedSubjectsList.maxBy { detectedSubject -> (detectedSubject.subjectBoundingBox.width() * detectedSubject.subjectBoundingBox.height()) }?.subjectBoundingBox ?: RectF() // Convert to MLKIT InputImage val inputImage = InputImage.fromBitmap(image, 0) // Wait for imageView to initialize parameters before running. // Otherwise, width and height will return 0. inputImageView.post { run { if (detectedSubjectsList.isNotEmpty()) { if (detectedSubjectsList.size == 1) { revealSubjectsButton.isEnabled = false } onSubjectsDetected(detectedSubjectsList, inputImage) } else { Toast.makeText( applicationContext, "No subjects detected", Toast.LENGTH_LONG ).show() revealSubjectsButton.isEnabled = false viewGradesButton.isEnabled = false revealSubjectsButton.visibility = View.INVISIBLE selectedSubjectLabel = "" updateCategoryTextView() // Redirect users back to upload/capture val alertDialog = AlertDialog.Builder(this) alertDialog.setMessage("No subject detected, try uploading or capturing again.") .setPositiveButton("Ok" ) { dialogInterface, _ -> run { // Return the user to either capture or upload captureMode = intent.getBooleanExtra("CAPTURE_MODE", false) uploadMode = intent.getBooleanExtra("UPLOAD_MODE", false) if (captureMode) { val intent = Intent( this.applicationContext, CameraActivity::class.java ) capturedImage?.recycle() startActivity(intent) } if (uploadMode) { val intent = Intent( this.applicationContext, NavigationActivity::class.java ) intent.putExtra("CAPTURE_MODE", false) .putExtra("UPLOAD_MODE", true) capturedImage?.recycle() startActivity(intent) } dialogInterface.dismiss() } } alertDialog.create().show() } } } } } @SuppressLint("CommitPrefEdits") private fun onSubjectsDetected( subjectsDetectedList: List<SubjectDetected>, inputImage: InputImage ) { subjectOverlayViewContainer.removeAllViews() // Select the most prominent subject as the main subject val mostProminentSubject = subjectsDetectedList.maxBy { subject -> (subject.subjectBoundingBox.width() * subject.subjectBoundingBox.height()) } // Create a Tap-able dot view for every subject on the picture. for (subjectDetected in subjectsDetectedList) { val pcSubjectDetected = PCSubjectDetected(subjectDetected, subjectDetected.subjectBoundingBox, inputImage) val subjectDotView = createSubjectDotView(pcSubjectDetected, true) if (subjectDetected == mostProminentSubject) { val boxView = SubjectBoundingBoxView( this, subjectDotView.boxInViewBoundingBox ) boxView.tag = "Selected Bounding Box" subjectOverlayViewContainer.addView(boxView) selectedSubjectBoundingBox = subjectDetected.subjectBoundingBox runLabeler(pcSubjectDetected) subjectDotView.visibility = View.VISIBLE animateBoxView(boxView) subjectDotView.tag = "Selected Subject" } else { subjectDotView.visibility = View.INVISIBLE } subjectDotView.setOnClickListener { runLabeler(pcSubjectDetected) for (view in subjectOverlayViewContainer.children) { // Remove the previously selected boxView and update this as the new bounding box view if (view.tag == "Selected Bounding Box") { subjectOverlayViewContainer.removeView(view) val boxView = SubjectBoundingBoxView( this, subjectDotView.boxInViewBoundingBox ) boxView.tag = "Selected Bounding Box" subjectOverlayViewContainer.addView(boxView) animateBoxView(boxView) } if (view.tag == "Selected Subject") { view.tag = "" subjectDotView.tag = "Selected Subject" } } animateDotView(subjectDotView) } subjectDotView.setOnLongClickListener { runLabelerLongClick(pcSubjectDetected) for (view in subjectOverlayViewContainer.children) { // Remove the previously selected boxView and update this as the new bounding box view if (view.tag == "Selected Bounding Box") { subjectOverlayViewContainer.removeView(view) val boxView = SubjectBoundingBoxView( this, subjectDotView.boxInViewBoundingBox ) boxView.tag = "Selected Bounding Box" subjectOverlayViewContainer.addView(boxView) animateBoxView(boxView) } if (view.tag == "Selected Subject") { view.tag = "" subjectDotView.tag = "Selected Subject" animateDotView(subjectDotView) } } return@setOnLongClickListener true } subjectOverlayViewContainer.addView(subjectDotView) } revealSubjectsButton.setOnCheckedChangeListener { _, isChecked -> // Subjects revealed if (isChecked) { for (view in subjectOverlayViewContainer.children) { if (view.visibility == View.INVISIBLE && view.tag != "Selected Subject" && view.tag != "Selected Bounding Box") { view.visibility = View.VISIBLE } } if (sharedPreferences.getBoolean("DISPLAYDIALOG", true)) { val alertDialog = AlertDialog.Builder(this) val rememberLabel = arrayOf("Don't show again.") var remember = false alertDialog.setMessage("Tap on the dot in the image to select your subject.") .setSingleChoiceItems( rememberLabel, 0 ) { _: DialogInterface, _: Int -> remember = !remember } .setPositiveButton("Ok" ) { dialogInterface, _ -> run { if (remember) { sharedPreferences.edit().putBoolean("DISPLAYDIALOG", false) } dialogInterface.dismiss() } } alertDialog.create().show() } } // Subjects hidden else { for (view in subjectOverlayViewContainer.children) { if (view.visibility == View.VISIBLE && view.tag != "Selected Subject" && view.tag != "Selected Bounding Box") { view.visibility = View.INVISIBLE } } } } } private fun animateDotView(targetView: View) { val animatorSet = AnimatorInflater.loadAnimator( this, R.animator.subject_dot_enter ) as AnimatorSet animatorSet.setTarget(targetView) animatorSet.start() } private fun animateBoxView(targetView: View) { val animatorSet = AnimatorInflater.loadAnimator( this, R.animator.subject_bounding_box_enter ) as AnimatorSet animatorSet.setTarget(targetView) animatorSet.start() } private fun runLabelerLongClick(pcSubjectDetected: PCSubjectDetected) { val croppedInputImage = InputImage.fromBitmap( pcSubjectDetected.imageData?.let { it1 -> ImageUtility.byteArrayToBitmap( it1 ) }, 0 ) val highAccuracyOpts = FaceDetectorOptions.Builder() .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST) .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL) .build() val faceDetector = FaceDetection.getClient(highAccuracyOpts) val arrayAdapter = ArrayAdapter<String>( this, android.R.layout.select_dialog_singlechoice ) faceDetector.process(croppedInputImage) .addOnSuccessListener { faces -> if (faces.size != 0) { selectedSubjectLabel = "Portrait" categoryTextView.text = selectedSubjectLabel.toUpperCase(Locale.ROOT) arrayAdapter.insert(selectedSubjectLabel, 0) } } val labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS) labeler.process(croppedInputImage) .addOnSuccessListener { subjectLabelList -> if (subjectLabelList.size != 0) { for (i in 0 until subjectLabelList.size) { if (i < 5) { arrayAdapter.add(subjectLabelList[i].text) } } val imageView = ImageView(applicationContext) imageView.maxHeight = 50 imageView.setImageBitmap(croppedInputImage.bitmapInternal) AlertDialog.Builder(this) .setTitle("Choose Subject Label") .setView(imageView) .setAdapter( arrayAdapter ) { _, which -> selectedSubjectBoundingBox = pcSubjectDetected.subjectBoundingBox selectedSubjectLabel = arrayAdapter.getItem(which) ?.toUpperCase(Locale.ROOT).toString() categoryTextView.text = arrayAdapter.getItem(which) ?.toUpperCase(Locale.ROOT) updateCategoryTextView() }.setNegativeButton( "Cancel" ) { dialog, _ -> dialog?.dismiss() }.show() } else { Toast.makeText( applicationContext, "Cannot identify subject, try again.", Toast.LENGTH_SHORT ).show() } } } private fun runLabeler(pcSubjectDetected: PCSubjectDetected) { selectedSubjectBoundingBox = pcSubjectDetected.subjectBoundingBox val croppedInputImage = InputImage.fromBitmap( pcSubjectDetected.imageData?.let { it1 -> ImageUtility.byteArrayToBitmap( it1 ) }, 0 ) val highAccuracyOpts = FaceDetectorOptions.Builder() .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST) .build() val faceDetector = FaceDetection.getClient(highAccuracyOpts) faceDetector.process(croppedInputImage) .addOnSuccessListener { faces -> if (faces.size != 0) { selectedSubjectLabel = "Portrait" categoryTextView.text = selectedSubjectLabel.toUpperCase(Locale.ROOT) updateCategoryTextView() for (face in faces) { } } else { val labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS) labeler.process(croppedInputImage) .addOnSuccessListener { subjectLabelList -> if (subjectLabelList.size != 0) { selectedSubjectLabel = subjectLabelList.maxBy { subjectDetected -> subjectDetected.confidence }!!.text selectedSubjectConfidenceScore = subjectLabelList.maxBy { subjectDetected -> subjectDetected.confidence }!!.confidence updateCategoryTextView() } else { Toast.makeText( applicationContext, "Cannot identify subject, try again.", Toast.LENGTH_SHORT ).show() } } .addOnFailureListener { Toast.makeText( applicationContext, "Cannot identify subject, try again.", Toast.LENGTH_SHORT ).show() } } } .addOnFailureListener { } } private fun updateCategoryTextView() { categoryTextView.text = selectedSubjectLabel.toUpperCase(Locale.ROOT) categoryTextView.invalidate() categoryTextView.forceLayout() // categoryTextView.requestLayout() // this requires the whole screen to be redrawn causing slow reload val animatorSet = AnimatorInflater.loadAnimator( this, R.animator.subject_bounding_box_enter ) as AnimatorSet animatorSet.setTarget(categoryTextView) animatorSet.start() } override fun onResume() { super.onResume() val intentFilterSelectedSubjectLabelUpdate = IntentFilter("SELECTED_SUBJECT_LABEL_UPDATE") val intentReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { categoryTextView.text = selectedSubjectLabel.toUpperCase(Locale.ROOT) categoryTextView.invalidate() categoryTextView.requestLayout() } } this.registerReceiver(intentReceiver, intentFilterSelectedSubjectLabelUpdate) } /** * Creates a dot view for every subject in the picture. */ private fun createSubjectDotView( subject: PCSubjectDetected, selected: Boolean ): SubjectDotView { val viewCoordinateScale: Float val horizontalGap: Float val verticalGap: Float val inputImageView = inputImageView val inputBitmap = capturedImage ?: throw NullPointerException() val inputImageViewRatio = inputImageView.width.toFloat() / inputImageView.height val inputBitmapRatio = inputBitmap.width.toFloat() / inputBitmap.height if (inputBitmapRatio <= inputImageViewRatio) { // Image content fills height viewCoordinateScale = inputImageView.height.toFloat() / inputBitmap.height horizontalGap = (inputImageView.width - inputBitmap.width * viewCoordinateScale) / 2 verticalGap = 0f } else { // Image content fills width viewCoordinateScale = inputImageView.width.toFloat() / inputBitmap.width horizontalGap = 0f verticalGap = (inputImageView.height - inputBitmap.height * viewCoordinateScale) / 2 } val subjectBoundingBox = subject.subjectBoundingBox // Calculate corresponding coordinate. val boxInViewCoordinate = RectF( subjectBoundingBox.left * viewCoordinateScale + horizontalGap, subjectBoundingBox.top * viewCoordinateScale + verticalGap, subjectBoundingBox.right * viewCoordinateScale + horizontalGap, subjectBoundingBox.bottom * viewCoordinateScale + verticalGap ) val dotView = SubjectDotView(this, selected, boxInViewCoordinate) val layoutParams = FrameLayout.LayoutParams(dotViewSize, dotViewSize) val dotCenter = PointF( (boxInViewCoordinate.right + boxInViewCoordinate.left) / 2, (boxInViewCoordinate.bottom + boxInViewCoordinate.top) / 2 ) layoutParams.setMargins( (dotCenter.x - dotViewSize / 2f).toInt(), (dotCenter.y - dotViewSize / 2f).toInt(), 0, 0 ) dotView.layoutParams = layoutParams return dotView } }
0
Kotlin
0
1
cda1cc5e6ab9f27cd37abd59f630fb0be3d85280
33,008
Photo-Composer
MIT License
app/src/main/java/com/rafay/gallery/di/AppModule.kt
rafayali
336,757,542
false
null
package com.rafay.gallery.di import com.rafay.gallery.api.ApiProvider import com.rafay.gallery.api.RetrofitApiProvider import org.koin.dsl.module val appModule = module { single<ApiProvider> { RetrofitApiProvider() } }
0
Kotlin
1
1
e5614032d391a6a4719a701010ff8141c8b6c3ce
225
PixabayGallery
MIT License
location/src/main/java/com/delbel/fluent/location/PermissionStateStorage.kt
matiasdelbel
254,102,707
false
null
package com.delbel.fluent.location import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import androidx.core.content.edit import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import javax.inject.Inject internal class PermissionStateStorage @Inject constructor(private val preferences: SharedPreferences) { private val preferencesListener = OnSharedPreferenceChangeListener { _, key -> if (key != KEY_FOREGROUND_ENABLED) return@OnSharedPreferenceChangeListener state.onNext(isForegroundEnabled()) } init { preferences.registerOnSharedPreferenceChangeListener(preferencesListener) } private val state = PublishSubject.create<Boolean>() fun state(): Observable<Boolean> = state.startWith(isForegroundEnabled()) fun save(areLocationPermissionEnable: Boolean) = preferences.edit { putBoolean(KEY_FOREGROUND_ENABLED, areLocationPermissionEnable) } private fun isForegroundEnabled() = preferences.getBoolean(KEY_FOREGROUND_ENABLED, false) companion object { private const val KEY_FOREGROUND_ENABLED = "tracking_foreground_location" } }
1
Kotlin
0
0
e6003db9ceda2a48284835d96a500525f03c244b
1,189
android-poc-fluent
Apache License 2.0
8vim/src/main/kotlin/inc/flide/vim8/lib/compose/AppTheme.kt
8VIM
72,917,629
false
null
package inc.flide.vim8.lib.compose import androidx.compose.material3.ColorScheme import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import inc.flide.vim8.theme.typography @Composable fun AppTheme(colorScheme: ColorScheme, content: @Composable () -> Unit) { MaterialTheme( colorScheme = colorScheme, typography = colorScheme.typography(), content = content ) }
73
null
61
461
089482f6bb5f715bc9168b8289957cee865573ae
434
8VIM
Apache License 2.0
lab2/src/main/kotlin/servlet/AreaCheckServlet.kt
band-of-four
152,893,488
false
null
package servlet import com.google.gson.Gson import com.google.gson.JsonArray import java.lang.NumberFormatException import javax.servlet.annotation.WebServlet import javax.servlet.http.HttpServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import kotlin.math.abs import kotlin.math.sqrt @WebServlet(name = "AreaCheckServlet") class AreaCheckServlet : HttpServlet() { override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) { try { val x = req.getParameter("x").toDouble() val y = req.getParameter("y").toDouble() val r = req.getParameter("r").toDouble() if (r <= 0) throw NumberFormatException("Radius can't be less than 0") resp.contentType = "application/json" val isIn = checkHit(x, y, r) val gson = Gson() if (req.session.getAttribute("responses") == null) { req.session.setAttribute("responses", "[]") } val arrayResponse = if (!req.session.isNew) { gson.fromJson<JsonArray>(req.session .getAttribute("responses").toString(), JsonArray::class.java) } else JsonArray() arrayResponse.add(gson.toJson(Response(isIn, x, y, r))) req.session.setAttribute("responses", arrayResponse) resp.writer.write(gson.toJson(arrayResponse)) } catch (e: Exception) { e.printStackTrace() resp.sendError(400, e.message) } } private fun checkHit(x: Double, y: Double, r: Double): Boolean { if (r <= 0) { return false } if (x in 0.0..r / 2 && y in 0.0..r) { return true } if (x in 0.0..r && y in -r..0.0 && sqrt(x * x + y * y) <= r) { return true } if (x in -r..0.0 && y in -r / 2..0.0 && abs(x) + 2*abs(y) <= r) { return true } return false } } data class Response(val isIn: Boolean, val x: Double, val y: Double, val radius: Double)
0
Kotlin
0
4
f20d2c076d9281c4696ab1d33b649c721fb3b011
1,894
pipchansky
Creative Commons Zero v1.0 Universal
app/src/main/java/com/cocdetails/utils/PathUtils.kt
iKhan1057
571,087,717
false
null
package com.cocdetails.utils object PathUtils { fun getCompletePath(sec: String, name: String): String { return when (sec) { "hv" -> { when (name) { "bowler", "golem", "headhunter", "hog", "ice_golem", "lava", "minion", "valkyrie", "witch" -> "/$name" "archer", "baby_dragon", "balloon", "barbarian", "dragon", "dragon_rider", "electro_dragon", "giant", "goblin", "healer", "miner", "pekka", "wall_breaker", "wizard", "yeti" -> "/$name" "archer_queen", "barbarian_king", "grand_warden", "royal_champion" -> "/$name" "electro_owl", "lassi", "mighty_yak", "unicorn", "poison_lizard", "phoenix", "diggy", "frosty" -> "/$name" "battle_blimp", "log_launcher", "siege_barracks", "stone_slammer", "flame_flinger", "battle_drill" -> "/$name" "army", "army_camp", "barracks", "dark_barracks", "dark_spell_factory", "laboratory", "pet_house", "spell_factory", "workshop" -> "/$name" "monolith","spell_tower","archer_tower","cannon","air_defense","air_sweeper","bomb_tower","builders_hut","eagle_artillery","giga_inferno_13","giga_inferno_14","giga_inferno_15","giga_tesla","hidden_tesla","inferno_tower","mortar","scattershot","walls","wizard_tower","x_bow"->"/$name" "air_bomb","bomb","giant_bomb","seeking_air_mine","skeleton_trap","spring_trap","tornado_trap"->"/$name" "resourse","gold_storage","gold_mine","elixir_storage","elixir_collector","dark_elixir_storage","dark_elixir_drill","clan_castle"-> "home/buildings/resource/$name" "army_buildings","defensive_building","levels","resourse_building","storage","trap" -> "home/buildings/resource/th/$name" "bat_spell","earthquake_spell","haste_spell","poison_spell","skeleton_spell"->"home/spells/dark/$name" "recall_spell","clone_spell","freeze_spell","healing_spell","invisibility_spell","jump_spell","lightning_spell","rage_spell"->"home/spells/elixir/$name" else -> "" } } "bb" -> "" "cc" -> "" else -> "" } } }
0
Kotlin
0
0
761228f09ea423a1745e556330c4c2b34fe0af38
2,252
cocinfo
Apache License 2.0
src/commonMain/kotlin/org/daiv/tick/list/readerWriter/ListReaderWriterFactory.kt
henry1986
625,890,395
false
null
package org.daiv.tick.list.readerWriter import mu.KotlinLogging import org.daiv.tick.* interface ListReaderWriterFactory { val storingFile: StoringFile fun create(lrwCreator: IOStreamGenerator): ListReaderWriter object LRWStrategyFactory : ListReaderWriterFactory { override val storingFile: StoringFile = WithRead override fun create(lrwCreator: IOStreamGenerator): ListReaderWriter { return LRWStrategy(lrwCreator) } } object StepByStepFactory : ListReaderWriterFactory { override val storingFile: StoringFile = WithoutRead override fun create(lrwCreator: IOStreamGenerator): ListReaderWriter { return StepByStepPlacer(lrwCreator) } } } class LRWStrategy(creator: IOStream) : ListReaderWriter, IOStream by creator { override fun <T> store(mapper: StreamMapper<T>, ticks: List<T>) { val d = getNativeDataReceiver() try { d.writeInt(ticks.size) ticks.forEach { mapper.toOutput(it, d) } d.flush() } finally { d.close() } } private fun <T> readFlexibleSizedData(mapper: StreamMapper<out T>): List<T> { val d = readStream() val ticks = mutableListOf<T>() try { val maxEntrys = d.readInt() for (i in 1..maxEntrys) { val stringLength = try { d.readInt() } catch (t: Throwable) { logger.error { "could not read anymore, currently read: $ticks" } break } val x = mapper.size + stringLength ticks.add(mapper.toElement(read(x, d))) } } finally { d.close() } return ticks } override fun <T> read(mapper: StreamMapper<out T>): List<T> { if (mapper is FlexibleStreamMapper) { return readFlexibleSizedData(mapper) } val d = readStream() val ticks = mutableListOf<T>() try { val size = d.readInt() * mapper.size // logger.trace { "file: $fileName size: $size" } val buffer = read(size, d) for (i in 1..(size / mapper.size)) { ticks.add(mapper.toElement(buffer)) } } finally { d.close() } return ticks } companion object { private val logger = KotlinLogging.logger { } } }
0
Kotlin
0
0
b8aec9056873d57dc56e04f9f1b9fb4f0a3ca240
2,483
timebased-datacompress
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/ServerOff.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline 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.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.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.ServerOff: ImageVector get() { if (_serverOff != null) { return _serverOff!! } _serverOff = Builder(name = "ServerOff", 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 = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 12.0f) horizontalLineToRelative(-6.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, -3.0f) verticalLineToRelative(-2.0f) curveToRelative(0.0f, -1.083f, 0.574f, -2.033f, 1.435f, -2.56f) moveToRelative(3.565f, -0.44f) horizontalLineToRelative(10.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, 3.0f) verticalLineToRelative(2.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, 3.0f) horizontalLineToRelative(-2.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.0f, 12.0f) horizontalLineToRelative(2.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, 3.0f) verticalLineToRelative(2.0f) moveToRelative(-1.448f, 2.568f) arcToRelative(2.986f, 2.986f, 0.0f, false, true, -1.552f, 0.432f) horizontalLineToRelative(-12.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, -3.0f) verticalLineToRelative(-2.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, -3.0f) horizontalLineToRelative(6.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.0f, 8.0f) verticalLineToRelative(0.01f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.0f, 16.0f) verticalLineToRelative(0.01f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 3.0f) lineToRelative(18.0f, 18.0f) } } .build() return _serverOff!! } private var _serverOff: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
3,999
compose-icon-collections
MIT License
feature/chat/src/main/kotlin/io/github/guowenlong/chatgptforandroid/chat/translation/adapter/TranslationUserViewBinder.kt
Wenlong-Guo
620,623,768
false
null
package io.github.guowenlong.chatgptforandroid.chat.translation.adapter import io.github.guowenlong.chatgptforandroid.chat.R import io.github.guowenlong.chatgptforandroid.chat.databinding.ItemTranslationUserBinding import io.github.guowenlong.chatgptforandroid.common.base.BaseBindingViewBinder import io.github.guowenlong.chatgptforandroid.common.base.BaseBindingViewHolder import io.github.guowenlong.chatgptforandroid.model.UserTranslation import java.text.SimpleDateFormat import java.util.* /** * Description: 用户翻译item * Author: 郭文龙 * Date: 2023/4/12 18:17 * Email: <EMAIL> */ class TranslationUserViewBinder(override val itemLayoutId: Int = R.layout.item_translation_user) : BaseBindingViewBinder<UserTranslation, ItemTranslationUserBinding>() { override fun bindData( holder: BaseBindingViewHolder<ItemTranslationUserBinding>, itemData: UserTranslation, binding: ItemTranslationUserBinding ) { binding.tvTime.text = SimpleDateFormat("MM-dd HH:mm:ss", Locale.getDefault()).format(Date(itemData.time)) binding.tvFile.text = itemData.filePath } }
0
Kotlin
1
6
af7966f1b6163462dee1ed897aa036a7722dbedd
1,144
ChatGPT-For-Android
Apache License 2.0
app/src/main/java/org/abishek/vaccinechecker/Constants.kt
abishekvashok
376,521,455
false
null
package org.abishek.vaccinechecker object Constants { object ConstantSharedPreferences { const val name = "VaccineCheckerSharedPref" const val district_id = "districtID" const val pincode = "pincode" const val category = "age_category" const val mode_set = 1 const val mode_unset = 2 const val mode_found = 3 const val mode_set_found = 4 const val mode = "mode" const val search_with = "search_with" const val center_name = "center_name" const val center_address = "center_address" const val capacity = "capacity" const val autostart = "autostart" const val autostart_enabled = 1 const val autostart_disabled = 0 const val dose_mode = "dose_mode" const val dose1 = 1 const val dose2 = 2 const val price_free = "price_free" const val price_paid = "price_paid" } object SearchWith { const val pincode = 1 const val district = 2 } const val NOTIFICATION_CHANNEL_ID = "Main Notifications" const val NOTIFICATION_ID = 123 const val NOTIFICATION_CHANNEL_V_ID = "Vaccine Found Notifications" const val NOTIFICATION_V_ID = 456 val district_ids = listOf("3","1","2","9","10","11","5","4","7","12","13","14","8","15","16","6","22","20","25","23","42","17","24","27","21","33","29","40","31","18","32","36","19","39","35","37","30","26","34","41","28","38","46","47","765","57","66","766","58","48","62","59","43","67","60","53","68","764","54","49","50","51","69","61","63","767","55","56","52","44","64","768","45","65","769","74","78","77","83","98","82","99","100","94","105","79","104","107","91","80","75","101","76","84","70","95","85","86","90","92","97","73","81","71","96","102","93","87","88","103","72","89","106","108","110","111","112","113","114","115","116","117","118","119","120","136","121","122","123","135","124","125","126","127","128","129","130","109","131","132","133","134","137","141","145","140","146","147","143","148","149","144","150","142","151","152","154","770","174","179","158","159","180","175","771","176","181","182","163","168","153","772","177","169","773","178","774","156","170","183","160","171","184","164","185","161","172","173","775","162","165","776","157","166","155","777","167","193","200","201","199","196","188","191","189","204","190","203","186","206","205","207","187","195","202","192","194","198","197","219","214","217","213","216","211","210","215","208","212","209","218","224","223","225","229","232","228","230","234","231","221","226","238","227","237","235","239","236","222","220","233","242","245","253","257","258","247","243","256","262","251","255","259","252","241","244","250","261","246","254","240","260","248","249","263","270","276","265","294","264","274","272","271","273","291","268","269","275","278","280","267","289","279","283","277","282","290","266","284","292","287","288","286","281","293","285","301","307","306","297","295","298","304","305","302","308","300","296","303","299","309","310","796","311","320","357","334","354","338","343","362","351","312","342","328","337","327","350","324","341","336","348","313","361","360","314","315","340","353","339","344","335","319","347","352","323","326","359","358","322","316","317","333","356","349","332","321","346","345","331","330","325","318","329","355","391","364","366","397","384","370","367","380","388","379","378","386","390","396","371","383","395","365","382","387","389","381","394","385","363","393","372","373","376","374","375","392","377","369","368","398","399","400","401","402","410","413","409","408","412","411","403","404","407","405","406","424","418","414","423","417","421","422","415","420","416","419","425","426","429","428","432","431","427","430","433","434","444","441","438","437","439","435","443","440","436","442","445","448","447","472","454","468","457","473","458","467","449","459","460","474","464","450","461","455","446","451","469","456","470","462","465","463","471","452","466","453","476","477","475","478","485","483","493","499","484","487","480","489","481","492","479","488","482","491","486","494","497","498","496","500","490","495","507","512","519","516","528","508","523","501","514","521","530","511","524","520","517","505","506","527","533","515","510","502","525","503","532","529","522","518","534","513","531","509","526","504","535","537","538","536","779","555","578","565","571","778","539","547","566","556","563","552","557","544","559","780","562","540","576","558","577","564","573","570","575","546","567","781","545","561","580","551","541","569","554","560","548","550","568","572","553","574","543","542","549","582","583","581","584","585","586","587","588","589","590","591","592","593","594","595","596","612","597","598","613","599","600","601","602","603","604","605","606","607","608","609","610","611","614","615","616","617","618","619","620","621","622","623","625","626","627","628","646","629","630","631","632","633","634","635","636","637","638","687","639","640","641","642","643","644","645","647","648","649","650","651","652","653","654","655","656","657","658","659","660","661","662","663","664","665","666","667","668","669","670","671","672","673","674","675","676","677","678","679","680","682","624","681","683","684","685","686","688","689","690","691","692","693","694","695","696","704","707","699","708","697","702","709","698","706","700","701","705","703","710","711","712","713","714","715","783","716","717","718","719","720","721","722","723","724","725","726","727","728","729","730","731","732","733","734","735","736","737","138","139") val district_names = listOf("Nicobar","North and Middle Andaman","South Andaman","Anantapur","Chittoor","East Godavari","Guntur","Krishna","Kurnool","Prakasam","Sri Potti Sriramulu Nellore","Srikakulam","Visakhapatnam","Vizianagaram","West Godavari","YSR District","Anjaw","Changlang","Dibang Valley","East Kameng","East Siang","Itanagar Capital Complex","Kamle","Kra Daadi","Kurung Kumey","Lepa Rada","Lohit","Longding","Lower Dibang Valley","Lower Siang","Lower Subansiri","Namsai","Pakke Kessang","Papum Pare","Shi Yomi","Siang","Tawang","Tirap","Upper Siang","Upper Subansiri","West Kameng","West Siang","Baksa","Barpeta","Biswanath","Bongaigaon","Cachar","Charaideo","Chirang","Darrang","Dhemaji","Dhubri","Dibrugarh","Dima Hasao","Goalpara","Golaghat","Hailakandi","Hojai","Jorhat","Kamrup Metropolitan","Kamrup Rural","Karbi-Anglong","Karimganj","Kokrajhar","Lakhimpur","Majuli","Morigaon","Nagaon","Nalbari","Sivasagar","Sonitpur","South Salmara Mankachar","Tinsukia","Udalguri","West Karbi Anglong","Araria","Arwal","Aurangabad","Banka","Begusarai","Bhagalpur","Bhojpur","Buxar","Darbhanga","East Champaran","Gaya","Gopalganj","Jamui","Jehanabad","Kaimur","Katihar","Khagaria","Kishanganj","Lakhisarai","Madhepura","Madhubani","Munger","Muzaffarpur","Nalanda","Nawada","Patna","Purnia","Rohtas","Saharsa","Samastipur","Saran","Sheikhpura","Sheohar","Sitamarhi","Siwan","Supaul","Vaishali","West Champaran","Chandigarh","Balod","Baloda bazar","Balrampur","Bastar","Bemetara","Bijapur","Bilaspur","Dantewada","Dhamtari","Durg","Gariaband","Gaurela Pendra Marwahi ","Janjgir-Champa","Jashpur","Kanker","Kawardha","Kondagaon","Korba","Koriya","Mahasamund","Mungeli","Narayanpur","Raigarh","Raipur","Rajnandgaon","Sukma","Surajpur","Surguja","Dadra and Nagar Haveli","Central Delhi","East Delhi","New Delhi","North Delhi","North East Delhi","North West Delhi","Shahdara","South Delhi","South East Delhi","South West Delhi","West Delhi","North Goa","South Goa","Ahmedabad","Ahmedabad Corporation","Amreli","Anand","Aravalli","Banaskantha","Bharuch","Bhavnagar","Bhavnagar Corporation","Botad","Chhotaudepur","Dahod","Dang","Devbhumi Dwaraka","Gandhinagar","Gandhinagar Corporation","Gir Somnath","Jamnagar","Jamnagar Corporation","Junagadh","Junagadh Corporation","Kheda","Kutch","Mahisagar","Mehsana","Morbi","Narmada","Navsari","Panchmahal","Patan","Porbandar","Rajkot","Rajkot Corporation","Sabarkantha","Surat","Surat Corporation","Surendranagar","Tapi","Vadodara","Vadodara Corporation","Valsad","Ambala","Bhiwani","Charkhi Dadri","Faridabad","Fatehabad","Gurgaon","Hisar","Jhajjar","Jind","Kaithal","Karnal","Kurukshetra","Mahendragarh","Nuh","Palwal","Panchkula","Panipat","Rewari","Rohtak","Sirsa","Sonipat","Yamunanagar","Bilaspur","Chamba","Hamirpur","Kangra","Kinnaur","Kullu","Lahaul Spiti","Mandi","Shimla","Sirmaur","Solan","Una","Anantnag","Bandipore","Baramulla","Budgam","Doda","Ganderbal","Jammu","Kathua","Kishtwar","Kulgam","Kupwara","Poonch","Pulwama","Rajouri","Ramban","Reasi","Samba","Shopian","Srinagar","Udhampur","Bokaro","Chatra","Deoghar","Dhanbad","Dumka","East Singhbhum","Garhwa","Giridih","Godda","Gumla","Hazaribagh","Jamtara","Khunti","Koderma","Latehar","Lohardaga","Pakur","Palamu","Ramgarh","Ranchi","Sahebganj","Seraikela Kharsawan","Simdega","West Singhbhum","Bagalkot","Bangalore Rural","Bangalore Urban","BBMP","Belgaum","Bellary","Bidar","Chamarajanagar","Chikamagalur","Chikkaballapur","Chitradurga","Dakshina Kannada","Davanagere","Dharwad","Gadag","Gulbarga","Hassan","Haveri","Kodagu","Kolar","Koppal","Mandya","Mysore","Raichur","Ramanagara","Shimoga","Tumkur","Udupi","Uttar Kannada","Vijayapura","Yadgir","Alappuzha","Ernakulam","Idukki","Kannur","Kasaragod","Kollam","Kottayam","Kozhikode","Malappuram","Palakkad","Pathanamthitta","Thiruvananthapuram","Thrissur","Wayanad","Kargil","Leh","Agatti Island","Lakshadweep","Agar","Alirajpur","Anuppur","Ashoknagar","Balaghat","Barwani","Betul","Bhind","Bhopal","Burhanpur","Chhatarpur","Chhindwara","Damoh","Datia","Dewas","Dhar","Dindori","Guna","Gwalior","Harda","Hoshangabad","Indore","Jabalpur","Jhabua","Katni","Khandwa","Khargone","Mandla","Mandsaur","Morena","Narsinghpur","Neemuch","Panna","Raisen","Rajgarh","Ratlam","Rewa","Sagar","Satna","Sehore","Seoni","Shahdol","Shajapur","Sheopur","Shivpuri","Sidhi","Singrauli","Tikamgarh","Ujjain","Umaria","Vidisha","Ahmednagar","Akola","Amravati","Aurangabad ","Beed","Bhandara","Buldhana","Chandrapur","Dhule","Gadchiroli","Gondia","Hingoli","Jalgaon","Jalna","Kolhapur","Latur","Mumbai","Nagpur","Nanded","Nandurbar","Nashik","Osmanabad","Palghar","Parbhani","Pune","Raigad","Ratnagiri","Sangli","Satara","Sindhudurg","Solapur","Thane","Wardha","Washim","Yavatmal","Bishnupur","Chandel","Churachandpur","Imphal East","Imphal West","Jiribam","Kakching","Kamjong","Kangpokpi","Noney","Pherzawl","Senapati","Tamenglong","Tengnoupal","Thoubal","Ukhrul","East Garo Hills","East Jaintia Hills","East Khasi Hills","North Garo Hills","Ri-Bhoi","South Garo Hills","South West Garo Hills","South West Khasi Hills","West Garo Hills","West Jaintia Hills","West Khasi Hills","Aizawl East","Aizawl West","Champhai","Kolasib","Lawngtlai","Lunglei","Mamit","Serchhip","Siaha","Dimapur","Kiphire","Kohima","Longleng","Mokokchung","Mon","Peren","Phek","Tuensang","Wokha","Zunheboto","Angul","Balangir","Balasore","Bargarh","Bhadrak","Boudh","Cuttack","Deogarh","Dhenkanal","Gajapati","Ganjam","Jagatsinghpur","Jajpur","Jharsuguda","Kalahandi","Kandhamal","Kendrapara","Kendujhar","Khurda","Koraput","Malkangiri","Mayurbhanj","Nabarangpur","Nayagarh","Nuapada","Puri","Rayagada","Sambalpur","Subarnapur","Sundargarh","Karaikal","Mahe","Puducherry","Yanam","Amritsar","Barnala","Bathinda","Faridkot","Fatehgarh Sahib","Fazilka","Ferozpur","Gurdaspur","Hoshiarpur","Jalandhar","Kapurthala","Ludhiana","Mansa","Moga","Pathankot","Patiala","Rup Nagar","Sangrur","SAS Nagar","SBS Nagar","Sri Muktsar Sahib","Tarn Taran","Ajmer","Alwar","Banswara","Baran","Barmer","Bharatpur","Bhilwara","Bikaner","Bundi","Chittorgarh","Churu","Dausa","Dholpur","Dungarpur","Hanumangarh","Jaipur I","Jaipur II","Jaisalmer","Jalore","Jhalawar","Jhunjhunu","Jodhpur","Karauli","Kota","Nagaur","Pali","Pratapgarh","Rajsamand","Sawai Madhopur","Sikar","Sirohi","Sri Ganganagar","Tonk","Udaipur","East Sikkim","North Sikkim","South Sikkim","West Sikkim","Aranthangi","Ariyalur","Attur","Chengalpet","Chennai","Cheyyar","Coimbatore","Cuddalore","Dharmapuri","Dindigul","Erode","Kallakurichi","Kanchipuram","Kanyakumari","Karur","Kovilpatti","Krishnagiri","Madurai","Nagapattinam","Namakkal","Nilgiris","Palani","Paramakudi","Perambalur","Poonamallee","Pudukkottai","Ramanathapuram","Ranipet","Salem","Sivaganga","Sivakasi","Tenkasi","Thanjavur","Theni","Thoothukudi (Tuticorin)","Tiruchirappalli","Tirunelveli","Tirupattur","Tiruppur","Tiruvallur","Tiruvannamalai","Tiruvarur","Vellore","Viluppuram","Virudhunagar","Adilabad","Bhadradri Kothagudem","Hyderabad","Jagtial","Jangaon","Jayashankar Bhupalpally","Jogulamba Gadwal","Kamareddy","Karimnagar","Khammam","Kumuram Bheem","Mahabubabad","Mahabubnagar","Mancherial","Medak","Medchal","Mulugu","Nagarkurnool","Nalgonda","Narayanpet","Nirmal","Nizamabad","Peddapalli","Rajanna Sircilla","Rangareddy","Sangareddy","Siddipet","Suryapet","Vikarabad","Wanaparthy","Warangal(Rural)","Warangal(Urban)","Yadadri Bhuvanagiri","Dhalai","Gomati","Khowai","North Tripura","Sepahijala","South Tripura","Unakoti","West Tripura","Agra","Aligarh","Ambedkar Nagar","Amethi","Amroha","Auraiya","Ayodhya","Azamgarh","Badaun","Baghpat","Bahraich","Balarampur","Ballia","Banda","Barabanki","Bareilly","Basti","Bhadohi","Bijnour","Bulandshahr","Chandauli","Chitrakoot","Deoria","Etah","Etawah","Farrukhabad","Fatehpur","Firozabad","Gautam Buddha Nagar","Ghaziabad","Ghazipur","Gonda","Gorakhpur","Hamirpur","Hapur","Hardoi","Hathras","Jalaun","Jaunpur","Jhansi","Kannauj","Kanpur Dehat","Kanpur Nagar","Kasganj","Kaushambi","Kushinagar","Lakhimpur Kheri","Lalitpur","Lucknow","Maharajganj","Mahoba","Mainpuri","Mathura","Mau","Meerut","Mirzapur","Moradabad","Muzaffarnagar","Pilibhit","Pratapgarh","Prayagraj","Raebareli","Rampur","Saharanpur","Sambhal","Sant Kabir Nagar","Shahjahanpur","Shamli","Shravasti","Siddharthnagar","Sitapur","Sonbhadra","Sultanpur","Unnao","Varanasi","Almora","Bageshwar","Chamoli","Champawat","Dehradun","Haridwar","Nainital","Pauri Garhwal","Pithoragarh","Rudraprayag","Tehri Garhwal","Udham Singh Nagar","Uttarkashi","Alipurduar District","Bankura","Basirhat HD (North 24 Parganas)","Birbhum","Bishnupur HD (Bankura)","Cooch Behar","COOCHBEHAR","Dakshin Dinajpur","Darjeeling","Diamond Harbor HD (S 24 Parganas)","East Bardhaman","Hoogly","Howrah","Jalpaiguri","Jhargram","Kalimpong","Kolkata","Malda","Murshidabad","Nadia","Nandigram HD (East Medinipore)","North 24 Parganas","Paschim Medinipore","Purba Medinipore","Purulia","Rampurhat HD (Birbhum)","South 24 Parganas","Uttar Dinajpur","West Bardhaman","Daman","Diu") }
0
Kotlin
1
6
1cbf319b70e9c0d9f7274e61cdaf9e5becce4739
14,690
vaccine-finder
MIT License
alarm-service/core/src/main/kotlin/org/a_cyb/sayitalarm/alarm_service/core/AlarmScheduler.kt
a-cyborg
751,578,623
false
{"Kotlin": 719375}
/* * Copyright (c) 2024 Mima Kang / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package org.a_cyb.sayitalarm.alarm_service.core import android.content.Context import androidx.work.Data import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import org.a_cyb.sayitalarm.domain.alarm_service.AlarmServiceContract import org.a_cyb.sayitalarm.entity.Snooze class AlarmScheduler( private val context: Context, ) : AlarmServiceContract.AlarmScheduler { override fun scheduleAlarms() { val data = Data.Builder() .putInt(SCHEDULER_WORKER_WORK_TYPE, SCHEDULER_WORKER_WORK_SET_ALARM) .build() enqueueWork(data) } override fun scheduleSnooze(alarmId: Long, snooze: Snooze) { val data = Data.Builder() .putInt(SCHEDULER_WORKER_WORK_TYPE, SCHEDULER_WORKER_WORK_SET_SNOOZE) .putLong(SCHEDULER_WORKER_INPUT_DATA_ALARM_ID, alarmId) .putInt(SCHEDULER_WORKER_INPUT_DATA_SNOOZE_MIN, snooze.snooze) .build() enqueueWork(data) } override fun cancelAlarm(alarmId: Long) { val data = Data.Builder() .putInt(SCHEDULER_WORKER_WORK_TYPE, SCHEDULER_WORKER_WORK_CANCEL_ALARM) .putLong(SCHEDULER_WORKER_INPUT_DATA_ALARM_ID, alarmId) .build() enqueueWork(data) } private fun enqueueWork(data: Data) { val request = OneTimeWorkRequestBuilder<AlarmSchedulerWorker>() .setInputData(data) .build() WorkManager .getInstance(context) .enqueue(request) } companion object { const val SCHEDULER_WORKER_WORK_TYPE = "org.a_cyb.sayitalarm.SCHEDULER_WORKER_WORK_TYPE" const val SCHEDULER_WORKER_INPUT_DATA_SNOOZE_MIN = "org.a_cyb.sayitalarm.SCHEDULER_WORKER_INPUT_DATA_SNOOZE_MIN" const val SCHEDULER_WORKER_INPUT_DATA_ALARM_ID = "org.a_cyb.sayitalarm.SCHEDULER_WORKER_INPUT_DATA_ALARM_ID" const val SCHEDULER_WORKER_WORK_SET_ALARM = 30145 const val SCHEDULER_WORKER_WORK_SET_SNOOZE = 13946 const val SCHEDULER_WORKER_WORK_CANCEL_ALARM = 13049 const val INTENT_ACTION_DELIVER_ALARM = "org.a_cyb.sayitalarm.DELIVER_ALARM" const val INTENT_EXTRA_ALARM_ID = "org.a_cyb.sayitalarm.EXTRA_ALARM_ID" } }
0
Kotlin
0
0
82b215f149cde250fcdd579a9abcdaa38b591cd2
2,359
SayItAlarm
Apache License 2.0
src/main/kotlin/com/atlassian/performance/tools/jiraactions/page/WebElementExtension.kt
atlassian
162,422,950
false
null
package com.atlassian.performance.tools.jiraactions.page import org.openqa.selenium.JavascriptExecutor import org.openqa.selenium.WebDriver import org.openqa.selenium.WebElement internal fun WebElement.scrollIntoView(driver: WebDriver): WebElement { (driver as JavascriptExecutor).executeScript("arguments[0].scrollIntoView()", this) return this }
7
null
31
26
6172d54002ad54a8064dea60a0547577905afefa
358
jira-actions
Apache License 2.0
app/src/main/java/com/topjohnwu/magisk/ui/module/ModuleRvItem.kt
Joyoe
438,411,665
false
{"C++": 805744, "Kotlin": 431917, "Java": 134018, "Shell": 49395, "Python": 25959, "C": 11376, "Makefile": 4928}
package com.topjohnwu.magisk.ui.module import androidx.databinding.Bindable import com.topjohnwu.magisk.BR import com.topjohnwu.magisk.R import com.topjohnwu.magisk.core.model.module.LocalModule import com.topjohnwu.magisk.core.model.module.OnlineModule import com.topjohnwu.magisk.databinding.DiffRvItem import com.topjohnwu.magisk.databinding.ObservableDiffRvItem import com.topjohnwu.magisk.databinding.RvContainer import com.topjohnwu.magisk.databinding.set object InstallModule : DiffRvItem<InstallModule>() { override val layoutRes = R.layout.item_module_download } class SectionTitle( val title: Int, _button: Int = 0, _icon: Int = 0 ) : ObservableDiffRvItem<SectionTitle>() { override val layoutRes = R.layout.item_section_md2 @get:Bindable var button = _button set(value) = set(value, field, { field = it }, BR.button) @get:Bindable var icon = _icon set(value) = set(value, field, { field = it }, BR.icon) @get:Bindable var hasButton = _button != 0 && _icon != 0 set(value) = set(value, field, { field = it }, BR.hasButton) } class OnlineModuleRvItem( override val item: OnlineModule ) : ObservableDiffRvItem<OnlineModuleRvItem>(), RvContainer<OnlineModule> { override val layoutRes: Int = R.layout.item_repo_md2 @get:Bindable var progress = 0 set(value) = set(value, field, { field = it }, BR.progress) var hasUpdate = false override fun itemSameAs(other: OnlineModuleRvItem): Boolean = item.id == other.item.id } class LocalModuleRvItem( override val item: LocalModule ) : ObservableDiffRvItem<LocalModuleRvItem>(), RvContainer<LocalModule> { override val layoutRes = R.layout.item_module_md2 @get:Bindable var online: OnlineModule? = null set(value) = set(value, field, { field = it }, BR.online) @get:Bindable var isEnabled = item.enable set(value) = set(value, field, { field = it }, BR.enabled) { item.enable = value } @get:Bindable var isRemoved = item.remove set(value) = set(value, field, { field = it }, BR.removed) { item.remove = value } val isUpdated get() = item.updated val isModified get() = isRemoved || isUpdated fun delete(viewModel: ModuleViewModel) { isRemoved = !isRemoved viewModel.updateActiveState() } override fun itemSameAs(other: LocalModuleRvItem): Boolean = item.id == other.item.id }
0
C++
1
2
b6b293331008a207ce70bae47becee351b9809c1
2,474
Magisk_jojo_build23013
MIT License
bee.persistent/src/blaze/kotlin/com/beeproduced/bee/persistent/blaze/meta/dsl/InlineValueUnwrapper.kt
bee-produced
696,363,229
false
{"Kotlin": 760065}
package com.beeproduced.bee.persistent.blaze.meta.dsl /** * * * @author <NAME> * @version 2024-01-11 */ fun interface InlineValueUnwrapper { fun unwrap(inline: Any): Any }
0
Kotlin
0
0
cf8172e6dccb73a4c9ba164525f4d7f22faa15bf
181
bee-built
MIT License
src/main/java/me/shadowalzazel/mcodyssey/enchantments/misc/Yank.kt
ShadowAlzazel
511,383,377
false
{"Kotlin": 1117218}
package me.shadowalzazel.mcodyssey.enchantments.misc import me.shadowalzazel.mcodyssey.enchantments.OdysseyEnchantment import net.minecraft.tags.ItemTags import net.minecraft.world.entity.EquipmentSlot import net.minecraft.world.item.enchantment.Enchantment.constantCost import net.minecraft.world.item.enchantment.Enchantment.dynamicCost import org.bukkit.Material import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemStack object Yank : OdysseyEnchantment( "yank", "Yank", 4, 10, constantCost(8), dynamicCost(8, 10), 3, ItemTags.FISHING_ENCHANTABLE, ItemTags.FISHING_ENCHANTABLE, arrayOf(EquipmentSlot.MAINHAND) ) { override fun canEnchantItem(item: ItemStack): Boolean { return when (item.type) { Material.ENCHANTED_BOOK, Material.FISHING_ROD -> { true } else -> { false } } } }
0
Kotlin
0
3
e284bef718969b7beca44b0c1836c4e9be1a5874
951
MinecraftOdyssey
MIT License
src/main/kotlin/eclipsegaming/MiniGameManager.kt
Apollointhehouse
831,574,625
false
{"Kotlin": 13760, "Java": 7329}
package eclipsegaming import eclipsegaming.EclipseGaming.LOGGER import eclipsegaming.events.EventHandler import eclipsegaming.events.EventManager import eclipsegaming.events.entity.DamageEvent import eclipsegaming.minigames.MiniGame import eclipsegaming.utils.PlayerExtensions.game import net.minecraft.core.player.gamemode.Gamemode import net.minecraft.server.entity.player.EntityPlayerMP object MiniGameManager { init { EventManager.subscribe(this) } fun addPlayer(game: MiniGame, player: EntityPlayerMP) { if (!game.addPlayer(player)) { LOGGER.error("Failed to add player ${player.username} to minigame!") return } player.game = game player.sendMessage("Joined ${game.name} queue") } fun removePlayer(player: EntityPlayerMP) { val game = player.game ?: return game.removePlayer(player) player.setPos(0.0, 12.0, 0.0) player.setGamemode(Gamemode.adventure) player.heal(20 - player.health) } @EventHandler fun onDamage(event: DamageEvent) { val player = event.entity as? EntityPlayerMP ?: return val game = player.game ?: return if (event.amount >= player.health) { game.onPlayerDie(player) event.cancel() } } }
0
Kotlin
0
0
4b4ad7296ccbd0fce1cb12ce1281d8dc1377685d
1,171
EclipseGaming
Creative Commons Zero v1.0 Universal
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Clipboardclose.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bulk import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.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.BulkGroup public val BulkGroup.Clipboardclose: ImageVector get() { if (_clipboardclose != null) { return _clipboardclose!! } _clipboardclose = Builder(name = "Clipboardclose", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.2391f, 3.6499f) horizontalLineTo(7.7591f) curveTo(5.2891f, 3.6499f, 3.2891f, 5.6599f, 3.2891f, 8.1199f) verticalLineTo(17.5299f) curveTo(3.2891f, 19.9899f, 5.2991f, 21.9999f, 7.7591f, 21.9999f) horizontalLineTo(16.2291f) curveTo(18.6991f, 21.9999f, 20.6991f, 19.9899f, 20.6991f, 17.5299f) verticalLineTo(8.1199f) curveTo(20.7091f, 5.6499f, 18.6991f, 3.6499f, 16.2391f, 3.6499f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.3498f, 2.0f) horizontalLineTo(9.6498f) curveTo(8.6098f, 2.0f, 7.7598f, 2.84f, 7.7598f, 3.88f) verticalLineTo(4.82f) curveTo(7.7598f, 5.86f, 8.5998f, 6.7f, 9.6398f, 6.7f) horizontalLineTo(14.3498f) curveTo(15.3898f, 6.7f, 16.2298f, 5.86f, 16.2298f, 4.82f) verticalLineTo(3.88f) curveTo(16.2398f, 2.84f, 15.3898f, 2.0f, 14.3498f, 2.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.5295f, 15.6199f) lineTo(13.0795f, 14.1699f) lineTo(14.4795f, 12.7699f) curveTo(14.7695f, 12.4799f, 14.7695f, 11.9999f, 14.4795f, 11.7099f) curveTo(14.1895f, 11.4199f, 13.7095f, 11.4199f, 13.4195f, 11.7099f) lineTo(12.0195f, 13.1099f) lineTo(10.5695f, 11.6599f) curveTo(10.2795f, 11.3699f, 9.7994f, 11.3699f, 9.5094f, 11.6599f) curveTo(9.2194f, 11.9499f, 9.2194f, 12.4299f, 9.5094f, 12.7199f) lineTo(10.9595f, 14.1699f) lineTo(9.4694f, 15.6599f) curveTo(9.1795f, 15.9499f, 9.1795f, 16.4299f, 9.4694f, 16.7199f) curveTo(9.6194f, 16.8699f, 9.8095f, 16.9399f, 9.9994f, 16.9399f) curveTo(10.1895f, 16.9399f, 10.3795f, 16.8699f, 10.5295f, 16.7199f) lineTo(12.0195f, 15.2299f) lineTo(13.4695f, 16.6799f) curveTo(13.6195f, 16.8299f, 13.8095f, 16.8999f, 13.9995f, 16.8999f) curveTo(14.1895f, 16.8999f, 14.3795f, 16.8299f, 14.5295f, 16.6799f) curveTo(14.8195f, 16.3899f, 14.8195f, 15.9199f, 14.5295f, 15.6199f) close() } } .build() return _clipboardclose!! } private var _clipboardclose: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,248
VuesaxIcons
MIT License
arch-components/src/test/kotlin/com/fibelatti/core/android/EventTest.kt
fibelatti
158,119,258
false
null
package com.fibelatti.core.android import com.fibelatti.core.InstantExecutorExtension import com.fibelatti.core.archcomponents.Event import com.fibelatti.core.archcomponents.EventObserver import com.fibelatti.core.archcomponents.MutableLiveEvent import com.fibelatti.core.test.extension.mock import com.fibelatti.core.test.extension.shouldBe import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mockito.verify @ExtendWith(InstantExecutorExtension::class) class EventTest { private val mockValue = true private lateinit var event: Event<Boolean> @BeforeEach fun setup() { event = Event(mockValue) } @Test fun whenGetContentIsCalledForTheFirstTimeThenValueIsReturned() { event.getContent() shouldBe mockValue } @Test fun givenGetContentWasAlreadyCalledWhenGetContentIsCalledAgainThenNullIsReturned() { event.run { getContent() shouldBe mockValue getContent() shouldBe null } } @Test fun givenGetContentWasAlreadyCalledWhenPeekContentIsCalledThenValueIsReturned() { event.run { getContent() shouldBe mockValue getContent() shouldBe null peekContent() shouldBe mockValue } } @Test fun whenPostValueIsCalledThenObserverFunctionIsCalled() { // GIVEN val mockOnEvent = mock<(Boolean) -> Unit>() val liveEvent = MutableLiveEvent<Boolean>().apply { observeForever(EventObserver(mockOnEvent)) } // WHEN liveEvent.postValue(event) // THEN verify(mockOnEvent).invoke(mockValue) } @Test fun givenPostValueWasAlreadyCalledWhenPostValueIsCalledAgainThenObserverFunctionIsNotCalledAgain() { // GIVEN val mockOnEvent = mock<(Boolean) -> Unit>() val liveEvent = MutableLiveEvent<Boolean>().apply { observeForever(EventObserver(mockOnEvent)) } // WHEN liveEvent.postValue(event) liveEvent.postValue(event) // THEN verify(mockOnEvent).invoke(mockValue) } }
0
Kotlin
0
4
8689cb557e91c9ac4809ab1820bf6f257d96711f
2,188
fibelatti-core
Apache License 2.0
mwheel/src/main/java/com/macv/mwheel/OnRotationListener.kt
MehulKK
331,375,336
false
{"Gradle": 4, "Java Properties": 4, "Shell": 1, "Text": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Ignore List": 2, "Java": 16, "XML": 25, "Kotlin": 21}
package com.macv.mwheel internal interface OnRotationListener { fun onFinishRotation() }
1
null
1
1
ee7296b4a4b3bbbd4f828963d5a309ee2653def8
93
SpinWheel
MIT License
feature/auth-impl/src/iosMain/kotlin/org/michaelbel/movies/auth/ui/AuthRoute.ios.kt
michaelbel
115,437,864
false
{"Kotlin": 908384, "Swift": 692, "HTML": 606, "Shell": 235}
package org.michaelbel.movies.auth.ui import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import org.koin.compose.koinInject import org.michaelbel.movies.auth.AuthViewModel import org.michaelbel.movies.common.browser.openUrl @Composable fun AuthRoute( onBackClick: () -> Unit, modifier: Modifier = Modifier, viewModel: AuthViewModel = koinInject<AuthViewModel>() ) { AuthScreenContent( error = null, signInLoading = false, loginLoading = false, requestToken = null, onBackClick = onBackClick, onSignInClick = { username, password -> }, onLoginClick = {}, onResetRequestToken = {}, onUrlClick = { url -> openUrl(url) }, modifier = modifier ) }
8
Kotlin
36
271
1da1d67e093ecb76057a06da0ef17f746ca06888
771
movies
Apache License 2.0
dairo-dfs-server/src/main/java/cn/dairo/dfs/controller/app/files/form/ComputeSubTotalForm.kt
DAIRO-HY
850,929,695
false
{"Kotlin": 384885, "HTML": 114552, "JavaScript": 39136, "Java": 27584, "Shell": 4220, "Dockerfile": 2974, "CSS": 2579, "Batchfile": 967, "SCSS": 33}
package cn.dairo.dfs.controller.app.files.form class ComputeSubTotalForm { /** * 大小 */ var size: Long = 0L /** * 文件数(文件夹属性专用) */ var fileCount: Int = 0 /** * 文件夹数(文件夹属性专用) */ var folderCount: Int = 0 }
0
Kotlin
0
0
c8613581ef4c8f39836ea9c69169fb0b3c1e8984
259
DairoDfs
Apache License 2.0
wui/src/main/kotlin/caches.kt
ez-corp
211,860,541
false
null
import queries.CourseInfo val CourseInfoCache: MutableMap<String, CourseInfo> = mutableMapOf()
0
Kotlin
0
0
c0cd3eb8787eb445cbf2ea2fab4f5320aa229012
98
easy
MIT License
app/src/main/java/flaskoski/rs/smartmuseum/util/AnimationUtil.kt
flaskoski
173,016,051
false
null
/* This is a modified version of the following code: Copyright 2013 Google Inc. Licensed under Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0.html Source - https://gist.github.com/broady/6314689 Video - https://www.youtube.com/watch?v=WKfZsCKSXVQ&feature=youtu.be //---------------------------------------- Converted to Kotlin by <NAME> */ package flaskoski.rs.smartmuseum.util import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import android.animation.ObjectAnimator; import android.animation.TypeEvaluator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.os.Build; import android.os.Handler; import android.os.SystemClock; import android.util.Property; import android.view.animation.AccelerateDecelerateInterpolator; import kotlin.math.abs import kotlin.math.sign /** * Animation utilities for moving markers from one location to another with Maps API. * */ class AnimationUtil { /** * Animates a marker from it's current position to the provided finalPosition * * @param marker marker to animate * @param finalPosition the final position of the marker after the animation */ fun animateMarkerTo(marker : Marker, finalPosition: LatLng) { // Use the appropriate implementation per API Level if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { animateMarkerToICS(marker, finalPosition) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { animateMarkerToHC(marker, finalPosition) } else { animateMarkerToGB(marker, finalPosition) } } private fun animateMarkerToGB(marker: Marker, finalPosition: LatLng) { val latLngInterpolator = LatLngInterpolator.Linear() val startPosition = marker.position val handler = Handler() val start = SystemClock.uptimeMillis() val interpolator = AccelerateDecelerateInterpolator() val durationInMs = 3000f handler.post(object : Runnable { internal var elapsed: Long = 0 internal var t: Float = 0.toFloat() internal var v: Float = 0.toFloat() override fun run() { // Calculate progress using interpolator elapsed = SystemClock.uptimeMillis() - start t = elapsed / durationInMs v = interpolator.getInterpolation(t) marker.position = latLngInterpolator.interpolate(v, startPosition, finalPosition) // Repeat till progress is complete. if (t < 1) { // Post again 16ms later. handler.postDelayed(this, 16) } } }) } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) private fun animateMarkerToHC(marker: Marker, finalPosition: LatLng) { val latLngInterpolator = LatLngInterpolator.Linear() val startPosition = marker.position val valueAnimator = ValueAnimator() valueAnimator.addUpdateListener { animation -> val v = animation.animatedFraction val newPosition = latLngInterpolator .interpolate(v, startPosition, finalPosition) marker.position = newPosition } valueAnimator.setFloatValues(0f, 1f) // Ignored. valueAnimator.duration = 3000 valueAnimator.start() } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private fun animateMarkerToICS(marker: Marker, finalPosition: LatLng) { val latLngInterpolator = LatLngInterpolator.Linear() val typeEvaluator = TypeEvaluator<LatLng> { fraction, startValue, endValue -> latLngInterpolator.interpolate(fraction, startValue, endValue) } val property = Property.of(Marker::class.java, LatLng::class.java, "position") val animator = ObjectAnimator .ofObject(marker, property, typeEvaluator, finalPosition) animator.duration = 3000 animator.start() } /** * For other LatLngInterpolator interpolators, see https://gist.github.com/broady/6314689 */ internal interface LatLngInterpolator { fun interpolate(fraction: Float, a: LatLng, b: LatLng): LatLng class Linear : LatLngInterpolator { override fun interpolate(fraction: Float, a: LatLng, b: LatLng): LatLng { val lat = (b.latitude - a.latitude) * fraction + a.latitude var lngDelta = b.longitude - a.longitude // Take the shortest path across the 180th meridian. if (abs(lngDelta) > 180) { lngDelta -= sign(lngDelta) * 360 } val lng = lngDelta * fraction + a.longitude return LatLng(lat, lng) } } } }
0
Kotlin
0
1
2e180a388298e0b827cea35daef4593ec52f5811
4,930
SmartMuseum
MIT License
src/main/kotlin/io/github/mrmlik12/github/api/URLs.kt
MRmlik12
338,544,143
false
null
package io.github.mrmlik12.github.api enum class URLs(val url: String) { User("https://api.github.com/users/"), UserRepo("https://api.github.com/users/{userName}/repos"), UserGist("https://api.github.com/users/{userName}/gists"), UserFollowers("https://api.github.com/users/{userName}/followers"), UserFollowing("https://api.github.com/users/{userName}/following"), UserStarred("https://api.github.com/users/{userName}/starred"), UserSubscriptions("https://api.github.com/users/{userName}/subscriptions"), UserOrganizations("https://api.github.com/users/{userName}/orgs"), UserEvents("https://api.github.com/users/{userName}/received_events") }
0
Kotlin
0
0
3fe24148427205ee63e56391dd74a7a22816fe9e
681
github-api
MIT License
app/src/main/java/com/msg/gcms/domain/usecase/auth/CheckLoginStatusUseCase.kt
GSM-MSG
465,292,111
false
null
package com.msg.gcms.domain.usecase.auth import com.msg.gcms.domain.repository.AuthRepository import javax.inject.Inject class CheckLoginStatusUseCase @Inject constructor( private val authRepository: AuthRepository ) { suspend operator fun invoke() = kotlin.runCatching { authRepository.checkLoginStatus() } }
12
Kotlin
0
8
65ba9a3e762676b9032ae8031f937e2b338b78f0
331
GCMS-Android
MIT License
app/src/main/java/org/simple/clinic/drugs/selection/entry/CustomPrescriptionEntryEvents.kt
moealmaw
138,648,110
true
{"Kotlin": 347838}
package org.simple.clinic.drugs.selection.entry import org.simple.clinic.widgets.UiEvent import java.util.UUID data class CustomPrescriptionSheetCreated(val patientUuid: UUID) : UiEvent data class CustomPrescriptionDrugNameTextChanged(val name: String) : UiEvent data class CustomPrescriptionDrugDosageTextChanged(val dosage: String) : UiEvent class SaveCustomPrescriptionClicked() : UiEvent
0
Kotlin
0
0
d59ebd983c0d08d85d91041e33b7927528bbb559
397
redapp
MIT License
modules/common_navigation/src/main/java/kekmech/ru/common_navigation/BottomTabsSwitcher.kt
alexberdreal
312,900,118
true
{"Kotlin": 408124, "Shell": 46}
package kekmech.ru.common_navigation import io.reactivex.Observable import kekmech.ru.common_kotlin.Option interface BottomTabsSwitcher { fun changeTab(tab: BottomTab) fun clearTab() fun observe(): Observable<Option<BottomTab>> }
0
null
0
0
44324701b5e121bfca3fc854d3f84dffbe8ae90c
246
mpeiapp
MIT License
app/src/main/java/com/waseefakhtar/doseapp/data/entity/MedicationEntity.kt
waseefakhtar
504,263,132
false
{"Kotlin": 135627}
package com.waseefakhtar.doseapp.data.entity import androidx.room.Entity import androidx.room.PrimaryKey import java.util.Date @Entity data class MedicationEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val name: String, val dosage: Int, val recurrence: String, val endDate: Date, val medicationTime: Date = Date(), val medicationTaken: Boolean, )
27
Kotlin
71
467
21745db8db92255139b79f0c8751976a3f8e4d57
390
dose-android
MIT License
common/src/commonMain/kotlin/it/nicolasfarabegoli/hotwarmcold/components/smartphone/Actuator.kt
nicolasfara
587,227,341
false
null
package it.nicolasfarabegoli.hotwarmcold.components.smartphone import it.nicolasfarabegoli.pulverization.component.Context import it.nicolasfarabegoli.pulverization.core.Actuator import it.nicolasfarabegoli.pulverization.core.ActuatorsContainer import it.nicolasfarabegoli.pulverization.runtime.componentsref.BehaviourRef import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.serialization.Serializable import org.koin.core.component.inject @Serializable data class NeighbourDistance(val deviceId: String, val distance: Double) class DeviceActuator( private val flow: MutableSharedFlow<List<NeighbourDistance>> ) : Actuator<List<NeighbourDistance>> { override suspend fun actuate(payload: List<NeighbourDistance>) = flow.emit(payload) } class DeviceActuatorContainer( private val flow: MutableSharedFlow<List<NeighbourDistance>> ) : ActuatorsContainer() { override val context: Context by inject() override suspend fun initialize() { val actuator = DeviceActuator(flow).apply { initialize() } this += actuator } } suspend fun deviceActuatorLogic( actuator: ActuatorsContainer, behaviourRef: BehaviourRef<List<NeighbourDistance>> ) { actuator.get<DeviceActuator> { behaviourRef.receiveFromComponent().collect { actuate(it) } } }
0
Kotlin
0
0
f452c8b913d0ce3a3fcf8e187bdc63ce4cb55b42
1,328
pulverization-hot-warm-cold
MIT License
android/BaiPiaoOcrAndroidOnnx/app/src/main/java/com/benjaminwan/ocr/onnx/CameraActivity.kt
RapidAI
326,610,757
false
null
package com.benjaminwan.ocr.onnx import android.graphics.Bitmap import android.os.Bundle import android.view.View import android.widget.SeekBar import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.core.content.ContextCompat import com.afollestad.assent.Permission import com.afollestad.assent.askForPermissions import com.afollestad.assent.isAllGranted import com.afollestad.assent.rationale.createDialogRationale import com.benjaminwan.ocr.onnx.app.App import com.benjaminwan.ocr.onnx.dialog.DebugDialog import com.benjaminwan.ocr.onnx.dialog.TextResultDialog import com.benjaminwan.ocr.onnx.utils.showToast import com.benjaminwan.ocrlibrary.OcrResult import com.bumptech.glide.Glide import com.orhanobut.logger.Logger import com.uber.autodispose.android.lifecycle.autoDisposable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_camera.* import kotlin.math.max class CameraActivity : AppCompatActivity(), View.OnClickListener, SeekBar.OnSeekBarChangeListener { private var ocrResult: OcrResult? = null private var preview: Preview? = null private var imageCapture: ImageCapture? = null private var camera: Camera? = null private lateinit var viewFinder: PreviewView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_camera) App.ocrEngine.doAngle = false//摄像头一般不需要考虑倒过来的情况 clearBtn.setOnClickListener(this) detectBtn.setOnClickListener(this) resultBtn.setOnClickListener(this) debugBtn.setOnClickListener(this) updatePadding(App.ocrEngine.padding) updateBoxScoreThresh((App.ocrEngine.boxScoreThresh * 100).toInt()) updateBoxThresh((App.ocrEngine.boxThresh * 100).toInt()) updateUnClipRatio((App.ocrEngine.unClipRatio * 10).toInt()) paddingSeekBar.setOnSeekBarChangeListener(this) boxScoreThreshSeekBar.setOnSeekBarChangeListener(this) boxThreshSeekBar.setOnSeekBarChangeListener(this) maxSideLenSeekBar.setOnSeekBarChangeListener(this) scaleUnClipRatioSeekBar.setOnSeekBarChangeListener(this) viewFinder = findViewById(R.id.viewFinder) cameraLensView.postDelayed({ updateMaxSideLen(100) }, 500) } override fun onResume() { super.onResume() val rationaleHandler = createDialogRationale(R.string.app_permission) { onPermission( Permission.CAMERA, "请点击允许" ) } if (!isAllGranted(Permission.CAMERA)) { askForPermissions( Permission.CAMERA, rationaleHandler = rationaleHandler ) { result -> val permissionGranted: Boolean = result.isAllGranted( Permission.CAMERA ) if (!permissionGranted) { showToast("未获取权限,应用无法正常使用!") } else { startCamera() } } } else { startCamera() } } override fun onClick(view: View?) { view ?: return when (view.id) { R.id.clearBtn -> { clearLastResult() } R.id.detectBtn -> { val width = cameraLensView.measuredWidth * 9 / 10 val height = cameraLensView.measuredHeight * 9 / 10 val ratio = maxSideLenSeekBar.progress.toFloat() / 100.toFloat() val maxSize = max(width, height) val maxSideLen = (ratio * maxSize).toInt() detect(maxSideLen) } R.id.resultBtn -> { val result = ocrResult ?: return TextResultDialog.instance .setTitle("识别结果") .setContent(result.strRes) .show(supportFragmentManager, "TextResultDialog") } R.id.debugBtn -> { val result = ocrResult ?: return DebugDialog.instance .setTitle("调试信息") .setResult(result) .show(supportFragmentManager, "DebugDialog") } else -> { } } } override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { seekBar ?: return when (seekBar.id) { R.id.maxSideLenSeekBar -> { updateMaxSideLen(progress) } R.id.paddingSeekBar -> { updatePadding(progress) } R.id.boxScoreThreshSeekBar -> { updateBoxScoreThresh(progress) } R.id.boxThreshSeekBar -> { updateBoxThresh(progress) } R.id.scaleUnClipRatioSeekBar -> { updateUnClipRatio(progress) } else -> { } } } override fun onStartTrackingTouch(seekBar: SeekBar?) { } override fun onStopTrackingTouch(seekBar: SeekBar?) { } private fun updateMaxSideLen(progress: Int) { val width = cameraLensView.measuredWidth * 9 / 10 val height = cameraLensView.measuredHeight * 9 / 10 val ratio = progress.toFloat() / 100.toFloat() val maxSize = max(width, height) val maxSideLen = (ratio * maxSize).toInt() Logger.i("======$width,$height,$ratio,$maxSize,$maxSideLen") maxSideLenTv.text = "MaxSideLen:$maxSideLen(${ratio * 100}%)" } private fun updatePadding(progress: Int) { paddingTv.text = "Padding:$progress" App.ocrEngine.padding = progress } private fun updateBoxScoreThresh(progress: Int) { val thresh = progress.toFloat() / 100.toFloat() boxScoreThreshTv.text = "${getString(R.string.box_score_thresh)}:$thresh" App.ocrEngine.boxScoreThresh = thresh } private fun updateBoxThresh(progress: Int) { val thresh = progress.toFloat() / 100.toFloat() boxThreshTv.text = "BoxThresh:$thresh" App.ocrEngine.boxThresh = thresh } private fun updateUnClipRatio(progress: Int) { val scale = progress.toFloat() / 10.toFloat() unClipRatioTv.text = "${getString(R.string.box_un_clip_ratio)}:$scale" App.ocrEngine.unClipRatio = scale } private fun showLoading() { loadingImg.visibility = View.VISIBLE Glide.with(this).load(R.drawable.loading_anim).into(loadingImg) } private fun hideLoading() { loadingImg.visibility = View.GONE } private fun clearLastResult() { cameraLensView.cameraLensBitmap = null timeTV.text = "" ocrResult = null } private fun detect(reSize: Int) { Single.fromCallable { val src = cameraLensView.cropCameraLensRectBitmap(viewFinder.bitmap, false) val boxImg: Bitmap = Bitmap.createBitmap( src.width, src.height, Bitmap.Config.ARGB_8888 ) Logger.i("selectedImg=${src.height},${src.width} ${src.config}") App.ocrEngine.detect(src, boxImg, reSize) }.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { showLoading() } .doFinally { hideLoading() } .autoDisposable(this) .subscribe { t1, t2 -> ocrResult = t1 timeTV.text = "识别时间:${t1.detectTime.toInt()}ms" cameraLensView.cameraLensBitmap = t1.boxImg } } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener(Runnable { // Used to bind the lifecycle of cameras to the lifecycle owner val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() // Preview preview = Preview.Builder() .setTargetAspectRatio(AspectRatio.RATIO_4_3) .build() val imageCaptureBuilder = ImageCapture.Builder() imageCaptureBuilder.setTargetAspectRatio(AspectRatio.RATIO_4_3) imageCapture = imageCaptureBuilder.build() // Select back camera val cameraSelector = CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build() try { // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture) preview?.setSurfaceProvider(viewFinder.surfaceProvider) } catch (exc: Exception) { Logger.e("Use case binding failed", exc.message.toString()) } }, ContextCompat.getMainExecutor(this)) } companion object { const val REQUEST_SELECT_IMAGE = 666 } }
1
C++
2
895
89d0b621c1ff9a82a3eedab901c67a234ac7cf10
9,276
RapidOCR
Apache License 2.0
j2k/tests/testData/ast/enum/class/colorEnum.kt
udalov
10,645,710
false
{"Java": 9931656, "Kotlin": 2142480, "JavaScript": 942412, "C++": 613791, "C": 193807, "Objective-C": 22634, "Shell": 12589, "Groovy": 1267}
package demo enum class MyEnum(_color : Int) { RED : MyEnum(10) BLUE : MyEnum(20) private val color : Int public fun getColor() : Int { return color } { color = _color } }
0
Java
1
6
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
171
kotlin-objc-diploma
Apache License 2.0
sample/src/main/kotlin/com/kronos/android/startup/sample/task/MyAnchorTask.kt
Leifzhang
431,806,948
false
null
package com.kronos.android.startup.sample.task import android.content.Context import com.kronos.android.startup.sample.AsyncTask1Provider import com.kronos.android.startup.sample.MyAnchorTaskProvider import com.kronos.lib.startup.SimpleStartupTask import com.kronos.startup.TaskNameProvider /** * * @Author LiABao * @Since 2021/11/26 * */ class MyAnchorTask : SimpleStartupTask() { override val taskNameProvider: TaskNameProvider get() = MyAnchorTaskProvider override fun run(context: Context) { info("MyAnchorTask") } init { dependOn(AsyncTask1Provider) } }
0
Kotlin
8
47
883e2be9c1c6b19714fa74c803bd517fad081944
613
AndroidStartup
Apache License 2.0
app/src/main/java/dev/robert/spacexgo/core/presentation/common/InfoRow.kt
robert-muriithi
586,537,208
false
{"Kotlin": 219684}
package dev.robert.spacexgo.core.presentation.common import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun InfoRows( label: String, value: String ) { Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 5.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = label, style = TextStyle( fontSize = 12.sp, fontFamily = FontFamily.Serif, fontWeight = FontWeight.Bold ) ) Text(text = value, style = TextStyle(fontSize = 12.sp, fontFamily = FontFamily.Serif)) } }
3
Kotlin
0
7
e33d59efc00fa315f4380253bebbb90ab27d7cab
1,144
SpaceXGo
Apache License 2.0
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/presentation/common/ConcurrentHashSet.kt
sceyt
549,073,085
false
{"Kotlin": 2675924, "Java": 107920}
package com.sceyt.sceytchatuikit.presentation.common import java.util.concurrent.ConcurrentHashMap class ConcurrentHashSet<E : Any> : MutableSet<E> { private val map = ConcurrentHashMap<E, Any>() private val present = Any() override val size: Int get() = map.size override fun isEmpty(): Boolean = map.isEmpty() override fun contains(element: E): Boolean = map.containsKey(element) override fun iterator(): MutableIterator<E> = map.keys.iterator() override fun add(element: E): Boolean = map.put(element, present) == null override fun remove(element: E): Boolean = map.remove(element) == present override fun containsAll(elements: Collection<E>): Boolean = elements.all { contains(it) } override fun addAll(elements: Collection<E>): Boolean = elements.fold(false) { acc, e -> acc or add(e) } override fun removeAll(elements: Collection<E>): Boolean = elements.fold(false) { acc, e -> acc or remove(e) } override fun retainAll(elements: Collection<E>): Boolean { val toRetain = elements.toSet() var modified = false val iterator = map.keys.iterator() while (iterator.hasNext()) { val key = iterator.next() if (!toRetain.contains(key)) { iterator.remove() modified = true } } return modified } override fun clear() = map.clear() }
0
Kotlin
1
2
ce9c1b95555fadaafcd11f0d073fcdb07ca49600
1,421
sceyt-chat-android-uikit
MIT License
kotlin-electron/src/jsMain/generated/electron/core/InAppPurchaseEvent.kt
JetBrains
93,250,841
false
{"Kotlin": 11782739, "JavaScript": 180094}
// Generated by Karakum - do not modify it manually! package electron.core @Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) @JsName("""(/*union*/{TRANSACTIONS_UPDATED: 'transactions-updated'}/*union*/)""") sealed external interface InAppPurchaseEvent : node.events.EventType { object TRANSACTIONS_UPDATED : InAppPurchaseEvent }
33
Kotlin
174
1,257
48cdb9f623f7686222300c850c4f8d0bade479d0
376
kotlin-wrappers
Apache License 2.0
data/notes/src/main/kotlin/ru/maksonic/beresta/data/notes/di/notesDataModule.kt
maksonic
580,058,579
false
null
package ru.maksonic.beresta.data.notes.di import org.koin.core.qualifier.named import org.koin.dsl.module import ru.maksonic.beresta.common.coroutine_dispatchers.CoroutineDispatchers import ru.maksonic.beresta.data.notes.NotesRepositoryImpl import ru.maksonic.beresta.data.notes.cache.NoteCacheMapper import ru.maksonic.beresta.data.notes.cache.NotesCacheDataSource import ru.maksonic.beresta.feature.notes.api.domain.NotesInteractor import ru.maksonic.beresta.feature.notes.api.domain.NotesRepository import ru.maksonic.beresta.feature.notes.api.domain.usecase.FetchNoteByIdUseCase import ru.maksonic.beresta.feature.notes.api.domain.usecase.FetchNotesByFolderTrashListUseCase import ru.maksonic.beresta.feature.notes.api.domain.usecase.FetchNotesUseCase import ru.maksonic.beresta.feature.notes.api.domain.usecase.FetchNotesWithoutFolderTrashListUseCase /** * @Author maksonic on 24.04.2023 */ val notesDataModule = module { single { NoteCacheMapper() } single { NotesCacheDataSource( noteDao = get(), dispatcher = get(named(CoroutineDispatchers.IO)) ) } single<NotesRepository> { NotesRepositoryImpl(cache = get(), mapper = get()) } single<NotesInteractor> { NotesInteractor.Impl(repository = get()) } single { FetchNotesUseCase(repository = get()) } single { FetchNoteByIdUseCase(repository = get()) } single { FetchNotesWithoutFolderTrashListUseCase(repository = get()) } single { FetchNotesByFolderTrashListUseCase(repository = get()) } }
0
Kotlin
0
0
f01672d89b5772c250d237ce5f3db4f73e3af819
1,512
Beresta
MIT License
livekit-android-sdk/src/test/java/io/livekit/android/events/EventCollector.kt
livekit
339,892,560
false
null
package io.livekit.android.events import kotlinx.coroutines.CoroutineScope class EventCollector<T : Event>( eventListenable: EventListenable<T>, coroutineScope: CoroutineScope ) : FlowCollector<T>(eventListenable.events, coroutineScope)
9
Kotlin
35
99
5b49711143729c497d77684f892ee5fa3ef5d900
246
client-sdk-android
Apache License 2.0
app/src/main/java/com/springer/patryk/decisionaid/model/network/endpoints/GroupsWS.kt
Gralls
164,907,645
false
{"Kotlin": 94763}
package com.springer.patryk.decisionaid.model.network.endpoints import com.springer.patryk.decisionaid.model.UsersGroup import com.springer.patryk.decisionaid.view.loggedin.groupmembers.addmember.model.NewMemberRequest import com.springer.patryk.decisionaid.view.loggedin.groups.details.model.GroupDetails import com.springer.patryk.decisionaid.view.loggedin.groups.model.NewGroup import kotlinx.coroutines.Deferred import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path /** * Created by <NAME> on 09.03.2019. */ interface GroupsWS { @GET(EndpointsName.Groups.USER_GROUPS) fun getUserGroups( @Path("userId") userId: Int ): Deferred<Response<List<UsersGroup>>> @POST(EndpointsName.Groups.GROUPS) fun createNewGroup( @Body group: NewGroup ): Deferred<Response<UsersGroup>> @GET(EndpointsName.Groups.GROUP_DETAILS) fun getGroupDetails( @Path("groupId") groupId: Int ): Deferred<Response<GroupDetails>> @DELETE(EndpointsName.Groups.REMOVE_GROUP_MEMBER) fun removeMemberFromGroup( @Path("groupId") groupId: Int, @Path("userId") userId: Int ): Deferred<Response<Unit>> @POST(EndpointsName.Groups.GROUP_DETAILS) fun assignUserToGroup( @Path("groupId") groupId: Int, @Body login: NewMemberRequest ): Deferred<Response<Unit>> }
2
Kotlin
0
0
18989953f855dc41e21fc95c17615c04d2c0071a
1,377
DecisionAid
Apache License 2.0
src/main/kotlin/navigation/NavigationHost.kt
yveskalume
629,345,265
true
{"Maven POM": 5, "Markdown": 1, "Text": 1, "Ignore List": 2, "Java": 446, "YAML": 1, "Protocol Buffer": 2, "INI": 2, "Gradle Kotlin DSL": 2, "Shell": 1, "Batchfile": 1, "Kotlin": 4}
package nav import androidx.compose.runtime.Composable class NavigationHost( val navController: NavController, val contents: @Composable NavigationGraphBuilder.() -> Unit ) { @Composable fun build() { NavigationGraphBuilder().renderContents() } inner class NavigationGraphBuilder( val navController: NavController = this@NavigationHost.navController ) { @Composable fun renderContents() { this@NavigationHost.contents(this) } } } /** * Composable to build the Navigation Host */ @Composable fun NavigationHost.NavigationGraphBuilder.composable( route: String, content: @Composable () -> Unit ) { if (navController.currentScreen.value == route) { content() } }
0
null
0
0
6aa20917990524d5524250972668e9ccc1f00f3f
795
WhatsappWeb4j
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/BookCompass.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.BookCompass: ImageVector get() { if (_bookCompass != null) { return _bookCompass!! } _bookCompass = fluentIcon(name = "Filled.BookCompass") { fluentPath { moveTo(11.0f, 10.0f) arcToRelative(1.25f, 1.25f, 0.0f, true, true, 2.5f, 0.0f) arcToRelative(1.25f, 1.25f, 0.0f, false, true, -2.5f, 0.0f) close() moveTo(4.0f, 4.5f) arcTo(2.5f, 2.5f, 0.0f, false, true, 6.5f, 2.0f) lineTo(18.0f, 2.0f) arcToRelative(2.5f, 2.5f, 0.0f, false, true, 2.5f, 2.5f) verticalLineToRelative(14.25f) curveToRelative(0.0f, 0.41f, -0.34f, 0.75f, -0.75f, 0.75f) lineTo(5.5f, 19.5f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, 1.0f) horizontalLineToRelative(13.25f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f) lineTo(6.5f, 22.0f) arcTo(2.5f, 2.5f, 0.0f, false, true, 4.0f, 19.5f) verticalLineToRelative(-15.0f) close() moveTo(13.0f, 5.75f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -1.5f, 0.0f) verticalLineToRelative(1.6f) arcTo(2.75f, 2.75f, 0.0f, false, false, 10.35f, 12.0f) lineToRelative(-1.3f, 3.23f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.4f, 0.56f) lineToRelative(1.23f, -3.09f) arcToRelative(2.76f, 2.76f, 0.0f, false, false, 1.14f, 0.0f) lineToRelative(1.23f, 3.09f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.4f, -0.56f) lineTo(14.15f, 12.0f) arcTo(2.74f, 2.74f, 0.0f, false, false, 13.0f, 7.35f) verticalLineToRelative(-1.6f) close() } } return _bookCompass!! } private var _bookCompass: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,286
compose-fluent-ui
Apache License 2.0
imageeditor/src/main/java/xyz/parkly/imageedit/editimage/interfaces/OnLoadingDialogListener.kt
ParklyInc
493,957,261
false
{"Java": 311069, "C": 137907, "Makefile": 10182, "Kotlin": 8949}
package me.mixal.edits.editor.interfaces interface OnLoadingDialogListener { fun showLoadingDialog() fun dismissLoadingDialog() }
1
null
1
1
7fb7ecf62cc9d3638e25ec0f793f23506f99e7d6
139
ImageEditor
MIT License
android/src/main/kotlin/com/baseflow/flutter/plugin/geolocator/tasks/LocationUsingLocationServicesTask.kt
sidlatau
166,651,204
false
{"Markdown": 12, "YAML": 4, "Text": 2, "Ignore List": 6, "Git Attributes": 1, "EditorConfig": 1, "Gradle": 5, "INI": 4, "Java Properties": 2, "XML": 10, "Kotlin": 26, "Dart": 15, "Java": 1, "Ruby": 2, "OpenStep Property List": 3, "Objective-C": 3, "Swift": 13, "JSON": 2, "Shell": 2}
package com.baseflow.flutter.plugin.geolocator.tasks import com.baseflow.flutter.plugin.geolocator.data.LocationOptions internal abstract class LocationUsingLocationServicesTask(taskContext: TaskContext<LocationOptions>) : Task<LocationOptions>(taskContext) { val locationOptions: LocationOptions = taskContext.options }
1
null
1
1
e12a0f57ef2ba30efbca4d2c06480b1081966e44
328
flutter-geolocator
MIT License
app/src/main/java/com/app/albums/shared/di/AppModule.kt
AhmedTawfiqM
486,283,872
false
null
package com.app.albums.shared.di import android.content.Context import com.app.albums.shared.App import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Singleton @Provides fun provideApplication(@ApplicationContext app: Context): App { return app as App } }
0
Kotlin
0
7
cb34d425033d5a8127bd74dad693fb3745f06fbd
504
Albums
Apache License 2.0
app/src/main/java/com/doctoror/splittor/presentation/groupsoverview/GroupsOverviewViewModelUpdater.kt
Doctoror
639,914,602
false
null
package com.doctoror.splittor.presentation.groupsoverview import com.doctoror.splittor.R import com.doctoror.splittor.domain.groups.Group class GroupsOverviewViewModelUpdater( private val groupItemViewModelMapper: GroupItemViewModelMapper, private val viewModel: GroupsOverviewViewModel ) { fun updateOnGroupsListLoaded(groups: List<Group>) { viewModel.groups.set(groups.map(groupItemViewModelMapper::map)) viewModel.displayedChildId.set( if (groups.isEmpty()) { R.id.fragmentGroupsEmpty } else { R.id.fragmentGroupsContent } ) } }
0
Kotlin
0
1
4d2e88ecc753210cc6e98b7b2118464308160aba
643
Android-Architecture-Demos
Apache License 2.0
plugins/src/main/kotlin/com/project/starter/quality/internal/AndroidCoverage.kt
tooploox
247,662,214
true
{"Kotlin": 93194}
package com.project.starter.quality.internal import com.android.build.gradle.api.BaseVariant import org.gradle.api.DomainObjectSet import org.gradle.api.Project import org.gradle.testing.jacoco.plugins.JacocoTaskExtension import org.gradle.testing.jacoco.tasks.JacocoReport internal fun Project.configureAndroidCoverage(variants: DomainObjectSet<out BaseVariant>, projectExclusions: List<String>) { pluginManager.apply("jacoco") variants.all { variant -> tasks.register("jacoco${variant.name.capitalize()}TestReport", JacocoReport::class.java) { report -> val capitalizedVariant = variant.name.capitalize() val testTask = tasks.getByName("test${capitalizedVariant}UnitTest") val jacocoTestTaskExtension = testTask.extensions.getByType(JacocoTaskExtension::class.java).apply { isIncludeNoLocationClasses = true } report.dependsOn(testTask) report.group = "verification" report.description = "Generates Jacoco coverage reports for the ${variant.name} variant." report.reports { it.html.isEnabled = true it.xml.isEnabled = true } val sourceDirs = variant.sourceSets.flatMap { it.javaDirectories } val classesDir = variant.javaCompileProvider.get().destinationDir val executionData = jacocoTestTaskExtension.destinationFile val coverageExcludes = excludes + projectExclusions val kotlinClassesDir = "$buildDir/tmp/kotlin-classes/${variant.name}" val kotlinTree = fileTree(mapOf("dir" to kotlinClassesDir, "excludes" to coverageExcludes)) val javaTree = fileTree(mapOf("dir" to classesDir, "excludes" to coverageExcludes)) report.classDirectories.setFrom(javaTree + kotlinTree) report.executionData.setFrom(files(executionData)) report.sourceDirectories.setFrom(files(sourceDirs)) } } } private val databinding = listOf( "android/databinding/**/*.class", "androidx/databinding/**/*.class", "**/databinding/*Binding.class", "**/databinding/*BindingImpl.class", "**/BR.*", "**/IssuesRegistry.*" ) private val framework = listOf( "**/R.class", "**/R$*.class", "**/BuildConfig.*", "**/Manifest*.*" ) private val butterKnife = listOf( "**/*${"$"}ViewInjector*.*", "**/*${"$"}ViewBinder*.*" ) internal val dagger = listOf( "**/*_MembersInjector.class", "**/Dagger*Component.class", "**/Dagger*Component${"$"}Builder.class", "**/*_*Factory.class", "**/*_Factory.class" ) private val excludes = databinding + framework + butterKnife + dagger
0
Kotlin
0
0
4c64478ee81a707008337e147fa12d14da728a81
2,710
project-starter
MIT License
domain/src/main/java/com/gabrielmorenoibarra/weatherlocation/domain/keys/routes/response/WeatherObservationKeys.kt
soygabimoreno
200,456,364
false
null
package com.gabrielmorenoibarra.weatherlocation.domain.keys.routes.response object WeatherObservationKeys { const val ITEMS_NAME = "weatherObservations" }
0
Kotlin
0
0
750e6b6283ab91c0a405a0ff928ee82dff140004
160
Weather-Location
Apache License 2.0
contracts/src/main/kotlin/com/contractsAndStates/states/TileSides.kt
abellagonzalo
197,566,849
true
{"Kotlin": 357987, "HTML": 168, "JavaScript": 53}
package com.contractsAndStates.states import net.corda.core.contracts.UniqueIdentifier import net.corda.core.serialization.ConstructorForDeserialization import net.corda.core.serialization.CordaSerializable @CordaSerializable data class TileSides @ConstructorForDeserialization constructor( val value: List<TileSide> = List(HexTile.SIDE_COUNT) { TileSide() } ) : TileSideLocator, CornerLocator, RoadLocator, NeighborLocator { init { require(value.size == HexTile.SIDE_COUNT) { "value.size cannot be ${value.size}" } val nonNullNeighbors = value.filter { it.neighbor != null } require(nonNullNeighbors.size == nonNullNeighbors.toSet().size) { "There should be no non-null duplicates in the neighbors list" } val nonNullRoads = value.filter { it.roadId != null } require(nonNullRoads.size == nonNullRoads.toSet().size) { "There should be no non-null duplicates in the roadIds list" } } override fun getSideOn(sideIndex: TileSideIndex) = value[sideIndex.value] override fun indexOf(tileSide: TileSide) = value.indexOf(tileSide).let { if (it < 0) null else TileSideIndex(it) } override fun getNeighborOn(sideIndex: TileSideIndex) = getSideOn(sideIndex).neighbor fun indexOf(tileIndex: HexTileIndex) = value.map { it.neighbor }.indexOf(tileIndex).let { if (it < 0) null else TileSideIndex(it) } override fun getRoadOn(sideIndex: TileSideIndex) = getSideOn(sideIndex).roadId override fun getRoads() = value.map { it.roadId } /** * The neighbor corners returned are ordered clockwise. */ override fun getOverlappedCorners(cornerIndex: TileCornerIndex) = getNeighborsOn(cornerIndex) .zip(cornerIndex.getOverlappedCorners()) .map { pair -> pair.first.let { if (it == null) null else AbsoluteCorner(it, pair.second) } } class Builder( private val value: MutableList<TileSide> = MutableList(HexTile.SIDE_COUNT) { TileSide() } ) : TileSideLocator, TileSideBuilder, CornerLocator, RoadLocator, RoadBuilder, NeighborLocator, NeighborBuilder { constructor(tileSides: TileSides) : this(tileSides.value.toMutableList()) override fun getSideOn(sideIndex: TileSideIndex) = value[sideIndex.value] override fun indexOf(tileSide: TileSide) = value.indexOf(tileSide).let { if (it < 0) null else TileSideIndex(it) } override fun setSideOn(sideIndex: TileSideIndex, tileSide: TileSide) = apply { require(getNeighborOn(sideIndex).let { it == null || it == tileSide.neighbor }) { "You cannot replace an existing neighbor" } require(getRoadOn(sideIndex).let { it == null || it == tileSide.roadId }) { "You cannot build a new road on top of a current one" } value[sideIndex.value] = tileSide } /** * The neighbor corners returned are ordered clockwise. */ override fun getOverlappedCorners(cornerIndex: TileCornerIndex) = getNeighborsOn(cornerIndex) .zip(cornerIndex.getOverlappedCorners()) .map { pair -> pair.first.let { if (it == null) null else AbsoluteCorner(it, pair.second) } } override fun getNeighborOn(sideIndex: TileSideIndex) = getSideOn(sideIndex).neighbor override fun setNeighborOn(sideIndex: TileSideIndex, neighbor: HexTileIndex) = apply { require(getNeighborOn(sideIndex).let { it == null || it == neighbor }) { "You cannot replace an existing neighbor" } setSideOn(sideIndex, getSideOn(sideIndex).copy(neighbor = neighbor)) } override fun getRoadOn(sideIndex: TileSideIndex) = getSideOn(sideIndex).roadId override fun getRoads() = value.map { it.roadId } override fun setRoadOn(sideIndex: TileSideIndex, roadId: UniqueIdentifier) = apply { require(getRoadOn(sideIndex).let { it == null || it == roadId }) { "You cannot build a new road on top of a current one" } setSideOn(sideIndex, getSideOn(sideIndex).copy(roadId = roadId)) } fun build() = TileSides(ImmutableList(value).toMutableList()) } } @CordaSerializable data class TileSide(val neighbor: HexTileIndex? = null, val roadId: UniqueIdentifier? = null) interface TileSideLocator { fun getSideOn(sideIndex: TileSideIndex): TileSide fun indexOf(tileSide: TileSide): TileSideIndex? } interface TileSideBuilder { fun setSideOn(sideIndex: TileSideIndex, tileSide: TileSide): TileSideBuilder } interface CornerLocator { fun getOverlappedCorners(cornerIndex: TileCornerIndex): List<AbsoluteCorner?> } interface RoadLocator { fun getRoadOn(sideIndex: TileSideIndex): UniqueIdentifier? fun hasRoadOn(sideIndex: TileSideIndex) = getRoadOn(sideIndex) != null fun getRoads(): List<UniqueIdentifier?> fun indexOf(roadId: UniqueIdentifier) = getRoads().indexOf(roadId).let { if (it < 0) null else TileSideIndex(it) } } interface RoadBuilder { fun setRoadOn(sideIndex: TileSideIndex, roadId: UniqueIdentifier): RoadBuilder } interface NeighborLocator { fun getNeighborOn(sideIndex: TileSideIndex): HexTileIndex? fun isNeighborOn(sideIndex: TileSideIndex, tileIndex: HexTileIndex) = getNeighborOn(sideIndex) == tileIndex fun hasNeighborOn(sideIndex: TileSideIndex) = getNeighborOn(sideIndex) != null /** * The neighbors returned are ordered as per the argument. */ fun getNeighborsOn(sideIndices: Iterable<TileSideIndex>) = sideIndices.map { getNeighborOn(it) } /** * The neighbors returned are ordered clockwise. */ fun getNeighborsOn(cornerIndex: TileCornerIndex) = getNeighborsOn(cornerIndex.getAdjacentSides()) } interface NeighborBuilder { fun setNeighborOn(sideIndex: TileSideIndex, neighbor: HexTileIndex): NeighborBuilder }
0
Kotlin
0
0
15d49b0524ce6835ff5cf5ce22891bc8d65c6894
6,302
SettlersOfCordan
Apache License 2.0
web/src/test/java/no/nav/modiapersonoversikt/rest/person/PersonsokControllerTest.kt
navikt
218,512,058
false
{"Kotlin": 905019, "Java": 487956, "Mustache": 29354, "Shell": 1401, "Dockerfile": 345}
package no.nav.modiapersonoversikt.rest.person import no.nav.modiapersonoversikt.consumer.pdl.generated.enums.KjoennType import no.nav.modiapersonoversikt.consumer.pdl.generated.sokperson.* import no.nav.modiapersonoversikt.consumer.pdl.generated.sokperson.Matrikkeladresse import no.nav.modiapersonoversikt.consumer.pdl.generated.sokperson.Person import no.nav.modiapersonoversikt.service.pdl.PdlOppslagService.* import no.nav.personoversikt.common.test.snapshot.SnapshotExtension import no.nav.tjeneste.virksomhet.personsoek.v1.informasjon.* import no.nav.tjeneste.virksomhet.personsoek.v1.informasjon.Bostedsadresse import no.nav.tjeneste.virksomhet.personsoek.v1.informasjon.Kjoenn import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import java.math.BigInteger import java.time.* import javax.xml.datatype.DatatypeFactory import javax.xml.datatype.XMLGregorianCalendar import no.nav.modiapersonoversikt.consumer.pdl.generated.sokperson.Bostedsadresse as PdlBostedsadresse import no.nav.modiapersonoversikt.consumer.pdl.generated.sokperson.Kjoenn as PdlKjoenn class PersonsokControllerTest { @Nested inner class PersonResponseMapper { @JvmField @RegisterExtension val snapshot = SnapshotExtension() private val fixedDate: XMLGregorianCalendar = DatatypeFactory .newInstance() .newXMLGregorianCalendarDate(2020, 10, 12, 0) @Test internal fun `should map tps response`() { val person = Bruker().apply { diskresjonskode = Diskresjonskoder().apply { kodeverksRef = "kodeverkref" kodeRef = "SPSF" value = "SPSF" } postadresse = Postadresse().apply { ustrukturertAdresse = UstrukturertAdresse().apply { adresselinje1 = "adresselinje1" adresselinje2 = "adresselinje2" adresselinje3 = "adresselinje3" adresselinje4 = "adresselinje4" landkode = Landkoder().apply { kodeverksRef = "landkodeRef" kodeRef = "NOR" value = "NOR" } } } bostedsadresse = Bostedsadresse().apply { strukturertAdresse = Gateadresse().apply { gatenummer = BigInteger.TWO gatenavn = "Supervegen" husnummer = BigInteger.TEN husbokstav = "Z" poststed = Postnummer().apply { kodeverksRef = "postnummerRef" kodeRef = "1234" value = "Svingen" } bolignummer = "1234" kommunenummer = "654321" } } kjoenn = Kjoenn().apply { kjoenn = Kjoennstyper().apply { kodeverksRef = "kjonnRef" kodeRef = "M" value = "M" } } personnavn = Personnavn().apply { fornavn = "fornavn" mellomnavn = "mellomnavn" etternavn = "etternavn" sammensattNavn = "fornavn mellomnavn etternavn" } personstatus = Personstatus().apply { personstatus = Personstatuser().apply { kodeverksRef = "personstatusRef" kodeRef = "DOD" value = "DOD" } } ident = NorskIdent().apply { ident = "12345679810" type = Personidenter().apply { kodeverksRef = "personidenterRef" kodeRef = "FNR" value = "FNR" } } gjeldendePostadresseType = Postadressetyper().apply { kodeverksRef = "postadresseRef" kodeRef = "postadresseRef" value = "NA" } midlertidigPostadresse = MidlertidigPostadresseNorge().apply { ustrukturertAdresse = UstrukturertAdresse().apply { adresselinje1 = "adresselinje1" adresselinje2 = "adresselinje2" adresselinje3 = "adresselinje3" adresselinje4 = "adresselinje4" landkode = Landkoder().apply { kodeverksRef = "landkodeRef" kodeRef = "NOR" value = "NOR" } } postleveringsPeriode = Gyldighetsperiode().apply { fom = fixedDate tom = fixedDate } } harAnsvarligEnhet = AnsvarligEnhet().apply { enhet = Organisasjonsenhet().apply { organisasjonselementID = "1234" } } } snapshot.assertMatches(lagPersonResponse(person)) } @Test internal fun `should map pdl response`() { val person = PersonSearchHit( score = 1.0, person = Person( navn = listOf( Navn( fornavn = "fornavn", mellomnavn = "mellomnavn", etternavn = "etternavn", originaltNavn = null, ), ), kjoenn = listOf( PdlKjoenn( KjoennType.KVINNE, ), ), utenlandskIdentifikasjonsnummer = listOf( UtenlandskIdentifikasjonsnummer( identifikasjonsnummer = "987654-987", utstederland = "SWE", opphoert = false, ), ), folkeregisteridentifikator = listOf( Folkeregisteridentifikator( identifikasjonsnummer = "12345678910", status = "AKTIV", type = "FNR", ), ), kontaktadresse = listOf( Kontaktadresse( vegadresse = Vegadresse( husbokstav = "Z", husnummer = "10", bruksenhetsnummer = null, adressenavn = "Supervegen", kommunenummer = "654321", postnummer = "1234", bydelsnummer = null, tilleggsnavn = null, ), postboksadresse = null, postadresseIFrittFormat = null, utenlandskAdresse = null, utenlandskAdresseIFrittFormat = null, ), ), bostedsadresse = listOf( PdlBostedsadresse( matrikkeladresse = Matrikkeladresse( bruksenhetsnummer = "123101", tilleggsnavn = "Supergården", postnummer = "1234", kommunenummer = "654321", ), vegadresse = null, utenlandskAdresse = null, ukjentBosted = null, ), ), ), ) snapshot.assertMatches(lagPersonResponse(person)) } } @Nested inner class PdlKriterierMapper { private val clock: Clock = Clock.fixed( Instant.parse("2020-12-02T12:00:00.00Z"), ZoneId.systemDefault(), ) @Test internal fun `regner ut tidligste dato basert på alderFra`() { val kriterier = requestV3 .copy(alderFra = 30) .tilPdlKriterier(clock) assertThat(kriterier).contains(PdlKriterie(PdlFelt.FODSELSDATO_TIL, "1990-12-02", searchHistorical = PdlSokeOmfang.GJELDENDE)) } @Test internal fun `regner ut seneste dato basert på alderTil`() { val kriterier = requestV3 .copy(alderTil = 32) .tilPdlKriterier(clock) assertThat(kriterier).contains(PdlKriterie(PdlFelt.FODSELSDATO_FRA, "1987-12-03", searchHistorical = PdlSokeOmfang.GJELDENDE)) } @Test internal fun `mapper kjønn til pdl-format`() { val mann = requestV3 .copy(kjonn = "M") .tilPdlKriterier(clock) assertThat(mann).contains(PdlKriterie(PdlFelt.KJONN, "MANN", searchHistorical = PdlSokeOmfang.GJELDENDE)) val kvinne = requestV3 .copy(kjonn = "K") .tilPdlKriterier(clock) assertThat(kvinne).contains(PdlKriterie(PdlFelt.KJONN, "KVINNE", searchHistorical = PdlSokeOmfang.GJELDENDE)) val ukjent = requestV3 .copy(kjonn = "U") .tilPdlKriterier(clock) assertThat(ukjent).contains(PdlKriterie(PdlFelt.KJONN, null, searchHistorical = PdlSokeOmfang.GJELDENDE)) } @Test internal fun `mapper adresse til pdl-format`() { val kriterier = requestV3 .copy( adresse = "Gatenavn 1 A 0100", ) .tilPdlKriterier(clock) assertThat(kriterier).contains(PdlKriterie(PdlFelt.ADRESSE, "Gatenavn 1 A 0100", searchHistorical = PdlSokeOmfang.GJELDENDE)) } @Test internal fun `mapper navn til pdl-format`() { val kriterier = requestV3 .copy( navn = "Fornavn Etternavn", ) .tilPdlKriterier(clock) assertThat( kriterier, ).contains(PdlKriterie(PdlFelt.NAVN, "Fornavn Etternavn", searchHistorical = PdlSokeOmfang.HISTORISK_OG_GJELDENDE)) } private val requestV3 = PersonsokRequestV3( null, null, null, null, null, null, null, null, null, null, ) } }
3
Kotlin
1
2
bc0e6063468be3001e0999e6e1d36b99599cc9d4
14,133
modiapersonoversikt-api
MIT License
src/2020/Day2_2.kts
Ozsie
318,802,874
false
null
import java.io.File var count = 0 File("input/2020/day2").forEachLine { val (rule,value) = it.split(":").map { it.trim() } val (limits,letter) = rule.split(" ").map { it.trim() } val (x,y) = limits.split("-").map{ it.toInt() - 1 } if ((value[x] == letter[0]).xor(value[y] == letter[0])) count++ } println(count)
0
Kotlin
0
0
f404eeb9d8a85511ffbe3e38d939dfa25281c4bf
328
adventofcode
MIT License
skribenten-backend/src/main/kotlin/no/nav/pensjon/brev/skribenten/routes/Brev.kt
navikt
375,334,697
false
{"Kotlin": 3101141, "TypeScript": 459486, "TeX": 12813, "Shell": 8986, "CSS": 8051, "Python": 4661, "JavaScript": 4382, "Dockerfile": 2406, "HTML": 1053}
package no.nav.pensjon.brev.skribenten.routes import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.util.* import io.ktor.util.pipeline.* import no.nav.pensjon.brev.skribenten.letter.Edit import no.nav.pensjon.brev.skribenten.model.Api import no.nav.pensjon.brev.skribenten.model.SaksbehandlerValg import no.nav.pensjon.brev.skribenten.services.BrevredigeringService import no.nav.pensjon.brev.skribenten.services.ServiceResult import org.slf4j.LoggerFactory private val logger = LoggerFactory.getLogger("no.nav.brev.skribenten.routes.Brev") fun Route.brev(brevredigeringService: BrevredigeringService) { route("/brev") { put<Edit.Letter>("/{brevId}/redigertBrev") { request -> respond( brevredigeringService.oppdaterBrev( call = call, saksId = null, brevId = call.parameters.getOrFail<Long>("brevId"), nyeSaksbehandlerValg = null, nyttRedigertbrev = request, ) ) } put<SaksbehandlerValg>("/{brevId}/saksbehandlerValg") { request -> respond( brevredigeringService.oppdaterBrev( call = call, saksId = null, brevId = call.parameters.getOrFail<Long>("brevId"), nyeSaksbehandlerValg = request, nyttRedigertbrev = null, ) ) } put<String>("/{brevId}/signatur") { signatur -> if (signatur.trim().isNotEmpty()) { respond(brevredigeringService.oppdaterSignatur(call, brevId = call.parameters.getOrFail<Long>("brevId"), signaturSignerende = signatur)) } else { call.respond(HttpStatusCode.BadRequest, "Signatur kan ikke være tom") } } get("/{brevId}/reservasjon") { val brevId = call.parameters.getOrFail<Long>("brevId") brevredigeringService.fornyReservasjon(call, brevId) ?.also { call.respond(it) } ?: call.respond(HttpStatusCode.NotFound, "Fant ikke brev med id: $brevId") } } } private suspend fun PipelineContext<Unit, ApplicationCall>.respond(brevResponse: ServiceResult<Api.BrevResponse>?) = brevResponse?.onOk { brev -> call.respond(HttpStatusCode.OK, brev) } ?.onError { message, statusCode -> logger.error("$statusCode - Feil ved oppdatering av brev: $message") call.respond(HttpStatusCode.InternalServerError, "Feil ved oppdatering av brev.") } ?: call.respond(HttpStatusCode.NotFound, "Fant ikke brev")
4
Kotlin
3
1
da4b4a6ac36d9732874e658d081054c07c560619
2,763
pensjonsbrev
MIT License
remote/src/main/java/com/hariofspades/remote/model/SymbolLocal.kt
Hariofspades
151,868,084
false
null
package com.hariofspades.remote.model import com.google.gson.annotations.SerializedName data class SymbolLocal(@SerializedName("symbol") val symbol: String, @SerializedName("code") val code: String, @SerializedName("symbolAppearsAfter") val symbolAppearsAfter: Boolean = false, @SerializedName("name") val name: String, @SerializedName("local") val local: Boolean, @SerializedName("conversion") val conversion: Double)
0
Kotlin
2
16
e98461cc896e72703a94b2b6de6bdc4d117e38fe
673
my-wallet
MIT License
app/src/main/java/com/koflox/currency_exchanger/util/result/ResultUtil.kt
koflox
718,336,050
false
{"Kotlin": 62046}
package com.koflox.currency_exchanger.util.result import kotlinx.coroutines.TimeoutCancellationException import kotlin.coroutines.cancellation.CancellationException inline fun <R> runSafeCatching(block: () -> R): Result<R> { return try { Result.success(block()) } catch (e: Throwable) { val isCoroutineCancellation = e is CancellationException && e !is TimeoutCancellationException when { isCoroutineCancellation || e is RuntimeException || e is Error -> throw e else -> Result.failure(e) } } }
0
Kotlin
0
0
cca367643b8f8a53a0725fe0140d3751246d18fb
582
currency-exchanger
Apache License 2.0
src/test/kotlin/day17/Day17Test.kt
alxgarcia
435,549,527
false
null
package day17 import org.junit.jupiter.api.Test import kotlin.test.assertEquals internal class Day17Test { @Test fun `test part 1 - max vertical speed the probe can reach without missing the target`() { val input = "target area: x=20..30, y=-10..-5" val (_, rangeY) = parseInput(input) val (time, maxInitialVerticalSpeed) = findMaxInitialVerticalVelocity(rangeY) assertEquals(9, maxInitialVerticalSpeed) assertEquals(45, computeMaxHeight(time, maxInitialVerticalSpeed)) } @Test fun `problem part 1 - max vertical speed the probe can reach without missing the target`() { val input = "target area: x=277..318, y=-92..-53" val (_, rangeY) = parseInput(input) val (time, maxInitialVerticalSpeed) = findMaxInitialVerticalVelocity(rangeY) assertEquals(91, maxInitialVerticalSpeed) assertEquals(4186, computeMaxHeight(time, maxInitialVerticalSpeed)) } @Test fun `test part 2 - number of unique solutions`() { val input = "target area: x=20..30, y=-10..-5" val (rangeX, rangeY) = parseInput(input) assertEquals(112, findAllPossibleSolutions(rangeX, rangeY).size) } @Test fun `problem part 2 - number of unique solutions`() { val input = "target area: x=277..318, y=-92..-53" val (rangeX, rangeY) = parseInput(input) assertEquals(2709, findAllPossibleSolutions(rangeX, rangeY).size) } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
1,373
advent-of-code-2021
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/ParkingSlash.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.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 me.localx.icons.straight.Icons public val Icons.Bold.ParkingSlash: ImageVector get() { if (_parkingSlash != null) { return _parkingSlash!! } _parkingSlash = Builder(name = "ParkingSlash", 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) { moveTo(20.5f, 0.0f) lineTo(3.5f, 0.0f) curveTo(1.57f, 0.0f, 0.0f, 1.57f, 0.0f, 3.5f) lineTo(0.0f, 24.0f) lineTo(24.0f, 24.0f) lineTo(24.0f, 3.5f) curveToRelative(0.0f, -1.93f, -1.57f, -3.5f, -3.5f, -3.5f) close() moveTo(21.0f, 3.5f) verticalLineToRelative(15.379f) lineToRelative(-4.935f, -4.935f) curveToRelative(1.182f, -0.924f, 1.935f, -2.364f, 1.935f, -3.944f) curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f) horizontalLineToRelative(-2.5f) curveToRelative(-0.934f, 0.0f, -1.784f, 0.368f, -2.412f, 0.967f) lineToRelative(-2.967f, -2.967f) horizontalLineToRelative(15.379f) curveToRelative(0.275f, 0.0f, 0.5f, 0.224f, 0.5f, 0.5f) close() moveTo(13.904f, 11.783f) lineToRelative(-3.692f, -3.692f) curveToRelative(0.081f, -0.057f, 0.18f, -0.092f, 0.287f, -0.092f) horizontalLineToRelative(2.5f) curveToRelative(1.103f, 0.0f, 2.0f, 0.897f, 2.0f, 2.0f) curveToRelative(0.0f, 0.766f, -0.442f, 1.449f, -1.096f, 1.783f) close() moveTo(3.0f, 5.121f) lineToRelative(15.879f, 15.879f) lineTo(3.0f, 21.0f) lineTo(3.0f, 5.121f) close() moveTo(10.051f, 15.0f) horizontalLineToRelative(-0.051f) verticalLineToRelative(4.0f) horizontalLineToRelative(-3.0f) verticalLineToRelative(-7.051f) lineToRelative(3.051f, 3.051f) close() } } .build() return _parkingSlash!! } private var _parkingSlash: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,071
icons
MIT License
chargeStatistics/src/test/java/at/sunilson/chargestatistics/GetChargingProceduresTests.kt
sunilson
271,761,302
false
null
package at.sunilson.chargestatistics import at.sunilson.chargestatistics.domain.ExtractChargingProcedures import at.sunilson.chargestatistics.domain.entities.ChargingProcedure import at.sunilson.chargetracking.domain.GetAllChargeTrackingPoints import at.sunilson.chargetracking.domain.entities.ChargeTrackingPoint import at.sunilson.testcore.BaseUnitTest import at.sunilson.vehiclecore.domain.entities.Vehicle import io.mockk.every import io.mockk.impl.annotations.MockK import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runBlockingTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.time.Instant import java.time.ZoneId class GetChargingProceduresTests : BaseUnitTest() { private lateinit var extractUseCase: ExtractChargingProcedures @MockK private lateinit var getAllChargeTrackingPoints: GetAllChargeTrackingPoints @BeforeEach fun before() { extractUseCase = ExtractChargingProcedures() extractUseCase.dispatcher = Dispatchers.Main } @ParameterizedTest @MethodSource("data") fun `Charges are correctly extracted`( chargePoints: List<ChargeTrackingPoint>, result: List<ChargingProcedure> ) = runBlockingTest { every { getAllChargeTrackingPoints(any()) } returns flowOf(chargePoints) assertEquals(result, extractUseCase(chargePoints).get()) } companion object { private fun batteryStatus(level: Int, energy: Int, charging: Boolean) = Vehicle.BatteryStatus( level, 0, 0, energy, true, if (charging) { Vehicle.BatteryStatus.ChargeState.CHARGING } else { Vehicle.BatteryStatus.ChargeState.NOT_CHARGING }, 0f, 0 ) @JvmStatic fun data() = listOf( Arguments.of( listOf<ChargeTrackingPoint>(), listOf<ChargingProcedure>() ), Arguments.of( listOf( ChargeTrackingPoint("1", 0L, batteryStatus(10, 10, false), 0), ChargeTrackingPoint("1", 1L, batteryStatus(10, 10, false), 0), ChargeTrackingPoint("1", 2L, batteryStatus(10, 10, true), 0), ChargeTrackingPoint("1", 3L, batteryStatus(12, 20, true), 0), ChargeTrackingPoint("1", 4L, batteryStatus(12, 20, false), 0), ChargeTrackingPoint("1", 5L, batteryStatus(10, 10, false), 0) ), listOf( ChargingProcedure( 10, 12, 10, Instant.ofEpochMilli(1L).atZone(ZoneId.systemDefault()), Instant.ofEpochMilli(4L).atZone(ZoneId.systemDefault()) ) ) ), Arguments.of( listOf( ChargeTrackingPoint("1", 0L, batteryStatus(10, 10, false), 0), ChargeTrackingPoint("1", 1L, batteryStatus(11, 10, false), 0), ChargeTrackingPoint("1", 2L, batteryStatus(10, 10, false), 0) ), listOf<ChargingProcedure>() ) ) } }
0
Kotlin
0
5
7774eeeb923432cc22c9d1833f37d5a13f65c317
3,618
Zoe
Apache License 2.0
datasources/src/main/java/com/santukis/datasources/local/daos/CardClassDao.kt
santukis
504,046,648
false
{"Kotlin": 206975}
package com.santukis.datasources.local.daos import androidx.room.Dao import androidx.room.Query import com.santukis.datasources.entities.dbo.CardClassDB @Dao interface CardClassDao: BaseDao<CardClassDB> { @Query("SELECT * FROM cardclass") fun getCardClasses(): List<CardClassDB> }
0
Kotlin
0
3
7baff042a3bf97fc82eb5e7a73669cad9820ed39
291
HearthStone
Apache License 2.0
kafkistry-state-scraping/src/main/kotlin/com/infobip/kafkistry/kafkastate/AbstractKafkaStateProvider.kt
infobip
456,885,171
false
null
package com.infobip.kafkistry.kafkastate import com.infobip.kafkistry.utils.deepToString import com.infobip.kafkistry.kafkastate.config.PoolingProperties import com.infobip.kafkistry.model.KafkaCluster import com.infobip.kafkistry.model.KafkaClusterIdentifier import com.infobip.kafkistry.repository.KafkaClustersRepository import com.infobip.kafkistry.service.background.BackgroundJobIssuesRegistry import java.util.concurrent.ConcurrentHashMap abstract class AbstractKafkaStateProvider<V>( clustersRepository: KafkaClustersRepository, clusterFilter: ClusterEnabledFilter, poolingProperties: PoolingProperties, private val issuesRegistry: BackgroundJobIssuesRegistry ) : BaseKafkaStateProvider(clustersRepository, clusterFilter, poolingProperties) { abstract val stateTypeName: String private val clusterStates: MutableMap<KafkaClusterIdentifier, StateData<V>> = ConcurrentHashMap() fun getLatestState(kafkaClusterIdentifier: KafkaClusterIdentifier): StateData<V> { return clusterStates[kafkaClusterIdentifier] ?: StateData(StateType.UNKNOWN, kafkaClusterIdentifier, stateTypeName, System.currentTimeMillis()) } fun getLatestStateValue(kafkaClusterIdentifier: KafkaClusterIdentifier): V { return getLatestState(kafkaClusterIdentifier).value() } fun getAllLatestStates(): Map<KafkaClusterIdentifier, StateData<V>> = clusterStates.toMap() fun listAllLatestStates(): List<StateData<V>> = clusterStates.values.toList() override fun setupCachedState(enabledClusters: List<KafkaClusterIdentifier>, disabledClusters: List<KafkaClusterIdentifier>) { clusterStates.keys.removeIf { val shouldRemove = it !in enabledClusters && it !in disabledClusters if (shouldRemove) { clusterRemoved(it) issuesRegistry.clearIssue(it.issueKey()) } shouldRemove } disabledClusters.forEach { clusterIdentifier -> clusterStates.computeIfAbsent(clusterIdentifier) { StateData(StateType.DISABLED, it, stateTypeName, System.currentTimeMillis()) } } } /** * Allow implementations to know that cluster is removed from registry so that any kind of cleanup is easy to trigger */ protected open fun clusterRemoved(clusterIdentifier: KafkaClusterIdentifier) = Unit override fun doRefreshCluster(kafkaCluster: KafkaCluster): RefreshStatus { log.debug("Refreshing {} for cluster '{}'", stateTypeName, kafkaCluster.identifier) val issueKey = kafkaCluster.identifier.issueKey() val jobName = "Pooling of ${stateTypeName.replace("_", " ")} on cluster ${kafkaCluster.identifier}" val startTime = System.currentTimeMillis() fun durationSec() = (System.currentTimeMillis() - startTime) / 1000.0 val clusterState = try { val stateValue = fetchState(kafkaCluster) log.debug("Refreshed {} of cluster '{}' in {} sec", stateTypeName, kafkaCluster.identifier, durationSec()) issuesRegistry.clearIssue(issueKey) StateData(StateType.VISIBLE, kafkaCluster.identifier, stateTypeName, startTime, stateValue) } catch (ex: InvalidClusterIdException) { issuesRegistry.reportIssue(issueKey, jobName, ex.deepToString()) StateData(StateType.INVALID_ID, kafkaCluster.identifier, stateTypeName, startTime) } catch (ex: Throwable) { log.error("Exception while refreshing {} for cluster {}, setting it's state as 'unreachable' after {} sec", stateTypeName, kafkaCluster, durationSec(), ex ) issuesRegistry.reportIssue(issueKey, jobName, ex.deepToString()) StateData(StateType.UNREACHABLE, kafkaCluster.identifier, stateTypeName, startTime) } clusterStates[kafkaCluster.identifier] = clusterState return RefreshStatus( scrapeType = stateTypeName, clusterState = clusterState.stateType, durationMs = System.currentTimeMillis() - startTime ) } private fun KafkaClusterIdentifier.issueKey() = "kafka-$stateTypeName-$this" abstract fun fetchState(kafkaCluster: KafkaCluster): V protected class InvalidClusterIdException(message: String) : RuntimeException(message) }
0
Kotlin
0
19
ca65af134cc534ca30ab8c5093e64122fccc9030
4,370
kafkistry
Apache License 2.0
app/src/androidTest/java/org/bspb/smartbirds/pro/tools/form/PylonsCasualtiesFormHelper.kt
BspbOrg
68,009,904
false
null
package org.bspb.smartbirds.pro.tools.form import androidx.test.espresso.action.ViewActions.scrollTo import org.bspb.smartbirds.pro.R import org.bspb.smartbirds.pro.tools.action.SBViewActions.setChecked import org.bspb.smartbirds.pro.tools.fillTextField import org.bspb.smartbirds.pro.tools.form.entry.FormEntry import org.bspb.smartbirds.pro.tools.robot.PylonsCasualtiesFormTestRobot.Companion.pylonsCasualtiesScreen import org.bspb.smartbirds.pro.tools.selectSingleChoice import org.bspb.smartbirds.pro.tools.selectSpecies class PylonsCasualtiesFormHelper { companion object { fun fillFormFields(entry: FormEntry) { var fields: Map<Int, Any> = entry.toUiMap() fields.forEach { (key, value) -> fillFormField(key, value) } } private fun fillFormField(key: Int, value: Any) { pylonsCasualtiesScreen { when (key) { R.string.monitoring_moderator_review -> { fieldModeratorReview().perform(scrollTo(), setChecked(value as Boolean)) } R.string.monitoring_pylons_casualties_private -> { fieldConfidential().perform(scrollTo(), setChecked(value as Boolean)) } R.string.monitoring_pylons_casualties_name -> { selectSpecies(fieldSpecies(), value as String) } R.string.monitoring_birds_count -> { fillTextField(fieldCount(), value as String) } R.string.monitoring_pylons_casualties_age -> { selectSingleChoice(fieldAge(), value as String) } R.string.monitoring_pylons_casualties_gender -> { selectSingleChoice(fieldGender(), value as String) } R.string.monitoring_pylons_casualties_cause_of_death -> { selectSingleChoice(fieldCauseOfDeath(), value as String) } R.string.monitoring_pylons_casualties_body_condition -> { selectSingleChoice(fieldBodyCondition(), value as String) } R.string.monitoring_pylons_casualties_primary_habitat -> { selectSingleChoice(fieldPrimaryHabitat(), value as String) } R.string.monitoring_pylons_casualties_secondary_habitat -> { selectSingleChoice(fieldSecondaryHabitat(), value as String) } R.string.monitoring_pylons_casualties_notes -> { fillTextField(fieldNotes(), value as String) } } } } } }
5
Kotlin
0
0
c91a0a9269092d4fbc9ae9732f95acb478b395f4
2,874
smartbirds-android
Apache License 2.0
src/main/java/uk/gov/justice/hmpps/casenotes/controllers/ControllerAdvice.kt
ministryofjustice
195,988,411
false
{"Kotlin": 307204, "Java": 66924, "Mustache": 1803, "Dockerfile": 1357, "Shell": 580}
package uk.gov.justice.hmpps.casenotes.controllers import jakarta.persistence.EntityExistsException import jakarta.validation.ValidationException import lombok.extern.slf4j.Slf4j import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.access.AccessDeniedException import org.springframework.web.bind.MissingServletRequestParameterException import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestControllerAdvice import org.springframework.web.reactive.function.client.WebClientException import org.springframework.web.reactive.function.client.WebClientResponseException import uk.gov.justice.hmpps.casenotes.dto.ErrorResponse import uk.gov.justice.hmpps.casenotes.services.EntityNotFoundException @RestControllerAdvice @Slf4j class ControllerAdvice { @ExceptionHandler(AccessDeniedException::class) fun handleAccessDeniedException(e: AccessDeniedException): ResponseEntity<ErrorResponse> { return ResponseEntity .status(HttpStatus.FORBIDDEN) .body(ErrorResponse(status = (HttpStatus.FORBIDDEN.value()), developerMessage = e.message)) } @ExceptionHandler(WebClientResponseException::class) fun handleWebClientResponseException(e: WebClientResponseException): ResponseEntity<ByteArray> { return ResponseEntity .status(e.statusCode) .body(e.responseBodyAsByteArray) } @ExceptionHandler(EntityExistsException::class) fun handleEntityExistsException(e: Exception): ResponseEntity<ErrorResponse> { return ResponseEntity .status(HttpStatus.CONFLICT) .body(ErrorResponse(status = (HttpStatus.CONFLICT.value()), developerMessage = e.message)) } @ExceptionHandler(EntityNotFoundException::class) fun handleEntityNotFoundException(e: Exception): ResponseEntity<ErrorResponse> { return ResponseEntity .status(HttpStatus.NOT_FOUND) .body(ErrorResponse(status = (HttpStatus.NOT_FOUND.value()), developerMessage = e.message)) } @ExceptionHandler( MissingServletRequestParameterException::class, ValidationException::class, IllegalArgumentException::class, IllegalStateException::class, ) fun handleValidationException(e: Exception): ResponseEntity<ErrorResponse> { return ResponseEntity .status(HttpStatus.BAD_REQUEST) .body(ErrorResponse(status = (HttpStatus.BAD_REQUEST.value()), developerMessage = e.message)) } @ExceptionHandler(WebClientException::class, Exception::class) fun handleException(e: Exception): ResponseEntity<ErrorResponse> { return ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .body(ErrorResponse(status = (HttpStatus.INTERNAL_SERVER_ERROR.value()), developerMessage = e.message)) } }
3
Kotlin
1
1
b9f809ab29db64f84237da8ab6991c6df324d165
2,790
offender-case-notes
MIT License
app/src/main/java/com/polar/androidblesdk/DialogUtility.kt
LetMarq
801,298,442
false
{"Kotlin": 32890}
package com.polar.androidblesdk import android.app.Activity import android.app.Dialog import android.view.View import android.view.Window import android.widget.Button import android.widget.RadioGroup import android.widget.TextView import com.google.android.material.radiobutton.MaterialRadioButton import com.polar.sdk.api.model.PolarSensorSetting import com.polar.sdk.api.model.PolarSensorSetting.SettingType import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.core.SingleEmitter import java.util.* object DialogUtility { fun showAllSettingsDialog(activity: Activity, available: Map<SettingType, Set<Int>>, all: Map<SettingType, Set<Int>>): Single<PolarSensorSetting> { // custom dialog val dialog = Dialog(activity) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setContentView(R.layout.sensor_settings_dialog) val samplingRateRg = dialog.findViewById<RadioGroup>(R.id.sampling_rate_group) val resolutionRg = dialog.findViewById<RadioGroup>(R.id.resolution_group) val rangeRg = dialog.findViewById<RadioGroup>(R.id.range_group) val channelsRg = dialog.findViewById<RadioGroup>(R.id.channel_group) drawAllAndAvailableSettingsGroup( activity, samplingRateRg, SettingType.SAMPLE_RATE, available, all ) drawAllAndAvailableSettingsGroup( activity, resolutionRg, SettingType.RESOLUTION, available, all ) drawAllAndAvailableSettingsGroup(activity, rangeRg, SettingType.RANGE, available, all) drawAllAndAvailableSettingsGroup(activity, channelsRg, SettingType.CHANNELS, available, all) if (samplingRateRg.childCount == 0) { val noValues = dialog.findViewById<TextView>(R.id.sampling_rate_no_values) noValues.visibility = View.VISIBLE } if (resolutionRg.childCount == 0) { val noValues = dialog.findViewById<TextView>(R.id.resolution_no_values) noValues.visibility = View.VISIBLE } if (rangeRg.childCount == 0) { val noValues = dialog.findViewById<TextView>(R.id.range_no_values) noValues.visibility = View.VISIBLE } if (channelsRg.childCount == 0) { val noValues = dialog.findViewById<TextView>(R.id.channel_no_values) noValues.visibility = View.VISIBLE } val ok = dialog.findViewById<Button>(R.id.dialog_ok_button) ok.setOnClickListener { dialog.dismiss() } return Single.create { e: SingleEmitter<PolarSensorSetting> -> val selected: MutableMap<SettingType, Int> = EnumMap(SettingType::class.java) dialog.setOnDismissListener { handleSettingsGroupSelection(dialog, samplingRateRg, selected, SettingType.SAMPLE_RATE) handleSettingsGroupSelection(dialog, resolutionRg, selected, SettingType.RESOLUTION) handleSettingsGroupSelection(dialog, rangeRg, selected, SettingType.RANGE) handleSettingsGroupSelection(dialog, channelsRg, selected, SettingType.CHANNELS) e.onSuccess(PolarSensorSetting(selected)) } dialog.setOnCancelListener { e.tryOnError(Throwable("")) } dialog.show() }.subscribeOn(AndroidSchedulers.mainThread()) } private fun handleSettingsGroupSelection(dialog: Dialog, rg: RadioGroup, selected: MutableMap<SettingType, Int>, type: SettingType) { if (rg.childCount != 0) { val s = rg.indexOfChild(dialog.findViewById(rg.checkedRadioButtonId)) val button = rg.getChildAt(s) as MaterialRadioButton val value = Integer.valueOf(button.text.toString()) selected[type] = value } } private fun drawAllAndAvailableSettingsGroup(activity: Activity, rg: RadioGroup, type: SettingType, availableSettings: Map<SettingType, Set<Int>>, allSettings: Map<SettingType, Set<Int>>) { if (availableSettings.containsKey(type) && allSettings.containsKey(type)) { val availableValues = availableSettings[type]?.toList() allSettings[type]?.toList()?.sorted()?.let { allValues -> for (value in allValues) { val rb = MaterialRadioButton(activity) var rbText: String if (availableValues?.contains(value) == true) { rb.isEnabled = true rbText = value.toString() } else { rb.isEnabled = false rbText = "$value Available in SDK mode" } rb.text = rbText rg.addView(rb) } } } else if (availableSettings.containsKey(type)) { availableSettings[type]?.toList()?.sorted()?.let { availableValues -> for (availableValue in availableValues) { val rb = MaterialRadioButton(activity) rb.text = availableValue.toString() rg.addView(rb) } } } // Choose one to set selected val rgChildCount = rg.childCount if (rgChildCount > 0) { var index = 0 while (index < rgChildCount) { val button = rg.getChildAt(index) as MaterialRadioButton if (button.isEnabled) { break } index++ } val button = rg.getChildAt(index) as MaterialRadioButton button.isChecked = true } } }
0
Kotlin
0
0
c768c0866f707c41b458dce3cfd34d9353ec9d8f
5,827
MoveApp
MIT License
KotlinToSwift/src/main/kotlin/fr/jhelp/kotlinToSwift/postTreatment/ExtensionPostTreatment.kt
jhelpgg
600,408,546
false
null
package fr.jhelp.kotlinToSwift.postTreatment private const val EXTENSION_HEADER = "public extension " fun parseExtension(file: String): String { if (file.contains(EXTENSION_HEADER)) { return "$file\n}" } return file }
0
Kotlin
0
0
6ab79ff8f826b8c6fbf059b4ca68b9ec1da965e8
245
Kotlwift
Apache License 2.0
aTalk/src/main/java/net/java/sip/communicator/plugin/defaultresourcepack/DefaultImagePackImpl.kt
cmeng-git
704,328,019
false
{"Kotlin": 14462775, "Java": 2824517, "C": 275021, "Shell": 49203, "Makefile": 28273, "C++": 13642, "HTML": 7793, "CSS": 3127, "JavaScript": 2758, "AIDL": 375}
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * 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 net.java.sip.communicator.plugin.defaultresourcepack import net.java.sip.communicator.service.resources.ImagePack import java.util.* /** * The default image resource pack. * * @author <NAME> * @author <NAME> * @author <NAME> */ class DefaultImagePackImpl : ImagePack { /** * Returns a `Map`, containing all [key, value] pairs for this * resource pack. * * @return a `Map`, containing all [key, value] pairs for this * resource pack. */ override fun getResources(): MutableMap<String?, String?> { val resourceBundle = ResourceBundle.getBundle(DEFAULT_RESOURCE_PATH) val resources = TreeMap<String?, String?>() initResources(resourceBundle, resources) initPluginResources(resources) return resources } /** * Returns the name of this resource pack. * * @return the name of this resource pack. */ override fun getName(): String { return "Default Image Resources" } /** * Returns the description of this resource pack. * * @return the description of this resource pack. */ override fun getDescription(): String { return "Provide Jitsi default Image resource pack." } /** * Fills the given resource map with all (key,value) pairs obtained from the * given `ResourceBundle`. This method will look in the properties * files for references to other properties files and will include in the * final map data from all referenced files. * * @param resourceBundle The initial `ResourceBundle`, corresponding * to the "main" properties file. * @param resources A `Map` that would store the data. */ private fun initResources(resourceBundle: ResourceBundle, resources: MutableMap<String?, String?>) { val colorKeys = resourceBundle.keys while (colorKeys.hasMoreElements()) { val key = colorKeys.nextElement() val value = resourceBundle.getString(key) resources[key] = value } } /** * Finds all plugin color resources, matching the "images-*.properties" * pattern and adds them to this resource pack. */ private fun initPluginResources(resources: MutableMap<String?, String?>) { val pluginProperties = DefaultResourcePackActivator.findResourcePaths("resources/images", "images-*.properties") while (pluginProperties.hasNext()) { val resourceBundleName = pluginProperties.next() val resourceBundle = ResourceBundle.getBundle( resourceBundleName.substring(0, resourceBundleName.indexOf(".properties"))) initResources(resourceBundle, resources) } } companion object { private const val DEFAULT_RESOURCE_PATH = "resources.images.images" } }
0
Kotlin
0
0
393d94a8b14913b718800238838801ce6cdf5a1f
3,481
atalk-hmos_kotlin
Apache License 2.0
src/main/java/io/github/cdsap/parsetimeline/model/TimelineGraph.kt
cdsap
820,222,423
false
{"Kotlin": 26459}
package io.github.cdsap.parsetimeline.model data class TimelineGraph( val phases: List<Phase> )
0
Kotlin
0
3
db7d54a8c6c16277da894d5ef215972b75972a8b
101
TimelineParser
MIT License
app/src/main/java/com/bytemedrive/navigation/NavigationBottomBar.kt
bytemedrive
604,147,693
false
null
package com.bytemedrive.navigation import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Login import androidx.compose.material.icons.filled.Upload import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController fun getNavigationBarItems(actions: MainActions): List<NavigationBarItem> = listOf( NavigationBarItem("Sign in", Route.SIGN_IN, Icons.Filled.Login, actions.goToSignIn), NavigationBarItem("Upload", Route.UPLOAD, Icons.Filled.Upload, actions.goToUpload), ) @Composable fun NavigationBottomBar(navController: NavHostController) { val actions = remember(navController) { MainActions(navController) } val navItems = getNavigationBarItems(actions) val selectedItem = remember { mutableStateOf(navItems[0]) } BottomNavigation(elevation = 10.dp, backgroundColor = MaterialTheme.colorScheme.primary) { navItems.forEach { item -> BottomNavigationItem(icon = { Icon(imageVector = item.icon, "") }, label = { Text(text = item.title, color = MaterialTheme.colorScheme.inversePrimary) }, selected = selectedItem.value == item, onClick = { item.onPress() selectedItem.value = item }, ) } } }
0
Kotlin
0
0
90e0abb9c3d5503f771d0a9492fc615c87480ba3
1,693
android
MIT License
app/src/main/java/in/silive/lateentryproject/repositories/LoginRepository.kt
its-me-debk007
660,292,889
false
{"Kotlin": 86393}
package `in`.silive.lateentryproject.repositories import `in`.silive.lateentryproject.models.MessageDataClass import `in`.silive.lateentryproject.network.ServiceBuilder import `in`.silive.lateentryproject.sealed_class.ErrorPojoClass import `in`.silive.lateentryproject.sealed_class.Response import androidx.lifecycle.MutableLiveData import com.google.gson.Gson import com.google.gson.GsonBuilder import retrofit2.Call import retrofit2.Callback class LoginRepository { private val liveData = MutableLiveData<Response<MessageDataClass>>() fun login(email: String, password: String): MutableLiveData<Response<MessageDataClass>> { val call = ServiceBuilder.buildService(isTokenRequired = false).login(email, password) call.enqueue(object : Callback<MessageDataClass> { override fun onResponse( call: Call<MessageDataClass>, response: retrofit2.Response<MessageDataClass> ) { when { response.isSuccessful -> liveData.postValue(Response.Success(response.body()!!)) response.code() == 403 -> { val gson: Gson = GsonBuilder().create() val mError: ErrorPojoClass = gson.fromJson( response.errorBody()?.string(), ErrorPojoClass::class.java ) liveData.postValue(mError.message?.let { Response.Error(it) }) } else -> liveData.postValue(Response.Error(response.message())) } } override fun onFailure(call: Call<MessageDataClass>, t: Throwable) { val message = t.message?.let { if (it.length == 7 || it.substring(0, 17) .equals("failed to connect", ignoreCase = true) || it.substring(0, 22) == "Unable to resolve host" ) "No or poor Internet connection!" // it.length == 7 refers to it = "timeout" else "$it Please try again" } ?: "Please try again" liveData.postValue(Response.Error(message)) } }) return liveData } }
0
Kotlin
0
0
a3427a89895ba214ade1f6570274eb186c809f43
2,231
Late-Entry-Project
MIT License
src/main/kotlin/com/mark/netrune/buffer/ReadableBufferSkipDelegate.kt
Mark7625
641,050,293
false
null
package com.mark.netrune.buffer import kotlin.reflect.KProperty class ReadableBufferSkipDelegate( private val bytesToSkip: Int ) : ReadableBufferDelegate { override fun read(buffer: ReadableBuffer) { buffer.skipBytes(bytesToSkip) } operator fun getValue(thisRef: Any?, property: KProperty<*>) = Unit }
1
Kotlin
1
1
8cff984c258cf12b440e30626b60dd3f36aa9824
331
Osrs-Data-packer
MIT License
sample/base/src/main/java/club/fdawei/comkit/sample/base/CommonAppDelegate.kt
fangdawei
194,708,082
false
{"Groovy": 46142, "Kotlin": 10022}
package club.fdawei.comkit.sample.base import android.app.Application import android.util.Log import club.fdawei.comkit.annotation.AppDelegate import club.fdawei.comkit.api.app.IAppDelegate import club.fdawei.nrouter.api.NRouter /** * Created by david on 2019/07/19. */ @AppDelegate class CommonAppDelegate : IAppDelegate { override fun onCreate(app: Application) { Log.i("base", "CommonAppDelegate onCreate") NRouter.debug = BuildConfig.DEBUG NRouter.init(app) } }
0
Groovy
0
1
9845e262613487880d70598a19df6187a513e171
502
ComKit
Apache License 2.0
app/src/main/java/com/shankarlohar/pedopt_adoptapet/data/domain/PedoptUser.kt
shankarlohar
639,915,465
false
{"Kotlin": 137146}
package com.shankarlohar.pedopt_adoptapet.data.domain import android.net.Uri /** * A domain model class that represents a user with a [name], * [email] and a [photoUrl] that will be used as the profile * picture of the user. */ data class PedoptUser( val id:String, val name: String?, val email: String?, val photoUrl: Uri? )
0
Kotlin
0
0
a2e40fcc56db26d41419668671456fedf7a2aae3
347
Pedopt-Adopt-a-Pet
MIT License
AndroidGPT-android/app/src/main/java/ai/cloudcnctrai/cloudcnctrai/screens/TabThreeScreen.kt
arunabhdas
513,167,542
false
null
package ai.cloudcnctrai.cloudcnctrai.screens import ai.cloudcnctrai.cloudcnctrai.network.domain.item.GameItem import ai.cloudcnctrai.cloudcnctrai.network.domain.item.ProductItem import ai.cloudcnctrai.cloudcnctrai.theme.DeepBlue import ai.cloudcnctrai.cloudcnctrai.theme.PrimaryColor import ai.cloudcnctrai.cloudcnctrai.viewmodel.MainViewModel import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import coil.compose.rememberImagePainter @Composable fun TabThreeScreen( mainViewModel: MainViewModel = hiltViewModel() ) { val products by mainViewModel.products.collectAsState() Box( modifier = Modifier .fillMaxSize() .background(PrimaryColor), contentAlignment = Alignment.Center ) { LazyColumn { items(products) {productItem: ProductItem -> ProductCard(productItem = productItem) } } } } @Composable fun ProductCard(productItem: ProductItem) { val image = rememberImagePainter(data = productItem.image) Card ( elevation = 5.dp, shape = RoundedCornerShape(5.dp), modifier = Modifier .padding(top = 5.dp, bottom = 5.dp, start = 10.dp, end = 10.dp) .fillMaxSize() ) { Column { Image( painter = image, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .fillMaxWidth() .height(250.dp) ) Column(modifier = Modifier.padding(10.dp)) { Text( text = productItem.title, fontWeight = FontWeight.Bold ) Text( text = productItem.description, maxLines = 2, overflow = TextOverflow.Ellipsis ) } } } } @Composable @Preview fun TabThreeScreenPreview() { TabThreeScreen() }
0
Kotlin
0
0
b8a4bc43447c410b5aa98c76f4eb1f173d04a434
3,157
AndroidGPT
MIT License
lazybones/src/test/kotlin/com/skydoves/lazybones/UnitTestActivity.kt
skydoves
232,824,014
false
{"Kotlin": 46382}
/* * Designed and developed by 2020 skydoves (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.skydoves.lazybones import androidx.fragment.app.FragmentActivity class UnitTestActivity : FragmentActivity() { val testModel by lifecycleAware { TestModel() } .onCreate { number = 15 } .onStart { number = 20 } .onResume { number = 25 } .onStop { number = 30 } .onPause { number = 35 } .onDestroy { number = 40 } .lazy() }
0
Kotlin
17
350
abf63266b4445fdb00d88f12120ecdeb0d681113
980
lazybones
Apache License 2.0
app/src/main/java/com/akka/kasel/data/source/local/TransactionsLocalDataSource.kt
akkasel
445,143,540
false
null
package com.akka.kasel.data.source.local import com.akka.kasel.data.Result import com.akka.kasel.data.Result.Error import com.akka.kasel.data.Result.Success import com.akka.kasel.data.Transaction import com.akka.kasel.data.source.TransactionsDataSource import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * Concrete implementation of a data source as a db. */ class TransactionsLocalDataSource internal constructor( private val transactionsDao: TransactionsDao, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) : TransactionsDataSource { override suspend fun getTransactions() : Result<List<Transaction>> = withContext(ioDispatcher) { return@withContext try { Success(transactionsDao.getTransactions()) } catch (e: Exception) { Error(e) } } override suspend fun getTransaction(transactionId: String): Result<Transaction> = withContext(ioDispatcher) { try { val transaction = transactionsDao.getTransactionsById(transactionId) if (transaction != null) { return@withContext Success(transaction) } else { return@withContext Error(Exception("Transaction not found!")) } } catch (e: Exception) { return@withContext Error(e) } } override suspend fun saveTransaction(transaction: Transaction) = withContext(ioDispatcher) { transactionsDao.insertTransaction(transaction) } override suspend fun completeTransaction(transaction: Transaction) = withContext(ioDispatcher) { transactionsDao.updateTransaction(transaction) } override suspend fun completeTransaction(transactionId: String) { transactionsDao.updateCompleted(transactionId, true) } override suspend fun activateTransaction(transaction: Transaction) = withContext(ioDispatcher) { transactionsDao.updateCompleted(transaction.id, false) } override suspend fun activateTransaction(transactionId: String) { transactionsDao.updateCompleted(transactionId, false) } /** override suspend fun clearCompletedTasks() = withContext<Unit>(ioDispatcher) { tasksDao.deleteCompletedTasks() } */ override suspend fun deleteAllTransactions() = withContext(ioDispatcher) { transactionsDao.deleteAllTransactions() } override suspend fun deleteTransaction(transactionId: String) = withContext<Unit>(ioDispatcher) { transactionsDao.deleteTransactionById(transactionId) } }
0
Kotlin
0
1
06d514ee09d4d8ef361cafc8244c2f89702fa148
2,627
expensetracker
MIT License
app/src/androidTest/java/me/androidbox/tamboon/utils/Utilites.kt
steve1rm
279,474,581
false
null
package me.androidbox.tamboon.utils object Utilites { fun loadFromResources(path: String): String { this.javaClass.classLoader?.let { val stream = it.getResource(path) return String(stream.readBytes()) } ?: run { return "" } } }
0
Kotlin
0
0
b078d4b31bc0c0fe9bf050c1a69ffb193a2d9f20
299
donations
MIT License
src/commonMain/kotlin/your/game/MyGame.kt
minigdx
367,647,528
false
null
package your.game import com.dwursteisen.minigdx.scene.api.Scene import com.dwursteisen.minigdx.scene.api.relation.ObjectType import com.github.dwursteisen.minigdx.GameContext import com.github.dwursteisen.minigdx.ecs.Engine import com.github.dwursteisen.minigdx.ecs.components.Color import com.github.dwursteisen.minigdx.ecs.entities.EntityFactory import com.github.dwursteisen.minigdx.ecs.systems.System import com.github.dwursteisen.minigdx.file.get import com.github.dwursteisen.minigdx.game.Game import com.github.dwursteisen.minigdx.graph.GraphScene import com.github.minigdx.docs.quick.start.Cube import com.github.minigdx.docs.quick.start.RotatingCubeSystem class MyGame(override val gameContext: GameContext) : Game { private val scene by gameContext.fileHandler.get<GraphScene>("cube.protobuf") override val clearColor: Color = Color(0.5f, 0.5f) override fun createEntities(entityFactory: EntityFactory) { // Create all entities needed at startup // The scene is the node graph that can be updated in Blender scene.nodes.forEach { node -> // Create an entity using all information from this node (model, position, camera, ...) val entity = entityFactory.createFromNode(node) // The node is the cube from the Blender file if (node.type == ObjectType.MODEL) { // Mark this entity as being a cube entity.add(Cube()) } } } override fun createSystems(engine: Engine): List<System> { // Create all systems used by the game return listOf(RotatingCubeSystem()) } }
0
Kotlin
0
0
99b86266c042c47e72e81a93a3146ceb62e3a3c2
1,638
minigdx-docs
MIT License
app/src/main/java/com/ganhuo/app/ui/fragment/wan/knowledge/SquareWanFragment.kt
robertchar
250,484,237
false
null
package com.ganhuo.app.ui.fragment.wan.knowledge import android.view.LayoutInflater import androidx.recyclerview.widget.LinearLayoutManager import com.ganhuo.app.R import com.ganhuo.app.adpter.brvah.more.WanSquareAdapter import com.ganhuo.app.base.BaseFragment import com.ganhuo.app.bean.SquareData import com.ganhuo.app.constant.Constant import com.ganhuo.app.ui.activity.AgentWebActivity import com.github.kittinunf.fuel.Fuel import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.gyf.immersionbar.ImmersionBar import kotlinx.android.synthetic.main.fragment_project_wan.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.support.v4.startActivity import org.jetbrains.anko.support.v4.toast import org.jetbrains.anko.uiThread /** * author : zkk * date : 2020-03-31 14:55 * desc :wan广场 */ class SquareWanFragment : BaseFragment() { private val wanSquareAdapter by lazy { WanSquareAdapter(null) } private var page = 0 override fun getLayout(): Int { return R.layout.fragment_square_wan } companion object { fun newInstance(): SquareWanFragment { return SquareWanFragment() } } override fun initData() { super.initData() smartRefreshLayout.run { setOnRefreshListener { refresh() } setOnLoadMoreListener { loadMore() } } wanSquareAdapter.run { //设置空布局 setEmptyView( LayoutInflater.from(activity) .inflate(R.layout.fragment_home_empty, null) ) setOnItemClickListener { adapter, view, position -> val dataProject = wanSquareAdapter.data val link = dataProject[position]?.link startActivity<AgentWebActivity>( Constant.CONTENT_URL_KEY to link ) } } recyclerView.run { layoutManager = LinearLayoutManager(activity) setHasFixedSize(true) adapter = wanSquareAdapter } refresh() } private fun refresh() { page = 0 getSquareData(true) } private fun loadMore() { page++ getSquareData(false) } // 广场列表数据 private fun getSquareData(refresh: Boolean) { doAsync { Fuel.get("https://wanandroid.com/user_article/list/${page}/json") .responseString { request, response, result -> result.fold({ success -> val fromJson = Gson().fromJson<SquareData>( success, object : TypeToken<SquareData>() {}.type ) uiThread { if (fromJson.errorCode != 0) { return@uiThread } val toMutableList = fromJson.data.datas.toMutableList() if (refresh) { wanSquareAdapter.setNewData(toMutableList) smartRefreshLayout.finishRefresh(true) } else { wanSquareAdapter.addData(toMutableList) smartRefreshLayout.finishLoadMore(true) } } }, { err -> uiThread { toast(err.toString()) if (refresh) { wanSquareAdapter.setNewData(null) smartRefreshLayout.finishRefresh(false) } else { smartRefreshLayout.finishLoadMore(false) } } }) } } } }
0
Kotlin
0
1
3ce1dedf35d203a5f878fc4b2353d4e112cac8f2
3,999
KotlinGanhuo
Apache License 2.0
app/src/main/java/com/github/cirorizzo/kshows/view/MainActivityInterface.kt
usetsai
53,048,542
true
{"Kotlin": 7713}
package com.github.cirorizzo.kshows.view interface MainActivityInterface { }
0
Kotlin
0
0
4a74ad688a6c2a841cc7b71af9edfa7f5f2512e3
78
KShows
Apache License 2.0
KirraDungeonServer/src/main/kotlin/net/sakuragame/eternal/kirradungeon/server/zone/data/ZoneTriggerData.kt
Eternalland-Server
569,813,142
false
null
package net.sakuragame.eternal.kirradungeon.server.zone.data import net.sakuragame.eternal.kirradungeon.server.zone.ZoneLocation import net.sakuragame.eternal.kirradungeon.server.zone.data.sub.ZoneBlockData data class ZoneTriggerData(val triggerLoc: ZoneLocation, val blocks: MutableList<List<ZoneBlockData>>)
0
Kotlin
0
0
537f062f32d1b14cf26c89161a8efc178e596d14
311
KirraDungeon
Creative Commons Zero v1.0 Universal