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/example/android/coordinatedeffort/behaviors/navbars/ButtonsLayoutBehavior.kt
gdragan
214,374,692
true
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 32, "Java": 14, "Kotlin": 8}
package com.example.android.coordinatedeffort.behaviors.navbars import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.isGone import com.google.android.material.bottomnavigation.BottomNavigationView class ButtonsLayoutBehavior(context: Context, attrs: AttributeSet) : NavigationBarsBehavior<FrameLayout>(context, attrs) { override fun layoutDependsOn(parent: CoordinatorLayout, child: FrameLayout, dependency: View): Boolean { return dependency is BottomNavigationView } override fun onDependentViewChanged(parent: CoordinatorLayout, child: FrameLayout, dependency: View): Boolean { return updateButtonsLayout(child, dependency) } override fun onLayoutChild(parent: CoordinatorLayout, child: FrameLayout, layoutDirection: Int): Boolean { updateButtonsLayout(child, getBottomNavBar(parent)) return super.onLayoutChild(parent, child, layoutDirection) } private fun updateButtonsLayout(child: FrameLayout, dependency: View): Boolean { if (!child.isGone) { child.translationY = dependency.translationY - dependency.height return true } return false } }
0
Java
0
0
8afd0b9700bed9b93df2bcb195c4ee547fac8094
1,319
coordinated-effort
MIT License
kotlin-electron/src/jsMain/generated/electron/renderer/OnResponseStartedListenerDetails.kt
JetBrains
93,250,841
false
{"Kotlin": 11411371, "JavaScript": 154302}
package electron.renderer typealias OnResponseStartedListenerDetails = electron.core.OnResponseStartedListenerDetails
28
Kotlin
173
1,250
9e9dda28cf74f68b42a712c27f2e97d63af17628
120
kotlin-wrappers
Apache License 2.0
wow-core/src/test/kotlin/me/ahoo/wow/saga/stateless/ExchangeCommandStreamKtTest.kt
Ahoo-Wang
628,167,080
false
{"Kotlin": 1902621, "Java": 34050, "TypeScript": 31834, "HTML": 11619, "Lua": 3978, "JavaScript": 2288, "Dockerfile": 820, "SCSS": 500, "Less": 342}
package me.ahoo.wow.saga.stateless import io.mockk.mockk import me.ahoo.wow.api.event.DomainEvent import me.ahoo.wow.event.SimpleDomainEventExchange import org.hamcrest.MatcherAssert.* import org.hamcrest.Matchers.* import org.junit.jupiter.api.Test class ExchangeCommandStreamKtTest { @Test fun setCommandStream() { val exchange = SimpleDomainEventExchange(mockk<DomainEvent<Any>>()) assertThat(exchange.setCommandStream(mockk()).getCommandStream(), notNullValue()) } }
6
Kotlin
8
98
eed438bab2ae009edf3a1db03396de402885c681
502
Wow
Apache License 2.0
app/src/main/java/dev/marcos/podcast/MainActivity.kt
mrcsxsiq
360,927,587
false
null
package dev.marcos.podcast import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.LinearLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.imageview.ShapeableImageView import dev.marcos.podcast.data.Home import dev.marcos.podcast.utils.HorizontalMarginItemDecoration import retrofit2.Call import retrofit2.Callback import retrofit2.Response import kotlin.math.abs class MainActivity : AppCompatActivity() { private lateinit var viewPager: ViewPager2 private lateinit var recyclerView: RecyclerView private lateinit var bottomSheet: LinearLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) recyclerView = findViewById(R.id.recyclerView) viewPager = findViewById(R.id.pager) bottomSheet = findViewById(R.id.bottomSheet) APIService.podcastService.get().enqueue(object : Callback<Home?> { override fun onResponse(call: Call<Home?>, response: Response<Home?>) { response.body()?.let { home: Home -> // thread { viewPager.adapter = CustomAdapterViewPager(baseContext, home.featured) viewPager.offscreenPageLimit = 1 viewPager.currentItem = Int.MAX_VALUE / 2 recyclerView.adapter = CustomAdapterHorizontal(baseContext, home.regions) // } } } override fun onFailure(call: Call<Home?>, t: Throwable) { TODO("Not yet implemented") } }) val nextItemVisiblePx = resources.getDimension(R.dimen.viewpager_next_item_visible) val currentItemHorizontalMarginPx = resources.getDimension(R.dimen.viewpager_current_item_horizontal_margin) val pageTranslationX = nextItemVisiblePx + currentItemHorizontalMarginPx val pageTransformer = ViewPager2.PageTransformer { page: View, position: Float -> page.translationX = -pageTranslationX * position page.scaleY = 1 - (0.25f * abs(position)) page.alpha = 0.5f + (1 - abs(position)) } viewPager.setPageTransformer(pageTransformer) val itemDecoration = HorizontalMarginItemDecoration( baseContext, R.dimen.viewpager_current_item_horizontal_margin ) viewPager.addItemDecoration(itemDecoration) BottomSheetBehavior.from(bottomSheet).addBottomSheetCallback( object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) {} override fun onSlide(bottomSheet: View, slideOffset: Float) { val fragment = supportFragmentManager.findFragmentById(R.id.fragment_player) val playerFragment = fragment as? PlayerFragment playerFragment?.animate(slideOffset) } } ) } }
10
Kotlin
0
0
eaf4d8402a0036f298b47baa4f02ca2d7e4a01d7
3,281
Podcast
Apache License 2.0
domain/src/test/kotlin/com/example/domain/ClarifyingQuestionsSpec.kt
upelsin
133,687,964
false
null
package com.example.domain import com.example.domain.models.* import com.example.domain.submitProposal.ClarifyingQuestions import com.example.domain.submitProposal.ClarifyingQuestions.Command.INIT import com.example.domain.submitProposal.ClarifyingQuestions.Command.UpdateAnswer import com.example.domain.submitProposal.ClarifyingQuestions.Result.* import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.xit //@RunWith(JUnitPlatform::class) class ClarifyingQuestionsSpec : Spek({ val withNoQuestions = ItemOpportunity( ItemDetails("1234", false,null), Proposal(0, null, "") ) val questions = listOf( Question("1", "q1"), Question("2", "q1") ) val withQuestions = ItemOpportunity( ItemDetails("1234", false, questions), Proposal(0, null, "") ) val answers = listOf( AnsweredQuestion("1", "answer1"), AnsweredQuestion("2", "answer2") ) val withAnsweredQuestions = ItemOpportunity( ItemDetails("1234", false, questions), Proposal(0, answers, "") ) component(::ClarifyingQuestions) { initialized(INIT(withQuestions)) { describe("client initializes with data with non-empty questions") { it("should emit those questions") { assertResultAt(0, QuestionsLoaded(questions)) } it("should emit status as 'not answered'") { assertResultAt(1, AllQuestionsAnswered(false)) } describe("client updates question with a valid answer") { perform { command(UpdateAnswer("1", "answer")) } it("should emit result with a valid answer") { assertResultAt(2, ValidAnswer("1", "answer")) } } describe("client updates a question with answer leading and trailing spaces") { perform { command(UpdateAnswer("1", " answer ")) } it("should emit result with a trimmed answer") { assertResultAt(2, ValidAnswer("1", "answer")) } } describe("client updates question with answer containing only spaces") { perform { command(UpdateAnswer("1", " ")) } it("should emit result as invalid answer") { assertResultAt(2, EmptyAnswer("1")) } } } //vs /*describe("client updates question with a valid answer") { perform { command(UpdateAnswer("1", "answer")) } it("should emit result with a valid answer") { assertResultAt(2, ValidAnswer("1", "answer")) } } describe("client updates a question with answer leading and trailing spaces") { perform { command(UpdateAnswer("1", " answer ")) } it("should emit result with a trimmed answer") { assertResultAt(2, ValidAnswer("1", "answer")) } } describe("client updates question with answer containing only spaces") { perform { command(UpdateAnswer("1", " ")) } it("should emit result as invalid answer") { assertResultAt(2, EmptyAnswer("1")) } }*/ } initialized(INIT(withNoQuestions)) { describe("client initialized with data containing no questions") { it("should emit result as no questions") { //assertResultAt(0, NoQuestions) assertValuesOnly(NoQuestionsRequired) } } } //merge initialized with first describe initialized(INIT(withAnsweredQuestions)) { describe("client initializes with data with all answered questions") { it("should emit those questions") { assertResultAt(0, QuestionsLoaded(questions)) } it("should emit status as 'not answered'") { assertResultAt(1, AllQuestionsAnswered(false)) } it("should emit each answer as valid, followed by status update") { assertResultAt(2, ValidAnswer(answers[0].id, answers[0].answer)) assertResultAt(3, AllQuestionsAnswered(false)) assertResultAt(4, ValidAnswer(answers[1].id, answers[1].answer)) assertResultAt(5, AllQuestionsAnswered(true)) } xit("should emit status as all questions answered") { assertResultAt(5, AllQuestionsAnswered(true)) } describe("client deletes changes one answer to invalid") { once { println("once") command(UpdateAnswer("1", "")) } //perform { // command(UpdateAnswer("1", "")) //} it("should emit answer as invalid") { assertResultAt(6, EmptyAnswer("1")) } it("should emit status as 'not answered'") { assertResultAt(7, AllQuestionsAnswered(false)) } } } //VS /*describe("client deletes changes one answer to invalid") { perform { command(UpdateAnswer("1", "")) } it("should emit answer as invalid") { assertResultAt(6, EmptyAnswer("1")) } it("should emit status as 'not answered'") { assertResultAt(7, AllQuestionsAnswered(false)) } }*/ } } })
0
Kotlin
0
0
94462f1294059f8078c0f6e34caabc3c2eadd44d
6,379
true-clean-architecture
Apache License 2.0
shared/java/top/fpsmaster/features/impl/render/MoreParticles.kt
FPSMasterTeam
816,161,662
false
{"Java": 620089, "Kotlin": 396547, "GLSL": 2647}
package top.fpsmaster.features.impl.render import net.minecraft.block.BlockRedstoneDiode import net.minecraft.block.state.BlockStateBase import net.minecraft.block.state.BlockWorldState import net.minecraft.entity.Entity import net.minecraft.entity.EntityLivingBase import net.minecraft.init.Blocks import net.minecraft.util.EnumParticleTypes import top.fpsmaster.event.Subscribe import top.fpsmaster.event.events.EventAttack import top.fpsmaster.event.events.EventUpdate import top.fpsmaster.features.manager.Category import top.fpsmaster.features.manager.Module import top.fpsmaster.features.settings.impl.BooleanSetting import top.fpsmaster.features.settings.impl.ModeSetting import top.fpsmaster.features.settings.impl.NumberSetting import top.fpsmaster.interfaces.ProviderManager import top.fpsmaster.wrapper.WrapperEntityLightningBolt import top.fpsmaster.wrapper.blockpos.WrapperBlockPos class MoreParticles : Module("MoreParticles", Category.RENDER) { private var target: Entity? = null private var lastEffect: Entity? = null init { addSettings(sharpness, alwaysSharpness, crit, alwaysCrit, special, killEffect) } @Subscribe fun onUpdate(e: EventUpdate?) { if (target !is EntityLivingBase) return val entityLivingBase = target as EntityLivingBase if (lastEffect !== target && (entityLivingBase.health <= 0 || !entityLivingBase.isEntityAlive)) { if (killEffect.value == 1) { // summon lightning effect ProviderManager.worldClientProvider.addWeatherEffect( WrapperEntityLightningBolt( ProviderManager.worldClientProvider.getWorld(), entityLivingBase.posX, entityLivingBase.posY, entityLivingBase.posZ, false ) ) ProviderManager.soundProvider.playExplosion( entityLivingBase.posX, entityLivingBase.posY, entityLivingBase.posZ, 1f, 1.0f, false ) } else if (killEffect.value == 2) { // explosion mc.effectRenderer.emitParticleAtEntity(target, EnumParticleTypes.EXPLOSION_LARGE) ProviderManager.soundProvider.playExplosion( entityLivingBase.posX, entityLivingBase.posY, entityLivingBase.posZ, 1f, 1.0f, false ) } lastEffect = target target = null } } @Subscribe fun onAttack(e: EventAttack) { if (e.target.isEntityAlive) { target = e.target if (ProviderManager.mcProvider.getPlayer()!!.fallDistance != 0f || alwaysCrit.value) { for (i in 0 until crit.value.toInt()) { mc.effectRenderer.emitParticleAtEntity(e.target, EnumParticleTypes.CRIT) } } var needSharpness = false if (ProviderManager.mcProvider.getPlayer()!!.inventory.getCurrentItem() != null) needSharpness = !ProviderManager.utilityProvider.isItemEnhancementEmpty(ProviderManager.mcProvider.getPlayer()!!.inventory.getCurrentItem()) && ProviderManager.mcProvider.getPlayer()!!.inventory.getCurrentItem().enchantmentTagList.toString() .contains("id:16s") if (needSharpness || alwaysSharpness.value) { for (i in 0 until sharpness.value.toInt()) { mc.effectRenderer.emitParticleAtEntity(e.target, EnumParticleTypes.CRIT_MAGIC) } } if (special.value == 1) { mc.effectRenderer.emitParticleAtEntity(e.target, EnumParticleTypes.HEART) } else if (special.value == 2) { mc.effectRenderer.emitParticleAtEntity(e.target, EnumParticleTypes.FLAME) } else if (special.value == 3) { ProviderManager.soundProvider.playRedStoneBreak( e.target.posX, e.target.posY, e.target.posZ, 1f, 1f, true ) ProviderManager.effectManager.addRedStoneBreak(WrapperBlockPos(e.target.position)) } } } companion object { var sharpness = NumberSetting("Sharpness", 2, 0, 30, 1) var alwaysSharpness = BooleanSetting("AlwaysSharpness", false) var crit = NumberSetting("Crit", 2, 0, 30, 1) var alwaysCrit = BooleanSetting("AlwaysCrit", false) var special = ModeSetting("Special", 0, "None", "Heart", "Flame", "Blood") var killEffect = ModeSetting("killEffect", 0, "None", "Lightning", "Explosion") } }
19
Java
34
97
34a00cc1834e80badd0df6f5d17ae027163d0ce9
4,970
FPSMaster
MIT License
app/src/main/kotlin/net/primal/android/explore/db/TrendingHashtagDao.kt
PrimalHQ
639,579,258
false
{"Kotlin": 2548226}
package net.primal.android.explore.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface TrendingHashtagDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun upsertAll(data: List<TrendingHashtag>) @Query("DELETE FROM TrendingHashtag") fun deleteAlL() @Query("SELECT * FROM TrendingHashtag ORDER BY score DESC") fun allSortedByScore(): Flow<List<TrendingHashtag>> }
56
Kotlin
4
98
438072af7f67762c71c5dceffa0c83dedd8e2e85
520
primal-android-app
MIT License
app/src/main/java/com/zhou/android/kotlin/album/AlbumScrollListener.kt
maxiaozhou1234
81,295,250
false
null
package com.zhou.android.kotlin.album import android.support.v7.widget.RecyclerView import android.support.v7.widget.SnapHelper open class AlbumScrollListener : RecyclerView.OnScrollListener { private var helper: SnapHelper private var currentPosition = RecyclerView.NO_POSITION constructor(helper: SnapHelper) { this@AlbumScrollListener.helper = helper } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView?.layoutManager var position = 0 layoutManager?.also { val view = helper.findSnapView(it) view?.apply { position = it.getPosition(this) } } if (position == RecyclerView.NO_POSITION) { return } if (position != currentPosition) { currentPosition = position onPageSelected(position) } } override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (currentPosition == RecyclerView.NO_POSITION) return if (newState == RecyclerView.SCROLL_STATE_IDLE) { onPageScrolled(currentPosition, 0f, 0) } } public fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } open fun onPageSelected(position: Int) { } }
0
Java
72
91
1ac1fb02463856a47fd71b9925f8212693b84926
1,487
AndroidDemo
MIT License
Section 20 - Aplicativo - Gasto Viagem/Projects/GastoViagem/app/src/main/kotlin/business/TravelCostBusiness.kt
vilaJJ
861,494,712
false
{"Kotlin": 131603, "Java": 1684}
package business import business.enums.TravelCostValidateResult import business.interfaces.IValidate import entity.TravelCost internal class TravelCostBusiness : IValidate<TravelCost, TravelCostValidateResult> { override fun validate(value: TravelCost): TravelCostValidateResult { with(value) { val fieldsToValidate = arrayOf(distance, pricePerLiter, autonomy) if (fieldsToValidate.contains(null)) return TravelCostValidateResult.IncompleteFields if (autonomy!! <= 0) return TravelCostValidateResult.AutonomyIsZero return TravelCostValidateResult.Valid } } internal fun calculate(value: TravelCost): Float { with(value) { return (distance!! * pricePerLiter!!) / autonomy!! } } }
0
Kotlin
0
0
bbf9ccbd09aac27cadd8fd9fad226a86d68da992
824
Course_AndroidKotlinDevelopment_GF
The Unlicense
src/basic_control_flow/DoWhile.kt
tumininucodes
326,037,478
false
null
package basic_control_flow fun main() { var sum = 1 do { sum += 2 println(sum) } while (sum < 3) while (true) { sum += 3 println(sum) if (sum >= 200) { break } } }
0
Kotlin
0
1
cd7f87ebaabde14000879097a912f796f971ba90
246
kotlin
MIT License
src/basic_control_flow/DoWhile.kt
tumininucodes
326,037,478
false
null
package basic_control_flow fun main() { var sum = 1 do { sum += 2 println(sum) } while (sum < 3) while (true) { sum += 3 println(sum) if (sum >= 200) { break } } }
0
Kotlin
0
1
cd7f87ebaabde14000879097a912f796f971ba90
246
kotlin
MIT License
src/main/kotlin/com/hiberus/anaya/redmineeditor/components/CalendarComponent.kt
anayaHiberus
645,313,511
false
{"Kotlin": 210045, "Java": 692, "Batchfile": 504, "Shell": 240, "CSS": 43}
package com.hiberus.anaya.redmineeditor.components import com.hiberus.anaya.redmineeditor.dialogs.MyException import com.hiberus.anaya.redmineeditor.model.AppController import com.hiberus.anaya.redmineeditor.model.ChangeEvent import com.hiberus.anaya.redmineeditor.model.Model import com.hiberus.anaya.redmineeditor.utils.* import javafx.event.EventHandler import javafx.fxml.FXML import javafx.scene.control.Label import javafx.scene.layout.* import javafx.scene.paint.Color import java.time.DayOfWeek import java.time.LocalDate import java.time.format.DateTimeFormatterBuilder import java.time.format.TextStyle import java.time.temporal.ChronoField import java.util.* /** * A calendar view with colored days */ internal class CalendarComponent { /* ------------------------- properties ------------------------- */ /** * the currently displayed labels */ private val days = arrayOfNulls<Label>(31) /** * the selected day index from [days] */ private var selected = -1 /* ------------------------- views ------------------------- */ @FXML lateinit var calendarLabel: Label // month/year label @FXML lateinit var calendar: GridPane // grid /* ------------------------- init ------------------------- */ @FXML private fun initialize() { // create the header DayOfWeek.values().forEach { // append each day calendar.add( CenteredLabel( it.getDisplayName(TextStyle.SHORT, Locale.getDefault()) ), it.value - 1, 0 ) } // on new month, draw grid AppController.onChanges(setOf(ChangeEvent.Month)) { model: Model -> drawGrid(model) } // when hours change, recolor day AppController.onChanges(setOf(ChangeEvent.DayHours)) { model: Model -> model.day?.let { colorDay(it, model) } } // when month or hours change, set label AppController.onChanges(setOf(ChangeEvent.Month, ChangeEvent.DayHours, ChangeEvent.MonthHours)) { model -> updateLabel(model) } // when month or month hours change, color days AppController.onChanges(setOf(ChangeEvent.Month, ChangeEvent.MonthHours)) { model: Model -> // color days colorDays(model) } // when day changes (or month), set selection AppController.onChanges(setOf(ChangeEvent.Day, ChangeEvent.Month)) { model: Model -> // unselect unselectDay() // select new (if there is a selection) model.day?.let { selected = it - 1 days[selected]?.border = Border(BorderStroke(Color.DARKGRAY, BorderStrokeStyle.SOLID, CornerRadii(5.0), BorderWidths(1.0))) } } } /* ------------------------- actions ------------------------- */ @FXML private fun onNextMonth() = AppController.runBackground { model: Model.Editor -> // next month loadMonth(1, model) } @FXML private fun onPreviousMonth() = AppController.runBackground { model: Model.Editor -> // previous month loadMonth(-1, model) } /* ------------------------- internal ------------------------- */ @Throws(MyException::class) private fun loadMonth(offset: Int, model: Model.Editor) = with(model) { // change month by offset month = month.plusMonths(offset.toLong()) // unselect the day day = null } /** * color all days of current month */ private fun colorDays(model: Model) = (1..model.month.lengthOfMonth()) .forEach { colorDay(it, model) } /** * color a single day of current month */ private fun colorDay(day: Int, model: Model) = model.month.atDay(day).let { date -> days[day - 1]?.let { label -> // main color val mainColor = model.getSpent(date)?.let { getColor( date.expectedHours, it, date ) } label.backgroundColor = mainColor // special color if (mainColor != null) { model.getLoadedEntriesFromDate(date)?.filter { it.spent > 0 }?.map { (it.issue.color ?: mainColor) to it.spent }?.average?.takeIf { it != mainColor }?.let { // set weighted average of issues colors if different label.indicatorColor(mainColor, it) } } } } /** * Updates the month/year label and color */ private fun updateLabel(model: Model) { val month = model.month // month info var label = DateTimeFormatterBuilder() .appendText(ChronoField.MONTH_OF_YEAR) .appendLiteral(", ") .appendText(ChronoField.YEAR) .toFormatter() .format(month) val spent = model.getSpent(month) if (spent != null) { // loaded, append spent/expected and set color val expected = month.expectedHours label += " (${spent.formatHours()}/${expected.formatHours()})" calendarLabel.backgroundColor = getColor( expected, spent, // last/today/first when { month == LocalDate.now().yearMonth -> LocalDate.now() month > LocalDate.now().yearMonth -> month.atDay(1) else -> month.atEndOfMonth() } ) } else { // not loaded, clear calendarLabel.backgroundColor = null } // set calendarLabel.text = label } /** * recreates the days grid */ private fun drawGrid(model: Model) { // clear calendar.children.removeAll(days) days.fill(null) unselectDay() // draw month val month = model.month val padding = month.atDay(1).dayOfWeek.value - 1 // number of days between monday and 1 val numberOfDays = month.lengthOfMonth() // days in month for (day in 1..numberOfDays) { // foreach day in month val index = day + padding - 1 val column = index / 7 + 1 // add missing row if needed if (column >= calendar.rowCount) calendar.rowConstraints += RowConstraints().apply { vgrow = Priority.SOMETIMES } // add and save label calendar.add(CenteredLabel(day.toString()).apply { onMouseClicked = EventHandler { selectDay(day) } // today in bold if (LocalDate.now() == month.atDay(day)) style = "-fx-font-weight: bold" days[day - 1] = this }, index % 7, column) } // remove extra rows while (calendar.rowCount > (numberOfDays + padding - 1) / 7 + 2) { calendar.rowConstraints.removeAt(calendar.rowCount - 1) } } /** * select a specific day */ private fun selectDay(day: Int) = AppController.runBackground { model -> model.day = day } /** * unselect if existing */ private fun unselectDay() { if (selected != -1) days[selected]?.border = null selected = -1 } }
1
Kotlin
0
3
b0bac42c74907f2b29b832a2e6bd1d57f3831e5f
7,540
redmineeditor
Creative Commons Attribution 4.0 International
src/main/kotlin/li/cli/oc/blockentity/Assembler.kt
rschulman
321,812,124
true
{"Kotlin": 146460}
package li.cli.oc.blockentity import li.cli.oc.blockentity.commons.TecBlockEntity import li.cli.oc.components.BlockEntitiesComponent class Assembler: TecBlockEntity(BlockEntitiesComponent.Assembler)
0
Kotlin
0
1
5f7e00057e053151967990b5a5db63184a2d22c8
200
OpenComputers
Creative Commons Zero v1.0 Universal
infrastructure/gateway/src/main/kotlin/com/hyosakura/gateway/config/CorsConfig.kt
LovesAsuna
452,657,888
false
null
package com.hyosakura.gateway.config import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.reactive.CorsWebFilter import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource import org.springframework.web.util.pattern.PathPatternParser @Configuration open class CorsConfig { @Bean open fun corsFilter(): CorsWebFilter { val config = CorsConfiguration() config.addAllowedMethod("*") config.addAllowedOrigin("*") config.addAllowedHeader("*") val source = UrlBasedCorsConfigurationSource(PathPatternParser()) source.registerCorsConfiguration("/**", config) return CorsWebFilter(source) } }
0
Kotlin
0
0
3a65bc1383e9a161d3a1e036551d9990437f4881
820
OnlineEducation
MIT License
src/main/kotlin/br/com/lucascm/mangaeasy/micro_api_monolito/core/service/HandleExceptions.kt
manga-easy
627,169,031
false
{"Kotlin": 251162, "Dockerfile": 130}
package br.com.lucascm.mangaeasy.micro_api_monolito.core.service import br.com.lucascm.mangaeasy.micro_api_monolito.core.entities.BusinessException import br.com.lucascm.mangaeasy.micro_api_monolito.core.entities.ResultEntity import br.com.lucascm.mangaeasy.micro_api_monolito.core.entities.StatusResultEnum import io.sentry.Sentry import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service @Deprecated("Descontinuado") class HandleExceptions { val log: Logger = LoggerFactory.getLogger(this::class.java) fun handleCatch(e: Exception): ResultEntity { if (e is BusinessException) { return ResultEntity( total = 0, status = StatusResultEnum.ERROR, data = listOf(), message = e.message ) } Sentry.captureException(e); log.error("HandleExceptions", e) throw e } }
0
Kotlin
1
3
15fd84cde173a9973225b5563fd137271e3d0c8f
952
manga_easy_micro_api_monolito
MIT License
app/src/main/java/com/bsuir/bsuirschedule/presentation/viewModels/ScheduleViewModel.kt
Saydullin
526,953,048
false
null
package com.bsuir.bsuirschedule.presentation.viewModels import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bsuir.bsuirschedule.BuildConfig import com.bsuir.bsuirschedule.domain.models.* import com.bsuir.bsuirschedule.domain.models.scheduleSettings.ScheduleSettings import com.bsuir.bsuirschedule.domain.usecase.GetCurrentWeekUseCase import com.bsuir.bsuirschedule.domain.usecase.GetSavedScheduleUseCase import com.bsuir.bsuirschedule.domain.usecase.SharedPrefsUseCase import com.bsuir.bsuirschedule.domain.usecase.schedule.* import com.bsuir.bsuirschedule.domain.utils.Resource import com.bsuir.bsuirschedule.domain.utils.StatusCode import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ScheduleViewModel( private val getScheduleUseCase: GetScheduleUseCase, private val scheduleSubjectUseCase: ScheduleSubjectUseCase, private val updateScheduleSettingsUseCase: UpdateScheduleSettingsUseCase, private val savedScheduleUseCase: GetSavedScheduleUseCase, private val saveScheduleUseCase: SaveScheduleUseCase, private val deleteScheduleUseCase: DeleteScheduleUseCase, private val sharedPrefsUseCase: SharedPrefsUseCase, private val getCurrentWeekUseCase: GetCurrentWeekUseCase, private val addScheduleSubjectUseCase: AddScheduleSubjectUseCase ) : ViewModel() { private val loading = MutableLiveData(false) private val update = MutableLiveData(false) private val dataLoading = MutableLiveData(true) private val scheduleLoaded = MutableLiveData<SavedSchedule>(null) private val activeSubject = MutableLiveData<ScheduleSubject>(null) private val groupLoading = MutableLiveData(false) private val settingsUpdated = MutableLiveData(false) private val employeeLoading = MutableLiveData(false) private val activeScheduleId = MutableLiveData<Int>(null) private val schedule = MutableLiveData<Schedule>(null) private val deletedSchedule = MutableLiveData<SavedSchedule>(null) private val error = MutableLiveData<StateStatus>(null) private val success = MutableLiveData<StatusCode>(null) val scheduleStatus = schedule val activeSubjectStatus = activeSubject val settingsUpdatedStatus = settingsUpdated val deletedScheduleStatus = deletedSchedule val errorStatus = error val successStatus = success val scheduleLoadedStatus = scheduleLoaded val loadingStatus = loading val dataLoadingStatus = dataLoading val groupLoadingStatus = groupLoading val employeeLoadingStatus = employeeLoading init { val scheduleId = activeScheduleId.value ?: -1 if (sharedPrefsUseCase.getScheduleCounter() < BuildConfig.SCHEDULES_UPDATE_COUNTER) { sharedPrefsUseCase.setScheduleCounter(BuildConfig.SCHEDULES_UPDATE_COUNTER) updateAllSchedules() } updateSchedule(scheduleId) } fun setScheduleLoadedNull() { scheduleLoaded.value = null } fun setSuccessNull() { success.value = null } fun setActiveSubject(subject: ScheduleSubject) { activeSubject.value = subject } fun setDeletedScheduleNull() { deletedSchedule.value = null } fun setUpdateStatus(updateStatus: Boolean) { update.value = updateStatus } fun updateSchedule(scheduleId: Int = activeScheduleId.value ?: -1) { if (update.value == true && scheduleId != -1) { settingsUpdated.postValue(false) getScheduleById(scheduleId, false) } } fun getActiveSubject(): ScheduleSubject? { return activeSubject.value } fun getActiveSchedule(): Schedule? { return schedule.value } fun ignoreSubject(scheduleSubject: ScheduleSubject, isIgnored: Boolean) { viewModelScope.launch(Dispatchers.IO) { if (schedule.value == null || schedule.value!!.id == -1) { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = StatusCode.DATA_ERROR, )) } val scheduleId = schedule.value!!.id when ( val result = scheduleSubjectUseCase.ignore( scheduleId = scheduleId, scheduleSubject = scheduleSubject, isIgnored = isIgnored ) ) { is Resource.Success -> { val data = result.data!! when ( val saveResponse = saveScheduleUseCase.execute(data) ) { is Resource.Success -> { if (isIgnored) { success.postValue(StatusCode.SCHEDULE_SUBJECT_IGNORED) } else { success.postValue(StatusCode.SCHEDULE_SUBJECT_NOT_IGNORED) } getScheduleById(data.id, isNotUpdate = false) } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = saveResponse.statusCode, )) } } } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = result.statusCode, )) } } } } fun editSubject(scheduleSubject: ScheduleSubject, changeSettings: ChangeSubjectSettings) { viewModelScope.launch(Dispatchers.IO) { if (schedule.value == null || schedule.value!!.id == -1) { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = StatusCode.DATA_ERROR, )) } val scheduleId = schedule.value!!.id when ( val result = scheduleSubjectUseCase.edit( scheduleId = scheduleId, scheduleSubject = scheduleSubject, deleteSettings = changeSettings ) ) { is Resource.Success -> { val data = result.data!! when ( val saveResponse = saveScheduleUseCase.execute(data) ) { is Resource.Success -> { success.postValue(StatusCode.SCHEDULE_SUBJECT_EDITED) getScheduleById(data.id, isNotUpdate = false) } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = saveResponse.statusCode, )) } } } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = result.statusCode, )) } } } } fun deleteSubject(scheduleSubject: ScheduleSubject, changeSettings: ChangeSubjectSettings) { viewModelScope.launch(Dispatchers.IO) { if (schedule.value == null || schedule.value!!.id == -1) { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = StatusCode.DATA_ERROR, )) } val scheduleId = schedule.value!!.id when ( val result = scheduleSubjectUseCase.delete( scheduleId = scheduleId, scheduleSubject = scheduleSubject, deleteSettings = changeSettings ) ) { is Resource.Success -> { val data = result.data!! when ( val saveResponse = saveScheduleUseCase.execute(data) ) { is Resource.Success -> { success.postValue(StatusCode.SCHEDULE_SUBJECT_DELETED) getScheduleById(data.id, isNotUpdate = false) } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = saveResponse.statusCode, )) } } } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = result.statusCode, )) } } } } fun addCustomSubject(subject: ScheduleSubject, sourceItemsText: String) { viewModelScope.launch(Dispatchers.IO) { val scheduleId = schedule.value?.id ?: return@launch when ( val res = addScheduleSubjectUseCase.execute(scheduleId, subject, sourceItemsText) ) { is Resource.Success -> { success.postValue(StatusCode.SCHEDULE_SUBJECT_ADDED) updateSchedule() } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = res.statusCode, message = res.message )) } } } } fun getOrUploadSchedule(savedSchedule: SavedSchedule) { viewModelScope.launch(Dispatchers.IO) { when ( val result = getScheduleUseCase.getById(savedSchedule.id) ) { is Resource.Success -> { val data = result.data!! saveScheduleToLiveData(data) } is Resource.Error -> { if (savedSchedule.isGroup) { getGroupScheduleAPI(savedSchedule.group) } else { getEmployeeScheduleAPI(savedSchedule.employee) } } } } } fun selectSchedule(scheduleId: Int) { activeScheduleId.value = scheduleId } fun closeError() { error.value = null } fun initActiveSchedule() { viewModelScope.launch(Dispatchers.IO) { val activeScheduleId = sharedPrefsUseCase.getActiveScheduleId() if (activeScheduleId != -1) { getScheduleById(activeScheduleId) } } } fun renameSchedule(scheduleId: Int, newTitle: String) { viewModelScope.launch(Dispatchers.IO) { when ( val result = getScheduleUseCase.getById(scheduleId) ) { is Resource.Success -> { val data = result.data!! if (data.isGroup()) { data.group.title = newTitle } else { data.employee.title = newTitle } saveSchedule(data) } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = result.statusCode, message = result.message )) } } } } fun getGroupScheduleAPI(group: Group, isUpdate: Boolean = false, toNotify: Boolean = true) { viewModelScope.launch(Dispatchers.IO) { loading.postValue(true) groupLoading.postValue(true) val currentWeek = getCurrentWeekUseCase.getCurrentWeek() if (currentWeek is Resource.Error) { val currentWeekAPI = launch(Dispatchers.IO) { getCurrentWeekUseCase.updateWeekNumber() } currentWeekAPI.join() } when ( val groupScheduleResponse = getScheduleUseCase.getGroupAPI(group.name) ) { is Resource.Success -> { val groupSchedule = groupScheduleResponse.data!! scheduleLoaded.postValue(group.toSavedSchedule(!groupSchedule.isExamsNotExist())) if (toNotify) { saveSchedule(groupSchedule) if (isUpdate) { success.postValue(StatusCode.SCHEDULE_UPDATED_SUCCESS) } else { success.postValue(StatusCode.SCHEDULE_LOADED_SUCCESS) } } else { saveScheduleSilently(groupSchedule) } } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = groupScheduleResponse.statusCode, message = groupScheduleResponse.message )) } } loading.postValue(false) groupLoading.postValue(false) } } fun getEmployeeScheduleAPI(employee: Employee, isUpdate: Boolean = false, toNotify: Boolean = true) { viewModelScope.launch(Dispatchers.IO) { loading.postValue(true) employeeLoading.postValue(true) when ( val groupSchedule = employee.urlId?.let { getScheduleUseCase.getEmployeeAPI(it) } ) { is Resource.Success -> { val data = groupSchedule.data!! scheduleLoaded.postValue(employee.toSavedSchedule(!data.isExamsNotExist())) if (toNotify) { saveSchedule(data) if (isUpdate) { success.postValue(StatusCode.SCHEDULE_UPDATED_SUCCESS) } else { success.postValue(StatusCode.SCHEDULE_LOADED_SUCCESS) } } else { saveScheduleSilently(data) } } else -> { error.postValue( StateStatus( state = StateStatus.ERROR_STATE, type = groupSchedule?.statusCode ?: StatusCode.UNKNOWN_ERROR, message = groupSchedule?.message ?: "" ) ) } } loading.postValue(false) employeeLoading.postValue(false) } } private fun saveSchedule(groupSchedule: Schedule) { viewModelScope.launch(Dispatchers.IO) { when ( val saveResponse = saveScheduleUseCase.execute(groupSchedule) ) { is Resource.Success -> { if (groupSchedule.id == -1) { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = StatusCode.DATA_ERROR )) schedule.postValue(null) } else { getScheduleById(groupSchedule.id) } } is Resource.Error -> { schedule.postValue(null) error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = saveResponse.statusCode, message = saveResponse.message )) } } } } private fun saveScheduleSilently(groupSchedule: Schedule) { viewModelScope.launch(Dispatchers.IO) { when ( val saveResponse = saveScheduleUseCase.execute(groupSchedule) ) { is Resource.Success -> { if (groupSchedule.id == -1) { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = StatusCode.DATA_ERROR )) } } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = saveResponse.statusCode, message = saveResponse.message )) } } } } fun updateScheduleSettings(id: Int, newSettings: ScheduleSettings) { viewModelScope.launch(Dispatchers.IO) { settingsUpdated.postValue(false) when ( val saveResponse = updateScheduleSettingsUseCase.invoke(id, newSettings) ) { is Resource.Success -> { settingsUpdated.postValue(true) getScheduleById(id) } is Resource.Error -> { schedule.postValue(null) error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = saveResponse.statusCode, message = saveResponse.message )) } } } } private fun saveScheduleToLiveData(scheduleData: Schedule) { activeScheduleId.postValue(scheduleData.id) schedule.postValue(scheduleData) sharedPrefsUseCase.setActiveScheduleId(scheduleData.id) } private fun getScheduleById(scheduleId: Int, isNotUpdate: Boolean = true) { if (scheduleId == -1) { schedule.postValue(null) error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = StatusCode.DATABASE_NOT_FOUND_ERROR )) return } viewModelScope.launch(Dispatchers.IO) { dataLoading.postValue(isNotUpdate) when ( val result = getScheduleUseCase.getById(scheduleId) ) { is Resource.Success -> { val data = result.data!! saveScheduleToLiveData(data) } is Resource.Error -> { schedule.postValue(null) error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = result.statusCode, message = result.message )) } } settingsUpdated.postValue(false) dataLoading.postValue(false) } } fun deleteSchedule(savedSchedule: SavedSchedule) { viewModelScope.launch(Dispatchers.IO) { when ( val isDeletedSchedule = deleteScheduleUseCase.invoke(savedSchedule) ) { is Resource.Success -> { success.postValue(StatusCode.SCHEDULE_DELETED_SUCCESS) deletedSchedule.postValue(savedSchedule) if (schedule.value?.id == savedSchedule.id) { schedule.postValue(null) activeScheduleId.postValue(null) sharedPrefsUseCase.setActiveScheduleId(-1) } } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = isDeletedSchedule.statusCode, message = isDeletedSchedule.message )) } } } } private fun updateAllSchedules() { viewModelScope.launch(Dispatchers.IO) { loading.postValue(true) when ( val savedSchedules = savedScheduleUseCase.getSavedSchedules() ) { is Resource.Success -> { val savedSchedulesList = savedSchedules.data ?: arrayListOf() val updateAllSchedulesIO = launch(Dispatchers.IO) { savedSchedulesList.forEach { savedSchedule -> when ( val groupScheduleResponse = if (savedSchedule.isGroup) getScheduleUseCase.getGroupAPI(savedSchedule.group.name) else savedSchedule.employee.urlId?.let { getScheduleUseCase.getEmployeeAPI( it ) } ) { is Resource.Success -> { val groupSchedule = groupScheduleResponse.data!! scheduleLoaded.postValue(savedSchedule) saveScheduleSilently(groupSchedule) } else -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = groupScheduleResponse?.statusCode ?: StatusCode.UNKNOWN_ERROR, message = groupScheduleResponse?.message )) } } } } updateAllSchedulesIO.join() if (updateAllSchedulesIO.isCancelled) { success.postValue(StatusCode.UPDATE_ERROR) } else { success.postValue(StatusCode.ALL_SCHEDULES_UPDATED_SUCCESS) if (schedule.value != null && schedule.value?.id != -1) { val scheduleId = schedule.value!!.id getScheduleById(scheduleId, false) } } } is Resource.Error -> { error.postValue(StateStatus( state = StateStatus.ERROR_STATE, type = savedSchedules.statusCode, message = savedSchedules.message )) } } loading.postValue(false) } } }
0
Kotlin
0
4
edb67f1ec3602227f4a4a757bc89a6ec587160c3
23,258
BSUIR_Schedule
Creative Commons Zero v1.0 Universal
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirDataClassNonPublicConstructorChecker.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.analysis.checkers.declaration import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.diagnostics.DiagnosticReporter import org.jetbrains.kotlin.diagnostics.reportOn import org.jetbrains.kotlin.fir.analysis.checkers.MppCheckerKind import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors import org.jetbrains.kotlin.fir.declarations.FirRegularClass import org.jetbrains.kotlin.fir.declarations.hasAnnotation import org.jetbrains.kotlin.fir.declarations.primaryConstructorIfAny import org.jetbrains.kotlin.fir.declarations.utils.isData import org.jetbrains.kotlin.fir.declarations.utils.visibility import org.jetbrains.kotlin.name.StandardClassIds object FirDataClassNonPublicConstructorChecker : FirRegularClassChecker(MppCheckerKind.Common) { override fun check(declaration: FirRegularClass, context: CheckerContext, reporter: DiagnosticReporter) { if (context.languageVersionSettings.supportsFeature(LanguageFeature.DataClassCopyRespectsConstructorVisibility)) { return } if (declaration.classKind != ClassKind.CLASS || !declaration.isData) { return } val primaryConstructor = declaration.primaryConstructorIfAny(context.session) ?: return if (primaryConstructor.visibility == Visibilities.Public) { return } val isAlreadyAnnotated = declaration.hasAnnotation(StandardClassIds.Annotations.ConsistentCopyVisibility, context.session) || declaration.hasAnnotation(StandardClassIds.Annotations.ExposedCopyVisibility, context.session) if (isAlreadyAnnotated) { return } reporter.reportOn(primaryConstructor.source, FirErrors.DATA_CLASS_COPY_VISIBILITY_WILL_BE_CHANGED, context) } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,189
kotlin
Apache License 2.0
fundamentos/fundamentos-gerais/src/main/kotlin/e/maisfuncoes/06-MaisFuncoes-Generics.kt
CarlosRobertoMedeiros
725,864,363
false
{"Kotlin": 64689, "Java": 78}
package e.maisfuncoes fun main() { println(calcularMedia(1f,2f,3f,5.75f)) println(calcularMediaOpcao2(false,2f,3f,5.75f)) } //Exemplo de Genérics cuidado com os tipos de dados de entrada fun <T> calcularMedia(vararg notas: T):Float{ var soma=0f for (n in notas) { if (n is Float) soma +=n } return (soma/notas.size) } //Exemplo 2 o varargs sempre tem que ser o último a ser exposto na função fun <T, J> calcularMediaOpcao2(abc:J, vararg notas: T):Float{ var soma=0f for (n in notas) { if (n is Float) soma +=n } return (soma/notas.size) } //Exemplo 3 Biblioteca do Kotlin usando Varargs com Generics fun exemplo3(){ arrayOf(2,2,3,6,2,6,45f,false) }
0
Kotlin
0
0
79bdb9a8f3d77df959149285ca5ab444f26c65b5
716
repo-kotlin-developer-
RSA Message-Digest License
core/network/src/main/java/com/hankki/core/network/StringExt.kt
Team-Hankki
816,081,730
false
{"Kotlin": 597927}
package com.hankki.core.network fun String?.isJsonObject(): Boolean = this?.startsWith("{") == true && this.endsWith("}") fun String?.isJsonArray(): Boolean = this?.startsWith("[") == true && this.endsWith("]")
1
Kotlin
0
43
959b647e3b42fe1ae96d85c87ea7cc7ebfb74266
213
hankki-android
Apache License 2.0
src/main/kotlin/org/elm/workspace/commandLineTools/ElmFormatCLI.kt
harxki
173,057,537
true
{"Kotlin": 865685, "Java": 76672, "Elm": 11060, "Lex": 5783, "HTML": 370}
package org.elm.workspace.commandLineTools import com.intellij.execution.ExecutionException import com.intellij.execution.process.ProcessOutput import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Document import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.elm.lang.core.psi.ElmFile import org.elm.openapiext.* import org.elm.workspace.ElmApplicationProject import org.elm.workspace.ElmPackageProject import org.elm.workspace.ParseException import org.elm.workspace.Version import java.nio.file.Path private val log = logger<ElmFormatCLI>() /** * Interact with external `elm-format` process. */ class ElmFormatCLI(private val elmFormatExecutablePath: Path) { private fun getFormattedContentOfDocument(elmVersion: Version, document: Document): ProcessOutput { val arguments = listOf( "--yes", "--elm-version=${elmVersion.x}.${elmVersion.y}", "--stdin" ) return GeneralCommandLine(elmFormatExecutablePath) .withParameters(arguments) .execute(document.text) } fun formatDocumentAndSetText(project: Project, document: Document, version: Version, addToUndoStack: Boolean) { val result = ProgressManager.getInstance().runProcessWithProgressSynchronously<ProcessOutput, ExecutionException>({ getFormattedContentOfDocument(version, document) }, "Running elm-format on current file...", true, project) if (result.isSuccess) { val formatted = result.stdout val source = document.text if (source != formatted) { val writeAction = { ApplicationManager.getApplication().runWriteAction { document.setText(formatted) } } if (addToUndoStack) { CommandProcessor.getInstance().executeCommand(project, writeAction, "Run elm-format on current file", null, document) } else { CommandProcessor.getInstance().runUndoTransparentAction(writeAction) } } } } fun queryVersion(): Result<Version> { // Output of `elm-format` is multiple lines where the first line is 'elm-format 0.8.1' val versionRegex = Regex("elm-format (\\d+(?:\\.\\d+){2})") val firstLine = try { GeneralCommandLine(elmFormatExecutablePath) .execute(timeoutInMilliseconds = 3000) .stdoutLines .firstOrNull() } catch (e: ExecutionException) { return Result.Err("failed to run elm-format: ${e.message}") } if (firstLine == null) { return Result.Err("no output from elm-format") } val matchResult = versionRegex.matchEntire(firstLine) ?: return Result.Err("could not find version in first line of elm-format output: ${firstLine}") val (elmVersionString) = matchResult.destructured return try { Result.Ok(Version.parse(elmVersionString)) } catch (e: ParseException) { Result.Err("invalid elm-format version: ${e.message}") } } companion object { fun getElmVersion(project: Project, file: VirtualFile): Version? { val psiFile = (file.toPsiFile(project) as? ElmFile) ?: return null return when (val elmProject = psiFile.elmProject) { is ElmApplicationProject -> elmProject.elmVersion is ElmPackageProject -> elmProject.elmVersion.low else -> return null } } } }
0
Kotlin
0
0
ca49fc75e1d9e0d05dbbdd10171b729bdcb455ec
3,906
intellij-elm
MIT License
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/targets/js/KotlinJsTargetPreset.kt
leo-from-spb
176,960,056
true
{"Kotlin": 34511216, "Java": 7467969, "JavaScript": 152998, "HTML": 73852, "Lex": 23159, "IDL": 10758, "ANTLR": 9803, "Shell": 7727, "Groovy": 6893, "Batchfile": 5362, "CSS": 4679, "Objective-C": 182, "Scala": 80}
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ @file:Suppress("PackageDirectoryMismatch") // Old package for compatibility package org.jetbrains.kotlin.gradle.plugin.mpp import org.gradle.api.Project import org.jetbrains.kotlin.gradle.plugin.Kotlin2JsSourceSetProcessor import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSetProcessor import org.jetbrains.kotlin.gradle.tasks.KotlinTasksProvider open class KotlinJsTargetPreset( project: Project, kotlinPluginVersion: String ) : KotlinOnlyTargetPreset<KotlinJsCompilation>( project, kotlinPluginVersion ) { override fun getName(): String = PRESET_NAME override fun createCompilationFactory(forTarget: KotlinOnlyTarget<KotlinJsCompilation>) = KotlinJsCompilationFactory(project, forTarget) override val platformType: KotlinPlatformType get() = KotlinPlatformType.js override fun buildCompilationProcessor(compilation: KotlinJsCompilation): KotlinSourceSetProcessor<*> { val tasksProvider = KotlinTasksProvider(compilation.target.targetName) return Kotlin2JsSourceSetProcessor(project, tasksProvider, compilation, kotlinPluginVersion) } companion object { const val PRESET_NAME = "js" } } class KotlinJsSingleTargetPreset( project: Project, kotlinPluginVersion: String ) : KotlinJsTargetPreset(project, kotlinPluginVersion) { // In a Kotlin/JS single-platform project, we don't need any disambiguation suffixes or prefixes in the names: override fun provideTargetDisambiguationClassifier(target: KotlinOnlyTarget<KotlinJsCompilation>): String? = null }
0
Kotlin
0
0
7f08ecee3919f4648a0a1f9254932a269809c680
1,792
kotlin
Apache License 2.0
LAB9/app/src/main/java/com/example/lab9/DatabaseHelper.kt
pear05
568,747,747
false
null
package com.example.lab9 import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper class DatabaseHelper(context : Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DB_VERSION){ companion object { private val DATABASE_NAME = "STRATHMORE" private val DB_VERSION = 1 val TABLE_NAME = "student_table" val ID_COLUMN = "id" val NAME_COLUMN = "name" val YOB_COLUMN = "YearOfBirth" val EMAIL_COLUMN = "email" } override fun onCreate(db: SQLiteDatabase?){ val query = ("CREATE TABLE $TABLE_NAME ($ID_COLUMN INTEGER PRIMARY KEY, " + "$NAME_COLUMN TEXT, $YOB_COLUMN TEXT, $EMAIL_COLUMN, TEXT)") db?.execSQL(query) } override fun onUpgrade(db: SQLiteDatabase?, p1: Int, p2: Int){ db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME") onCreate(db) } fun addRecord(name: String, yob:String, email:String){ val values = ContentValues() values.put(NAME_COLUMN, name) values.put(YOB_COLUMN, yob) values.put(EMAIL_COLUMN, email) val db = this.writableDatabase db.insert(TABLE_NAME, null, values) db.close() } fun getRecords() : Cursor { val db = this.readableDatabase return db.rawQuery("SELECT * FROM $TABLE_NAME", null) } }
0
Kotlin
0
0
c490b4a539d9cedf9073ac913efaee4c5946d2fd
1,464
Kotlin_sample_projects
The Unlicense
directappupdate/src/main/java/com/micoder/directappupdate/viewmodel/NotificationViewModel.kt
Micoder-dev
807,587,959
false
{"Kotlin": 34355}
package com.micoder.directappupdate.viewmodel import android.annotation.SuppressLint import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.micoder.directappupdate.di.DirectAppUpdateNotificationCompatBuilder import com.micoder.directappupdate.di.DirectAppUpdateNotificationManager import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject /** * A [ViewModel] that handles the notification progress. */ @SuppressLint("MissingPermission") @HiltViewModel class NotificationViewModel @Inject constructor( @DirectAppUpdateNotificationCompatBuilder private val notificationBuilder: NotificationCompat.Builder, @DirectAppUpdateNotificationManager private val notificationManager: NotificationManagerCompat ) : ViewModel() { fun showProgress(progress: Int, icon: Int) { val max = 100 viewModelScope.launch { notificationManager.notify(3, notificationBuilder .setContentTitle("Downloading $progress%") .setContentText("") .setSmallIcon(icon) .setProgress(max, progress, false) .build()) if (progress == max) { notificationManager.cancel(3) notificationManager.notify(3, notificationBuilder .setContentTitle("Completed!") .setContentText("") .setContentIntent(null) .clearActions() .setProgress(0, 0, false) .build()) } } } }
0
Kotlin
0
0
152a2adc27e1cc27f6ee0fd94f01e799b1e746fd
1,710
DirectAppUpdate
MIT License
src/main/kotlin/api/common/Beans.kt
cdimascio
151,765,325
false
null
package api.common import api.users.UsersService import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class Beans { @Bean fun userService(): UsersService { return UsersService() } }
0
Kotlin
8
22
f99b10ba0686abc82ddcd13993f804644f29af2c
277
kotlin-spring-mvc-template
Apache License 2.0
app/src/main/java/com/jadebyte/jadeplayer/main/common/view/ZoomOutPageTransformer.kt
wilburt
177,040,268
false
null
// Copyright (c) 2019 . <NAME>. All Rights Reserved. package com.jadebyte.jadeplayer.main.common.view import android.view.View import androidx.viewpager.widget.ViewPager import kotlin.math.abs import kotlin.math.max /** * Created by Wilberforce on 2019-05-02 at 01:58. * * Original source: https://developer.android.com/training/animation/screen-slide#zoom-out */ private const val MIN_SCALE = 0.6f private const val MIN_ALPHA = 0.8f class ZoomOutPageTransformer : ViewPager.PageTransformer { override fun transformPage(view: View, position: Float) { view.apply { val pageWidth = width val pageHeight = height when { position < -1 -> { // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0f } position <= 1 -> { // [-1,1] // Modify the default slide transition to shrink the page as well val scaleFactor = max(MIN_SCALE, 1 - abs(position)) val vertMargin = pageHeight * (1 - scaleFactor) / 2 val horzMargin = pageWidth * (1 - scaleFactor) / 2 translationX = if (position < 0) { horzMargin - vertMargin / 2 } else { horzMargin + vertMargin / 2 } // Scale the page down (between MIN_SCALE and 1) scaleX = scaleFactor scaleY = scaleFactor // Fade the page relative to its size. alpha = (MIN_ALPHA + (((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA))) } else -> { // (1,+Infinity] // This page is way off-screen to the right. alpha = 0f } } } } }
5
Kotlin
28
75
e8b887c5074c6dde830252e322869d0ff8d362c5
1,950
Jade-Player
Apache License 2.0
src/main/kotlin/entity/berries/BerryFirmness.kt
Tykok
518,240,433
false
null
package entity.berries import entity.common.Name import entity.common.NamedApiResource /** * @link https://pokeapi.co/docs/v2#berry-firmnesses * @author Tykok * @version 1.0.0 * @since 2022-07-27 */ class BerryFirmness( val id: Number, val name: String, /** * A list of the berries with this firmness. * @see NamedApiResource */ val berries: Array<NamedApiResource>, /** * The name of this resource listed in different languages. * @see Name */ val names: Array<Name> )
12
Kotlin
0
1
b017ec3b0cacc436e6ce975610b6bb9209e88026
532
PokeAPI-Kotlin
MIT License
buildSrc/src/main/kotlin/Dependency.kt
AChep
160,681,782
false
{"Kotlin": 130814}
/** * @author <NAME> */ data class Dependency( val name: String, val version: String, val notation: Any, val type: DependencyType )
4
Kotlin
0
8
0a067570b49474a049960d892a72749ca3cb903c
149
literaryclock
Apache License 2.0
app/src/main/java/com/zxhhyj/music/ui/common/AlbumMotionBlur.kt
ZXHHYJ
675,785,532
false
{"Kotlin": 422646}
package com.zxhhyj.music.ui.common import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.Drawable import android.view.animation.LinearInterpolator import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.viewinterop.AndroidView import androidx.core.graphics.blue import androidx.core.graphics.drawable.toBitmap import androidx.core.graphics.drawable.toDrawable import androidx.core.graphics.green import androidx.core.graphics.red import androidx.core.graphics.scale import coil.ImageLoader import coil.request.ImageRequest import com.flaviofaria.kenburnsview.KenBurnsView import com.flaviofaria.kenburnsview.RandomTransitionGenerator import com.google.android.renderscript.Toolkit import com.zxhhyj.music.logic.utils.BitmapUtils @Composable fun ImageMotionBlur( modifier: Modifier, whiteObscuration: Color = Color(0x20FFFFFF), blackObscuration: Color = Color(0x3C000000), imageUrl: String?, paused: Boolean ) { var drawable by remember { mutableStateOf<Drawable?>(null) } val context = LocalContext.current val imageLoader = ImageLoader(context) LaunchedEffect(imageUrl) { if (imageUrl == null) return@LaunchedEffect val request = ImageRequest.Builder(context) .data(imageUrl) .build() val bitmap = imageLoader.execute(request).drawable?.toBitmap()?.run { BitmapUtils.compressBitmap(this) } if (bitmap != null) { drawable = handleImageBlur( whiteObscuration, blackObscuration, bitmap ).toDrawable(context.resources) bitmap.recycle() } } AndroidView(factory = { KenBurnsView(it).apply { setTransitionGenerator( RandomTransitionGenerator( 3000, LinearInterpolator() ) ) } }, modifier = modifier) { if (drawable != null && it.drawable != drawable) { it.setImageDrawable(drawable!!) } if (paused) { it.pause() } else { it.resume() } } } private fun handleImageBlur( whiteObscuration: Color, blackObscuration: Color, image: Bitmap ): Bitmap { var blurBitmap = image.copy(Bitmap.Config.ARGB_8888, true) val brightnessList = arrayListOf<Double>() blurBitmap.scale(3, 3).let { for (i in 0 until 3) { for (j in 0 until 3) { val pixel = it.getPixel(i, j) val r = (0.299 * pixel.red) + (0.587 * pixel.green) + (0.114 * pixel.blue) brightnessList.add(r) } } } val average = calculateAverage(brightnessList) val median = calculateMedian(brightnessList) val canvas = Canvas(blurBitmap) if (average < 50 && median < 50) { canvas.drawColor(whiteObscuration.toArgb()) } else { canvas.drawColor(blackObscuration.toArgb()) } blurBitmap = blurBitmap.scale(150, 150) blurBitmap = meshBitmap(blurBitmap) blurBitmap = Toolkit.blur(blurBitmap, 25) return blurBitmap } //计算平均值 private fun calculateAverage(numbers: List<Double>): Double { if (numbers.isEmpty()) return 0.0 return numbers.sum() / numbers.size } //计算中位数 private fun calculateMedian(numbers: List<Double>): Double { val sortedNumbers = numbers.sorted() val middleIndex = sortedNumbers.size / 2 return if (sortedNumbers.size % 2 == 0) { (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2.0 } else { sortedNumbers[middleIndex] } } private val floats = floatArrayOf( -0.2351f, -0.0967f, 0.2135f, -0.1414f, 0.9221f, -0.0908f, 0.9221f, -0.0685f, 1.3027f, 0.0253f, 1.2351f, 0.1786f, -0.3768f, 0.1851f, 0.2f, 0.2f, 0.6615f, 0.3146f, 0.9543f, 0.0f, 0.6969f, 0.1911f, 1.0f, 0.2f, 0.0f, 0.4f, 0.2f, 0.4f, 0.0776f, 0.2318f, 0.6f, 0.4f, 0.6615f, 0.3851f, 1.0f, 0.4f, 0.0f, 0.6f, 0.1291f, 0.6f, 0.4f, 0.6f, 0.4f, 0.4304f, 0.4264f, 0.5792f, 1.2029f, 0.8188f, -0.1192f, 1.0f, 0.6f, 0.8f, 0.4264f, 0.8104f, 0.6f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.0f, 1.0f, 0.0776f, 1.0283f, 0.4f, 1.0f, 0.6f, 1.0f, 0.8f, 1.0f, 1.1868f, 1.0283f ) private fun meshBitmap(old: Bitmap): Bitmap { val fArr2 = FloatArray(72) var i = 0 while (i <= 5) { var i2 = 0 var i3 = 5 while (i2 <= i3) { val i4 = i * 12 + i2 * 2 val i5 = i4 + 1 fArr2[i4] = floats[i4] * old.width.toFloat() fArr2[i5] = floats[i5] * old.height.toFloat() i2++ i3 = 5 } i++ } val newBit = Bitmap.createBitmap(old) val canvas = Canvas(newBit) canvas.drawBitmapMesh(newBit, 5, 5, fArr2, 0, null, 0, null) return newBit }
0
Kotlin
1
9
c09f7c5904379e42d85d0d64f2842717e7bf177e
5,520
StarMusic
Apache License 2.0
app/src/main/java/ar/edu/unlam/mobile/scaffold/ui/components/GameScore.kt
unlam-tec-movil
691,293,842
false
{"Kotlin": 348767}
package ar.edu.unlam.mobile.scaffold.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Preview(showBackground = true) @Composable fun GameScore( modifier: Modifier = Modifier, playerScore: Int = 0, adversaryScore: Int = 0 ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceAround ) { IndividualScore( modifier = Modifier .border(1.dp, color = Color.Black), score = playerScore, text = "Jugador" ) IndividualScore( modifier = Modifier .border(1.dp, color = Color.Black), score = adversaryScore, text = "Adversario", backgroundColor = MaterialTheme.colorScheme.secondary, textColor = MaterialTheme.colorScheme.onSecondary ) } } @Preview(showBackground = true) @Composable fun IndividualScore( modifier: Modifier = Modifier, score: Int = 0, text: String = "Jugador o adversario:", backgroundColor: Color = MaterialTheme.colorScheme.tertiary, textColor: Color = MaterialTheme.colorScheme.onTertiary ) { Text( modifier = modifier .background(color = backgroundColor) .padding(5.dp), text = "$text: $score", color = textColor ) }
3
Kotlin
0
0
62f24b5a8117891e1656c23a6b6bd6289d54f198
1,820
A3-2023-H2-Cartas-Super
MIT License
covpass-sdk/src/test/java/de/rki/covpass/sdk/utils/serialization/BirthDateSerializerTest.kt
ljxx
388,073,819
false
null
/* * (C) Copyright IBM Deutschland GmbH 2021 * (C) Copyright IBM Corp. 2021 */ package de.rki.covpass.sdk.utils.serialization import assertk.assertThat import assertk.assertions.isEqualTo import de.rki.covpass.sdk.cert.models.BirthDate.Companion.BIRTH_DATE_EMPTY import io.mockk.* import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import org.junit.Test import java.time.DateTimeException import java.time.LocalDate import java.time.Year import java.time.YearMonth import java.time.format.DateTimeParseException internal class BirthDateSerializerTest { private val encoder: Encoder = mockk() private val decoder: Decoder = mockk() @Test fun `Serialize valid LocalDate`() { val birthDate = "2021-03-15" every { decoder.decodeString() } returns birthDate every { encoder.encodeString(any()) } just Runs val date = BirthDateSerializer.deserialize(decoder) BirthDateSerializer.serialize(encoder, date) verify { encoder.encodeString(birthDate) } } @Test fun `Serialize valid YearMonth`() { val birthDate = "2021-03" every { decoder.decodeString() } returns birthDate every { encoder.encodeString(any()) } just Runs val date = BirthDateSerializer.deserialize(decoder) BirthDateSerializer.serialize(encoder, date) verify { encoder.encodeString(birthDate) } } @Test fun `Serialize valid Year`() { val birthDate = "2021" every { decoder.decodeString() } returns birthDate every { encoder.encodeString(any()) } just Runs val date = BirthDateSerializer.deserialize(decoder) BirthDateSerializer.serialize(encoder, date) verify { encoder.encodeString(birthDate) } } @Test fun `Serialize empty Date`() { val birthDate = "" every { decoder.decodeString() } returns birthDate every { encoder.encodeString(any()) } just Runs val date = BirthDateSerializer.deserialize(decoder) BirthDateSerializer.serialize(encoder, date) verify { encoder.encodeString(birthDate) } } @Test fun `Deserialize LocalDate string`() { every { decoder.decodeString() } returns "2021-03-15" val date = BirthDateSerializer.deserialize(decoder) val expectedDate = LocalDate.of(2021, 3, 15) assertThat(date.birthDate).isEqualTo(expectedDate) } @Test fun `Deserialize YearMonth string`() { every { decoder.decodeString() } returns "2021-03" val date = BirthDateSerializer.deserialize(decoder) val expectedDate = YearMonth.of(2021, 3) assertThat(date.birthDate).isEqualTo(expectedDate) } @Test fun `Deserialize Year string`() { every { decoder.decodeString() } returns "2021" val date = BirthDateSerializer.deserialize(decoder) val expectedDate = Year.of(2021) assertThat(date.birthDate).isEqualTo(expectedDate) } @Test fun `Deserialize empty date`() { every { decoder.decodeString() } returns "" val date = BirthDateSerializer.deserialize(decoder) val expectedDate = BIRTH_DATE_EMPTY assertThat(date.birthDate).isEqualTo(expectedDate) } @Test(expected = DateTimeParseException::class) fun `Deserialize invalid LocalDate date`() { every { decoder.decodeString() } returns "2021-03-1X" BirthDateSerializer.deserialize(decoder) } @Test(expected = DateTimeParseException::class) fun `Deserialize invalid MonthYear date`() { every { decoder.decodeString() } returns "2021-1X" BirthDateSerializer.deserialize(decoder) } @Test(expected = DateTimeParseException::class) fun `Deserialize invalid Year date`() { every { decoder.decodeString() } returns "202X" BirthDateSerializer.deserialize(decoder) } @Test(expected = DateTimeException::class) fun `Deserialize invalid string`() { every { decoder.decodeString() } returns "abc123" BirthDateSerializer.deserialize(decoder) } }
0
Kotlin
0
2
390a45d0c8231e8203439018d0e6702ecb0f0d05
4,130
android-covpass-app
Apache License 2.0
android/app/src/main/java/com/fabirt/debty/domain/model/Movement.kt
fabirt
349,736,814
false
{"Kotlin": 164948}
package com.fabirt.debty.domain.model data class Movement( val id: Int, val personId: Int, val amount: Double, /** * Time in milliseconds since Epoch. */ val date: Long, val description: String, val type: MovementType )
0
Kotlin
8
46
fd9e7b97728f57c93104caa1c4c6ae70ff770ec7
258
debty-v2
MIT License
app/src/main/java/com/eyepetizer/android/ui/MainActivity.kt
VIPyinzhiwei
259,029,682
false
null
/* * Copyright (c) 2020. vipyinzhiwei <vipyinzhiwei@gmail.com> * * 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.eyepetizer.android.ui import android.content.Context import android.content.Intent import android.os.Bundle import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.Observer import androidx.work.WorkInfo import androidx.work.WorkManager import com.eyepetizer.android.R import com.eyepetizer.android.databinding.ActivityMainBinding import com.eyepetizer.android.event.MessageEvent import com.eyepetizer.android.event.RefreshEvent import com.eyepetizer.android.event.SwitchPagesEvent import com.eyepetizer.android.extension.logD import com.eyepetizer.android.extension.setOnClickListener import com.eyepetizer.android.extension.showToast import com.eyepetizer.android.ui.common.ui.BaseActivity import com.eyepetizer.android.ui.community.CommunityFragment import com.eyepetizer.android.ui.community.commend.CommendFragment import com.eyepetizer.android.ui.home.HomePageFragment import com.eyepetizer.android.ui.login.LoginActivity import com.eyepetizer.android.ui.mine.MineFragment import com.eyepetizer.android.ui.notification.NotificationFragment import com.eyepetizer.android.util.DialogAppraiseTipsWorker import com.eyepetizer.android.util.GlobalUtil import org.greenrobot.eventbus.EventBus /** * Eyepetizer的主界面。 * * @author vipyinzhiwei * @since 2020/5/29 */ class MainActivity : BaseActivity() { var _binding: ActivityMainBinding? = null val binding: ActivityMainBinding get() = _binding!! private var backPressTime = 0L private var homePageFragment: HomePageFragment? = null private var communityFragment: CommunityFragment? = null private var notificationFragment: NotificationFragment? = null private var mineFragment: MineFragment? = null private val fragmentManager: FragmentManager by lazy { supportFragmentManager } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } override fun onDestroy() { super.onDestroy() _binding = null } override fun setupViews() { observe() setOnClickListener( binding.navigationBar.btnHomePage, binding.navigationBar.btnCommunity, binding.navigationBar.btnNotification, binding.navigationBar.ivRelease, binding.navigationBar.btnMine ) { when (this) { binding.navigationBar.btnHomePage -> { notificationUiRefresh(0) setTabSelection(0) } binding.navigationBar.btnCommunity -> { notificationUiRefresh(1) setTabSelection(1) } binding.navigationBar.btnNotification -> { notificationUiRefresh(2) setTabSelection(2) } binding.navigationBar.ivRelease -> { LoginActivity.start(this@MainActivity) } binding.navigationBar.btnMine -> { notificationUiRefresh(3) setTabSelection(3) } } } setTabSelection(0) } override fun onMessageEvent(messageEvent: MessageEvent) { super.onMessageEvent(messageEvent) when { messageEvent is SwitchPagesEvent && CommendFragment::class.java == messageEvent.activityClass -> { binding.navigationBar.btnCommunity.performClick() } else -> { } } } override fun onBackPressed() { if (supportFragmentManager.backStackEntryCount > 0) { supportFragmentManager.popBackStack() } else { processBackPressed() } } private fun processBackPressed() { val now = System.currentTimeMillis() if (now - backPressTime > 2000) { String.format(GlobalUtil.getString(R.string.press_again_to_exit), GlobalUtil.appName).showToast() backPressTime = now } else { super.onBackPressed() } } private fun setTabSelection(index: Int) { clearAllSelected() fragmentManager.beginTransaction().apply { hideFragments(this) when (index) { 0 -> { binding.navigationBar.ivHomePage.isSelected = true binding.navigationBar.tvHomePage.isSelected = true if (homePageFragment == null) { homePageFragment = HomePageFragment.newInstance() add(R.id.homeActivityFragContainer, homePageFragment!!) } else { show(homePageFragment!!) } } 1 -> { binding.navigationBar.ivCommunity.isSelected = true binding.navigationBar.tvCommunity.isSelected = true if (communityFragment == null) { communityFragment = CommunityFragment() add(R.id.homeActivityFragContainer, communityFragment!!) } else { show(communityFragment!!) } } 2 -> { binding.navigationBar.ivNotification.isSelected = true binding.navigationBar.tvNotification.isSelected = true if (notificationFragment == null) { notificationFragment = NotificationFragment() add(R.id.homeActivityFragContainer, notificationFragment!!) } else { show(notificationFragment!!) } } 3 -> { binding.navigationBar.ivMine.isSelected = true binding.navigationBar.tvMine.isSelected = true if (mineFragment == null) { mineFragment = MineFragment.newInstance() add(R.id.homeActivityFragContainer, mineFragment!!) } else { show(mineFragment!!) } } else -> { binding.navigationBar.ivHomePage.isSelected = true binding.navigationBar.tvHomePage.isSelected = true if (homePageFragment == null) { homePageFragment = HomePageFragment.newInstance() add(R.id.homeActivityFragContainer, homePageFragment!!) } else { show(homePageFragment!!) } } } }.commitAllowingStateLoss() } private fun clearAllSelected() { binding.navigationBar.ivHomePage.isSelected = false binding.navigationBar.tvHomePage.isSelected = false binding.navigationBar.ivCommunity.isSelected = false binding.navigationBar.tvCommunity.isSelected = false binding.navigationBar.ivNotification.isSelected = false binding.navigationBar.tvNotification.isSelected = false binding.navigationBar.ivMine.isSelected = false binding.navigationBar.tvMine.isSelected = false } private fun hideFragments(transaction: FragmentTransaction) { transaction.run { if (homePageFragment != null) hide(homePageFragment!!) if (communityFragment != null) hide(communityFragment!!) if (notificationFragment != null) hide(notificationFragment!!) if (mineFragment != null) hide(mineFragment!!) } } private fun notificationUiRefresh(selectionIndex: Int) { when (selectionIndex) { 0 -> { if (binding.navigationBar.ivHomePage.isSelected) EventBus.getDefault().post(RefreshEvent(HomePageFragment::class.java)) } 1 -> { if (binding.navigationBar.ivCommunity.isSelected) EventBus.getDefault().post(RefreshEvent(CommunityFragment::class.java)) } 2 -> { if (binding.navigationBar.ivNotification.isSelected) EventBus.getDefault().post(RefreshEvent(NotificationFragment::class.java)) } 3 -> { if (binding.navigationBar.ivMine.isSelected) EventBus.getDefault().post(RefreshEvent(MineFragment::class.java)) } } } private fun observe() { WorkManager.getInstance(this).getWorkInfoByIdLiveData(DialogAppraiseTipsWorker.showDialogWorkRequest.id).observe(this, Observer { workInfo -> logD(TAG, "observe: workInfo.state = ${workInfo.state}") if (workInfo.state == WorkInfo.State.SUCCEEDED) { WorkManager.getInstance(this).cancelAllWork() } else if (workInfo.state == WorkInfo.State.RUNNING) { if (isActive) { DialogAppraiseTipsWorker.showDialog(this) WorkManager.getInstance(this).cancelAllWork() } } }) } companion object { fun start(context: Context) { context.startActivity(Intent(context, MainActivity::class.java)) } } }
3
null
404
1,759
bc2feccace17deac2917ae26728915030ed6ed22
9,992
Eyepetizer
Apache License 2.0
app/src/main/java/com/eyepetizer/android/ui/MainActivity.kt
VIPyinzhiwei
259,029,682
false
null
/* * Copyright (c) 2020. vipyinzhiwei <<EMAIL>> * * 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.eyepetizer.android.ui import android.content.Context import android.content.Intent import android.os.Bundle import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.Observer import androidx.work.WorkInfo import androidx.work.WorkManager import com.eyepetizer.android.R import com.eyepetizer.android.databinding.ActivityMainBinding import com.eyepetizer.android.event.MessageEvent import com.eyepetizer.android.event.RefreshEvent import com.eyepetizer.android.event.SwitchPagesEvent import com.eyepetizer.android.extension.logD import com.eyepetizer.android.extension.setOnClickListener import com.eyepetizer.android.extension.showToast import com.eyepetizer.android.ui.common.ui.BaseActivity import com.eyepetizer.android.ui.community.CommunityFragment import com.eyepetizer.android.ui.community.commend.CommendFragment import com.eyepetizer.android.ui.home.HomePageFragment import com.eyepetizer.android.ui.login.LoginActivity import com.eyepetizer.android.ui.mine.MineFragment import com.eyepetizer.android.ui.notification.NotificationFragment import com.eyepetizer.android.util.DialogAppraiseTipsWorker import com.eyepetizer.android.util.GlobalUtil import org.greenrobot.eventbus.EventBus /** * Eyepetizer的主界面。 * * @author vipyinzhiwei * @since 2020/5/29 */ class MainActivity : BaseActivity() { var _binding: ActivityMainBinding? = null val binding: ActivityMainBinding get() = _binding!! private var backPressTime = 0L private var homePageFragment: HomePageFragment? = null private var communityFragment: CommunityFragment? = null private var notificationFragment: NotificationFragment? = null private var mineFragment: MineFragment? = null private val fragmentManager: FragmentManager by lazy { supportFragmentManager } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } override fun onDestroy() { super.onDestroy() _binding = null } override fun setupViews() { observe() setOnClickListener( binding.navigationBar.btnHomePage, binding.navigationBar.btnCommunity, binding.navigationBar.btnNotification, binding.navigationBar.ivRelease, binding.navigationBar.btnMine ) { when (this) { binding.navigationBar.btnHomePage -> { notificationUiRefresh(0) setTabSelection(0) } binding.navigationBar.btnCommunity -> { notificationUiRefresh(1) setTabSelection(1) } binding.navigationBar.btnNotification -> { notificationUiRefresh(2) setTabSelection(2) } binding.navigationBar.ivRelease -> { LoginActivity.start(this@MainActivity) } binding.navigationBar.btnMine -> { notificationUiRefresh(3) setTabSelection(3) } } } setTabSelection(0) } override fun onMessageEvent(messageEvent: MessageEvent) { super.onMessageEvent(messageEvent) when { messageEvent is SwitchPagesEvent && CommendFragment::class.java == messageEvent.activityClass -> { binding.navigationBar.btnCommunity.performClick() } else -> { } } } override fun onBackPressed() { if (supportFragmentManager.backStackEntryCount > 0) { supportFragmentManager.popBackStack() } else { processBackPressed() } } private fun processBackPressed() { val now = System.currentTimeMillis() if (now - backPressTime > 2000) { String.format(GlobalUtil.getString(R.string.press_again_to_exit), GlobalUtil.appName).showToast() backPressTime = now } else { super.onBackPressed() } } private fun setTabSelection(index: Int) { clearAllSelected() fragmentManager.beginTransaction().apply { hideFragments(this) when (index) { 0 -> { binding.navigationBar.ivHomePage.isSelected = true binding.navigationBar.tvHomePage.isSelected = true if (homePageFragment == null) { homePageFragment = HomePageFragment.newInstance() add(R.id.homeActivityFragContainer, homePageFragment!!) } else { show(homePageFragment!!) } } 1 -> { binding.navigationBar.ivCommunity.isSelected = true binding.navigationBar.tvCommunity.isSelected = true if (communityFragment == null) { communityFragment = CommunityFragment() add(R.id.homeActivityFragContainer, communityFragment!!) } else { show(communityFragment!!) } } 2 -> { binding.navigationBar.ivNotification.isSelected = true binding.navigationBar.tvNotification.isSelected = true if (notificationFragment == null) { notificationFragment = NotificationFragment() add(R.id.homeActivityFragContainer, notificationFragment!!) } else { show(notificationFragment!!) } } 3 -> { binding.navigationBar.ivMine.isSelected = true binding.navigationBar.tvMine.isSelected = true if (mineFragment == null) { mineFragment = MineFragment.newInstance() add(R.id.homeActivityFragContainer, mineFragment!!) } else { show(mineFragment!!) } } else -> { binding.navigationBar.ivHomePage.isSelected = true binding.navigationBar.tvHomePage.isSelected = true if (homePageFragment == null) { homePageFragment = HomePageFragment.newInstance() add(R.id.homeActivityFragContainer, homePageFragment!!) } else { show(homePageFragment!!) } } } }.commitAllowingStateLoss() } private fun clearAllSelected() { binding.navigationBar.ivHomePage.isSelected = false binding.navigationBar.tvHomePage.isSelected = false binding.navigationBar.ivCommunity.isSelected = false binding.navigationBar.tvCommunity.isSelected = false binding.navigationBar.ivNotification.isSelected = false binding.navigationBar.tvNotification.isSelected = false binding.navigationBar.ivMine.isSelected = false binding.navigationBar.tvMine.isSelected = false } private fun hideFragments(transaction: FragmentTransaction) { transaction.run { if (homePageFragment != null) hide(homePageFragment!!) if (communityFragment != null) hide(communityFragment!!) if (notificationFragment != null) hide(notificationFragment!!) if (mineFragment != null) hide(mineFragment!!) } } private fun notificationUiRefresh(selectionIndex: Int) { when (selectionIndex) { 0 -> { if (binding.navigationBar.ivHomePage.isSelected) EventBus.getDefault().post(RefreshEvent(HomePageFragment::class.java)) } 1 -> { if (binding.navigationBar.ivCommunity.isSelected) EventBus.getDefault().post(RefreshEvent(CommunityFragment::class.java)) } 2 -> { if (binding.navigationBar.ivNotification.isSelected) EventBus.getDefault().post(RefreshEvent(NotificationFragment::class.java)) } 3 -> { if (binding.navigationBar.ivMine.isSelected) EventBus.getDefault().post(RefreshEvent(MineFragment::class.java)) } } } private fun observe() { WorkManager.getInstance(this).getWorkInfoByIdLiveData(DialogAppraiseTipsWorker.showDialogWorkRequest.id).observe(this, Observer { workInfo -> logD(TAG, "observe: workInfo.state = ${workInfo.state}") if (workInfo.state == WorkInfo.State.SUCCEEDED) { WorkManager.getInstance(this).cancelAllWork() } else if (workInfo.state == WorkInfo.State.RUNNING) { if (isActive) { DialogAppraiseTipsWorker.showDialog(this) WorkManager.getInstance(this).cancelAllWork() } } }) } companion object { fun start(context: Context) { context.startActivity(Intent(context, MainActivity::class.java)) } } }
3
null
404
1,759
bc2feccace17deac2917ae26728915030ed6ed22
9,977
Eyepetizer
Apache License 2.0
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/passport/encrypted/abstracts/EncryptedPassportElementWithPhoneNumber.kt
InsanusMokrassar
163,152,024
false
null
package dev.inmo.tgbotapi.types.passport.encrypted.abstracts import dev.inmo.tgbotapi.types.passport.encrypted.EncryptedElementSerializer import kotlinx.serialization.Serializable @Serializable(EncryptedElementSerializer::class) interface EncryptedPassportElementWithPhoneNumber : EncryptedPassportElement { val phoneNumber: String }
9
Kotlin
10
99
8206aefbb661db936d4078a8ef7cc9cecb5384e4
339
TelegramBotAPI
Apache License 2.0
feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/Notification.kt
chengdongqing
782,566,304
false
{"Kotlin": 894390}
package top.chengdongqing.weui.feature.system.screens import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.theme.R import top.chengdongqing.weui.core.utils.isTrue @OptIn(ExperimentalPermissionsApi::class) @Composable fun NotificationScreen() { WeScreen(title = "Notification", description = "系统通知") { val context = LocalContext.current val permissionState = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { rememberPermissionState(permission = Manifest.permission.POST_NOTIFICATIONS) } else { null } val channelId = "test_channel_id" val channelName = "Test Channel Name" WeButton(text = "发送通知") { if (permissionState?.status?.isGranted.isTrue() || permissionState == null) { createNotificationChannel(context, channelId, channelName) sendNotification(context, channelId, "测试标题", "测试内容") } else { permissionState.launchPermissionRequest() } } } } @SuppressLint("MissingPermission") private fun sendNotification(context: Context, channelId: String, title: String, content: String) { val builder = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_logo) // 设置通知小图标 .setContentTitle(title) // 设置通知标题 .setContentText(content) // 设置通知内容 .setPriority(NotificationCompat.PRIORITY_DEFAULT) NotificationManagerCompat.from(context).apply { notify(System.currentTimeMillis().toInt(), builder.build()) } } private fun createNotificationChannel(context: Context, channelId: String, channelName: String) { val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(channelId, channelName, importance).apply { description = "测试通道" } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) }
0
Kotlin
3
8
eb773e75aacb801cb24adb41db9fe17224eb883a
2,706
WeUI
Apache License 2.0
src/main/kotlin/no/tornado/tornadofx/idea/annotator/CSSColorAnnotator.kt
edvin
58,163,963
false
null
package no.tornado.tornadofx.idea.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.psi.PsiElement import com.intellij.ui.ColorPicker import com.intellij.util.ui.ColorIcon import no.tornado.tornadofx.idea.facet.TornadoFXFacet import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.js.descriptorUtils.getJetTypeFqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.types.KotlinType import java.awt.Color import java.util.* import javax.swing.Icon enum class ColorType { WEB_WITH_OPACITY, WEB_WITHOUT_OPACITY, RGB_DOUBLE_WITH_OPACITY, RGB_DOUBLE_WITHOUT_OPACITY, RGB_INT_WITH_OPACITY, RGB_INT_WITHOUT_OPACITY } class CSSColorAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (!element.isValid) return // TODO: Is this the proper way of checking if this is an element in file of a tfx project? if (TornadoFXFacet.get(element.project) != null) { when (element) { is KtBinaryExpression -> { val left = element.left if (left is KtNameReferenceExpression) { val prop = left.mainReference.resolve() val right = element.right if (prop is KtProperty && right != null) { handelProperty(prop, right, holder) } } } is KtProperty -> { handelProperty(element, element.children.last() as KtExpression, holder) } } } } private fun handelProperty(property: KtProperty, expr: KtExpression, holder: AnnotationHolder, ref: PsiElement? = null) { val returnType= property.declarationReturnType() when { expr is KtCallExpression && expr.text.startsWith("c(") -> annotateTFXColor(expr, ref, holder) expr is KtCallExpression && returnType.isColorMulti() -> annotateMulti(expr.valueArguments, ref, holder) expr is KtDotQualifiedExpression && expr.text.startsWith("Color.") -> annotateFXColor(expr, ref, holder, { property.replaceColor(it) }) expr is KtReferenceExpression -> annotateReference(expr, holder) } } /** * Annotates Color.* expressions */ private fun annotateFXColor(element: KtDotQualifiedExpression, ref: PsiElement? = null, holder: AnnotationHolder, transformer: (String) -> Unit) { val annotation = holder.createInfoAnnotation(ref ?: element, null) val fxColor = element.text.toColor() fxColor?.let { val color = Color(// fxColor.red.toFloat(), // fxColor.green.toFloat(), // fxColor.blue.toFloat(), // fxColor.opacity.toFloat()// ) // annotation.gutterIconRenderer = ColorRenderer(element.project, color, transformer) } } /** * Annotates multi(c() | Color.*, ...) expressions */ private fun annotateMulti(elements: List<KtValueArgument>, ref: PsiElement? = null, holder: AnnotationHolder) { for (element in elements) { val child = element.firstChild when { child is KtCallExpression && child.text.startsWith("c(") -> annotateTFXColor(child, ref, holder) child is KtDotQualifiedExpression && child.text.startsWith("Color.") -> annotateFXColor(child, ref, holder, { child.replaceColor(element, it) }) } } } /** * Annotates c(...) expressions */ private fun annotateTFXColor(element: KtCallExpression, ref: PsiElement? = null, holder: AnnotationHolder) { // TODO: Do we need to check if the expression is valid? val annotation = holder.createInfoAnnotation(ref ?: element, null) val args = element.valueArguments val (fxColor, colorType) = args.toColorType() ?: return val color = Color(// fxColor.red.toFloat(), // fxColor.green.toFloat(), // fxColor.blue.toFloat(), // fxColor.opacity.toFloat() // ) // annotation.gutterIconRenderer = PickerRenderer(color, colorType, { val factory = KtPsiFactory(element.project) element.replace(factory.createExpression(it)) }) } private fun annotateReference(element: KtReferenceExpression, holder: AnnotationHolder) { val resolvedRef = element.mainReference.resolve() if( resolvedRef is KtProperty) { val expr = resolvedRef.children.last(); if (expr is KtExpression) { handelProperty( resolvedRef, expr, holder, element ) } } } private fun KotlinType?.isColorMulti(): Boolean { val fqName = this?.getJetTypeFqName(true) return fqName == "tornadofx.MultiValue<javafx.scene.paint.Paint>" || fqName == "tornadofx.MultiValue<javafx.scene.paint.Color>" } private fun KtNamedDeclaration.declarationReturnType() = QuickFixUtil.getDeclarationReturnType(this) private fun KotlinType?.isFxColor(): Boolean { val fqName = this?.getJetTypeFqName(false) return fqName == "javafx.scene.paint.Color" || fqName == "javafx.scene.paint.Paint" } private fun List<KtValueArgument>.toColorType(): Pair<javafx.scene.paint.Color, ColorType>? { when (size) { 1, 2 -> { this[0] val colorCode = this[0].textReplace("\"", "") val fxColor: javafx.scene.paint.Color try { fxColor = javafx.scene.paint.Color.web(colorCode, this.getOrNull(1)?.textToDouble() ?: 1.0) } catch (e: IllegalArgumentException) { // No valid web color so we just show no color annotation return null } val colorType = if (this.size == 1) ColorType.WEB_WITHOUT_OPACITY else ColorType.WEB_WITHOUT_OPACITY return fxColor to colorType } 3, 4 -> { if (this[0].textContains('.')) { val fxColor: javafx.scene.paint.Color try { fxColor = this.floatToColor() } catch (e: Exception) { // One of the arguments is bigger the 1.0 or negative, so wie will not show an annotation. return null } val colorType = if (this.size == 4) ColorType.RGB_DOUBLE_WITH_OPACITY else ColorType.RGB_DOUBLE_WITHOUT_OPACITY return fxColor to colorType } else { val fxColor: javafx.scene.paint.Color try { fxColor = this.intToColor() } catch (ignored: Exception) { // One of the arguments is is not a integer, bigger then 255 or negative, so wie will not show an annotation. return null } val colorType = if (this.size == 4) ColorType.RGB_INT_WITH_OPACITY else ColorType.RGB_INT_WITHOUT_OPACITY return fxColor to colorType } } else -> return null } } private fun List<KtValueArgument>.floatToColor() = javafx.scene.paint.Color.color(this[0].textToDouble(), // this[1].textToDouble(), // this[2].textToDouble(), // if (this.size == 4) this[3].textToDouble() else 1.0) // private fun List<KtValueArgument>.intToColor() = javafx.scene.paint.Color.rgb(this[0].textToInt(), // this[1].textToInt(), // this[2].textToInt(), // if (this.size == 4) this[3].textToDouble() else 1.0) // private fun KtValueArgument.textToInt() = text.toInt() private fun KtValueArgument.textToDouble() = text.toDouble() private fun KtValueArgument.textReplace(pattern: String, replacment: String) = text.replace(pattern, replacment) class ColorRenderer(private val project: Project, val currentColor: Color, val transformer: (String) -> Unit) : GutterIconRenderer() { override fun getIcon(): Icon = ColorIcon(8, currentColor) override fun getClickAction(): AnAction? { return object : AnAction() { override fun actionPerformed(e: AnActionEvent) { val editor = CommonDataKeys.EDITOR.getData(e.dataContext) JBPopupFactory.getInstance() .createListPopup(object : BaseListPopupStep<String>( "Choose-Color", defaultFXColorNames, defaultFXColors) { override fun getTextFor(value: String) = value override fun onChosen(selectedValue: String?, finalChoice: Boolean): PopupStep<*>? { selectedValue?.let { ApplicationManager.getApplication().invokeLater { WriteCommandAction.runWriteCommandAction(project) { transformer("Color.$it") } } } return super.onChosen(selectedValue, finalChoice) } }).showInBestPositionFor(editor!!) } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ColorRenderer if (currentColor != other.currentColor) return false return true } override fun hashCode(): Int { return 31 * currentColor.hashCode() } } class PickerRenderer(val currentColor: Color, val colorType: ColorType, val transformer: (String) -> Unit) : GutterIconRenderer() { override fun getIcon(): Icon = ColorIcon(8, currentColor) override fun getClickAction() = object : AnAction() { override fun actionPerformed(e: AnActionEvent) { val editor = CommonDataKeys.EDITOR.getData(e.dataContext) if (editor != null) { val color = ColorPicker.showDialog(editor.component, "Choose Color", currentColor, true, null, false) color?.let { val colorExpression = it.transform(colorType) ApplicationManager.getApplication() .runWriteAction { transformer(colorExpression) } } } } } private fun Color.transform(colorType: ColorType) = when (colorType) { ColorType.WEB_WITH_OPACITY -> if (alpha == 255) toWeb() else toWebWithOpacity() ColorType.WEB_WITHOUT_OPACITY -> if (alpha == 255) toWeb() else toWebWithOpacity() ColorType.RGB_DOUBLE_WITH_OPACITY -> if (alpha == 255) toRGBDoubleWithoutOpacity() else toRGBDoubleWithOpacity() ColorType.RGB_DOUBLE_WITHOUT_OPACITY -> if (alpha == 255) toRGBDoubleWithoutOpacity() else toRGBDoubleWithOpacity() ColorType.RGB_INT_WITH_OPACITY -> if (alpha == 255) toRGBIntWithoutOpacity() else toRGBIntWithOpacity() ColorType.RGB_INT_WITHOUT_OPACITY -> if (alpha == 255) toRGBIntWithoutOpacity() else toRGBIntWithOpacity() } private fun Color.toWebWithOpacity() = """c("#${Integer.toString(red, 16)}${Integer.toString(green, 16)}${Integer.toString(blue, 16)}", %.2f)""".format(Locale.US, alpha.toDouble() / 255.0) private fun Color.toWeb() = """c("#${Integer.toString(red, 16)}${Integer.toString(green, 16)}${Integer.toString(blue, 16)}")""" private fun Color.toRGBIntWithOpacity() = "c($red, $green, $blue, %.2f)".format(Locale.US, alpha.toDouble() / 255.0) private fun Color.toRGBIntWithoutOpacity() = "c($red, $green, $blue)" private fun Color.toRGBDoubleWithOpacity() = "c(%.2f, %.2f, %.2f, %.2f)".format(Locale.US, red / 255.0, green / 255.0, blue / 255.0, alpha.toDouble() / 255.0) private fun Color.toRGBDoubleWithoutOpacity() = "c(%.2f, %.2f, %.2f)".format(Locale.US, red / 255.0, green / 255.0, blue / 255.0) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PickerRenderer if (currentColor != other.currentColor) return false if (colorType != other.colorType) return false if (transformer != other.transformer) return false return true } override fun hashCode(): Int { var result = 31 * currentColor.hashCode() result = 31 * result + colorType.hashCode() result = 31 * result + transformer.hashCode() return result } } private fun KtDotQualifiedExpression.replaceColor(parent: PsiElement, color: String) { val factory = KtPsiFactory(project) deleteChildInternal(this.node) parent.add(factory.createExpression(color)) } private fun KtProperty.replaceColor(color: String) { val factory = KtPsiFactory(project) deleteChildInternal(children.last().node) add(factory.createExpression(color)) } }
22
null
22
70
c02e7b8743c2d0213a6a2f6d1a823610fc3c14dd
14,641
tornadofx-idea-plugin
Apache License 2.0
http4k-incubator/src/main/kotlin/org/http4k/openapi/v3/server/server.kt
hoi-nx
266,249,576
true
{"Kotlin": 1692877, "JavaScript": 133282, "Java": 31515, "Shell": 10165, "HTML": 4506, "Python": 1592, "CSS": 832}
package org.http4k.openapi.v3.server import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier.OPERATOR import com.squareup.kotlinpoet.TypeSpec import org.http4k.openapi.v3.OpenApi3Spec import org.http4k.openapi.v3.apiName fun OpenApi3Spec.buildServer(endpoints: List<FunSpec>) = TypeSpec.objectBuilder((apiName() + "Server").capitalize()) .addFunction(constructionMethod(endpoints)) .build() private fun constructionMethod(endpoints: List<FunSpec>) = FunSpec.builder("invoke") .addModifiers(OPERATOR) .addCode(buildApi(endpoints)) .build()
0
null
0
0
2be3d93e98c09e1d8f5986a932e82852560e22c2
599
http4k
Apache License 2.0
src/main/kotlin/com/example/ddd/order/domain/repositories/OrderRepository.kt
cesar-lp
485,152,561
false
null
package com.example.ddd.order.domain.repositories import com.example.ddd.order.domain.models.entities.Order interface OrderRepository { fun save(order: Order): Order fun get(id: String): Order? fun getAll(): Set<Order> fun getByClient(clientId: String): Set<Order> }
0
Kotlin
0
0
094ea43a68cc6a50a5a42c1dfbb26726faaaa0b8
281
kotlin-ddd-example
MIT License
modules/domain/src/main/java/eu/automateeverything/domain/automation/NotAutomationNode.kt
tomaszbabiuk
488,678,209
false
null
/* * Copyright (c) 2019-2022 <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 eu.automateeverything.domain.automation import java.util.* class NotAutomationNode( private val nodeToNegate: EvaluatorNode?, ) : EvaluatorNode { override fun evaluate(now: Calendar): Boolean { if (nodeToNegate != null) { return !nodeToNegate.evaluate(now) } return false } }
0
Kotlin
1
0
6508322d8b83553e18bdde8a3ebe7c0a37aed744
936
automate-everything
Apache License 2.0
_pending/Projemanag_v51/app/src/main/java/com/projemanag/adapters/TaskListItemsAdapter.kt
luannguyen252
371,359,679
false
null
package com.projemanag.adapters import android.content.Context import android.content.res.Resources import android.util.Log import android.view.DragEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.projemanag.R import com.projemanag.activities.TaskListActivity import com.projemanag.model.Task import kotlinx.android.synthetic.main.item_task.view.* import java.util.* open class TaskListItemsAdapter( private val context: Context, private var list: ArrayList<Task> ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { // A global variable for position dragged FROM. private var mPositionDraggedFrom = -1 // A global variable for position dragged TO. private var mPositionDraggedTo = -1 /** * Inflates the item views which is designed in xml layout file * * create a new * {@link ViewHolder} and initializes some private fields to be used by RecyclerView. */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.item_task, parent, false) // Here the layout params are converted dynamically according to the screen size as width is 70% and height is wrap_content. val layoutParams = LinearLayout.LayoutParams( (parent.width * 0.7).toInt(), LinearLayout.LayoutParams.WRAP_CONTENT ) // Here the dynamic margins are applied to the view. layoutParams.setMargins((15.toDp()).toPx(), 0, (40.toDp()).toPx(), 0) view.layoutParams = layoutParams return MyViewHolder(view) } /** * Binds each item in the ArrayList to a view * * Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent * an item. * * This new ViewHolder should be constructed with a new View that can represent the items * of the given type. You can either create a new View manually or inflate it from an XML * layout file. */ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val model = list[position] if (holder is MyViewHolder) { if (position == list.size - 1) { holder.itemView.tv_add_task_list.visibility = View.VISIBLE holder.itemView.ll_task_item.visibility = View.GONE } else { holder.itemView.tv_add_task_list.visibility = View.GONE holder.itemView.ll_task_item.visibility = View.VISIBLE } holder.itemView.tv_task_list_title.text = model.title holder.itemView.tv_add_task_list.setOnClickListener { holder.itemView.tv_add_task_list.visibility = View.GONE holder.itemView.cv_add_task_list_name.visibility = View.VISIBLE } holder.itemView.ib_close_list_name.setOnClickListener { holder.itemView.tv_add_task_list.visibility = View.VISIBLE holder.itemView.cv_add_task_list_name.visibility = View.GONE } holder.itemView.ib_done_list_name.setOnClickListener { val listName = holder.itemView.et_task_list_name.text.toString() if (listName.isNotEmpty()) { // Here we check the context is an instance of the TaskListActivity. if (context is TaskListActivity) { context.createTaskList(listName) } } else { Toast.makeText(context, "Please Enter List Name.", Toast.LENGTH_SHORT).show() } } holder.itemView.ib_edit_list_name.setOnClickListener { holder.itemView.et_edit_task_list_name.setText(model.title) // Set the existing title holder.itemView.ll_title_view.visibility = View.GONE holder.itemView.cv_edit_task_list_name.visibility = View.VISIBLE } holder.itemView.ib_close_editable_view.setOnClickListener { holder.itemView.ll_title_view.visibility = View.VISIBLE holder.itemView.cv_edit_task_list_name.visibility = View.GONE } holder.itemView.ib_done_edit_list_name.setOnClickListener { val listName = holder.itemView.et_edit_task_list_name.text.toString() if (listName.isNotEmpty()) { if (context is TaskListActivity) { context.updateTaskList(position, listName, model) } } else { Toast.makeText(context, "Please Enter List Name.", Toast.LENGTH_SHORT).show() } } holder.itemView.ib_delete_list.setOnClickListener { alertDialogForDeleteList(position, model.title) } holder.itemView.tv_add_card.setOnClickListener { holder.itemView.tv_add_card.visibility = View.GONE holder.itemView.cv_add_card.visibility = View.VISIBLE holder.itemView.ib_close_card_name.setOnClickListener { holder.itemView.tv_add_card.visibility = View.VISIBLE holder.itemView.cv_add_card.visibility = View.GONE } holder.itemView.ib_done_card_name.setOnClickListener { val cardName = holder.itemView.et_card_name.text.toString() if (cardName.isNotEmpty()) { if (context is TaskListActivity) { context.addCardToTaskList(position, cardName) } } else { Toast.makeText(context, "Please Enter Card Detail.", Toast.LENGTH_SHORT) .show() } } } holder.itemView.rv_card_list.layoutManager = LinearLayoutManager(context) holder.itemView.rv_card_list.setHasFixedSize(true) val adapter = CardListItemsAdapter(context, model.cards) holder.itemView.rv_card_list.adapter = adapter adapter.setOnClickListener(object : CardListItemsAdapter.OnClickListener { override fun onClick(cardPosition: Int) { if (context is TaskListActivity) { context.cardDetails(position, cardPosition) } } }) /** * Creates a divider {@link RecyclerView.ItemDecoration} that can be used with a * {@link LinearLayoutManager}. * * @param context Current context, it will be used to access resources. * @param orientation Divider orientation. Should be {@link #HORIZONTAL} or {@link #VERTICAL}. */ val dividerItemDecoration = DividerItemDecoration(context, DividerItemDecoration.VERTICAL) holder.itemView.rv_card_list.addItemDecoration(dividerItemDecoration) // Creates an ItemTouchHelper that will work with the given Callback. val helper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) { /*Called when ItemTouchHelper wants to move the dragged item from its old position to the new position.*/ override fun onMove( recyclerView: RecyclerView, dragged: ViewHolder, target: ViewHolder ): Boolean { val draggedPosition = dragged.adapterPosition val targetPosition = target.adapterPosition if (mPositionDraggedFrom == -1) { mPositionDraggedFrom = draggedPosition } mPositionDraggedTo = targetPosition /** * Swaps the elements at the specified positions in the specified list. */ Collections.swap(list[position].cards, draggedPosition, targetPosition) // move item in `draggedPosition` to `targetPosition` in adapter. adapter.notifyItemMoved(draggedPosition, targetPosition) return false // true if moved, false otherwise } // Called when a ViewHolder is swiped by the user. override fun onSwiped( viewHolder: ViewHolder, direction: Int ) { // remove from adapter } /*Called by the ItemTouchHelper when the user interaction with an element is over and it also completed its animation.*/ override fun clearView(recyclerView: RecyclerView, viewHolder: ViewHolder) { super.clearView(recyclerView, viewHolder) if (mPositionDraggedFrom != -1 && mPositionDraggedTo != -1 && mPositionDraggedFrom != mPositionDraggedTo) { (context as TaskListActivity).updateCardsInTaskList( position, list[position].cards ) } // Reset the global variables mPositionDraggedFrom = -1 mPositionDraggedTo = -1 } }) /*Attaches the ItemTouchHelper to the provided RecyclerView. If TouchHelper is already attached to a RecyclerView, it will first detach from the previous one.*/ helper.attachToRecyclerView(holder.itemView.rv_card_list) } } /** * Gets the number of items in the list */ override fun getItemCount(): Int { return list.size } /** * A function to get density pixel from pixel */ private fun Int.toDp(): Int = (this / Resources.getSystem().displayMetrics.density).toInt() /** * A function to get pixel from density pixel */ private fun Int.toPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt() /** * Method is used to show the Alert Dialog for deleting the task list. */ private fun alertDialogForDeleteList(position: Int, title: String) { val builder = AlertDialog.Builder(context) //set title for alert dialog builder.setTitle("Alert") //set message for alert dialog builder.setMessage("Are you sure you want to delete $title.") builder.setIcon(android.R.drawable.ic_dialog_alert) //performing positive action builder.setPositiveButton("Yes") { dialogInterface, which -> dialogInterface.dismiss() // Dialog will be dismissed if (context is TaskListActivity) { context.deleteTaskList(position) } } //performing negative action builder.setNegativeButton("No") { dialogInterface, which -> dialogInterface.dismiss() // Dialog will be dismissed } // Create the AlertDialog val alertDialog: AlertDialog = builder.create() // Set other dialog properties alertDialog.setCancelable(false) // Will not allow user to cancel after clicking on remaining screen area. alertDialog.show() // show the dialog to UI } /** * A ViewHolder describes an item view and metadata about its place within the RecyclerView. */ class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) }
0
Kotlin
0
1
a9b5aef8662a1808042c820c3dfac02e1efd5800
12,147
my-android-journey
MIT License
src/main/kotlin/com/cognifide/gradle/aem/tooling/rcp/Rcp.kt
killakam3084
224,489,898
true
{"Kotlin": 642093, "Shell": 5281, "Java": 2130, "Batchfile": 267}
package com.cognifide.gradle.aem.tooling.rcp import com.cognifide.gradle.aem.AemDefaultTask import org.gradle.api.tasks.TaskAction open class Rcp : AemDefaultTask() { init { description = "Copy JCR content from one instance to another." } fun options(configurer: RcpClient.() -> Unit) { this.options = configurer } private var options: RcpClient.() -> Unit = {} @TaskAction fun run() { val summary = aem.rcp { options(); copy(); summary() } logger.info("RCP details: $summary") if (!summary.source.cmd && !summary.target.cmd) { aem.notifier.notify("RCP finished", "Copied ${summary.copiedPaths} JCR root(s) from instance ${summary.source.name} to ${summary.target.name}." + "Duration: ${summary.durationString}") } else { aem.notifier.notify("RCP finished", "Copied ${summary.copiedPaths} JCR root(s) between instances." + "Duration: ${summary.durationString}") } } companion object { const val NAME = "rcp" } }
0
null
0
0
8aadf05f2e8fd5b11b4a98b22492880bfafdddf9
1,089
gradle-aem-plugin
Apache License 2.0
door-runtime/src/commonJvmJs/kotlin/com/ustadmobile/door/room/RoomDatabaseJdbcImplHelper.kt
UstadMobile
344,538,858
false
null
package com.ustadmobile.door.room import com.ustadmobile.door.jdbc.Connection import com.ustadmobile.door.jdbc.DataSource import com.ustadmobile.door.room.InvalidationTracker import com.ustadmobile.door.room.RoomDatabase import com.ustadmobile.door.util.TransactionMode /** * Contains logic that is used by generated JDBC implementations on JVM and JS. The reason this is not in the parent * RoomDatabase class is because we want to be 100% sure that there is only one instance of this class per database * instance e.g. one set of invalidation listeners, one map of thread ids to transaction connections, etc. */ expect class RoomDatabaseJdbcImplHelper( dataSource: DataSource, db: RoomDatabase, tableNames: List<String>, invalidationTracker: InvalidationTracker, dbType: Int, ) : RoomDatabaseJdbcImplHelperCommon { fun <R> useConnection( transactionMode: TransactionMode, block: (Connection) -> R ) : R /** * */ fun <R> useConnection(block: (Connection) -> R) : R }
0
Kotlin
0
89
58f93d9057ece78cc3f8be3d4d235c0204a15f11
1,039
door
Apache License 2.0
src/test/kotlin/no/nav/arbeidsgiver/sykefravarsstatistikk/api/integrasjoner/kafka/EmbeddedKafkaBrokerConfig.kt
navikt
201,881,144
false
{"Kotlin": 796531, "Shell": 1600, "Dockerfile": 213}
package no.nav.arbeidsgiver.sykefravarsstatistikk.api.infrastruktur.kafka import no.nav.arbeidsgiver.sykefravarsstatistikk.api.config.KafkaTopic import org.springframework.boot.test.context.TestConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Profile import org.springframework.kafka.test.EmbeddedKafkaBroker import org.springframework.kafka.test.EmbeddedKafkaZKBroker @TestConfiguration open class EmbeddedKafkaBrokerConfig { private val embeddedKafkaBroker: EmbeddedKafkaBroker = EmbeddedKafkaZKBroker(1, true, *KafkaTopic.entries.map { it.navn }.toTypedArray()) init { embeddedKafkaBroker.brokerProperties(mapOf("listeners" to "PLAINTEXT://127.0.0.1:9092", "port" to "9092")) } @Bean("embeddedKafka", destroyMethod = "destroy") @Profile("kafka-test") open fun getEmbeddedKafkaBroker() = embeddedKafkaBroker }
1
Kotlin
2
0
fd3e4795c206dd0565fb8fc968504f0df5acae09
917
sykefravarsstatistikk-api
MIT License
exampleapp/src/androidTest/java/com/gerardbradshaw/exampleapp/squareview/SquareViewAndroidTest.kt
GerardBradshaw
294,220,706
false
null
package com.gerardbradshaw.exampleapp.squareview import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.gerardbradshaw.exampleapp.R import com.gerardbradshaw.exampleapp.SquareViewActivity import com.gerardbradshaw.exampleapp.squareview.SquareViewAndroidTestUtil.checkThumbIsAtRatioPosition import com.gerardbradshaw.exampleapp.util.EspressoTestUtil.checkViewColorTagIsApprox import com.gerardbradshaw.exampleapp.util.EspressoTestUtil.moveSeekBarTo import com.gerardbradshaw.exampleapp.squareview.SquareViewAndroidTestUtil.moveThumbTo import com.gerardbradshaw.exampleapp.testutil.GlobalTestUtil.getParameterizedTestIO import com.gerardbradshaw.exampleapp.testutil.ParamTestInput import com.gerardbradshaw.exampleapp.testutil.ParamTestOutput import com.gerardbradshaw.exampleapp.util.EspressoTestUtil.checkPickerRatiosAre import com.gerardbradshaw.exampleapp.util.EspressoTestUtil.checkSeekBarIsAtProgress import com.gerardbradshaw.exampleapp.util.EspressoTestUtil.setPickerRatios import org.junit.Rule import org.junit.Test import org.junit.experimental.runners.Enclosed import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Enclosed::class) internal class SquareViewAndroidTest { @RunWith(AndroidJUnit4::class) class LaunchTests { @Rule @JvmField val asr = ActivityScenarioRule<SquareViewActivity>(SquareViewActivity::class.java) @Test fun should_startThumbInTopRightCornerOfSquare_when_launched() { checkThumbIsAtRatioPosition(0.0, 0.0) } } @RunWith(Parameterized::class) class PreviewTests(private val input: ParamTestInput, private val expected: ParamTestOutput) { @Rule @JvmField val asr = ActivityScenarioRule<SquareViewActivity>(SquareViewActivity::class.java) @Test fun should_updatePreview_when_colorChangedInUI() { moveSeekBarTo(input.colorProgress) checkViewColorTagIsApprox(expected.pureColor, R.id.color_picker_library_large_preview_new) } @Test fun should_updatePreview_when_colorAndShadeChangedInUI() { moveSeekBarTo(input.colorProgress) moveThumbTo(0.0, input.shadeRatio) checkViewColorTagIsApprox(expected.shadedColor, R.id.color_picker_library_large_preview_new) } @Test fun should_updatePreview_when_colorAndTintChangedInUI() { moveSeekBarTo(input.colorProgress) moveThumbTo(input.tintRatio, 0.0) checkViewColorTagIsApprox(expected.tintedColor, R.id.color_picker_library_large_preview_new) } @Test fun should_updatePreview_when_colorAndShadeAndTintChangedInUI() { moveSeekBarTo(input.colorProgress) moveThumbTo(input.tintRatio, input.shadeRatio) checkViewColorTagIsApprox(expected.shadedAndTintedColor, R.id.color_picker_library_large_preview_new) } @Test fun should_updatePreview_when_ratiosChangedProgrammatically() { setPickerRatios( input.colorRatio, input.shadeRatio, input.tintRatio, R.id.example_square_picker) checkViewColorTagIsApprox( expected.shadedAndTintedColor, R.id.color_picker_library_large_preview_new) } companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun data(): Collection<Array<Any>> { return getParameterizedTestIO() } } } @RunWith(Parameterized::class) class ListenerTests(private val input: ParamTestInput, private val expected: ParamTestOutput) { @Rule @JvmField val asr = ActivityScenarioRule<SquareViewActivity>(SquareViewActivity::class.java) @Test fun should_updateListener_when_colorChangedInUI() { moveSeekBarTo(input.colorProgress) checkViewColorTagIsApprox(expected.pureColor, R.id.example_listener) } @Test fun should_updateListener_when_colorAndShadeChangedInUI() { moveSeekBarTo(input.colorProgress) moveThumbTo(0.0, input.shadeRatio) checkViewColorTagIsApprox(expected.shadedColor, R.id.example_listener) } @Test fun should_updateListener_when_colorAndTintChangedInUI() { moveSeekBarTo(input.colorProgress) moveThumbTo(input.tintRatio, 0.0) checkViewColorTagIsApprox(expected.tintedColor, R.id.example_listener) } @Test fun should_updateListener_when_colorAndShadeAndTintChangedInUI() { moveSeekBarTo(input.colorProgress) moveThumbTo(input.tintRatio, input.shadeRatio) checkViewColorTagIsApprox(expected.shadedAndTintedColor, R.id.example_listener) } @Test fun should_updateListener_when_ratiosChangedProgrammatically() { setPickerRatios( input.colorRatio, input.shadeRatio, input.tintRatio, R.id.example_square_picker) checkViewColorTagIsApprox(expected.shadedAndTintedColor, R.id.example_listener) } companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun data(): Collection<Array<Any>> { return getParameterizedTestIO() } } } @RunWith(Parameterized::class) class ThumbAndWindowTests(private val input: ParamTestInput, private val expected: ParamTestOutput) { @Rule @JvmField val asr = ActivityScenarioRule<SquareViewActivity>(SquareViewActivity::class.java) @Test fun should_updateWindowColor_when_colorChangedInUI() { moveSeekBarTo(input.colorProgress) checkViewColorTagIsApprox(expected.pureColor, R.id.color_picker_library_large_window) } @Test fun should_moveThumbToTappedPosition_when_windowTapped() { moveThumbTo(input.tintRatio, input.shadeRatio) checkThumbIsAtRatioPosition(input.tintRatio, input.shadeRatio) } @Test fun should_updateRatios_when_windowTapped() { moveSeekBarTo(input.colorProgress) moveThumbTo(input.tintRatio, input.shadeRatio) checkPickerRatiosAre( input.colorRatio, input.shadeRatio, input.tintRatio, R.id.example_square_picker) } @Test fun should_moveThumbToCorrectPosition_when_ratiosSetProgrammatically() { setPickerRatios( input.colorRatio, input.shadeRatio, input.tintRatio, R.id.example_square_picker) checkThumbIsAtRatioPosition(input.tintRatio, input.shadeRatio) } @Test fun should_moveSliderToCorrectPosition_when_colorRatioSetProgrammatically() { setPickerRatios( input.colorRatio, input.shadeRatio, input.tintRatio, R.id.example_square_picker) checkSeekBarIsAtProgress(input.colorProgress) } companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun data(): Collection<Array<Any>> { return getParameterizedTestIO() } } } }
0
Kotlin
0
1
1327b8d9bd92d71703f28d56e4763c1cbe03b085
6,795
ColorPicker
Apache License 2.0
packages/expo-image/android/src/main/java/expo/modules/image/okhttp/ExpoImageOkHttpClientGlideModule.kt
derekstavis
184,342,737
false
null
package expo.modules.image.okhttp import android.content.Context import com.bumptech.glide.Glide import com.bumptech.glide.Registry import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader import com.bumptech.glide.load.model.GlideUrl import com.bumptech.glide.module.LibraryGlideModule import okhttp3.OkHttpClient import java.io.InputStream @GlideModule class ExpoImageOkHttpClientGlideModule : LibraryGlideModule() { override fun registerComponents(context: Context, glide: Glide, registry: Registry) { val client = OkHttpClient .Builder() .addNetworkInterceptor(OkHttpClientProgressInterceptor) .build() val factory = OkHttpUrlLoader.Factory(client) registry.replace(GlideUrl::class.java, InputStream::class.java, factory) } }
1
null
1
2
e377f0cd22db5cd7feb8e80348cd7064db5429b1
820
expo
MIT License
Retos/Reto #14 - OCTAL Y HEXADECIMAL [Fácil]/kotlin/jaimefere.kt
mouredev
581,049,695
false
{"Python": 4194087, "JavaScript": 1590517, "Java": 1408944, "C#": 782329, "Kotlin": 533858, "TypeScript": 479964, "Rust": 357628, "Go": 322940, "PHP": 288620, "Swift": 278290, "C": 223896, "Jupyter Notebook": 221090, "C++": 175187, "Dart": 159755, "Ruby": 71132, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 33508, "Haskell": 27994, "Shell": 27979, "R": 19771, "Lua": 16964, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12839, "F#": 12816, "Pascal": 12673, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Carbon": 2611, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1394, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "Haxe": 112, "HolyC": 110, "OpenEdge ABL": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "TeX": 72, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Mojo": 37, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
class BasesNumber( var decimal: Int, var octa: String = "", var hexa: String = "" ) { override fun toString(): String { return "decimal: $decimal - octadecimal: $octa - hexadecimal: $hexa" } } fun Int.toOctadecimal(): String { var result = "" var rest = this.mod(8) var quotient: Int = this / 8 while(quotient > 8) { result = "$rest$result" rest = quotient.mod(8) quotient /= 8 } result = "$quotient$rest$result" return result } fun Int.toHexadecimal(): String { var result = "" var rest = this.mod(16) var quotient: Int = this / 16 while(quotient > 16) { result = "${rest.toHex()}$result" rest = quotient.mod(16) quotient /= 16 } result = "${quotient.toHex()}${rest.toHex()}$result" return result } fun Int.toHex(): String { return when(this) { 10 -> "A" 11 -> "B" 12 -> "C" 13 -> "D" 14 -> "E" 15 -> "F" else -> "$this" } } fun calculateBases(number: Int): BasesNumber { val result = BasesNumber(number) result.octa = number.toOctadecimal() result.hexa = number.toHexadecimal() return result } fun main() { println(calculateBases(768)) println(calculateBases(460)) }
1
Python
2974
5,192
f8c44ac12756b14a32abf57cbf4e0cd06ad58088
1,293
retos-programacion-2023
Apache License 2.0
kotlinextensions/src/main/kotlin/com/widget/cardview/CardValidator.kt
SimformSolutionsPvtLtd
118,210,511
false
null
package com.widget.cardview import java.util.Arrays import kotlin.collections.ArrayList class CardValidator(cardNo :String) { private var cardNumber :String? = null private var checkDigit :Int = 0 val isValidCardNumber :Boolean get() { if(cardNumber!!.trim {it <= ' '}.isEmpty()) return false dropLastNumber() return (addAllNumber() + checkDigit) % 10 == 0 } init { this.cardNumber = cardNo.replace("-", "") } private fun dropLastNumber() { checkDigit = Integer.parseInt(cardNumber!!.substring(cardNumber!!.length - 1)) this.cardNumber = cardNumber!!.substring(0, cardNumber!!.length - 1) } private fun addAllNumber() :Int { return (0 until cardNumber!!.length).sumBy { if(cardNumber!!.length % 2 != 0) multiplyOddByTwo(it + 1, Integer.parseInt(cardNumber!![it].toString())) else multiplyOddByTwo(it, Integer.parseInt(cardNumber!![it].toString())) } } private fun multiplyOddByTwo(i :Int, digit :Int) :Int { return if(i % 2 == 0) digit else subtractNine(digit * 2) } private fun subtractNine(digit :Int) :Int { return if(digit > 9) digit - 9 else digit } @Suppress("NAME_SHADOWING") fun guessCard() :Card? { for(cardEnum in CardEnum.values()) { val startWiths = ArrayList(Arrays.asList(*cardEnum.startWith.split(",".toRegex()).dropLastWhile {it.isEmpty()}.toTypedArray())) startWiths .map {cardStartIndex -> cardStartIndex.trim {it <= ' '}} .forEach {cardStartIndex -> if(cardStartIndex.contains("-")) { val range = cardStartIndex.split("-".toRegex()).dropLastWhile {it.isEmpty()}.toTypedArray() val start = java.lang.Long.parseLong(range[0].trim {it <= ' '}) val end = java.lang.Long.parseLong(range[1].trim {it <= ' '}) if(start.toString().length <= cardNumber!!.length) { val cardNumberSub = cardNumber!!.substring(0, start.toString().length) if(cardNumberSub.toLong() in start..end) { return Card(cardEnum.cardName, fetchPossibleLength(cardEnum), cardEnum.icon) } } } else { if(cardNumber!!.startsWith(cardStartIndex)) { return Card(cardEnum.cardName, fetchPossibleLength(cardEnum), cardEnum.icon) } } } } return null } private fun fetchPossibleLength(cardEnum :CardEnum) :ArrayList<Int> { val lengths = ArrayList(Arrays.asList(*cardEnum.length.split(",".toRegex()).dropLastWhile {it.isEmpty()}.toTypedArray())) val possibleLengths = ArrayList<Int>() for(length in lengths) { if(length.contains("-")) { val range = length.split("-".toRegex()).dropLastWhile {it.isEmpty()}.toTypedArray() val start = Integer.parseInt(range[0].trim {it <= ' '}) val end = Integer.parseInt(range[1].trim {it <= ' '}) possibleLengths += start..end } else { possibleLengths.add(Integer.parseInt(length.trim {it <= ' '})) } } return possibleLengths } }
0
Kotlin
2
7
211b47986e3a7993f85ca0a0ce9ff3141f3ae140
3,520
Kotlin-Extensions
Apache License 2.0
KMM_example/src/main/java/com/example/kmmExample/android/EncryptionActivity.kt
rKaiProgrammer
565,355,427
false
{"Kotlin": 20716, "Swift": 5786}
package com.example.kmmExample.android import android.os.Bundle import com.example.kmmExample.Encryption import com.example.kmmExample.Greeting import com.example.kmmExample.android.databinding.ActivityEncryptionBinding import com.example.kmmExample.android.databinding.ActivityMainBinding class EncryptionActivity : BaseActivity<ActivityEncryptionBinding>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.apply { aesEncryptButton.setOnClickListener { aesEncryptionText.text = Encryption().encryptAes(aesInputEdittext.text.toString()) } } } override fun getViewBinding(): ActivityEncryptionBinding { return ActivityEncryptionBinding.inflate(layoutInflater) } }
0
Kotlin
0
0
d630a442a518390949149fcebe33f4668eaba614
806
KMM-example
Apache License 2.0
cmpe/common/src/desktopMain/kotlin/xyz/mcxross/cohesive/cps/utils/FileUtils.kt
mcxross
514,846,313
false
null
package xyz.mcxross.cohesive.cps.utils import xyz.mcxross.cohesive.common.frontend.utils.delete import xyz.mcxross.cohesive.common.frontend.utils.exists import xyz.mcxross.cohesive.common.frontend.utils.isDirectory import xyz.mcxross.cohesive.common.frontend.utils.isZip import xyz.mcxross.cohesive.common.frontend.utils.isZipOrJarFile import xyz.mcxross.cohesive.common.frontend.utils.lastModified import xyz.mcxross.cohesive.common.frontend.utils.notExists import xyz.mcxross.cohesive.common.frontend.utils.toUri import xyz.mcxross.cohesive.common.utils.Log import java.io.File import java.io.FileFilter import java.net.URI import java.nio.file.FileSystem import java.nio.file.FileSystemNotFoundException import java.nio.file.FileSystems import okio.IOException import okio.Path import okio.Path.Companion.toOkioPath object FileUtils { fun getJars(folder: Path): List<File> { val bucket: MutableList<File> = ArrayList() getJars(bucket, folder) return bucket } private fun getJars(bucket: MutableList<File>, folder: Path) { val jarFilter: FileFilter = JarFileFilter() val directoryFilter: FileFilter = DirectoryFileFilter() if (isDirectory(folder)) { val jars = folder.toFile().listFiles(jarFilter) run { var i = 0 while (jars != null && (i < jars.size)) { bucket.add(jars[i]) ++i } } val directories = folder.toFile().listFiles(directoryFilter) var i = 0 while (directories != null && i < directories.size) { val directory = directories[i] getJars(bucket, directory.toOkioPath()) ++i } } } /** * Finds a path with various endings or null if not found. * * @param basePath the base name * @param endings a list of endings to search for * @return new path or null if not found */ fun findWithEnding(basePath: Path, vararg endings: String): Path? { for (ending in endings) { val newPath = basePath.toNioPath().resolveSibling(basePath.name + ending) if (exists(newPath.toOkioPath())) { return newPath.toOkioPath() } } return null } fun optimisticDelete(path: Path?) { if (path == null) { return } try { delete(path) } catch (ignored: IOException) { // ignored } } /** * Unzip a zip file in a directory that has the same name as the zip file. For example if the zip * file is `my-Plugin.zip` then the resulted directory is `my-Plugin`. * * @param filePath the file to evaluate * @return Path of unzipped folder or original path if this was not a zip file * @throws IOException on e */ @Throws(IOException::class) fun expandIfZip(filePath: Path): Path { if (!filePath.isZip()) { return filePath } val fileName = filePath.name val directoryName = fileName.substring(0, fileName.lastIndexOf(".")) val pluginDirectory = filePath.toNioPath().resolveSibling(directoryName).toOkioPath() if (notExists(pluginDirectory) || lastModified(filePath)!! > lastModified(pluginDirectory)!!) { // expand '.zip' file val unzip = Unzip(source = filePath.toFile(), destination = pluginDirectory.toFile()) unzip.extract() Log.d { "Expanded Plugin Zip ${filePath.name} in ${pluginDirectory.name}" } } Log.d { "Returning: $pluginDirectory" } return pluginDirectory } @Throws(IOException::class) fun getPath(path: Path, first: String, vararg more: String?): Path { var uri = path.toUri() if (isZipOrJarFile(path)) { var pathString = path.toFile().absolutePath // transformation for Windows OS pathString = StringUtils.addStart(pathString.replace("\\", "/"), "/") // space is replaced with %20 pathString = pathString.replace(" ", "%20") uri = URI.create("jar:file:$pathString") } return getPath(uri, first, *more) } @Throws(IOException::class) fun getPath(uri: URI?, first: String, vararg more: String?): Path { return getFileSystem(uri).getPath(first, *more).toOkioPath() } fun closePath(path: Path?) { if (path != null) { try { path.toNioPath().fileSystem.close() } catch (e: Exception) { // close silently } } } fun findFile(directoryPath: Path, fileName: String): Path? { val files = directoryPath.toFile().listFiles() if (files != null) { for (file in files) { if (file.isFile) { if (file.name == fileName) { return file.toOkioPath() } } else if (file.isDirectory) { val foundFile = findFile(file.toOkioPath(), fileName) if (foundFile != null) { return foundFile } } } } return null } @Throws(IOException::class) private fun getFileSystem(uri: URI?): FileSystem { return try { FileSystems.getFileSystem(uri) } catch (e: FileSystemNotFoundException) { FileSystems.newFileSystem(uri, emptyMap<String, String>()) } } }
0
Kotlin
0
3
be630e050c060bc5155e7ef7a65e3bc909ec58d6
5,024
cohesive
Apache License 2.0
core/src/main/java/me/kwsk/odptlibrary/core/api/bus/OdptBusStopPoleTimetableResponse.kt
teracy
115,876,824
false
null
package me.kwsk.odptlibrary.core.api.bus import com.google.gson.annotations.SerializedName import me.kwsk.odptlibrary.core.api.common.* import org.threeten.bp.Instant import org.threeten.bp.LocalTime import org.threeten.bp.ZoneId import org.threeten.bp.ZonedDateTime /** * バス停標柱時刻表 */ class OdptBusStopPoleTimetableResponse { /** * 固有識別子(ucode) */ @SerializedName("@id") var odptId: String = "" /** * データ生成時刻 */ @SerializedName("dc:date") var date: ZonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneId.systemDefault()) /** * バス路線名称(系統名等) */ @SerializedName("dc:title") var title: String? = null /** * データ保証期限(期限が存在する場合のみ格納) */ @SerializedName("dct:valid") var valid: ZonedDateTime? = null /** * バス方面ID(API仕様上はrequired) */ @SerializedName("odpt:busDirection") var busDirection: OdptBusDirection? = null /** * バス系統ID(API仕様上はrequired) */ @SerializedName("odpt:busroute") var busRoute: OdptBusRoute? = null /** * バス停のID(API仕様上はrequired) * @see OdptBusStopPoleResponse.sameAs */ @SerializedName("odpt:busstopPole") var busStopPole: OdptBusStopPole? = null // FIXME:API仕様書のAPI戻り値サンプルとオブジェクト定義でJSON名が食い違っている。オブジェクト定義では"busstopTimetableObject"だが、サンプルと実際に得られた値は"odpt:busstopPoleTimetableObject" /** * バス停標柱時刻表時分情報情報リスト */ @SerializedName("odpt:busstopPoleTimetableObject") var busStopPoleTimetableObjectList: List<OdptBusStopPoleTimetableObject> = ArrayList() /** * 運行を行う曜日・日付情報(API仕様上はrequired) */ @SerializedName("odpt:calendar") var calendar: OdptCalendar? = null /** * 運行会社を表す事業者ID(API仕様上はrequired) */ @SerializedName("odpt:operator") var operator: OdptOperator? = null /** * バス停標柱時刻表の固有識別子(API仕様上はrequired) */ @SerializedName("owl:sameAs") var sameAs: OdptBusStopPoleTimetable? = null } /** * バス停標柱時刻表時分情報 */ class OdptBusStopPoleTimetableObject { /** * バス到着時間 */ @SerializedName("odpt:arrivalTime") var arrivalTime: LocalTime? = null /** * バス路線ID */ @SerializedName("odpt:busroutePattern") var busRoutePattern: OdptBusRoutePattern? = null /** * 降車可能な場合true */ @SerializedName("odpt:canGetOff") var canGetOff: Boolean? = null /** * 乗車可能な場合true */ @SerializedName("odpt:canGetOn") var canGetOn: Boolean? = null /** * バス出発時間 */ @SerializedName("odpt:departureTime") var departureTime: LocalTime? = null /** * 行き先バス停標柱 */ @SerializedName("odpt:destinationBusstopPole") var destinationBusStopPole: OdptBusStopPole? = null /** * 行き先(方向幕)情報 */ @SerializedName("odpt:destinationSign") var destinationSign: String? = null /** * 深夜バスの場合true */ @SerializedName("odpt:isMidnight") var isMidnight: Boolean? = null /** * ノンステップバスの場合true */ @SerializedName("odpt:isNonStepBus") var isNonStepBus: Boolean? = null /** * 注記 */ @SerializedName("odpt:note") var note: String? = null }
0
null
0
5
b3fa9249598148fc9cca0574cb62998e42b538f9
3,159
OdptLibrary
Apache License 2.0
blockball-api/src/main/java/com/github/shynixn/blockball/api/business/service/GameExecutionService.kt
Shynixn
78,865,055
false
{"Kotlin": 1036766, "Dockerfile": 2558, "Shell": 2544}
package com.github.shynixn.blockball.api.business.service import com.github.shynixn.blockball.api.persistence.entity.Game /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ interface GameExecutionService { /** * Lets the given [player] in the given [game] respawn at the specified spawnpoint. */ fun <P, G : Game> respawn(game: G, player: P) /** * Applies points to the belonging teams when the given [player] dies in the given [game]. */ fun <P, G : Game> applyDeathPoints(game: G, player: P) }
0
Kotlin
23
66
a2e598f2062072635b32d7a8dbc7c1bde8b65ded
1,690
BlockBall
Apache License 2.0
tools/ingress-testing/api-client/src/main/kotlin/uk/gov/justice/digital/hmpps/client/ApiClient.kt
ministryofjustice
500,855,647
false
{"Kotlin": 4250610, "HTML": 70066, "D2": 42781, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268}
package uk.gov.justice.digital.hmpps.client import org.springframework.stereotype.Component import org.springframework.web.client.RestClient @Component class ApiClient(private val restClient: RestClient) { fun getTest(delay: Int) = restClient .get() .uri("/test/$delay") .exchange { _, res -> res.statusCode.toString() } }
3
Kotlin
0
2
76197df3761bc90253cbf0ec8854a9324d807a7c
353
hmpps-probation-integration-services
MIT License
kcrypto/src/main/kotlin/org/bouncycastle/kcrypto/cert/CertificateBuilder.kt
bcgit
196,159,414
false
{"Kotlin": 458444, "HTML": 419}
package org.bouncycastle.kcrypto.cert import org.bouncycastle.asn1.ASN1ObjectIdentifier import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x509.AlgorithmIdentifier import org.bouncycastle.asn1.x509.Extensions import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo import org.bouncycastle.cert.X509v1CertificateBuilder import org.bouncycastle.cert.X509v3CertificateBuilder import org.bouncycastle.kcrypto.PublicKey import org.bouncycastle.kcrypto.SignatureCalculator import org.bouncycastle.kcrypto.SigningKey import org.bouncycastle.kcrypto.spec.SigAlgSpec import org.bouncycastle.operator.ContentSigner import java.io.OutputStream import java.math.BigInteger import java.util.* private class Signer(var s: SignatureCalculator<AlgorithmIdentifier>) : ContentSigner { override fun getAlgorithmIdentifier(): AlgorithmIdentifier { return s.algorithmIdentifier } override fun getOutputStream(): OutputStream { return s.stream } override fun getSignature(): ByteArray { return s.signature() } } /** * Builder class for X.509 Certificates. * <p> * By default this will produce a version 1 certificate if the setExtensions() method is not called. * * @param signatureCalculator the signature calculator based on the issuer's private key. * @param issuerName the X.500 name for the certificate issuer. */ class CertificateBuilder(private val signatureCalculator: SignatureCalculator<AlgorithmIdentifier>, private val issuerName: X500Name) { /** * Create an X.509 certificate builder based on this signing key for the passed in signature specification. * * @param signingKey the key to use to sign the final certificate. * @param sigAlgSpec name of the signature algorithm the calculator is for. * @param issuerName the X.500 Name to use as the certificate issuer name. */ constructor(signingKey: SigningKey, sigAlgSpec: SigAlgSpec, issuerName: X500Name): this(signingKey.signatureCalculator(sigAlgSpec), issuerName) /** * Create an X.509 certificate builder based on this signing key for the passed in signature specification. * * @param signingKey the key to use to sign the final certificate. * @param sigAlgSpec name of the signature algorithm the calculator is for. * @param issuerCert the Certificate to use as the source of the certificate issuer name. */ constructor(signingKey: SigningKey, sigAlgSpec: SigAlgSpec, issuerCert: Certificate): this(signingKey.signatureCalculator(sigAlgSpec), issuerCert._cert.subject) private var notAfter: Date = Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000) // one year private var notBefore: Date = Date(System.currentTimeMillis() - 1000) private var extSet : Boolean = false; private var extensions : Extensions? = null; /** * Set the time from which the certificate is valid for use. * * @param startDate date at which the certificate becomes valid. * @return this builder object. */ fun setNotBefore(startDate: Date): CertificateBuilder { this.notBefore = Date(startDate.time) return this } /** * Set the time at which the certificate can no longer be used. * * @param expiryDate date at which the certificate becomes invalid. * @return this builder object. */ fun setNotAfter(expiryDate: Date): CertificateBuilder { this.notAfter = Date(expiryDate.time) return this } /** * Provide the certificate extensions for the builder to use. * * @param extensions the extension set to use for the certificate. * @return this builder object. */ fun setExtensions(extensions: Extensions?): CertificateBuilder { this.extSet = true; this.extensions = extensions; return this } /** * Build a self-issued certificate. * * @param serialNumber the serial number for the certificate. * @param publicKey the public key to issue the certificate for (usually the one corresponding to the issuer private key). */ fun build(serialNumber: BigInteger, publicKey: PublicKey): Certificate { return build(serialNumber, issuerName, publicKey) } /** * Build a certificate for the passed in subject and associated public key. * * @param serialNumber the serial number for the certificate. * @param subjectName the X.500 name to be associated with the public key. * @param publicKey the public key to issue the certificate for. */ fun build(serialNumber: BigInteger, subjectName: X500Name, publicKey: PublicKey): Certificate { return build(serialNumber, subjectName, SubjectPublicKeyInfo.getInstance(publicKey.encoding)) } /** * Build a self-issued certificate based on a SubjectPublicKeyInfo. * * @param serialNumber the serial number for the certificate. * @param publicKeyInfo the public key to issue the certificate for (usually the one corresponding to the issuer private key). */ fun build(serialNumber: BigInteger, publicKeyInfo: SubjectPublicKeyInfo): Certificate { return build(serialNumber, issuerName, publicKeyInfo) } /** * Build a certificate for the passed in subject and associated SubjectPublicKeyInfo. * * @param serialNumber the serial number for the certificate. * @param subjectName the X.500 name to be associated with the public key. * @param publicKeyInfo the public key to issue the certificate for. */ fun build(serialNumber: BigInteger, subjectName: X500Name, publicKeyInfo: SubjectPublicKeyInfo): Certificate { val exts = extensions if (extSet) { var bldr = X509v3CertificateBuilder( issuerName, serialNumber, notBefore, notAfter, subjectName, publicKeyInfo) if (exts != null) { for (oid in exts.oids()) { bldr.addExtension(exts.getExtension(oid as ASN1ObjectIdentifier?)) } } return Certificate(bldr.build(Signer(signatureCalculator)).encoded) } else { var bldr = X509v1CertificateBuilder( issuerName, serialNumber, notBefore, notAfter, subjectName, publicKeyInfo) return Certificate(bldr.build(Signer(signatureCalculator)).encoded) } } }
0
Kotlin
15
69
dc86103f5fef1baf9f6e1cdff17bbf31927637ab
6,435
bc-kotlin
MIT License
account_manager/src/main/java/in/windrunner/account_manager/TokenRequestApi.kt
dimskiy
477,723,999
false
null
package `in`.windrunner.account_manager sealed class TokenRequestApi { abstract class WithUsernamePassword : TokenRequestApi() { abstract suspend fun getToken(userName: String, password: String): String } }
0
Kotlin
0
0
947cf94cdff1e047be09a92e154928cf6e6c819a
226
android_accounts
MIT License
app/src/main/java/com/example/mrokey/besttrip/features/authentication/forgot/ForgotPasswordActivity.kt
youknowbaron
139,706,638
false
{"Kotlin": 109066}
package com.example.mrokey.besttrip.features.authentication.forgot import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Button import android.widget.Toast import com.example.mrokey.besttrip.R import kotlinx.android.synthetic.main.activity_forgot_password.* class ForgotPasswordActivity : AppCompatActivity(),ForgotPasswordContract.View { private lateinit var presenter: ForgotPasswordContract.Presenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_forgot_password) setSupportActionBar(toolbarForgot) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) presenter = ForgotPasswordPresenter(this) val btForgot = findViewById<Button>(R.id.btForgot) btForgot.setOnClickListener { getMail() } } override fun setPresenter(presenter: ForgotPasswordContract.Presenter) { this.presenter = presenter } override fun showLoading(isShow: Boolean) { loadForgot.visibility = if (isShow) View.VISIBLE else View.GONE } override fun showAnnounce(message: String) { Toast.makeText(this@ForgotPasswordActivity, message, Toast.LENGTH_SHORT).show() } override fun getMail() { val email = edtEmail?.text.toString() presenter.checkMail(email) } }
0
Kotlin
0
0
7677b547e6ef21729c6212bff39e62a6c7da8d86
1,485
week45-TogetherWeGo
Apache License 2.0
src/main/kotlin/com/cultureamp/eventsourcing/Route.kt
cultureamp
252,301,864
false
{"Kotlin": 213724, "Java": 2634, "Shell": 1465}
package com.cultureamp.eventsourcing import kotlin.reflect.KClass data class Route<CC : CreationCommand, UC : UpdateCommand, M : EventMetadata>( val creationCommandClass: KClass<CC>, val updateCommandClass: KClass<UC>, val executionContextClass: KClass<M>, val aggregateConstructor: AggregateConstructor<CC, *, *, UC, *, M, *> ) { companion object { inline fun <reified CC : CreationCommand, reified UC : UpdateCommand, reified M : EventMetadata> from( aggregateConstructor: AggregateConstructor<CC, *, *, UC, *, M, *> ): Route<CC, UC, M> = Route(CC::class, UC::class, M::class, aggregateConstructor) inline fun <reified CC : CreationCommand, reified UC : UpdateCommand, CE : CreationEvent, UE : UpdateEvent, reified M : EventMetadata> from( simpleAggregateConstructor: SimpleAggregateConstructor<CC, CE, UC, UE> ): Route<CC, UC, M> { return from(AggregateConstructor.from<CC, CE, UC, UE, M, SimpleAggregate<UC, UE>>(simpleAggregateConstructor)) } @JvmName("fromCreationCommandReturningMultipleEvents") inline fun <reified CC : CreationCommand, CE : CreationEvent, Err : DomainError, reified M : EventMetadata, reified UC : UpdateCommand, UE : UpdateEvent, reified A : Any> from( noinline create: (CC, M) -> Either<Err, Pair<CE, List<UE>>>, noinline update: A.(UC, M) -> Either<Err, List<UE>>, noinline created: (CE) -> A, noinline updated: A.(UE) -> A = { _ -> this }, noinline aggregateType: () -> String = { A::class.simpleName!! } ): Route<CC, UC, M> = from(AggregateConstructor.from(create, update, created, updated, aggregateType)) inline fun <reified CC : CreationCommand, CE : CreationEvent, Err : DomainError, reified M : EventMetadata, reified UC : UpdateCommand, UE : UpdateEvent, reified A : Any> from( noinline create: (CC, M) -> Either<Err, CE>, noinline update: A.(UC, M) -> Either<Err, List<UE>>, noinline created: (CE) -> A, noinline updated: A.(UE) -> A = { _ -> this }, noinline aggregateType: () -> String = { A::class.simpleName!! } ): Route<CC, UC, M> = from(AggregateConstructor.from(create, update, created, updated, aggregateType)) inline fun <reified CC : CreationCommand, CE : CreationEvent, Err : DomainError, reified M : EventMetadata, reified UC : UpdateCommand, UE : UpdateEvent, reified A : Any> from( noinline create: (CC) -> Either<Err, CE>, noinline update: A.(UC) -> Either<Err, List<UE>>, noinline created: (CE) -> A, noinline updated: A.(UE) -> A = { _ -> this }, noinline aggregateType: () -> String = { A::class.simpleName!! } ): Route<CC, UC, M> = from(AggregateConstructor.from(create, update, created, updated, aggregateType)) inline fun <reified CC : CreationCommand, CE : CreationEvent, Err : DomainError, reified UC : UpdateCommand, UE : UpdateEvent, reified M : EventMetadata, reified A : Any> fromStateless( noinline create: (CC, M) -> Either<Err, CE>, noinline update: (UC, M) -> Either<Err, List<UE>>, instance: A, noinline aggregateType: () -> String = { A::class.simpleName!! } ): Route<CC, UC, M> = from(AggregateConstructor.fromStateless(create, update, instance, aggregateType)) } }
3
Kotlin
6
53
3b71cd86f075e2d7c124d9706698cacc559f9db5
3,445
kestrel
Apache License 2.0
src/main/kotlin/org/teamvoided/dusk_autumn/block/SixWayFacingBlock.kt
TeamVoided
737,359,498
false
{"Kotlin": 562762, "Java": 6328}
package org.teamvoided.dusk_autumn.block import com.mojang.serialization.MapCodec import net.minecraft.block.Block import net.minecraft.block.BlockState import net.minecraft.item.ItemPlacementContext import net.minecraft.state.StateManager import net.minecraft.state.property.DirectionProperty import net.minecraft.state.property.Properties import net.minecraft.util.BlockMirror import net.minecraft.util.BlockRotation import net.minecraft.util.math.Direction class SixWayFacingBlock(settings: Settings) : Block(settings) { public override fun getCodec(): MapCodec<out SixWayFacingBlock> { return CODEC } init { this.defaultState = defaultState.with(FACING, Direction.UP) } override fun getPlacementState(ctx: ItemPlacementContext): BlockState { return defaultState.with(FACING, ctx.side) } override fun rotate(state: BlockState, rotation: BlockRotation): BlockState { return state.with(FACING, rotation.rotate(state.get(FACING))) } override fun mirror(state: BlockState, mirror: BlockMirror): BlockState { return state.rotate(mirror.getRotation(state.get(FACING))) } override fun appendProperties(builder: StateManager.Builder<Block, BlockState>) { builder.add(FACING) } companion object { val CODEC: MapCodec<SixWayFacingBlock> = createCodec { settings: Settings -> SixWayFacingBlock( settings ) } val FACING: DirectionProperty = Properties.FACING } }
0
Kotlin
0
0
8b5b16f6f4bdc2038f63a10808dd58897912c329
1,528
DusksAndDungeons
MIT License
src/commonMain/kotlin/net/orandja/obor/tags/CborDateTime.kt
L-Briand
289,461,298
false
{"Kotlin": 233324}
package net.orandja.obor.tags import kotlinx.serialization.Serializable import net.orandja.obor.annotations.CborTag import kotlin.jvm.JvmInline @CborTag(0, true) @Serializable @JvmInline value class CborDateTime(val dateTime: String) { override fun toString(): String = dateTime }
0
Kotlin
0
9
d5e54a02a8a2c7fda8cf93cad9ae1f1ee1bfe802
286
obor
The Unlicense
src/test/kotlin/IgnoreArraysOrderTest.kt
mkfl3x
615,517,304
false
{"Kotlin": 29043}
import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mkfl3x.jsondelta.* class IgnoreArraysOrderTest : BaseTest() { private val expectedArrayJson = "[1, 2, 3]" private val actualArrayJson = "[3, 2, 1]" private val expectedArrayFieldJson = """ { "val": true, "arr": [ {"x": 1 , "y": 2, "arr": [1, 2, 3]}, {"x": 3 , "y": 4, "arr": [4, 5, 6]}, {"x": 5 , "y": 6, "arr": [7, 8, 9]} ] } """.trimIndent() private val actualArrayFieldJson = """ { "val": true, "arr": [ {"x": 3 , "y": 4, "arr": [4, 5, 6]}, {"x": 1 , "y": 2, "arr": [1, 2, 3]}, {"x": 5 , "y": 6, "arr": [7, 8, 9]} ] } """.trimIndent() private val expectedDuplicatedArrayElementsJson = "[1, 1, 1]" private val actualDuplicatedArrayElementsJson = "[3, 1, 1]" @Test fun compareSimpleArrays() { val report = JsonDelta() .feature(Feature.IGNORE_ARRAYS_ORDER, true) .compare(expectedArrayJson, actualArrayJson) checkReportSuccess(report) } @Test fun compareObjectsWithArrayField() { val report = JsonDelta() .feature(Feature.IGNORE_ARRAYS_ORDER, true) .compare(expectedArrayFieldJson, actualArrayFieldJson, "root.val") checkReportSuccess(report) } @Test fun compareArraysWithDuplicatedValues() { val report = JsonDelta() .feature(Feature.IGNORE_ARRAYS_ORDER, true) .compare(expectedDuplicatedArrayElementsJson, actualDuplicatedArrayElementsJson) checkReportFailed(report) checkMismatchesPresence( report, ArrayElementNotFoundMismatch("root[3]", MismatchType.ARRAY_ELEMENT_NOT_FOUND) ) } @Test fun compareArrayWithIgnoringArrayIndex() { assertThrows<IgnoreArrayIndexException> { JsonDelta() .feature(Feature.IGNORE_ARRAYS_ORDER, true) .compare(expectedArrayJson, actualArrayJson, "root[1]") } } }
0
Kotlin
0
7
5124080cddec2b70b09b3ed8e90aee72e9fe8e4a
2,154
json-delta
MIT License
app/src/main/java/dev/tran/nam/gobear/mapper/DataMapper.kt
NamTranDev
163,314,406
false
null
package dev.tran.nam.gobear.mapper import javax.inject.Inject import javax.inject.Singleton @Singleton class DataMapper @Inject internal constructor(val articleModelMapper: ArticleModelMapper)
0
Kotlin
0
0
a1e2ff41ff708cbc867253bf27a1d2ac5dafa029
195
GoBear
Apache License 2.0
quide-crawler/src/main/kotlin/io/gitlab/arturbosch/quide/crawler/cli/CLI.kt
arturbosch
78,001,298
false
null
package io.gitlab.arturbosch.quide.crawler.cli import io.gitlab.arturbosch.kutils.readLines import io.gitlab.arturbosch.quide.crawler.Console import io.gitlab.arturbosch.quide.crawler.pipe.GitPipe /** * @author <NAME> */ object CLI { fun run(args: Args) { with(args) { require(input != null) { "Unexpected null input file!" } require(output != null) { "Unexpected null output directory!" } val gitEntries = input!!.readLines() val crawlerOptions = createCrawlerOptions() Console.write("Start piping to $output...") GitPipe(crawlerOptions).start(output!!, gitEntries) Console.write("Finished piping to $output!") } } }
9
Kotlin
1
1
01f9ba759c2bf08e7c57ecdd8bbe6fd4454696ec
649
quide
Apache License 2.0
zircon.core/src/main/kotlin/org/codetome/zircon/api/color/TextColorFactory.kt
opencollective
119,803,967
false
null
package org.codetome.zircon.api.color import org.codetome.zircon.internal.color.DefaultTextColor import java.awt.Color import java.util.regex.Pattern /** * Use this factory to create [TextColor]s. */ object TextColorFactory { /** * The default foreground color is `WHITE`. */ @JvmField val DEFAULT_FOREGROUND_COLOR = ANSITextColor.WHITE /** * The default background color is `BLACK`. */ @JvmField val DEFAULT_BACKGROUND_COLOR = ANSITextColor.BLACK /** * Shorthand for a [TextColor] which is fully transparent. */ @JvmField val TRANSPARENT = DefaultTextColor(0, 0, 0, 0) val DEFAULT_ALPHA = 255 private val RGB_COLOR_PATTERN = Pattern.compile("#[0-9a-fA-F]{6}") /** * Creates a [TextColor] from an awt [Color]. */ @JvmStatic fun fromAWTColor(color: Color): TextColor = DefaultTextColor(color.red, color.green, color.blue, color.alpha) /** * Creates a [TextColor] from a <code>red</code>, <code>green</code>, <code>blue</code> triple. */ @JvmStatic @JvmOverloads fun fromRGB(red: Int, green: Int, blue: Int, alpha: Int = 255): TextColor = DefaultTextColor(red, green, blue, alpha) /** * Parses a string into a color. Formats: * * *blue* - Constant value from the [ANSI] enum * * *#1a1a1a* - Hash character followed by three hex-decimal tuples; creates a [DefaultTextColor] color entry by * parsing the tuples as Red, Green and Blue. */ @JvmStatic fun fromString(value: String): TextColor { value.trim { it <= ' ' }.let { cleanValue -> return if (RGB_COLOR_PATTERN.matcher(cleanValue).matches()) { val r = Integer.parseInt(cleanValue.substring(1, 3), 16) val g = Integer.parseInt(cleanValue.substring(3, 5), 16) val b = Integer.parseInt(cleanValue.substring(5, 7), 16) DefaultTextColor(r, g, b) } else { try { ANSITextColor.valueOf(cleanValue.toUpperCase()) } catch (e: Exception) { throw IllegalArgumentException("Unknown color definition \"" + cleanValue + "\"", e) } } } } }
0
null
1
1
3c1cd8aa4b6ddcbc39b9873c54ac64e3ec6cda4d
2,280
zircon
MIT License
app/src/main/java/com/fourthwall/android/di/NetworkServiceModule.kt
sancarbar
425,257,426
false
{"Kotlin": 27006}
package com.fourthwall.android.di import com.fourthwall.android.BuildConfig import com.fourthwall.android.network.service.PicsumService import com.fourthwall.android.utils.ISO_DATE_FORMAT import com.google.gson.GsonBuilder import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton /** * @author <NAME> * 6/11/21. */ @Module @InstallIn(SingletonComponent::class) object NetworkServiceModule { @Provides @Singleton fun provideRetrofit(): Retrofit { val gson = GsonBuilder() .setDateFormat(ISO_DATE_FORMAT) .create() val builder = Retrofit.Builder() .baseUrl(BuildConfig.API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(CoroutineCallAdapterFactory()) val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY val okHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .writeTimeout(0, TimeUnit.MILLISECONDS) .readTimeout(2, TimeUnit.MINUTES) .connectTimeout(1, TimeUnit.MINUTES).build() return builder.client(okHttpClient).build() } @Provides @Singleton fun providePicsumService(retrofit: Retrofit): PicsumService { return retrofit.create(PicsumService::class.java) } @Provides @Singleton fun provideCoroutineDispatcher(): CoroutineDispatcher { return Dispatchers.IO } }
0
Kotlin
0
0
450ef704b018a54fde80c1b403d0fca1f4489161
1,973
fourthwall-android-challenge
Apache License 2.0
app/src/main/java/me/amitshekhar/ridesharing/ui/maps/MapsActivity.kt
universal9622
776,662,268
false
null
package com.mindorks.ridesharing.ui.maps import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.os.Bundle import android.os.Looper import android.util.Log import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.common.api.Status import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.* import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.widget.Autocomplete import com.google.android.libraries.places.widget.AutocompleteActivity import com.google.android.libraries.places.widget.model.AutocompleteActivityMode import com.mindorks.ridesharing.R import com.mindorks.ridesharing.data.network.NetworkService import com.mindorks.ridesharing.utils.AnimationUtils import com.mindorks.ridesharing.utils.MapUtils import com.mindorks.ridesharing.utils.PermissionUtils import com.mindorks.ridesharing.utils.ViewUtils import kotlinx.android.synthetic.main.activity_maps.* class MapsActivity : AppCompatActivity(), MapsView, OnMapReadyCallback { companion object { private const val TAG = "MapsActivity" private const val LOCATION_PERMISSION_REQUEST_CODE = 999 private const val PICKUP_REQUEST_CODE = 1 private const val DROP_REQUEST_CODE = 2 } private lateinit var presenter: MapsPresenter private lateinit var googleMap: GoogleMap private var fusedLocationProviderClient: FusedLocationProviderClient? = null private lateinit var locationCallback: LocationCallback private var currentLatLng: LatLng? = null private var pickUpLatLng: LatLng? = null private var dropLatLng: LatLng? = null private val nearbyCabMarkerList = arrayListOf<Marker>() private var destinationMarker: Marker? = null private var originMarker: Marker? = null private var greyPolyLine: Polyline? = null private var blackPolyline: Polyline? = null private var previousLatLngFromServer: LatLng? = null private var currentLatLngFromServer: LatLng? = null private var movingCabMarker: Marker? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_maps) ViewUtils.enableTransparentStatusBar(window) val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) presenter = MapsPresenter(NetworkService()) presenter.onAttach(this) setUpClickListener() } private fun setUpClickListener() { pickUpTextView.setOnClickListener { launchLocationAutoCompleteActivity(PICKUP_REQUEST_CODE) } dropTextView.setOnClickListener { launchLocationAutoCompleteActivity(DROP_REQUEST_CODE) } requestCabButton.setOnClickListener { statusTextView.visibility = View.VISIBLE statusTextView.text = getString(R.string.requesting_your_cab) requestCabButton.isEnabled = false pickUpTextView.isEnabled = false dropTextView.isEnabled = false presenter.requestCab(pickUpLatLng!!, dropLatLng!!) } nextRideButton.setOnClickListener { reset() } } private fun launchLocationAutoCompleteActivity(requestCode: Int) { val fields: List<Place.Field> = listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG) val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields) .build(this) startActivityForResult(intent, requestCode) } private fun moveCamera(latLng: LatLng?) { googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)) } private fun animateCamera(latLng: LatLng?) { val cameraPosition = CameraPosition.Builder().target(latLng).zoom(15.5f).build() googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)) } private fun addCarMarkerAndGet(latLng: LatLng): Marker { val bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(MapUtils.getCarBitmap(this)) return googleMap.addMarker(MarkerOptions().position(latLng).flat(true).icon(bitmapDescriptor)) } private fun addOriginDestinationMarkerAndGet(latLng: LatLng): Marker { val bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(MapUtils.getDestinationBitmap()) return googleMap.addMarker(MarkerOptions().position(latLng).flat(true).icon(bitmapDescriptor)) } private fun setCurrentLocationAsPickUp() { pickUpLatLng = currentLatLng pickUpTextView.text = getString(R.string.current_location) } private fun enableMyLocationOnMap() { googleMap.setPadding(0, ViewUtils.dpToPx(48f), 0, 0) googleMap.isMyLocationEnabled = true } private fun setUpLocationListener() { fusedLocationProviderClient = FusedLocationProviderClient(this) // for getting the current location update after every 2 seconds val locationRequest = LocationRequest().setInterval(2000).setFastestInterval(2000) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { super.onLocationResult(locationResult) if (currentLatLng == null) { for (location in locationResult.locations) { if (currentLatLng == null) { currentLatLng = LatLng(location.latitude, location.longitude) setCurrentLocationAsPickUp() enableMyLocationOnMap() moveCamera(currentLatLng) animateCamera(currentLatLng) presenter.requestNearbyCabs(currentLatLng!!) } } } // Few more things we can do here: // For example: Update the location of user on server } } fusedLocationProviderClient?.requestLocationUpdates( locationRequest, locationCallback, Looper.myLooper() ) } private fun checkAndShowRequestButton() { if (pickUpLatLng !== null && dropLatLng !== null) { requestCabButton.visibility = View.VISIBLE requestCabButton.isEnabled = true } } private fun reset() { statusTextView.visibility = View.GONE nextRideButton.visibility = View.GONE nearbyCabMarkerList.forEach { it.remove() } nearbyCabMarkerList.clear() previousLatLngFromServer = null currentLatLngFromServer = null if (currentLatLng != null) { moveCamera(currentLatLng) animateCamera(currentLatLng) setCurrentLocationAsPickUp() presenter.requestNearbyCabs(currentLatLng!!) } else { pickUpTextView.text = "" } pickUpTextView.isEnabled = true dropTextView.isEnabled = true movingCabMarker?.remove() dropLatLng = null dropTextView.text = "" greyPolyLine?.remove() blackPolyline?.remove() originMarker?.remove() destinationMarker?.remove() greyPolyLine = null blackPolyline = null originMarker = null destinationMarker = null movingCabMarker = null } override fun onStart() { super.onStart() if (currentLatLng == null) { when { PermissionUtils.isAccessFineLocationGranted(this) -> { when { PermissionUtils.isLocationEnabled(this) -> { setUpLocationListener() } else -> { PermissionUtils.showGPSNotEnabledDialog(this) } } } else -> { PermissionUtils.requestAccessFineLocationPermission( this, LOCATION_PERMISSION_REQUEST_CODE ) } } } } override fun onDestroy() { presenter.onDetach() fusedLocationProviderClient?.removeLocationUpdates(locationCallback) super.onDestroy() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { LOCATION_PERMISSION_REQUEST_CODE -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { when { PermissionUtils.isLocationEnabled(this) -> { setUpLocationListener() } else -> { PermissionUtils.showGPSNotEnabledDialog(this) } } } else { Toast.makeText( this, getString(R.string.location_permission_not_granted), Toast.LENGTH_LONG ).show() } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PICKUP_REQUEST_CODE || requestCode == DROP_REQUEST_CODE) { when (resultCode) { Activity.RESULT_OK -> { val place = Autocomplete.getPlaceFromIntent(data!!) Log.d(TAG, "Place: " + place.name + ", " + place.id + ", " + place.latLng) when (requestCode) { PICKUP_REQUEST_CODE -> { pickUpTextView.text = place.name pickUpLatLng = place.latLng checkAndShowRequestButton() } DROP_REQUEST_CODE -> { dropTextView.text = place.name dropLatLng = place.latLng checkAndShowRequestButton() } } } AutocompleteActivity.RESULT_ERROR -> { val status: Status = Autocomplete.getStatusFromIntent(data!!) Log.d(TAG, status.statusMessage!!) } Activity.RESULT_CANCELED -> { Log.d(TAG, "Place Selection Canceled") } } } } override fun onMapReady(googleMap: GoogleMap) { this.googleMap = googleMap } override fun showNearbyCabs(latLngList: List<LatLng>) { nearbyCabMarkerList.clear() for (latLng in latLngList) { val nearbyCabMarker = addCarMarkerAndGet(latLng) nearbyCabMarkerList.add(nearbyCabMarker) } } override fun informCabBooked() { nearbyCabMarkerList.forEach { it.remove() } nearbyCabMarkerList.clear() requestCabButton.visibility = View.GONE statusTextView.text = getString(R.string.your_cab_is_booked) } override fun showPath(latLngList: List<LatLng>) { val builder = LatLngBounds.Builder() for (latLng in latLngList) { builder.include(latLng) } val bounds = builder.build() googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 2)) val polylineOptions = PolylineOptions() polylineOptions.color(Color.GRAY) polylineOptions.width(5f) polylineOptions.startCap(SquareCap()) polylineOptions.endCap(SquareCap()) polylineOptions.jointType(JointType.ROUND) polylineOptions.addAll(latLngList) greyPolyLine = googleMap.addPolyline(polylineOptions) val blackPolylineOptions = PolylineOptions() blackPolylineOptions.width(5f) blackPolylineOptions.color(Color.BLACK) blackPolylineOptions.startCap(SquareCap()) blackPolylineOptions.endCap(SquareCap()) blackPolylineOptions.jointType(JointType.ROUND) blackPolyline = googleMap.addPolyline(blackPolylineOptions) originMarker = addOriginDestinationMarkerAndGet(latLngList[0]) originMarker?.setAnchor(0.5f, 0.5f) destinationMarker = addOriginDestinationMarkerAndGet(latLngList[latLngList.size - 1]) destinationMarker?.setAnchor(0.5f, 0.5f) val polylineAnimator = AnimationUtils.polyLineAnimator() polylineAnimator.addUpdateListener { valueAnimator -> val percentValue = (valueAnimator.animatedValue as Int) val index = (greyPolyLine?.points!!.size * (percentValue / 100.0f)).toInt() blackPolyline?.points = greyPolyLine?.points!!.subList(0, index) } polylineAnimator.start() } override fun updateCabLocation(latLng: LatLng) { if (movingCabMarker == null) { movingCabMarker = addCarMarkerAndGet(latLng) } if (previousLatLngFromServer == null) { currentLatLngFromServer = latLng previousLatLngFromServer = currentLatLngFromServer movingCabMarker?.position = currentLatLngFromServer movingCabMarker?.setAnchor(0.5f, 0.5f) animateCamera(currentLatLngFromServer) } else { previousLatLngFromServer = currentLatLngFromServer currentLatLngFromServer = latLng val valueAnimator = AnimationUtils.cabAnimator() valueAnimator.addUpdateListener { va -> if (currentLatLngFromServer != null && previousLatLngFromServer != null) { val multiplier = va.animatedFraction val nextLocation = LatLng( multiplier * currentLatLngFromServer!!.latitude + (1 - multiplier) * previousLatLngFromServer!!.latitude, multiplier * currentLatLngFromServer!!.longitude + (1 - multiplier) * previousLatLngFromServer!!.longitude ) movingCabMarker?.position = nextLocation movingCabMarker?.setAnchor(0.5f, 0.5f) val rotation = MapUtils.getRotation(previousLatLngFromServer!!, nextLocation) if (!rotation.isNaN()) { movingCabMarker?.rotation = rotation } animateCamera(nextLocation) } } valueAnimator.start() } } override fun informCabIsArriving() { statusTextView.text = getString(R.string.your_cab_is_arriving) } override fun informCabArrived() { statusTextView.text = getString(R.string.your_cab_has_arrived) greyPolyLine?.remove() blackPolyline?.remove() originMarker?.remove() destinationMarker?.remove() } override fun informTripStart() { statusTextView.text = getString(R.string.you_are_on_a_trip) previousLatLngFromServer = null } override fun informTripEnd() { statusTextView.text = getString(R.string.trip_end) nextRideButton.visibility = View.VISIBLE greyPolyLine?.remove() blackPolyline?.remove() originMarker?.remove() destinationMarker?.remove() } override fun showRoutesNotAvailableError() { val error = getString(R.string.route_not_available_choose_different_locations) Toast.makeText(this, error, Toast.LENGTH_LONG).show() reset() } override fun showDirectionApiFailedError(error: String) { Toast.makeText(this, error, Toast.LENGTH_LONG).show() reset() } }
6
null
456
4
e1cfc921dc0e13683ca662f87af0f0fedeb44fb4
16,618
app-rs-uber-lyft
Apache License 2.0
components/archive/impl/src/main/java/com/flipperdevices/archive/impl/composable/page/ArchivePage.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.archive.impl.composable.page import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.flipperdevices.archive.impl.model.ArchiveTab import com.flipperdevices.archive.impl.viewmodel.TabViewModel import com.flipperdevices.archive.impl.viewmodel.TabViewModelFactory import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState @Composable fun ArchivePage( tab: ArchiveTab.Specified, tabViewModel: TabViewModel = viewModel( key = tab.fileType.humanReadableName, factory = TabViewModelFactory(tab) ) ) { val keys by tabViewModel.getKeys().collectAsState() SwipeRefresh( state = rememberSwipeRefreshState(false), onRefresh = { tabViewModel.refresh() } ) { LazyColumn( modifier = Modifier .fillMaxSize() .padding(top = 18.dp), verticalArrangement = Arrangement.spacedBy(space = 12.dp) ) { KeysList(keys) } } }
3
null
29
267
6b116430ac0b16c9fe0a00d119507de6fff5474a
1,466
Flipper-Android-App
MIT License
project-system-gradle-psd/src/com/android/tools/idea/gradle/structure/daemon/PsSdkIndexCheckerDaemon.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.structure.daemon import com.android.annotations.concurrency.UiThread import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.gradle.repositories.IdeGoogleMavenRepository import com.android.tools.idea.gradle.structure.model.PsProject import com.android.tools.idea.projectsystem.gradle.IdeGooglePlaySdkIndex import com.intellij.openapi.Disposable import com.intellij.util.EventDispatcher import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import java.util.EventListener class PsSdkIndexCheckerDaemon( parentDisposable: Disposable, private val project: PsProject ) : PsDaemon(parentDisposable) { private val eventDispatcher = EventDispatcher.create(SdkIndexIssuesListener::class.java) fun queueCheck() { mainQueue.queue(RefreshSdkIndexIssues()) } fun add(@UiThread listener: () -> Unit, parentDisposable: Disposable) { eventDispatcher.addListener( object : SdkIndexIssuesListener { @UiThread override fun availableIssues() = listener() }, parentDisposable) } private inner class RefreshSdkIndexIssues : Update(project) { override fun run() { IdeGooglePlaySdkIndex.initializeAndSetFlags(IdeGoogleMavenRepository); resultsUpdaterQueue.queue(SdkIndexAvailable()) } } private inner class SdkIndexAvailable : Update(project) { @UiThread override fun run() { eventDispatcher.multicaster.availableIssues() } } override val mainQueue: MergingUpdateQueue = createQueue("Project Structure Daemon SDK Index Checker", null) override val resultsUpdaterQueue: MergingUpdateQueue = createQueue("Project Structure SDK Index Results Updater", MergingUpdateQueue.ANY_COMPONENT) private interface SdkIndexIssuesListener : EventListener { @UiThread fun availableIssues() } }
5
Kotlin
230
948
10110983c7e784122d94c7467e9d243aba943bf4
2,566
android
Apache License 2.0
app/src/main/java/app/eluvio/wallet/network/dto/v2/MediaPageSectionDto.kt
eluv-io
719,801,077
false
{"Kotlin": 748789, "Java": 22753}
package app.eluvio.wallet.network.dto.v2 import app.eluvio.wallet.network.dto.AssetLinkDto import app.eluvio.wallet.network.dto.v2.permissions.DtoWithPermissions import app.eluvio.wallet.network.dto.v2.permissions.PermissionsDto import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class MediaPageSectionDto( val content: List<SectionItemDto>?, @field:Json(name = "hero_items") val heroItems: List<HeroItemDto>?, val description: String?, val id: String, val type: String, val display: DisplaySettingsDto?, // TODO: this also has "filter options", needs to be implemented. @field:Json(name = "primary_filter") val primaryFilter: String?, @field:Json(name = "secondary_filter") val secondaryFilter: String?, override val permissions: PermissionsDto?, // Section of type "container" will have this field defined (assuming ?resolve_subsections=true) @field:Json(name = "sections_resolved") val subSections: List<MediaPageSectionDto>?, ) : DtoWithPermissions @JsonClass(generateAdapter = true) data class SectionItemDto( val id: String, val type: String, @field:Json(name = "media_type") val mediaType: String?, val media: MediaItemV2Dto?, @field:Json(name = "use_media_settings") val useMediaSettings: Boolean?, // Subproperty link data @field:Json(name = "subproperty_id") val subpropertyId: String?, @field:Json(name = "subproperty_page_id") val subpropertyPageId: String?, // Property link data @field:Json(name = "property_id") val propertyId: String?, @field:Json(name = "property_page_id") val propertyPageId: String?, // Page link data @field:Json(name = "page_id") val pageId: String?, val display: DisplaySettingsDto?, override val permissions: PermissionsDto?, // SectionsItems inside a Banner section will have this field defined @field:Json(name = "banner_image") val bannerImage: AssetLinkDto?, ) : DtoWithPermissions @JsonClass(generateAdapter = true) data class HeroItemDto( val id: String, val display: DisplaySettingsDto?, )
8
Kotlin
1
0
d9fc4a936b1b8c0186812fc75faaaf6ffbcec7f5
2,177
elv-wallet-android
MIT License
nav/safeargs/tests/common/src/com/android/tools/idea/nav/safeargs/psi/java/LightArgsAndBuilderClassInferredTypeTest.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.nav.safeargs.psi.java import com.android.tools.idea.nav.safeargs.SafeArgsRule import com.android.tools.idea.nav.safeargs.extensions.Parameter import com.android.tools.idea.nav.safeargs.extensions.checkSignaturesAndReturnType import com.android.tools.idea.nav.safeargs.psi.SafeArgsFeatureVersions import com.android.tools.idea.res.ResourceRepositoryManager import com.android.tools.idea.testing.findClass import com.google.common.truth.Truth.assertThat import com.intellij.psi.PsiTypes import com.intellij.testFramework.RunsInEdt import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized /** * Tests that would normally go in [LightArgsBuilderClassTest] and [LightArgsClass] but are related to * a bunch of arguments types that we want to test with parametrization. */ @RunsInEdt @RunWith(Parameterized::class) class LightArgsAndBuilderClassInferredTypeTest( private val defaultValueTypeMapping: DefaultValueTypeMapping ) { @get:Rule val safeArgsRule = SafeArgsRule() companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun data() = listOf( DefaultValueTypeMapping("1", PsiTypes.intType().name), DefaultValueTypeMapping("0x21", PsiTypes.intType().name), DefaultValueTypeMapping("1f", PsiTypes.floatType().name), DefaultValueTypeMapping("1L", PsiTypes.longType().name), DefaultValueTypeMapping("true", PsiTypes.booleanType().name), DefaultValueTypeMapping("someString", "String"), DefaultValueTypeMapping("@null", "String"), DefaultValueTypeMapping("@resourceType/resourceName", PsiTypes.intType().name), DefaultValueTypeMapping("someCustomType", "String"), // custom type can't be recognized DefaultValueTypeMapping("someEnumType", "String") // custom type can't be recognized ) } @Test fun expectedBuilderConstructorsAndMethodsAreCreated_inferredType() { safeArgsRule.fixture.addFileToProject( "res/navigation/main.xml", //language=XML """ <?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main" app:startDestination="@id/fragment1"> <fragment android:id="@+id/fragment" android:name="test.safeargs.Fragment" android:label="Fragment"> <argument android:name="arg1" android:defaultValue="${defaultValueTypeMapping.defaultValue}"/> </fragment> </navigation> """.trimIndent()) // Initialize repository after creating resources, needed for codegen to work ResourceRepositoryManager.getInstance(safeArgsRule.androidFacet).moduleResources val context = safeArgsRule.fixture.addClass("package test.safeargs; public class Fragment {}") // Classes can be found with context val builderClass = safeArgsRule.fixture.findClass("test.safeargs.FragmentArgs.Builder", context) as LightArgsBuilderClass // We expect two constructors - a copy constructor (which is initialized with the parent args builderClass.constructors.let { constructors -> assertThat(constructors.size).isEqualTo(2) constructors[0].checkSignaturesAndReturnType( name = "Builder", returnType = "null", parameters = listOf( Parameter("original", "FragmentArgs") ) ) constructors[1].checkSignaturesAndReturnType( name = "Builder", returnType = "null" ) } // For the above xml, we expect a getter and setter for each <argument> tag as well as a final // `build()` method that generates its parent args class. builderClass.methods.let { methods -> assertThat(methods.size).isEqualTo(3) methods[0].checkSignaturesAndReturnType( name = "setArg1", returnType = "Builder", parameters = listOf( Parameter("arg1", defaultValueTypeMapping.inferredTypeStr) ) ) methods[1].checkSignaturesAndReturnType( name = "getArg1", returnType = defaultValueTypeMapping.inferredTypeStr, isReturnTypeNullable = defaultValueTypeMapping.defaultValue == "@null" ) methods[2].checkSignaturesAndReturnType( name = "build", returnType = "FragmentArgs" ) } } @Test fun expectedMethodsAreCreated_inferredType_fromSavedStateHandle() { // Use version [SafeArgsFeatureVersions.FROM_SAVED_STATE_HANDLE] and check the corresponding methods and field. safeArgsRule.addFakeNavigationDependency(SafeArgsFeatureVersions.FROM_SAVED_STATE_HANDLE) safeArgsRule.fixture.addFileToProject( "res/navigation/main.xml", //language=XML """ <?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main" app:startDestination="@id/fragment1"> <fragment android:id="@+id/fragment" android:name="test.safeargs.Fragment" android:label="Fragment"> <argument android:name="arg1" android:defaultValue="${defaultValueTypeMapping.defaultValue}" /> </fragment> </navigation> """.trimIndent()) // Initialize repository after creating resources, needed for codegen to work ResourceRepositoryManager.getInstance(safeArgsRule.androidFacet).moduleResources val context = safeArgsRule.fixture.addClass("package test.safeargs; public class Fragment {}") // Classes can be found with context val argClass = safeArgsRule.fixture.findClass("test.safeargs.FragmentArgs", context) as LightArgsClass argClass.methods.let { methods -> assertThat(methods.size).isEqualTo(4) methods[0].checkSignaturesAndReturnType( name = "getArg1", returnType = defaultValueTypeMapping.inferredTypeStr, isReturnTypeNullable = defaultValueTypeMapping.defaultValue == "@null" ) methods[1].checkSignaturesAndReturnType( name = "fromBundle", returnType = "FragmentArgs", parameters = listOf( Parameter("bundle", "Bundle") ) ) methods[2].checkSignaturesAndReturnType( name = "fromSavedStateHandle", returnType = "FragmentArgs", parameters = listOf( Parameter("savedStateHandle", "SavedStateHandle") ) ) methods[3].checkSignaturesAndReturnType( name = "toBundle", returnType = "Bundle" ) } } @Test fun expectedMethodsAreCreated_inferredType_toSavedStateHandle() { // Use version [SafeArgsFeatureVersions.TO_SAVED_STATE_HANDLE] and check the corresponding methods and field. safeArgsRule.addFakeNavigationDependency(SafeArgsFeatureVersions.TO_SAVED_STATE_HANDLE) safeArgsRule.fixture.addFileToProject( "res/navigation/main.xml", //language=XML """ <?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main" app:startDestination="@id/fragment1"> <fragment android:id="@+id/fragment" android:name="test.safeargs.Fragment" android:label="Fragment"> <argument android:name="arg1" android:defaultValue="${defaultValueTypeMapping.defaultValue}" /> </fragment> </navigation> """.trimIndent()) // Initialize repository after creating resources, needed for codegen to work ResourceRepositoryManager.getInstance(safeArgsRule.androidFacet).moduleResources val context = safeArgsRule.fixture.addClass("package test.safeargs; public class Fragment {}") // Classes can be found with context val argClass = safeArgsRule.fixture.findClass("test.safeargs.FragmentArgs", context) as LightArgsClass argClass.methods.let { methods -> assertThat(methods.size).isEqualTo(5) methods[0].checkSignaturesAndReturnType( name = "getArg1", returnType = defaultValueTypeMapping.inferredTypeStr, isReturnTypeNullable = defaultValueTypeMapping.defaultValue == "@null" ) methods[1].checkSignaturesAndReturnType( name = "fromBundle", returnType = "FragmentArgs", parameters = listOf( Parameter("bundle", "Bundle") ) ) methods[2].checkSignaturesAndReturnType( name = "fromSavedStateHandle", returnType = "FragmentArgs", parameters = listOf( Parameter("savedStateHandle", "SavedStateHandle") ) ) methods[3].checkSignaturesAndReturnType( name = "toSavedStateHandle", returnType = "SavedStateHandle" ) methods[4].checkSignaturesAndReturnType( name = "toBundle", returnType = "Bundle" ) } } } data class DefaultValueTypeMapping(val defaultValue: String, val inferredTypeStr: String)
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
9,908
android
Apache License 2.0
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/touch/ReactHitSlopView.kt
react-native-tvos
177,633,560
false
{"C++": 4398815, "Java": 2649623, "JavaScript": 2551815, "Objective-C++": 1803949, "Kotlin": 1628327, "Objective-C": 1421207, "Ruby": 453872, "CMake": 109113, "TypeScript": 85912, "Shell": 58251, "C": 57980, "Assembly": 14920, "HTML": 1473, "Swift": 739}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.touch import android.graphics.Rect /** * This interface should be implemented by all [View] subclasses that want to use the hitSlop prop * to extend their touch areas. */ public interface ReactHitSlopView { public val hitSlopRect: Rect? }
7
C++
147
942
692bc66a98c8928c950bece9a22d04c13f0c579d
464
react-native-tvos
MIT License
play-services-maps/core/mapbox/src/main/kotlin/org/microg/gms/maps/mapbox/AbstractGoogleMap.kt
kazimmt
645,813,057
false
null
package org.microg.gms.maps.mapbox import android.content.Context import android.location.Location import android.os.Bundle import android.util.DisplayMetrics import android.util.Log import com.google.android.gms.dynamic.IObjectWrapper import com.google.android.gms.dynamic.ObjectWrapper import com.google.android.gms.maps.internal.* import com.mapbox.mapboxsdk.location.engine.LocationEngineCallback import com.mapbox.mapboxsdk.location.engine.LocationEngineResult import org.microg.gms.maps.mapbox.model.AbstractMarker import org.microg.gms.maps.mapbox.model.DefaultInfoWindowAdapter import org.microg.gms.maps.mapbox.model.InfoWindow import org.microg.gms.maps.mapbox.utils.MapContext abstract class AbstractGoogleMap(context: Context) : IGoogleMapDelegate.Stub() { internal val mapContext = MapContext(context) val dpiFactor: Float get() = mapContext.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT internal var currentInfoWindow: InfoWindow? = null internal var infoWindowAdapter: IInfoWindowAdapter = DefaultInfoWindowAdapter(mapContext) internal var onInfoWindowClickListener: IOnInfoWindowClickListener? = null internal var onInfoWindowLongClickListener: IOnInfoWindowLongClickListener? = null internal var onInfoWindowCloseListener: IOnInfoWindowCloseListener? = null internal var mapClickListener: IOnMapClickListener? = null internal var mapLongClickListener: IOnMapLongClickListener? = null internal var markerClickListener: IOnMarkerClickListener? = null internal var circleClickListener: IOnCircleClickListener? = null internal var myLocationChangeListener: IOnMyLocationChangeListener? = null internal val locationEngineCallback = object : LocationEngineCallback<LocationEngineResult> { override fun onSuccess(result: LocationEngineResult?) { result?.lastLocation?.let { location -> Log.d(TAG, "myLocationChanged: $location") myLocationChangeListener?.onMyLocationChanged(ObjectWrapper.wrap(location)) onLocationUpdate(location) } } override fun onFailure(e: Exception) { Log.e(TAG, "Failed to obtain location update", e) } } internal abstract fun showInfoWindow(marker: AbstractMarker): Boolean internal abstract fun onLocationUpdate(location: Location) override fun setOnInfoWindowClickListener(listener: IOnInfoWindowClickListener?) { onInfoWindowClickListener = listener } override fun setOnInfoWindowLongClickListener(listener: IOnInfoWindowLongClickListener) { onInfoWindowLongClickListener = listener } override fun setOnInfoWindowCloseListener(listener: IOnInfoWindowCloseListener) { onInfoWindowCloseListener = listener } override fun setInfoWindowAdapter(adapter: IInfoWindowAdapter?) { infoWindowAdapter = adapter ?: DefaultInfoWindowAdapter(mapContext) } override fun setOnMapClickListener(listener: IOnMapClickListener?) { mapClickListener = listener } override fun setOnMapLongClickListener(listener: IOnMapLongClickListener?) { mapLongClickListener = listener } override fun setOnMarkerClickListener(listener: IOnMarkerClickListener?) { markerClickListener = listener } override fun setOnCircleClickListener(listener: IOnCircleClickListener?) { circleClickListener = listener } override fun setOnPolygonClickListener(listener: IOnPolygonClickListener?) { Log.d(TAG, "Not yet implemented: setOnPolygonClickListener") } override fun setOnPolylineClickListener(listener: IOnPolylineClickListener?) { Log.d(TAG, "Not yet implemented: setOnPolylineClickListener") } override fun setOnGroundOverlayClickListener(listener: IOnGroundOverlayClickListener?) { Log.d(TAG, "Not yet implemented: setOnGroundOverlayClickListener") } override fun setOnMyLocationClickListener(listener: IOnMyLocationClickListener?) { Log.d(TAG, "Not yet implemented: setOnMyLocationClickListener") } override fun getMyLocation(): Location? { Log.d(TAG, "unimplemented Method: getMyLocation") return null } override fun setLocationSource(locationSource: ILocationSourceDelegate?) { Log.d(TAG, "unimplemented Method: setLocationSource") } override fun setOnMyLocationChangeListener(listener: IOnMyLocationChangeListener?) { myLocationChangeListener = listener } override fun setOnMyLocationButtonClickListener(listener: IOnMyLocationButtonClickListener?) { Log.d(TAG, "unimplemented Method: setOnMyLocationButtonClickListener") } override fun getTestingHelper(): IObjectWrapper { Log.d(TAG, "unimplemented Method: getTestingHelper") return ObjectWrapper.wrap(null) } override fun isBuildingsEnabled(): Boolean { Log.d(TAG, "unimplemented Method: isBuildingsEnabled") return false } override fun setBuildingsEnabled(buildings: Boolean) { Log.d(TAG, "unimplemented Method: setBuildingsEnabled") } override fun useViewLifecycleWhenInFragment(): Boolean { Log.d(TAG, "unimplemented Method: useViewLifecycleWhenInFragment") return false } override fun onEnterAmbient(bundle: Bundle?) { Log.d(TAG, "unimplemented Method: onEnterAmbient") } override fun onExitAmbient() { Log.d(TAG, "unimplemented Method: onExitAmbient") } override fun isTrafficEnabled(): Boolean { Log.d(TAG, "unimplemented Method: isTrafficEnabled") return false } override fun setTrafficEnabled(traffic: Boolean) { Log.d(TAG, "unimplemented Method: setTrafficEnabled") } override fun isIndoorEnabled(): Boolean { Log.d(TAG, "unimplemented Method: isIndoorEnabled") return false } override fun setIndoorEnabled(indoor: Boolean) { Log.d(TAG, "unimplemented Method: setIndoorEnabled") } companion object { val TAG = "GmsMapAbstract" } }
990
null
1707
96
30e774b23b845d20eb82f8a611345cf32fdc991e
6,132
mMicroG
Apache License 2.0
app/src/main/java/com/abidria/presentation/scene/show/SceneDetailView.kt
jordifierro
98,501,336
false
null
package com.abidria.presentation.scene.show import com.abidria.data.scene.Scene interface SceneDetailView { fun showScene(scene: Scene) fun navigateToEditScene(sceneId: String, experienceId: String) }
0
null
1
2
f6ec0112c4a555232c8544e4f380dd733dddb286
212
abidria-android
Apache License 2.0
populator/coroutine-source-cache/src/main/java/com/cube/fusion/populator/coroutinesourcecache/cache/LruDataCache.kt
3sidedcube
465,637,089
false
{"Kotlin": 145310}
package com.cube.fusion.populator.coroutinesourcecache.cache import android.util.LruCache /** * [FusionDataCache] implementation utilising Android [LruCache] to store pages in memory with a maximum size * * Created by <NAME> on 10/March/2022. * Copyright ® 3SidedCube. All rights reserved. * * @param cache the LruCache to store Fusion data in * @param CachedType the type in which the data is stored */ class LruDataCache<CachedType>(val cache: LruCache<String, CachedType>) : FusionDataCache<CachedType>() { constructor(maxSize: Int): this(LruCache(maxSize)) override suspend fun cache(screenLink: String, data: CachedType) { cache.put(screenLink, data) } override suspend fun retrieve(screenLink: String): Result<CachedType> = cache[screenLink]?.let { Result.success(it) } ?: Result.failure(NoSuchElementException()) }
0
Kotlin
0
0
8b12af27a4a6bb5641c744681989bc0f06dc60c9
840
Android-Fusion-Core
MIT License
src/main/kotlin/com/ridi/books/helper/view/BindingAdapters.kt
ridi
70,668,180
false
{"Java Properties": 2, "Gradle": 1, "Proguard": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Markdown": 1, "Kotlin": 27, "XML": 1, "Java": 2, "YAML": 1}
package com.ridi.books.helper.view import android.graphics.drawable.GradientDrawable import android.view.View import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.Px import androidx.databinding.BindingAdapter import com.ridi.books.helper.text.makeSpannedFromHtml class BindingAdapters { companion object { @BindingAdapter(value = ["strokeColor", "strokeSize", "backgroundColor", "radius"], requireAll = false) @JvmStatic fun setCustomBackground( view: View, @ColorInt strokeColor: Int?, @Px strokeSize: Int?, @ColorInt backgroundColor: Int?, @Px radius: Int? ) { view.apply { val prevPaddingLeft = paddingLeft val prevPaddingRight = paddingRight val prevPaddingTop = paddingTop val prevPaddingBottom = paddingBottom val gradientDrawable = GradientDrawable() radius?.let { gradientDrawable.cornerRadius = dip(radius) } backgroundColor?.let { gradientDrawable.setColor(backgroundColor) } strokeColor?.let { gradientDrawable.setStroke(dip(strokeSize ?: 1).toInt(), strokeColor) } background = gradientDrawable setPadding(prevPaddingLeft, prevPaddingTop, prevPaddingRight, prevPaddingBottom) } } @BindingAdapter("htmlText") @JvmStatic fun setHtmlText(textView: TextView, htmlText: String) { textView.text = makeSpannedFromHtml(htmlText) } } }
0
Kotlin
0
3
8a72a827a5ad747c7194836dbf3fbae1327e189b
1,621
rbhelper-android
MIT License
examples/imageviewer/shared/src/commonMain/kotlin/example/imageviewer/Dependencies.kt
JetBrains
293,498,508
false
null
package example.imageviewer import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.ImageBitmap import example.imageviewer.filter.PlatformContext import example.imageviewer.model.PictureData import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.readResourceBytes @OptIn(ExperimentalResourceApi::class) abstract class Dependencies { abstract val notification: Notification abstract val imageStorage: ImageStorage abstract val sharePicture: SharePicture val pictures: SnapshotStateList<PictureData> = mutableStateListOf(*resourcePictures) open val externalEvents: Flow<ExternalImageViewerEvent> = emptyFlow() val localization: Localization = getCurrentLocalization() val imageProvider: ImageProvider = object : ImageProvider { override suspend fun getImage(picture: PictureData): ImageBitmap = when (picture) { is PictureData.Resource -> { readResourceBytes(picture.resource).toImageBitmap() } is PictureData.Camera -> { imageStorage.getImage(picture) } } override suspend fun getThumbnail(picture: PictureData): ImageBitmap = when (picture) { is PictureData.Resource -> { readResourceBytes(picture.thumbnailResource).toImageBitmap() } is PictureData.Camera -> { imageStorage.getThumbnail(picture) } } override fun saveImage(picture: PictureData.Camera, image: PlatformStorableImage) { imageStorage.saveImage(picture, image) } override fun delete(picture: PictureData) { pictures.remove(picture) if (picture is PictureData.Camera) { imageStorage.delete(picture) } } override fun edit(picture: PictureData, name: String, description: String): PictureData { when (picture) { is PictureData.Resource -> { val edited = picture.copy( name = name, description = description, ) pictures[pictures.indexOf(picture)] = edited return edited } is PictureData.Camera -> { val edited = picture.copy( name = name, description = description, ) pictures[pictures.indexOf(picture)] = edited imageStorage.rewrite(edited) return edited } } } } } interface Notification { fun notifyImageData(picture: PictureData) } abstract class PopupNotification(private val localization: Localization) : Notification { abstract fun showPopUpMessage(text: String) override fun notifyImageData(picture: PictureData) = showPopUpMessage( "${localization.picture} ${picture.name}" ) } interface Localization { val appName: String val back: String val picture: String val takePhoto: String val addPhoto: String val kotlinConfName: String val kotlinConfDescription: String val newPhotoName: String val newPhotoDescription: String } interface ImageProvider { suspend fun getImage(picture: PictureData): ImageBitmap suspend fun getThumbnail(picture: PictureData): ImageBitmap fun saveImage(picture: PictureData.Camera, image: PlatformStorableImage) fun delete(picture: PictureData) fun edit(picture: PictureData, name: String, description: String): PictureData } interface ImageStorage { fun saveImage(picture: PictureData.Camera, image: PlatformStorableImage) fun delete(picture: PictureData.Camera) fun rewrite(picture: PictureData.Camera) suspend fun getThumbnail(picture: PictureData.Camera): ImageBitmap suspend fun getImage(picture: PictureData.Camera): ImageBitmap } interface SharePicture { fun share(context: PlatformContext, picture: PictureData) } internal val LocalLocalization = staticCompositionLocalOf<Localization> { noLocalProvidedFor("LocalLocalization") } internal val LocalNotification = staticCompositionLocalOf<Notification> { noLocalProvidedFor("LocalNotification") } internal val LocalImageProvider = staticCompositionLocalOf<ImageProvider> { noLocalProvidedFor("LocalImageProvider") } internal val LocalInternalEvents = staticCompositionLocalOf<Flow<ExternalImageViewerEvent>> { noLocalProvidedFor("LocalInternalEvents") } internal val LocalSharePicture = staticCompositionLocalOf<SharePicture> { noLocalProvidedFor("LocalSharePicture") } private fun noLocalProvidedFor(name: String): Nothing { error("CompositionLocal $name not present") }
64
null
1174
16,150
7e9832f6494edf3e7967082c11417e78cfd1d9d0
5,043
compose-multiplatform
Apache License 2.0
app/src/main/java/dev/teogor/ceres/presentation/feature/home/HomeFragment.kt
teogor
555,090,893
false
null
/* * Copyright 2022 teogor (<NAME>) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.teogor.ceres.presentation.feature.home import androidx.databinding.library.baseAdapters.BR import dagger.hilt.android.AndroidEntryPoint import dev.teogor.ceres.R import dev.teogor.ceres.databinding.FragmentHomeBinding import dev.teogor.ceres.m3.app.BaseFragmentM3 @AndroidEntryPoint class HomeFragment : BaseFragmentM3<FragmentHomeBinding, HomeViewModel>() { override fun getContentViewId(): Int = R.layout.fragment_home override fun getBindingVariable() = BR.viewModel override fun getViewModelClass() = HomeViewModel::class.java override fun onRefresh() { super.onRefresh() binding.root.scrollToTop() } }
6
Kotlin
3
22
dd556d2f43fa8b0fd44edf9d091d8059a9c8caac
1,261
ceres
Apache License 2.0
philarios-structurizr/src/main/kotlin/io/philarios/structurizr/sugar/PersonBuilder.kt
taxpon
180,252,847
true
{"Kotlin": 666395, "Ruby": 7769, "Shell": 1002, "HTML": 398}
package io.philarios.structurizr.sugar import io.philarios.structurizr.Location import io.philarios.structurizr.PersonBuilder import io.philarios.structurizr.RelationshipBuilder fun <C, T : Any> PersonBuilder<C>.id(id: T) { id(id.hierarchicalId()) } fun <C, T : Any> PersonBuilder<C>.relationship(destinationId: T, body: RelationshipBuilder<C>.() -> Unit = {}) { relationship { destinationId(destinationId) apply(body) } } fun <C> PersonBuilder<C>.internal() { location(Location.Internal) } fun <C> PersonBuilder<C>.external() { location(Location.External) }
0
Kotlin
0
0
ea311f14fe3e62ea5f2b76f13bafe76ac5dfe073
601
philarios
MIT License
app/src/main/kotlin/de/marionoll/wgautoconnect/service/NetworkMonitorService.kt
MarioNoll
749,964,440
false
{"Kotlin": 81070}
package de.marionoll.wgautoconnect.service import android.Manifest import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo import android.location.LocationManager import android.net.ConnectivityManager import android.net.ConnectivityManager.NetworkCallback import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.os.Build import android.os.IBinder import androidx.annotation.StringRes import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.datastore.core.DataStore import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.qualifiers.ApplicationContext import de.marionoll.wgautoconnect.MainActivity import de.marionoll.wgautoconnect.R import de.marionoll.wgautoconnect.data.AutoConnectState import de.marionoll.wgautoconnect.data.SSID import de.marionoll.wgautoconnect.data.Tunnel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.trySendBlocking import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import javax.inject.Inject const val NETWORK_MONITOR_SERVICE_NETWORK_KEY = "network" const val NETWORK_MONITOR_SERVICE_TUNNEL_KEY = "tunnel" val NETWORK_SERVICE_PERMISSIONS = buildList { add(Manifest.permission.ACCESS_FINE_LOCATION) add("com.wireguard.android.permission.CONTROL_TUNNELS") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { add(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } } @AndroidEntryPoint class NetworkMonitorService : Service() { @Inject @ApplicationContext lateinit var context: Context @Inject lateinit var connectivityManager: ConnectivityManager @Inject lateinit var locationManager: LocationManager @Inject lateinit var wifiManager: WifiManager @Inject lateinit var notificationManager: NotificationManagerCompat @Inject lateinit var autoConnectStateDataStore: DataStore<AutoConnectState?> private lateinit var network: String private lateinit var tunnel: String private var monitorJob: Job? = null private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob()) override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { startForeground( 1, foregroundServiceNotification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION ) } else { startForeground( 1, foregroundServiceNotification, ) } if (monitorJob == null && intent != null) { network = intent.getStringExtra(NETWORK_MONITOR_SERVICE_NETWORK_KEY)!! tunnel = intent.getStringExtra(NETWORK_MONITOR_SERVICE_TUNNEL_KEY)!! monitorJob = scope.launch { isWifiAvailable() .distinctUntilChanged() .collectLatest { isWifiAvailable -> checkWifiState(isWifiAvailable) } } } return START_REDELIVER_INTENT } override fun onDestroy() { monitorJob?.cancel() scope.cancel() } override fun onBind(intent: Intent): IBinder? = null private fun isWifiAvailable(): Flow<Boolean> = callbackFlow { val networkCallback = object : NetworkCallback() { override fun onAvailable(network: Network) { trySendBlocking(true) } override fun onLost(network: Network) { trySendBlocking(false) } } val networkRequest = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .build() connectivityManager.registerNetworkCallback(networkRequest, networkCallback) awaitClose { connectivityManager.unregisterNetworkCallback(networkCallback) } } private suspend fun checkWifiState(isWifiAvailable: Boolean) { updateTunnel( if (isWifiAvailable) tunnelStateForWifi() else TunnelState.Up ) } private suspend fun tunnelStateForWifi(): TunnelState { return connectedWifiSSID() .first() ?.let { ssid -> ssid.value == network } ?.let { trusted -> if (trusted) TunnelState.Down else TunnelState.Up } ?: TunnelState.Up } private fun connectedWifiSSID(): Flow<SSID?> = callbackFlow { fun WifiInfo?.sendSSID() { this?.ssid ?.removeSurrounding("\"") ?.let(::SSID) .run(::trySendBlocking) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val networkCallback = object : NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) { override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { (networkCapabilities.transportInfo as? WifiInfo)?.sendSSID() } } connectivityManager.registerNetworkCallback( NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .build(), networkCallback, ) awaitClose { connectivityManager.unregisterNetworkCallback(networkCallback) } } else { val connectionInfo = if (wifiManager.isWifiEnabled) { @Suppress("DEPRECATION") wifiManager.connectionInfo } else { null } connectionInfo.sendSSID() awaitClose() } } private fun updateTunnel(desiredState: TunnelState) { desiredState .takeIf(::shouldUpdateTunnel) ?.toIntent(Tunnel(tunnel)) ?.also(::sendBroadcast) } private fun shouldUpdateTunnel(desiredState: TunnelState): Boolean { return when (desiredState) { TunnelState.Up -> !vpnEnabled TunnelState.Down -> vpnEnabled } } private val vpnEnabled: Boolean get() = connectivityManager .getNetworkCapabilities(connectivityManager.activeNetwork) ?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true private val foregroundServiceNotification: Notification get() { val contentIntent = Intent(this, MainActivity::class.java) .let { PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE) } val channelId = "network_service" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManager.getNotificationChannel(channelId) == null ) { notificationManager.createNotificationChannel( NotificationChannel( channelId, context.getString(R.string.vpn_auto_connect_notification_channel), NotificationManager.IMPORTANCE_LOW, ) ) } return NotificationCompat.Builder(context, channelId) .apply { setContentTitle(R.string.network_service_active) setOngoing(true) setSmallIcon(R.drawable.notification_app_icon) setContentIntent(contentIntent) foregroundServiceBehavior = NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE } .build() } } context(Context) fun NotificationCompat.Builder.setContentTitle(@StringRes title: Int) { setContentTitle( getString(title) ) }
1
Kotlin
1
4
71dd60d9e99bdc6ebaacd3499622fbbab5508c69
8,519
WG-Auto-Connect
MIT License
app/src/main/java/org/mightyfrog/android/s4fd/details/tabcontents/attributes/AttributesAdapter.kt
dena-appleseed
85,302,865
true
{"Kotlin": 121067, "Java": 54160}
package org.mightyfrog.android.s4fd.details.tabcontents.attributes import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.raizlabs.android.dbflow.sql.language.Select import org.mightyfrog.android.s4fd.R import org.mightyfrog.android.s4fd.data.KHCharacter import org.mightyfrog.android.s4fd.data.MovementDatum import org.mightyfrog.android.s4fd.data.MovementDatum_Table /** * @author <NAME> */ class AttributesAdapter(var mList: List<MovementDatum>) : RecyclerView.Adapter<AttributesAdapter.AttributeViewHolder>() { private var mCharToCompare: KHCharacter? = null init { setHasStableIds(true) } override fun getItemCount(): Int = mList.size override fun getItemId(position: Int): Long = mList[position].id.toLong() override fun onBindViewHolder(holder: AttributeViewHolder?, position: Int) { holder?.bind(mList[position]) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): AttributeViewHolder = AttributeViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.vh_attribute, parent, false)) fun update(list: List<MovementDatum>) { mList = list notifyDataSetChanged() } fun compare(char: KHCharacter?) { mCharToCompare = char notifyDataSetChanged() } inner class AttributeViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { private val nameTv = itemView?.findViewById(R.id.name) as TextView private val valueTv = itemView?.findViewById(R.id.value) as TextView fun bind(datum: MovementDatum) { nameTv.text = datum.name val value = datum.value?.replace("frame", " frame") if (mCharToCompare != null) { val datumToComp = Select().from(MovementDatum::class.java) .where(MovementDatum_Table.ownerId.eq(mCharToCompare!!.id)) .and(MovementDatum_Table.name.eq(datum.name)) .querySingle() if (datum.ownerId != datumToComp?.ownerId) { val compValue = datumToComp?.value?.replace("frame", " frame") valueTv.text = itemView.context.getString(R.string.attr_compare, value, compValue) } else { valueTv.text = value } } else { valueTv.text = value } } } }
0
Kotlin
0
0
99527af4124c33e3599160e5311da6dc9e32ad60
2,535
S4FD
Apache License 2.0
common/src/main/java/jp/co/soramitsu/common/domain/GetEducationalStoriesUseCase.kt
soramitsu
278,060,397
false
{"Kotlin": 5206254, "Java": 18796}
package jp.co.soramitsu.common.domain import jp.co.soramitsu.common.data.OnboardingStoriesDataSource class GetEducationalStoriesUseCase(private val storiesDataSource: OnboardingStoriesDataSource) { operator fun invoke() = storiesDataSource.stories }
11
Kotlin
27
83
0ff0b5dd515b72316dbe7c995a33459d7a4160b9
256
fearless-Android
Apache License 2.0
mediator/src/test/kotlin/no/nav/dagpenger/saksbehandling/saksbehandler/SaksbehandlerOppslagImplTest.kt
navikt
571,475,339
false
{"Kotlin": 420779, "PLpgSQL": 7983, "Mustache": 4238, "HTML": 699, "Dockerfile": 77}
package no.nav.dagpenger.saksbehandling.saksbehandler import io.kotest.matchers.shouldBe import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond import io.ktor.client.engine.mock.respondError import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf import io.prometheus.metrics.model.registry.PrometheusRegistry import io.prometheus.metrics.model.snapshots.HistogramSnapshot import kotlinx.coroutines.runBlocking import no.nav.dagpenger.saksbehandling.api.models.BehandlerDTO import no.nav.dagpenger.saksbehandling.api.models.BehandlerEnhetDTO import no.nav.dagpenger.saksbehandling.getSnapShot import org.junit.jupiter.api.Test class SaksbehandlerOppslagImplTest { val enhet = BehandlerEnhetDTO( navn = "Test Enhet", enhetNr = "1234", postadresse = "Postboks 5678, Test, 1234 Oslo", ) private val saksbehandler = BehandlerDTO( ident = "navIdent", fornavn = "sonet", etternavn = "electram", enhet = enhet, ) private val mockTokenProvider = { "mockToken" } private val mockEngine = MockEngine { request -> when (request.url.encodedPath) { "/v1.0/users" -> respond( content = """ { "value": [ { "givenName": "${saksbehandler.fornavn}", "surname": "${saksbehandler.etternavn}", "streetAddress": "${enhet.enhetNr}" } ] } """.trimIndent(), status = HttpStatusCode.OK, headers = headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString()), ) "/api/v1/enhet/${enhet.enhetNr}" -> respond( content = """{"navn": "${enhet.navn}"}""", status = HttpStatusCode.OK, headers = headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString()), ) "/api/v1/enhet/1234/kontaktinformasjon" -> respond( content = """{"postadresse": {"postnummer": "1234", "poststed": "Oslo", "type": "B", | "postboksnummer": "5678", "postboksanlegg": "Test"}} """.trimMargin(), status = HttpStatusCode.OK, headers = headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString()), ) else -> respondError(HttpStatusCode.NotFound) } } private val registry = PrometheusRegistry() private val saksbehandlerOppslag = SaksbehandlerOppslagImpl( norgBaseUrl = "http://localhost", msGraphBaseUrl = "http://localhost", tokenProvider = mockTokenProvider, prometheusRegistry = registry, engine = mockEngine, ) @Test fun `test hentSaksbehandler happy days `(): Unit = runBlocking { val result: BehandlerDTO = saksbehandlerOppslag.hentSaksbehandler(saksbehandler.ident) result shouldBe saksbehandler registry.getSnapShot<HistogramSnapshot> { it == "dp_saksbehandling_saksbehandler_oppslag_duration" }.dataPoints.size shouldBe 1 } }
1
Kotlin
0
0
acd8745348d9187b179e0c1f11f4730c0feba5f0
3,828
dp-saksbehandling
MIT License
repo/gradle-build-conventions/asm-deprecating-transformer/src/main/kotlin/org/jetbrains/kotlin/build/asm/AsmDeprecationExtension.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.build.asm import com.github.difflib.DiffUtils import com.github.difflib.UnifiedDiffUtils import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.file.ArchiveOperations import org.gradle.api.tasks.Copy import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.util.PatternSet import org.gradle.kotlin.dsl.named import org.gradle.kotlin.dsl.register import org.gradle.kotlin.dsl.support.serviceOf import org.jetbrains.org.objectweb.asm.ClassReader import org.jetbrains.org.objectweb.asm.ClassWriter import java.io.File import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream /** * Allows configuring ad-hoc deprecation of classes included in fat jar generated by a [ShadowJar] task. * Context: https://youtrack.jetbrains.com/issue/KT-70251 */ abstract class AsmDeprecationExtension { /** * Transforms class FQN-like pattern to file names pattern * Examples: * * `org.example.**` -> `org/example/**/*.class` * * `org.example.Class` -> `org/example/Class.class` */ private fun String.transformPattern() = "${replace('.', '/').replace("**", "**/*")}.class" fun ShadowJar.deprecateClassesByPattern(pattern: String, deprecationMessage: String, exclusions: List<String> = emptyList()) { val patternSet = PatternSet() patternSet.include(pattern.transformPattern()) patternSet.exclude(exclusions.map { it.transformPattern() }) val spec = patternSet.asSpec val archiveOperations = project.serviceOf<ArchiveOperations>() val deprecationList = project.provider { val outputFile = archiveFile.get().asFile outputFile.parentFile.resolve("${outputFile.name}$PATH_SUFFIX") } inputs.property("pattern", pattern) inputs.property("deprecationMessage", deprecationMessage) for ((index, exclusion) in exclusions.withIndex()) { inputs.property("exclusion$index", exclusion) } outputs.file(deprecationList) doLast { val intermediateZipFilePath = temporaryDir.resolve("${UUID.randomUUID()}.${archiveExtension.get()}") ZipOutputStream(intermediateZipFilePath.outputStream()).use { intermediateZipFile -> val deprecatedPackages = sortedSetOf<String>() archiveOperations.zipTree(archiveFile.get().asFile).visit { if (name.endsWith(".class") && spec.isSatisfiedBy(this)) { val classReader = ClassReader(file.inputStream()) val classWriter = ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES) val classVisitor = DeprecatingClassTransformer(classWriter, deprecationMessage) { className -> require(className.contains('.')) { "Deprecating classes in the default (unnamed) package is not supported. Tried to deprecate $className" } logger.info("Deprecating class $className") deprecatedPackages.add(className.substringBeforeLast(".")) } classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES) val newBytes = classWriter.toByteArray() val newEntry = ZipEntry(path) intermediateZipFile.putNextEntry(newEntry) intermediateZipFile.write(newBytes) intermediateZipFile.closeEntry() } else { val newEntry = ZipEntry(if (isDirectory) "$path/" else path) intermediateZipFile.putNextEntry(newEntry) if (!isDirectory) { file.inputStream().use { it.copyTo(intermediateZipFile) } } intermediateZipFile.closeEntry() } } deprecationList.get().outputStream().bufferedWriter().use { deprecationListWriter -> deprecationListWriter.appendLine("The following packages are (non-transitively) deprecated by the `asm-deprecating-transformer` plugin:") deprecatedPackages.forEach { packageName -> deprecationListWriter.appendLine("package $packageName") } } } intermediateZipFilePath.renameTo(archiveFile.get().asFile) } } fun TaskContainer.registerDumpDeprecationsTask(shadowJarTaskName: String, suffix: String) = register<Copy>("dumpDeprecationsFor${suffix}") { val shadowJarTask = named<ShadowJar>(shadowJarTaskName) val actualDeprecations = shadowJarTask.map { it.archiveFile.get().asFile.parentFile.resolve("${it.archiveFile.get().asFile.name}$PATH_SUFFIX") } from(actualDeprecations) into(project.layout.projectDirectory.dir(BUILD_DIRECTORY)) rename { "$suffix$PATH_SUFFIX" } } fun TaskContainer.registerCheckDeprecationsTask( shadowJarTaskName: String, suffix: String, expectedFileDoesNotExistMessage: String, checkFailureMessage: String, ) = register<DefaultTask>("checkDeprecationsFor${suffix}") { val shadowJarTask = named<ShadowJar>(shadowJarTaskName) val actualDeprecations = shadowJarTask.map { it.archiveFile.get().asFile.parentFile.resolve("${it.archiveFile.get().asFile.name}$PATH_SUFFIX") } val expectedDeprecations = project.layout.projectDirectory.file("$BUILD_DIRECTORY/$suffix$PATH_SUFFIX") inputs.file(actualDeprecations) // `files` to check it manually and give an actionable failure message. // otherwise Gradle will complain that the input file does not exist inputs.files(expectedDeprecations) doFirst { val expectedFile = expectedDeprecations.asFile if (!expectedFile.exists()) { throw GradleException(expectedFileDoesNotExistMessage) } val actualFile = actualDeprecations.get() val diff = getDiff(expectedFile, actualFile) if (diff != null) { throw GradleException("$checkFailureMessage\nDifference:\n$diff") } } } companion object { private const val PATH_SUFFIX = ".deprecations" private const val BUILD_DIRECTORY = "asm-deprecation" private fun getDiff(expectedFile: File, actualFile: File): String? { val expectedLines = expectedFile.readText().lines() val actualLines = actualFile.readText().lines() if (expectedLines == actualLines) return null val patch = DiffUtils.diff(expectedLines, actualLines) val diff = UnifiedDiffUtils.generateUnifiedDiff(expectedFile.absolutePath, actualFile.absolutePath, expectedLines, patch, 3) return diff.joinToString("\n") } } }
184
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
7,593
kotlin
Apache License 2.0
app/src/main/java/com/utsman/osmapp/MainActivity.kt
utsmannn
631,322,826
false
null
package com.utsman.osmapp import android.graphics.drawable.Drawable import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement 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.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.utsman.osmandcompose.MapProperties import com.utsman.osmandcompose.Marker import com.utsman.osmandcompose.OpenStreetMap import com.utsman.osmandcompose.Polygon import com.utsman.osmandcompose.Polyline import com.utsman.osmandcompose.PolylineCap import com.utsman.osmandcompose.ZoomButtonVisibility import com.utsman.osmandcompose.rememberCameraState import com.utsman.osmandcompose.rememberMarkerState import com.utsman.osmandcompose.rememberOverlayManagerState import com.utsman.osmapp.navigation.LocalNavigation import com.utsman.osmapp.navigation.Navigation import com.utsman.osmapp.navigation.Route import com.utsman.osmapp.ui.theme.OsmAndroidComposeTheme import org.osmdroid.tileprovider.MapTileProviderBasic import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.util.MapTileIndex import org.osmdroid.views.overlay.CopyrightOverlay import org.osmdroid.views.overlay.TilesOverlay class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { OsmAndroidComposeTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { val navHostController = rememberNavController() val navigation = remember { Navigation(navHostController) } CompositionLocalProvider(LocalNavigation provides navigation) { MainGraph(navHostController = navHostController) } } } } } } @Composable fun MainGraph( navHostController: NavHostController ) { NavHost(navController = navHostController, startDestination = Route.Main.routeArg) { composable(route = Route.Main.routeArg) { Main() } composable(route = Route.Simple.routeArg) { SimplePage() } composable(route = Route.Marker.routeArg) { MarkerPage() } composable(route = Route.Polyline.routeArg) { PolylinePage() } composable(route = Route.Polygon.routeArg) { PolygonPage() } } } @Composable fun Main() { val navigation = LocalNavigation.current Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Button(onClick = { navigation.goToSimpleNode() }) { Text(text = "Simple maps") } Button(onClick = { navigation.goToMarker() }) { Text(text = "Marker") } Button(onClick = { navigation.goToPolyline() }) { Text(text = "Polyline") } Button(onClick = { navigation.goToPolygon() }) { Text(text = "Polygon") } } } /** * Playground * */ @Composable fun MarkerPage1() { val depokState = rememberMarkerState(geoPoint = GeoPoint(-6.3970066, 106.8224316)) val jakartaState = rememberMarkerState(geoPoint = GeoPoint(-6.1907982, 106.8315909)) val depokState2 = rememberMarkerState(geoPoint = GeoPoint(-6.3729963,106.75806)) val cameraState = rememberCameraState { geoPoint = depokState.geoPoint zoom = 12.0 } val overlayManagerState = rememberOverlayManagerState() val context = LocalContext.current var depokIcon: Drawable? by remember { mutableStateOf(context.getDrawable(R.drawable.round_eject_24)) } var depokVisible by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() var mapProperties by remember { mutableStateOf(MapProperties()) } val tileOverlay = remember { val tileUrl = "https://osm.rrze.fau.de/osmhd/" val rrzeSource = object : OnlineTileSourceBase( "RRZE", 0, 20, 256, "", arrayOf(tileUrl) ) { override fun getTileURLString(pMapTileIndex: Long): String { val url = baseUrl + MapTileIndex.getZoom(pMapTileIndex) + "/" + MapTileIndex.getX(pMapTileIndex) + "/" + MapTileIndex.getY(pMapTileIndex) + ".png" return url } } val tileProvider = MapTileProviderBasic( context, rrzeSource ) TilesOverlay(tileProvider, context) } val polygonHoles = remember { val hole1 = listOf( GeoPoint(-6.3690298,106.7791744), GeoPoint(-6.3393337,106.8030781), GeoPoint(-6.3537767,106.7629521) ) val hole2 = listOf( GeoPoint(-6.3083577,106.7829421), GeoPoint(-6.3105647,106.7866221) ) listOf(hole1, hole2) } SideEffect { mapProperties = mapProperties .copy(isTilesScaledToDpi = true) .copy(tileSources = TileSourceFactory.MAPNIK) .copy(isEnableRotationGesture = true) .copy(zoomButtonVisibility = ZoomButtonVisibility.NEVER) } Box { OpenStreetMap( modifier = Modifier.fillMaxSize(), cameraState = cameraState, overlayManagerState = overlayManagerState, properties = mapProperties, onMapClick = { println("on click -> $it") }, onMapLongClick = { depokState.geoPoint = it println("on long click -> ${it.latitude}, ${it.longitude}") }, onFirstLoadListener = { println("on loaded ... ") overlayManagerState.overlayManager.add(CopyrightOverlay(context)) } ) { Marker( state = depokState, icon = depokIcon, title = "anuan", snippet = "haah" ) { Column( modifier = Modifier .size(100.dp) .background(color = Color.Gray, shape = RoundedCornerShape(12.dp)) ) { Text(text = it.title) Text(text = it.snippet) } } Polyline( geoPoints = listOf(depokState.geoPoint, jakartaState.geoPoint), color = Color.Cyan, cap = PolylineCap.ROUND ) { Column( modifier = Modifier .size(100.dp) .background(color = Color.Red, shape = RoundedCornerShape(6.dp)) ) { Text(text = it.title) Text(text = it.snippet) } } Polygon( geoPoints = listOf(depokState.geoPoint, GeoPoint(-6.2076517,106.7439701), depokState2.geoPoint), geoPointHoles = polygonHoles, color = Color.Blue, outlineColor = Color.Green ) } Column( modifier = Modifier .align(Alignment.BottomCenter) .fillMaxWidth() .padding(horizontal = 100.dp) ) { Button( onClick = { cameraState.geoPoint = depokState.geoPoint cameraState.speed = 1000 cameraState.zoom = 16.0 }) { Text(text = "marker visible") } Button( onClick = { depokState.rotation = depokState.rotation + 90f }) { Text(text = "rotasi") } Button( onClick = { cameraState.normalizeRotation() }) { Text(text = "rotasi normal") } } } } @Preview(showBackground = true) @Composable fun DefaultPreview() { OsmAndroidComposeTheme { MarkerPage() } }
1
Kotlin
2
6
8513df0e09c2e5f13e17e15ce9581446ff3025de
10,105
osm-android-compose
Apache License 2.0
app/src/main/java/com/example/mytunes/model/MusicData.kt
MinusMallard
780,522,151
false
{"Kotlin": 176701}
package com.example.mytunes.model import com.google.gson.annotations.SerializedName data class MusicData( @SerializedName("success") val success: Boolean, @SerializedName("data") val data: MusicDataDetails ) data class MusicDataDetails( @SerializedName("id") val id: String?, @SerializedName("name") val name: String?, @SerializedName("description") val description: String?, @SerializedName("year") val year: Int?, @SerializedName("type") val type: String?, @SerializedName("playCount") val playCount: Int?, @SerializedName("language") val language: String?, @SerializedName("explicitContent") val explicitContent: Boolean, @SerializedName("songCount") val songCount: Int?, @SerializedName("url") val url: String?, @SerializedName("image") val image: List<Image>, @SerializedName("songs") val songs: List<Song>, @SerializedName("artists") val artists: List<PlaylistArtist> ) data class PlaylistArtist( @SerializedName("id") val id: String?, @SerializedName("name") val name: String?, @SerializedName("role") val role: String?, @SerializedName("type") val type: String?, @SerializedName("image") val image: List<Image>, @SerializedName("url") val url: String? )
0
Kotlin
0
1
90cae21311d20c53de1fb80c6a5a7685bbedf9f6
1,248
My-Tunes
MIT License
rubik/rubik_plugins/src/main/java/com/rubik/plugins/RubikPlugin.kt
baidu
504,447,693
false
{"Kotlin": 607049, "Java": 37304}
/** * Copyright (C) Baidu Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rubik.plugins import com.ktnail.gradle.p import com.ktnail.x.Logger import com.rubik.plugins.basic.LogTags import com.rubik.context.exception.RubikPluginNotApplyException import com.rubik.plugins.basic.extra.* import org.gradle.api.Plugin import org.gradle.api.Project /** * The super class of all gradle plugin in rubik. * * @since 1.3 */ abstract class RubikPlugin : Plugin<Project> { private var _project: Project? = null val project: Project get() = _project ?: throw RubikPluginNotApplyException() override fun apply(project: Project) { _project = project Logger.p(LogTags.PLUGIN, project) { " APPLIED PLUGIN (${this::class.java})" } project.rubik project.addRubikRepository() } }
1
Kotlin
7
153
065ba8f4652b39ff558a5e3f18b9893e2cf9bd25
1,378
Rubik
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/assessrisksandneeds/services/AssessmentOffenceServiceTest.kt
ministryofjustice
373,137,019
false
{"Kotlin": 311917, "Dockerfile": 1027}
package uk.gov.justice.digital.hmpps.assessrisksandneeds.services import io.mockk.every import io.mockk.junit5.MockKExtension import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.verify import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.ExtendWith import org.slf4j.MDC import org.springframework.http.HttpMethod import uk.gov.justice.digital.hmpps.assessrisksandneeds.api.model.AssessmentDto import uk.gov.justice.digital.hmpps.assessrisksandneeds.api.model.AssessmentOffenceDto import uk.gov.justice.digital.hmpps.assessrisksandneeds.api.model.UserAccessResponse import uk.gov.justice.digital.hmpps.assessrisksandneeds.restclient.CommunityApiRestClient import uk.gov.justice.digital.hmpps.assessrisksandneeds.restclient.ExternalService import uk.gov.justice.digital.hmpps.assessrisksandneeds.restclient.OffenderAssessmentApiRestClient import uk.gov.justice.digital.hmpps.assessrisksandneeds.restclient.api.OasysAssessmentDto import uk.gov.justice.digital.hmpps.assessrisksandneeds.restclient.api.OasysAssessmentOffenceDto import uk.gov.justice.digital.hmpps.assessrisksandneeds.restclient.api.TimelineDto import uk.gov.justice.digital.hmpps.assessrisksandneeds.services.exceptions.EntityNotFoundException import uk.gov.justice.digital.hmpps.assessrisksandneeds.services.exceptions.ExternalApiEntityNotFoundException import java.time.LocalDateTime @ExtendWith(MockKExtension::class) class AssessmentOffenceServiceTest { private val assessmentClient: OffenderAssessmentApiRestClient = mockk() private val communityClient: CommunityApiRestClient = mockk() private val assessmentOffenceService = AssessmentOffenceService(assessmentClient, communityClient) @BeforeEach fun setup() { every { communityClient.verifyUserAccess(any(), any()) } returns UserAccessResponse(null, null, false, false) mockkStatic(MDC::class) every { MDC.get(any()) } returns "userName" } @Test fun `should call offender Api to retrieve offence data for a given CRN`() { // Given val crn = "X12345" val dateCompleted = LocalDateTime.of(2022, 1, 7, 12, 0) val initiationDate = LocalDateTime.of(2022, 1, 3, 12, 0) val assessmentOffenceDto = OasysAssessmentOffenceDto( crn = crn, limitedAccessOffender = false, assessments = listOf( OasysAssessmentDto( assessmentPk = 3, assessmentType = "LAYER1", dateCompleted = dateCompleted, initiationDate = initiationDate, assessmentStatus = "COMPLETE", patternOfOffending = "patternOfOffending", offenceInvolved = listOf("Carrying or using a weapon"), laterWIPAssessmentExists = true, ), ), timeline = listOf( TimelineDto( assessmentPk = 1, assessmentType = "LAYER1", initiationDate = LocalDateTime.of(2022, 1, 1, 12, 0), status = "LOCKED_INCOMPLETE", completedDate = LocalDateTime.of(2022, 1, 5, 12, 0), partcompStatus = "Signed", ), TimelineDto( assessmentPk = 2, assessmentType = "LAYER1", initiationDate = LocalDateTime.of(2022, 1, 2, 12, 0), status = "SIGNED", completedDate = null, ), TimelineDto( assessmentPk = 3, assessmentType = "LAYER1", initiationDate = initiationDate, status = "COMPLETE", completedDate = dateCompleted, ), ), ) every { assessmentClient.getAssessmentOffence(any(), any()) }.returns(assessmentOffenceDto) // When val result = assessmentOffenceService.getAssessmentOffence(crn) // Then verify(exactly = 1) { assessmentClient.getAssessmentOffence(crn, "ALLOW") } assertThat(result) .isEqualTo( AssessmentOffenceDto( crn = crn, limitedAccessOffender = false, assessments = listOf( AssessmentDto( assessmentId = 1, dateCompleted = LocalDateTime.of(2022, 1, 5, 12, 0), initiationDate = LocalDateTime.of(2022, 1, 1, 12, 0), assessmentStatus = "LOCKED_INCOMPLETE", assessmentType = "LAYER1", partcompStatus = "Signed", ), AssessmentDto( assessmentId = 2, dateCompleted = null, initiationDate = LocalDateTime.of(2022, 1, 2, 12, 0), assessmentStatus = "SIGNED", assessmentType = "LAYER1", ), AssessmentDto( assessmentId = 3, dateCompleted = dateCompleted, initiationDate = initiationDate, assessmentStatus = "COMPLETE", patternOfOffending = "patternOfOffending", offenceInvolved = listOf("Carrying or using a weapon"), assessmentType = "LAYER1", laterWIPAssessmentExists = true, ), ), ), ) } @Test fun `should successfully map a offender api response where not all complete assessments are present`() { // Given val crn = "X12345" val dateCompleted = LocalDateTime.of(2022, 1, 7, 12, 0) val initiationDate = LocalDateTime.of(2022, 1, 3, 12, 0) val assessmentOffenceDto = OasysAssessmentOffenceDto( crn = crn, limitedAccessOffender = false, assessments = listOf( OasysAssessmentDto( assessmentPk = 3, assessmentType = "LAYER1", dateCompleted = dateCompleted, initiationDate = initiationDate, assessmentStatus = "COMPLETE", patternOfOffending = "patternOfOffending", offenceInvolved = listOf("Carrying or using a weapon"), ), ), timeline = listOf( TimelineDto( assessmentPk = 1, assessmentType = "LAYER1", initiationDate = LocalDateTime.of(2022, 1, 1, 12, 0), status = "LOCKED_INCOMPLETE", completedDate = LocalDateTime.of(2022, 1, 5, 12, 0), ), TimelineDto( assessmentPk = 2, assessmentType = "LAYER1", initiationDate = LocalDateTime.of(2022, 1, 2, 12, 0), status = "SIGNED", completedDate = null, ), TimelineDto( assessmentPk = 3, assessmentType = "LAYER1", initiationDate = initiationDate, status = "COMPLETE", completedDate = dateCompleted, ), TimelineDto( assessmentPk = 4, assessmentType = "LAYER1", initiationDate = initiationDate.plusDays(1), status = "COMPLETE", completedDate = dateCompleted.plusDays(1), ), ), ) every { assessmentClient.getAssessmentOffence(any(), any()) }.returns(assessmentOffenceDto) // When val result = assessmentOffenceService.getAssessmentOffence(crn) // Then verify(exactly = 1) { assessmentClient.getAssessmentOffence(crn, "ALLOW") } assertThat(result) .isEqualTo( AssessmentOffenceDto( crn = crn, limitedAccessOffender = false, assessments = listOf( AssessmentDto( assessmentId = 1, dateCompleted = LocalDateTime.of(2022, 1, 5, 12, 0), initiationDate = LocalDateTime.of(2022, 1, 1, 12, 0), assessmentStatus = "LOCKED_INCOMPLETE", assessmentType = "LAYER1", ), AssessmentDto( assessmentId = 2, dateCompleted = null, initiationDate = LocalDateTime.of(2022, 1, 2, 12, 0), assessmentStatus = "SIGNED", assessmentType = "LAYER1", ), AssessmentDto( assessmentId = 3, dateCompleted = dateCompleted, initiationDate = initiationDate, assessmentStatus = "COMPLETE", patternOfOffending = "patternOfOffending", offenceInvolved = listOf("Carrying or using a weapon"), assessmentType = "LAYER1", ), AssessmentDto( assessmentId = 4, dateCompleted = dateCompleted.plusDays(1), initiationDate = initiationDate.plusDays(1), assessmentStatus = "COMPLETE", patternOfOffending = null, offenceInvolved = emptyList(), assessmentType = "LAYER1", ), ), ), ) } @Test fun `should successfully map a offender api response with no complete assessments`() { // Given val crn = "X12345" val dateCompleted = LocalDateTime.of(2022, 1, 7, 12, 0) val initiationDate = LocalDateTime.of(2022, 1, 3, 12, 0) val assessmentOffenceDto = OasysAssessmentOffenceDto( crn = crn, limitedAccessOffender = false, timeline = listOf( TimelineDto( assessmentPk = 1, assessmentType = "LAYER1", initiationDate = LocalDateTime.of(2022, 1, 1, 12, 0), status = "LOCKED_INCOMPLETE", completedDate = LocalDateTime.of(2022, 1, 5, 12, 0), ), TimelineDto( assessmentPk = 2, assessmentType = "LAYER1", initiationDate = LocalDateTime.of(2022, 1, 2, 12, 0), status = "SIGNED", completedDate = null, ), ), ) every { assessmentClient.getAssessmentOffence(any(), any()) }.returns(assessmentOffenceDto) // When val result = assessmentOffenceService.getAssessmentOffence(crn) // Then verify(exactly = 1) { assessmentClient.getAssessmentOffence(crn, "ALLOW") } assertThat(result) .isEqualTo( AssessmentOffenceDto( crn = crn, limitedAccessOffender = false, assessments = listOf( AssessmentDto( assessmentId = 1, dateCompleted = LocalDateTime.of(2022, 1, 5, 12, 0), initiationDate = LocalDateTime.of(2022, 1, 1, 12, 0), assessmentStatus = "LOCKED_INCOMPLETE", assessmentType = "LAYER1", ), AssessmentDto( assessmentId = 2, dateCompleted = null, initiationDate = LocalDateTime.of(2022, 1, 2, 12, 0), assessmentStatus = "SIGNED", assessmentType = "LAYER1", ), ), ), ) } @Test fun `should throw exception when offence is not found for given CRN`() { // Given val crn = "DOES_NOT_EXIST" every { assessmentClient.getAssessmentOffence( any(), any(), ) }.throws(EntityNotFoundException("Bad crn")) // When assertThrows<EntityNotFoundException>() { assessmentOffenceService.getAssessmentOffence(crn) } } @Test fun `should NOT call get assessment offence when user is forbidden to access CRN`() { // Given val crn = "X12345" every { communityClient.verifyUserAccess(crn, any()) }.throws(ExternalApiEntityNotFoundException(msg = "User cannot access $crn", HttpMethod.GET, "url", ExternalService.COMMUNITY_API)) // When assertThrows<ExternalApiEntityNotFoundException> { assessmentOffenceService.getAssessmentOffence(crn) } // Then verify(exactly = 0) { assessmentClient.getAssessmentOffence(crn, "ALLOW") } } }
5
Kotlin
0
0
f7ce36f529e0d66528f08b3d9bf2c036ca390104
11,509
hmpps-assess-risks-and-needs
MIT License
Application/src/os/default/kotlin/net/milosvasic/factory/mail/application/OSInit.kt
Server-Factory
325,304,402
true
{"Kotlin": 6435, "Shell": 198}
package net.milosvasic.factory.mail.application import net.milosvasic.factory.log import net.milosvasic.factory.web_service.application.BuildInfo object OSInit : Runnable { override fun run() = log.v("Starting: ${BuildInfo.versionName}, ${BuildInfo.version}") }
0
Kotlin
0
2
4b53b63247af11c96cabe4b8f169257855cfa832
268
Web-Service-Factory
Apache License 2.0
android/src/main/java/com/theoplayer/source/SourceAdapter.kt
THEOplayer
500,366,784
false
{"TypeScript": 287744, "Swift": 285892, "Kotlin": 210202, "CSS": 168106, "Objective-C": 14818, "JavaScript": 8487, "Ruby": 4706, "HTML": 851, "Shell": 613, "Starlark": 602, "C": 208}
package com.theoplayer.source import android.text.TextUtils import android.util.Log import com.facebook.react.bridge.Arguments import com.google.gson.Gson import com.theoplayer.android.api.error.THEOplayerException import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.WritableArray import com.facebook.react.bridge.WritableMap import com.theoplayer.android.api.source.SourceDescription import com.theoplayer.android.api.source.TypedSource import com.theoplayer.android.api.source.metadata.MetadataDescription import com.theoplayer.android.api.source.addescription.AdDescription import com.theoplayer.android.api.source.TextTrackDescription import com.theoplayer.android.api.source.SourceType import com.theoplayer.android.api.source.ssai.SsaiIntegration import com.theoplayer.android.api.source.GoogleDaiTypedSource import com.theoplayer.android.api.source.ssai.dai.GoogleDaiVodConfiguration import com.theoplayer.android.api.source.ssai.dai.GoogleDaiLiveConfiguration import com.theoplayer.android.api.source.hls.HlsPlaybackConfiguration import com.theoplayer.android.api.event.ads.AdIntegrationKind import com.theoplayer.android.api.source.addescription.GoogleImaAdDescription import com.theoplayer.android.api.player.track.texttrack.TextTrackKind import com.theoplayer.android.api.source.metadata.ChromecastMetadataImage import com.theoplayer.BuildConfig import com.theoplayer.android.api.error.ErrorCode import com.theoplayer.android.api.source.dash.DashPlaybackConfiguration import com.theoplayer.drm.ContentProtectionAdapter import com.theoplayer.util.BridgeUtils import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.ArrayList import java.util.HashMap private const val TAG = "SourceAdapter" private const val PROP_CONTENT_PROTECTION = "contentProtection" private const val PROP_LIVE_OFFSET = "liveOffset" private const val PROP_HLS_DATERANGE = "hlsDateRange" private const val PROP_HLS_PLAYBACK_CONFIG = "hls" private const val PROP_TIME_SERVER = "timeServer" private const val PROP_DATA = "data" private const val PROP_METADATA = "metadata" private const val PROP_SSAI = "ssai" private const val PROP_TYPE = "type" private const val PROP_SRC = "src" private const val PROP_SOURCES = "sources" private const val PROP_DEFAULT = "default" private const val PROP_LABEL = "label" private const val PROP_KIND = "kind" private const val PROP_TIME_OFFSET = "timeOffset" private const val PROP_INTEGRATION = "integration" private const val PROP_TEXT_TRACKS = "textTracks" private const val PROP_POSTER = "poster" private const val PROP_ADS = "ads" private const val PROP_AVAILABILITY_TYPE = "availabilityType" private const val PROP_DASH = "dash" private const val PROP_DASH_IGNORE_AVAILABILITYWINDOW = "ignoreAvailabilityWindow" private const val ERROR_DAI_NOT_ENABLED = "Google DAI support not enabled." private const val ERROR_UNSUPPORTED_SSAI_INTEGRATION = "Unsupported SSAI integration" private const val ERROR_MISSING_SSAI_INTEGRATION = "Missing SSAI integration" private const val ERROR_IMA_NOT_ENABLED = "Google IMA support not enabled." private const val ERROR_UNSUPPORTED_CSAI_INTEGRATION = "Unsupported CSAI integration" private const val ERROR_MISSING_CSAI_INTEGRATION = "Missing CSAI integration" class SourceAdapter { private val gson = Gson() @Throws(THEOplayerException::class) fun parseSourceFromJS(source: ReadableMap?): SourceDescription? { if (source == null) { return null } try { val jsonSourceObject = JSONObject(gson.toJson(source.toHashMap())) // typed sources val typedSources = ArrayList<TypedSource>() // sources can be an array or single object val jsonSources = jsonSourceObject.optJSONArray(PROP_SOURCES) if (jsonSources != null) { for (i in 0 until jsonSources.length()) { val typedSource = parseTypedSource(jsonSources[i] as JSONObject) if (typedSource != null) { typedSources.add(typedSource) } } } else { val jsonSource = jsonSourceObject.optJSONObject(PROP_SOURCES) ?: return null val typedSource = parseTypedSource(jsonSource) if (typedSource != null) { typedSources.add(typedSource) } } // poster val poster = jsonSourceObject.optString(PROP_POSTER) // metadata var metadataDescription: MetadataDescription? = null val jsonMetadata = jsonSourceObject.optJSONObject(PROP_METADATA) if (jsonMetadata != null) { metadataDescription = parseMetadataDescription(jsonMetadata) } // ads val jsonAds = jsonSourceObject.optJSONArray(PROP_ADS) val ads = ArrayList<AdDescription>() if (jsonAds != null) { for (i in 0 until jsonAds.length()) { val jsonAdDescription = jsonAds[i] as JSONObject // Currently only ima-ads are supported. ads.add(parseAdFromJS(jsonAdDescription)) } } // Side-loaded text tracks val textTracks = jsonSourceObject.optJSONArray(PROP_TEXT_TRACKS) val sideLoadedTextTracks = ArrayList<TextTrackDescription>() if (textTracks != null) { for (i in 0 until textTracks.length()) { val jsonTextTrack = textTracks[i] as JSONObject sideLoadedTextTracks.add(parseTextTrackFromJS(jsonTextTrack)) } } val builder = SourceDescription.Builder(*typedSources.toTypedArray()) .poster(poster) .ads(*ads.toTypedArray()) .textTracks(*sideLoadedTextTracks.toTypedArray()) if (metadataDescription != null) { builder.metadata(metadataDescription) } return builder.build() } catch (e: JSONException) { e.printStackTrace() } return null } @Throws(THEOplayerException::class) private fun parseTypedSource(jsonTypedSource: JSONObject): TypedSource? { try { var tsBuilder = TypedSource.Builder(jsonTypedSource.optString(PROP_SRC)) val sourceType = parseSourceType(jsonTypedSource) if (jsonTypedSource.has(PROP_SSAI)) { val ssaiJson = jsonTypedSource.getJSONObject(PROP_SSAI) // Check for valid SsaiIntegration val ssaiIntegrationStr = ssaiJson.optString(PROP_INTEGRATION) if (!TextUtils.isEmpty(ssaiIntegrationStr)) { val ssaiIntegration = SsaiIntegration.from(ssaiIntegrationStr) ?: throw THEOplayerException( ErrorCode.AD_ERROR, "$ERROR_UNSUPPORTED_SSAI_INTEGRATION: $ssaiIntegrationStr" ) when (ssaiIntegration) { SsaiIntegration.GOOGLE_DAI -> { if (!BuildConfig.EXTENSION_GOOGLE_DAI) { throw THEOplayerException(ErrorCode.AD_ERROR, ERROR_DAI_NOT_ENABLED) } tsBuilder = if (ssaiJson.optString(PROP_AVAILABILITY_TYPE) == "vod") { GoogleDaiTypedSource.Builder( gson.fromJson(ssaiJson.toString(), GoogleDaiVodConfiguration::class.java) ) } else { GoogleDaiTypedSource.Builder( gson.fromJson(ssaiJson.toString(), GoogleDaiLiveConfiguration::class.java) ) } // Prefer DASH if not SSAI type specified if (sourceType == null) { tsBuilder.type(SourceType.DASH) } } else -> throw THEOplayerException( ErrorCode.AD_ERROR, "$ERROR_UNSUPPORTED_SSAI_INTEGRATION: $ssaiIntegrationStr" ) } } else { throw THEOplayerException(ErrorCode.AD_ERROR, ERROR_MISSING_SSAI_INTEGRATION) } } if (sourceType != null) { tsBuilder.type(sourceType) } if (jsonTypedSource.has(PROP_DASH)) { tsBuilder.dash(parseDashConfig(jsonTypedSource.getJSONObject(PROP_DASH))) } if (jsonTypedSource.has(PROP_LIVE_OFFSET)) { tsBuilder.liveOffset(jsonTypedSource.getDouble(PROP_LIVE_OFFSET)) } if (jsonTypedSource.has(PROP_HLS_DATERANGE)) { tsBuilder.hlsDateRange(jsonTypedSource.getBoolean(PROP_HLS_DATERANGE)) } if (jsonTypedSource.has(PROP_HLS_PLAYBACK_CONFIG)) { val hlsConfig = gson.fromJson( jsonTypedSource[PROP_HLS_PLAYBACK_CONFIG].toString(), HlsPlaybackConfiguration::class.java ) tsBuilder.hls(hlsConfig) } if (jsonTypedSource.has(PROP_TIME_SERVER)) { tsBuilder.timeServer(jsonTypedSource.getString(PROP_TIME_SERVER)) } if (jsonTypedSource.has(PROP_CONTENT_PROTECTION)) { val drmConfig = ContentProtectionAdapter.drmConfigurationFromJson( jsonTypedSource.getJSONObject(PROP_CONTENT_PROTECTION) ) if (drmConfig != null) { tsBuilder.drm(drmConfig) } } return tsBuilder.build() } catch (e: JSONException) { e.printStackTrace() } return null } @Throws(THEOplayerException::class) fun parseAdFromJS(map: ReadableMap): AdDescription? { return try { val jsonAdDescription = JSONObject(gson.toJson(map.toHashMap())) parseAdFromJS(jsonAdDescription) } catch (e: JSONException) { e.printStackTrace() null } } private fun parseSourceType(jsonTypedSource: JSONObject): SourceType? { val type = jsonTypedSource.optString(PROP_TYPE) if (type.isNotEmpty()) { if ("application/dash+xml" == type) { return SourceType.DASH } if ("application/x-mpegurl" == type) { return SourceType.HLSX } if ("application/vnd.theo.hesp+json" == type) { return SourceType.HESP } if ("application/vnd.apple.mpegurl" == type) { return SourceType.HLS } if ("video/mp4" == type) { return SourceType.MP4 } if ("audio/mpeg" == type) { return SourceType.MP3 } } else { // No type given, check for known extension. val src = jsonTypedSource.optString(PROP_SRC) if (src.endsWith(".mpd")) { return SourceType.DASH } if (src.endsWith(".m3u8")) { return SourceType.HLSX } if (src.endsWith(".mp4")) { return SourceType.MP4 } if (src.endsWith(".mp3")) { return SourceType.MP3 } } return null } @Throws(JSONException::class, THEOplayerException::class) fun parseAdFromJS(jsonAdDescription: JSONObject): AdDescription { val integrationKindStr = jsonAdDescription.optString(PROP_INTEGRATION) return if (!TextUtils.isEmpty(integrationKindStr)) { when (AdIntegrationKind.from(integrationKindStr)) { AdIntegrationKind.GOOGLE_IMA -> parseImaAdFromJS( jsonAdDescription ) AdIntegrationKind.DEFAULT -> { throw THEOplayerException( ErrorCode.AD_ERROR, "$ERROR_UNSUPPORTED_CSAI_INTEGRATION: $integrationKindStr" ) } else -> { throw THEOplayerException( ErrorCode.AD_ERROR, "$ERROR_UNSUPPORTED_CSAI_INTEGRATION: $integrationKindStr" ) } } } else { throw THEOplayerException( ErrorCode.AD_ERROR, "$ERROR_MISSING_CSAI_INTEGRATION: $integrationKindStr" ) } } @Throws(THEOplayerException::class) private fun parseImaAdFromJS(jsonAdDescription: JSONObject): GoogleImaAdDescription { if (!BuildConfig.EXTENSION_GOOGLE_IMA) { throw THEOplayerException(ErrorCode.AD_ERROR, ERROR_IMA_NOT_ENABLED) } val source: String // Property `sources` is of type string | AdSource. val sourceObj = jsonAdDescription.optJSONObject(PROP_SOURCES) source = if (sourceObj != null) { sourceObj.optString(PROP_SRC) } else { jsonAdDescription.optString(PROP_SOURCES) } return GoogleImaAdDescription.Builder(source) .timeOffset(jsonAdDescription.optString(PROP_TIME_OFFSET)) .build() } @Throws(JSONException::class) private fun parseTextTrackFromJS(jsonTextTrack: JSONObject): TextTrackDescription { val builder = TextTrackDescription.Builder(jsonTextTrack.optString(PROP_SRC)) .isDefault(jsonTextTrack.optBoolean(PROP_DEFAULT)) .label(jsonTextTrack.optString(PROP_LABEL)) .kind(parseTextTrackKind(jsonTextTrack.optString(PROP_KIND))!!) return builder.build() } private fun parseTextTrackKind(kind: String?): TextTrackKind? { if (kind == null) { return null } when (kind) { "subtitles" -> return TextTrackKind.SUBTITLES "metadata" -> return TextTrackKind.METADATA "captions" -> return TextTrackKind.CAPTIONS "chapters" -> return TextTrackKind.CHAPTERS "descriptions" -> return TextTrackKind.DESCRIPTIONS } return null } private fun parseMetadataDescription(metadataDescription: JSONObject): MetadataDescription { val metadata = HashMap<String, Any>() val keys = metadataDescription.keys() while (keys.hasNext()) { val key = keys.next() try { if (key == "images") { metadata[key] = parseMetadataImages(metadataDescription.getJSONArray(key)) } else { metadata[key] = metadataDescription[key] } } catch (e: JSONException) { Log.w(TAG, "Failed to parse metadata key $key") } } return MetadataDescription(metadata) } private fun parseDashConfig(dashConfig: JSONObject): DashPlaybackConfiguration { return DashPlaybackConfiguration.Builder() .ignoreAvailabilityWindow(dashConfig.optBoolean(PROP_DASH_IGNORE_AVAILABILITYWINDOW)) .build() } @Throws(JSONException::class) private fun parseMetadataImages(metadataImages: JSONArray): List<ChromecastMetadataImage> { val imageList: MutableList<ChromecastMetadataImage> = ArrayList() for (i in 0 until metadataImages.length()) { imageList.add(parseMetadataImage(metadataImages.getJSONObject(i))) } return imageList } @Throws(JSONException::class) private fun parseMetadataImage(metadataImage: JSONObject): ChromecastMetadataImage { val width = if (metadataImage.has("width")) metadataImage.getInt("width") else null val height = if (metadataImage.has("height")) metadataImage.getInt("height") else null return ChromecastMetadataImage(metadataImage.optString("src"), width, height) } fun fromSourceDescription(source: SourceDescription): WritableMap { val json = JSONObject(gson.toJson(source)) // Normalize metadata // The player SDK adds an extra 'data' level within metadata: flatten. json.optJSONObject(PROP_METADATA)?.optJSONObject(PROP_DATA)?.let { newMetadata -> json.put(PROP_METADATA, newMetadata) } return BridgeUtils.fromJSONObjectToBridge(json) } }
9
TypeScript
20
55
f29a525a0c2ebb6f33ed8540f80024999e7672dc
14,821
react-native-theoplayer
MIT License
idea/tests/testData/inspectionsLocal/complexRedundantLet/letNoSafeCall.kt
JetBrains
278,369,660
false
null
// PROBLEM: none // WITH_RUNTIME fun foo() { val foo: String = "" foo.let<caret> { it.length } }
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
118
intellij-kotlin
Apache License 2.0
app/src/main/java/com/app/moodtrack_android/di/DatabaseModule.kt
martinheitmann
431,879,047
false
{"Kotlin": 272822}
package com.app.moodtrack_android.di import android.content.Context import androidx.room.Room import com.app.moodtrack_android.database.AppDatabase import com.app.moodtrack_android.database.dao.FileDao 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 @InstallIn(SingletonComponent::class) @Module object DatabaseModule { @Singleton @Provides fun provideFileDao(appDatabase: AppDatabase) : FileDao { return appDatabase.fileDao() } @Singleton @Provides fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase { return Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "app_database" ).build() } }
0
Kotlin
1
0
9b774c65c5e99e646c50370f17d97575b07ac46b
893
moodtrack-android
MIT License
turtle/src/test/kotlin/com/lordcodes/turtle/ShellRunExceptionTest.kt
lordcodes
202,986,234
false
null
package com.lordcodes.turtle import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.Test internal class ShellRunExceptionTest { @Test fun message() { val message = ShellRunException(1, "unexpected input").message assertThat(message).isEqualTo("Running shell command failed with code 1 and message: unexpected input") } }
4
Kotlin
3
94
39e1bd599be780f30b39cea15657756881e077b2
374
turtle
Apache License 2.0
app/src/main/java/com/justwayward/reader/manager/SettingManager.kt
petma
198,171,907
true
{"Kotlin": 1560776, "Java": 34640, "JavaScript": 31488, "HTML": 5286, "CSS": 4040}
/** * Copyright 2016 JustWayward Team * * * 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.justwayward.reader.manager import com.justwayward.reader.R import com.justwayward.reader.base.Constant import com.justwayward.reader.bean.support.BookMark import com.justwayward.reader.utils.AppUtils import com.justwayward.reader.utils.ScreenUtils import com.justwayward.reader.utils.SharedPreferencesUtil import com.justwayward.reader.utils.ToastUtils import java.util.ArrayList /** * @author yuyh. * @date 2016/9/23. */ class SettingManager { val readFontSize: Int get() = getReadFontSize("") val readBrightness: Int get() = ScreenUtils.screenBrightness private val lightnessKey: String get() = "readLightness" val readTheme: Int get() = if (SharedPreferencesUtil.instance!!.getBoolean(Constant.ISNIGHT, false)) { ThemeManager.NIGHT } else SharedPreferencesUtil.instance!!.getInt("readTheme", 3) val isVolumeFlipEnable: Boolean get() = SharedPreferencesUtil.instance!!.getBoolean("volumeFlip", true) val isAutoBrightness: Boolean get() = SharedPreferencesUtil.instance!!.getBoolean("autoBrightness", false) /** * 获取用户选择性别 * * @return */ val userChooseSex: String? get() = SharedPreferencesUtil.instance!!.getString("userChooseSex", Constant.Gender.MALE) val isUserChooseSex: Boolean get() = SharedPreferencesUtil.instance!!.exists("userChooseSex") val isNoneCover: Boolean get() = SharedPreferencesUtil.instance!!.getBoolean("isNoneCover", false) /** * 保存书籍阅读字体大小 * * @param bookId 需根据bookId对应,避免由于字体大小引起的分页不准确 * @param fontSizePx * @return */ fun saveFontSize(bookId: String, fontSizePx: Int) { // 书籍对应 SharedPreferencesUtil.instance!!.putInt(getFontSizeKey(bookId), fontSizePx) } /** * 保存全局生效的阅读字体大小 * * @param fontSizePx */ fun saveFontSize(fontSizePx: Int) { saveFontSize("", fontSizePx) } fun getReadFontSize(bookId: String): Int { return SharedPreferencesUtil.instance!!.getInt(getFontSizeKey(bookId), ScreenUtils.dpToPxInt(16f)) } private fun getFontSizeKey(bookId: String): String { return "$bookId-readFontSize" } /** * 保存阅读界面屏幕亮度 * * @param percent 亮度比例 0~100 */ fun saveReadBrightness(percent: Int) { var percent = percent if (percent > 100) { ToastUtils.showToast("saveReadBrightnessErr CheckRefs") percent = 100 } SharedPreferencesUtil.instance!!.putInt(lightnessKey, percent) } @Synchronized fun saveReadProgress(bookId: String, currentChapter: Int, m_mbBufBeginPos: Int, m_mbBufEndPos: Int) { SharedPreferencesUtil.instance!! .putInt(getChapterKey(bookId), currentChapter) .putInt(getStartPosKey(bookId), m_mbBufBeginPos) .putInt(getEndPosKey(bookId), m_mbBufEndPos) } /** * 获取上次阅读章节及位置 * * @param bookId * @return */ fun getReadProgress(bookId: String): IntArray { val lastChapter = SharedPreferencesUtil.instance!!.getInt(getChapterKey(bookId), 1) val startPos = SharedPreferencesUtil.instance!!.getInt(getStartPosKey(bookId), 0) val endPos = SharedPreferencesUtil.instance!!.getInt(getEndPosKey(bookId), 0) return intArrayOf(lastChapter, startPos, endPos) } fun removeReadProgress(bookId: String) { SharedPreferencesUtil.instance!! .remove(getChapterKey(bookId)) .remove(getStartPosKey(bookId)) .remove(getEndPosKey(bookId)) } private fun getChapterKey(bookId: String): String { return "$bookId-chapter" } private fun getStartPosKey(bookId: String): String { return "$bookId-startPos" } private fun getEndPosKey(bookId: String): String { return "$bookId-endPos" } fun addBookMark(bookId: String, mark: BookMark): Boolean { var marks: MutableList<BookMark>? = SharedPreferencesUtil.instance!!.getObject(getBookMarksKey(bookId), ArrayList<*>::class.java) if (marks != null && marks.size > 0) { for (item in marks) { if (item.chapter == mark.chapter && item.startPos == mark.startPos) { return false } } } else { marks = ArrayList() } marks.add(mark) SharedPreferencesUtil.instance!!.putObject(getBookMarksKey(bookId), marks) return true } fun getBookMarks(bookId: String): List<BookMark>? { return SharedPreferencesUtil.instance!!.getObject(getBookMarksKey(bookId), ArrayList<*>::class.java) } fun clearBookMarks(bookId: String) { SharedPreferencesUtil.instance!!.remove(getBookMarksKey(bookId)) } private fun getBookMarksKey(bookId: String): String { return "$bookId-marks" } fun saveReadTheme(theme: Int) { SharedPreferencesUtil.instance!!.putInt("readTheme", theme) } /** * 是否可以使用音量键翻页 * * @param enable */ fun saveVolumeFlipEnable(enable: Boolean) { SharedPreferencesUtil.instance!!.putBoolean("volumeFlip", enable) } fun saveAutoBrightness(enable: Boolean) { SharedPreferencesUtil.instance!!.putBoolean("autoBrightness", enable) } /** * 保存用户选择的性别 * * @param sex male female */ fun saveUserChooseSex(sex: String) { SharedPreferencesUtil.instance!!.putString("userChooseSex", sex) } fun saveNoneCover(isNoneCover: Boolean) { SharedPreferencesUtil.instance!!.putBoolean("isNoneCover", isNoneCover) } companion object { @Volatile private var manager: SettingManager? = null val instance: SettingManager? get() = if (manager != null) manager else manager = SettingManager() } }
0
Kotlin
0
0
d011466692aae7c583ab8a264f760f7ff7d17458
6,550
BookReader-1
Apache License 2.0
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/presentation/uicomponents/channels/viewmodels/ChannelsViewModel.kt
sceyt
549,073,085
false
{"Kotlin": 2675924, "Java": 107920}
package com.sceyt.chatuikit.presentation.uicomponents.channels.viewmodels import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.sceyt.chat.models.user.User import com.sceyt.chatuikit.data.models.LoadKeyData import com.sceyt.chatuikit.data.models.PaginationResponse import com.sceyt.chatuikit.data.models.SceytResponse import com.sceyt.chatuikit.data.models.channels.SceytChannel import com.sceyt.chatuikit.koin.SceytKoinComponent import com.sceyt.chatuikit.persistence.interactor.ChannelInteractor import com.sceyt.chatuikit.persistence.interactor.ChannelMemberInteractor import com.sceyt.chatuikit.persistence.extensions.asLiveData import com.sceyt.chatuikit.persistence.extensions.getPeer import com.sceyt.chatuikit.persistence.extensions.isDirect import com.sceyt.chatuikit.persistence.extensions.isPeerDeleted import com.sceyt.chatuikit.persistence.extensions.isPublic import com.sceyt.chatuikit.presentation.root.BaseViewModel import com.sceyt.chatuikit.presentation.uicomponents.channels.adapter.ChannelListItem import com.sceyt.chatuikit.presentation.uicomponents.channels.events.ChannelEvent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import org.koin.core.component.inject class ChannelsViewModel : BaseViewModel(), SceytKoinComponent { private val channelInteractor: ChannelInteractor by inject() private val channelMemberInteractor: ChannelMemberInteractor by inject() private var getChannelsJog: Job? = null val selectedChannels = mutableSetOf<Long>() var searchQuery = "" private set private val _loadChannelsFlow = MutableStateFlow<PaginationResponse<SceytChannel>>(PaginationResponse.Nothing()) val loadChannelsFlow: StateFlow<PaginationResponse<SceytChannel>> = _loadChannelsFlow private val _blockUserLiveData = MutableLiveData<SceytResponse<List<User>>>() val blockUserLiveData = _blockUserLiveData.asLiveData() fun getChannels(offset: Int, query: String = searchQuery, loadKey: LoadKeyData? = null, ignoreDb: Boolean = false) { searchQuery = query setPagingLoadingStarted(PaginationResponse.LoadType.LoadNext, ignoreDb = ignoreDb) notifyPageLoadingState(false) getChannelsJog?.cancel() getChannelsJog = viewModelScope.launch(Dispatchers.IO) { channelInteractor.loadChannels(offset, query, loadKey, ignoreDb).collect { initPaginationResponse(it) } } } private fun initPaginationResponse(response: PaginationResponse<SceytChannel>) { when (response) { is PaginationResponse.DBResponse -> { if (!checkIgnoreDatabasePagingResponse(response)) { _loadChannelsFlow.value = response notifyPageStateWithResponse(SceytResponse.Success(null), wasLoadingMore = response.offset > 0, isEmpty = response.data.isEmpty(), searchQuery = response.query) } } is PaginationResponse.ServerResponse -> { _loadChannelsFlow.value = response notifyPageStateWithResponse(response.data, wasLoadingMore = response.offset > 0, isEmpty = response.cacheData.isEmpty(), searchQuery = response.query) } else -> return } pagingResponseReceived(response) } internal fun mapToChannelItem(data: List<SceytChannel>?, hasNext: Boolean, includeDirectChannelsWithDeletedPeers: Boolean = true): List<ChannelListItem> { val filteredChannels = if (includeDirectChannelsWithDeletedPeers) data ?: emptyList() else data?.filter { channel -> !channel.isPeerDeleted() } ?: emptyList() if (filteredChannels.isEmpty()) return emptyList() val channelItems: List<ChannelListItem> channelItems = filteredChannels.map { item -> ChannelListItem.ChannelItem(item) } if (hasNext) (channelItems as ArrayList).add(ChannelListItem.LoadingMoreItem) return channelItems } fun markChannelAsRead(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.markChannelAsRead(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun markChannelAsUnRead(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.markChannelAsUnRead(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun blockAndLeaveChannel(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.blockAndLeaveChannel(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun blockUser(userId: String) { viewModelScope.launch(Dispatchers.IO) { val response = channelMemberInteractor.blockUnBlockUser(userId, true) _blockUserLiveData.postValue(response) } } fun unBlockUser(userId: String) { viewModelScope.launch(Dispatchers.IO) { val response = channelMemberInteractor.blockUnBlockUser(userId, false) _blockUserLiveData.postValue(response) } } fun clearHistory(channelId: Long, forEveryone: Boolean) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.clearHistory(channelId, forEveryone) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun deleteChannel(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.deleteChannel(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun leaveChannel(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.leaveChannel(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun muteChannel(channelId: Long, muteUntil: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.muteChannel(channelId, muteUntil) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun unMuteChannel(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.unMuteChannel(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun pinChannel(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.pinChannel(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun unpinChannel(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.unpinChannel(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } fun hideChannel(channelId: Long) { viewModelScope.launch(Dispatchers.IO) { val response = channelInteractor.hideChannel(channelId) if (response is SceytResponse.Error) notifyPageStateWithResponse(response) } } internal fun onChannelCommandEvent(event: ChannelEvent) { when (event) { is ChannelEvent.MarkAsRead -> markChannelAsRead(event.channel.id) is ChannelEvent.MarkAsUnRead -> markChannelAsUnRead(event.channel.id) is ChannelEvent.BlockChannel -> blockAndLeaveChannel(event.channel.id) is ChannelEvent.ClearHistory -> clearHistory(event.channel.id, event.channel.isPublic()) is ChannelEvent.LeaveChannel -> leaveChannel(event.channel.id) is ChannelEvent.BlockUser -> { if (event.channel.isDirect()) blockUser((event.channel.getPeer() ?: return).id) } is ChannelEvent.UnBlockUser -> { if (event.channel.isDirect()) unBlockUser((event.channel.getPeer() ?: return).id) } is ChannelEvent.DeleteChannel -> deleteChannel(event.channel.id) is ChannelEvent.Mute -> muteChannel(event.channel.id, 0) is ChannelEvent.UnMute -> unMuteChannel(event.channel.id) is ChannelEvent.Pin -> pinChannel(event.channel.id) is ChannelEvent.UnPin -> unpinChannel(event.channel.id) } } }
0
Kotlin
1
2
ce9c1b95555fadaafcd11f0d073fcdb07ca49600
9,113
sceyt-chat-android-uikit
MIT License
module-common/src/main/kotlin/io/klaytn/finder/infra/utils/ValidatorUtils.kt
klaytn
678,353,482
false
{"Kotlin": 1783784, "Solidity": 71874, "Shell": 4003}
package io.klaytn.finder.infra.utils class ValidatorUtils { companion object { private val emailRegEx = Regex("^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$") fun isValidEmail(email: String): Boolean { return emailRegEx.matches(email) } fun isValidWebSiteAddress(webSiteAddress: String): Boolean { return webSiteAddress.startsWith("https://") } } }
7
Kotlin
0
0
19229490436cf5c0096f25310959286645dc3914
428
finder-api
MIT License
examples/kotlin-spring-kafka-consumer/src/main/kotlin/no/njm/WorkshopMessageListener.kt
njmittet
468,862,154
false
null
package no.njm import org.apache.kafka.clients.consumer.ConsumerRecord import org.springframework.kafka.annotation.KafkaListener import org.springframework.kafka.support.Acknowledgment import org.springframework.stereotype.Component @Component class WorkshopMessageListener { private val log = getLogger() @KafkaListener( topics = [WORKSHOP_TOPIC], groupId = "kotlin-consumer-concurrent", properties = ["auto.offset.reset=earliest"], concurrency = "3", ) fun listen(consumerRecord: ConsumerRecord<String, String>, acknowledgment: Acknowledgment) { try { val message = consumerRecord.value().toWorkshopMessage() log.info( "Message with key:[${consumerRecord.key()}] on partition:[${consumerRecord.partition()}] is: $message." ) acknowledgment.acknowledge() } catch (e: Exception) { log.error("Error processing message with key: [${consumerRecord.key()}].") // Make sure the error is picked up by the KafkaErrorHandler. throw e } } @KafkaListener( topics = [WORKSHOP_TOPIC], groupId = "kotlin-consumer-concurrent", properties = ["auto.offset.reset=earliest", "max.poll.records=50"], concurrency = "3", batch = "true" ) fun listenBatch(consumerRecords: List<ConsumerRecord<String, String>>, acknowledgment: Acknowledgment) { consumerRecords.forEach() { try { val message = it.value().toWorkshopMessage() log.info( "Message with key:[${it.key()}] on partition:[${it.partition()}] is: $message." ) } catch (e: Exception) { log.error("Error processing message with key: [${it.key()}].") // Make sure the error is picked up by the KafkaErrorHandler. throw e } } acknowledgment.acknowledge() } }
0
null
2
1
cccc4c88b43f841a16f747b164c6fd5795c7fe51
2,002
kafka-workshop
MIT License
src/test/kotlin/io/github/michaelliv/lucene4k/QueryBuilderKtTest.kt
Michaelliv
484,571,545
false
{"Kotlin": 22378}
package io.github.michaelliv.lucene4k import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeTypeOf import org.apache.lucene.index.Term import org.apache.lucene.search.BooleanClause import org.apache.lucene.search.BooleanQuery import org.apache.lucene.search.PhraseQuery import org.apache.lucene.search.TermQuery class QueryBuilderKtTest : ShouldSpec({ should("buildBooleanQuery creates scope returns boolean query") { val empty = buildBooleanQuery { } empty.isEmpty() shouldBe true empty.isNotEmpty() shouldBe false } should("clausesAboveOr creates scope returns boolean query") { val notEmpty = buildBooleanQuery { shouldOccur { termQuery("field", "test") } shouldOccur { termQuery("field", "test") } shouldOccur { termQuery("field", "test") } shouldOccur { termQuery("field", "test") } } notEmpty.isNotEmpty() shouldBe true notEmpty.clausesAboveOrEquals(2) shouldBe true } should("shouldOccur creates SHOULD clause") { val q = buildBooleanQuery { shouldOccur { TermQuery(Term("test", "tests")) } } q.firstOrNull()?.occur shouldBe BooleanClause.Occur.SHOULD } should("mustOccur creates MUST clause") { val q = buildBooleanQuery { mustOccur { TermQuery(Term("test", "tests")) } } q.firstOrNull()?.occur shouldBe BooleanClause.Occur.MUST } should("mustNotOccur creates a MUST_NOT clause") { val q = buildBooleanQuery { mustNotOccur { TermQuery(Term("test", "tests")) } } q.firstOrNull()?.occur shouldBe BooleanClause.Occur.MUST_NOT } should("filter creates FILTER clause") { val q = buildBooleanQuery { filter { TermQuery(Term("test", "tests")) } } q.firstOrNull()?.occur shouldBe BooleanClause.Occur.FILTER } should("Multiple clauses can be created together") { val q = buildBooleanQuery { shouldOccur { TermQuery(Term("test", "tests")) } mustOccur { TermQuery(Term("test", "tests")) } } val clauses = q.clauses() clauses.first().occur shouldBe BooleanClause.Occur.SHOULD clauses.second().occur shouldBe BooleanClause.Occur.MUST } should("Boolean queries can contain boolean queries") { val q = buildBooleanQuery { shouldOccur { buildBooleanQuery { mustOccur { TermQuery(Term("test", "tests")) } } } } q.clauses() shouldHaveSize 1 q.clauses().first().occur shouldBe BooleanClause.Occur.SHOULD q.clauses().first().query.shouldBeTypeOf<BooleanQuery>() (q.clauses().first().query as BooleanQuery).clauses() shouldHaveSize 1 (q.clauses().first().query as BooleanQuery).clauses().first().occur shouldBe BooleanClause.Occur.MUST } should("phraseQuery should create an object of type PhraseQuery") { phraseQuery("field", slop = 0, "asd").shouldBeTypeOf<PhraseQuery>() phraseQuery("field", "asd").shouldBeTypeOf<PhraseQuery>() } })
0
Kotlin
0
0
6e4ec1edf1a096431a0af203d02f9d61b41b743c
3,206
lucene4k
MIT License
src/main/kotlin/rchabot/model/Tournament.kt
RomainChabot
401,110,284
false
null
package rchabot.model import org.bson.types.ObjectId import rchabot.common.annotation.Default data class Tournament @Default constructor( val _id: ObjectId?, val name: String, var players: List<Player> = listOf() ) { constructor(name: String) : this(_id = null, name = name) }
0
Kotlin
0
0
fb7c3847b6eec77ff9f8e038128438175000b0aa
295
tournament
MIT License
app/src/main/java/edu/rosehulman/condrak/roseschedule/RightNowFragment.kt
keith-cr
164,172,313
false
null
package edu.rosehulman.condrak.roseschedule import android.os.Bundle import android.os.Handler import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_right_now.view.* import org.joda.time.LocalTime /** * A simple [Fragment] subclass. * Use the [RightNowFragment.newInstance] factory method to * create an instance of this fragment. * */ class RightNowFragment : Fragment() { private var schedule: Schedule? = null private var scheduleTiming: ScheduleTiming? = null private val refreshHandler = Handler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) arguments?.let { schedule = it.getParcelable(ARG_SCHEDULE) scheduleTiming = it.getParcelable(ARG_SCHEDULE_TIMING) } } override fun onDestroyView() { super.onDestroyView() refreshHandler.removeCallbacksAndMessages(null) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment activity?.title = getString(R.string.schedule) val view = inflater.inflate(R.layout.fragment_right_now, container, false) drawView(view) val runnable = object : Runnable { override fun run() { drawView(view) refreshHandler.postDelayed(this, 60 * 1000) } } refreshHandler.postDelayed(runnable, ((60 * 1000) - (LocalTime().secondOfMinute * 1000)).toLong()) return view } private fun drawView(view: View) { if (scheduleTiming!!.isEmptySchedule(schedule!!)) { view.currentClassLayout.visibility = View.GONE view.nextClassLayout.visibility = View.GONE view.welcomeLayout.visibility = View.VISIBLE } else { val currClass = scheduleTiming?.getCurrentClass(schedule!!) val nextClass = scheduleTiming?.getNextClass(schedule!!) if (currClass != null) { view.currentClassPeriodNumber.text = currClass.periodText() view.currentClassInfo.text = if (currClass.hasLocation()) resources.getString(R.string.class_text, currClass.className, currClass.classLocation) else currClass.className view.currentClassEndTime.text = resources.getString( R.string.class_end_time, scheduleTiming!!.getEndTime(currClass).toString("h:mm a") ) view.currentClassEndTimeRelative.text = resources.getString( R.string.class_time_relative, scheduleTiming!!.getRelativeEndTime(currClass) ) } else { view.currentClassLayout.visibility = View.GONE } if (nextClass != null) { view.nextClassPeriodNumber.text = nextClass.periodText() view.nextClassInfo.text = if (nextClass.hasLocation()) resources.getString(R.string.class_text, nextClass.className, nextClass.classLocation) else nextClass.className view.nextClassStartTime.text = resources.getString( R.string.class_start_time, scheduleTiming!!.getStartTime(nextClass).toString("h:mm a") ) view.nextClassStartTimeRelative.text = resources.getString( R.string.class_time_relative, scheduleTiming!!.getRelativeStartTime(schedule!!, nextClass) ) } else { view.nextClassLayout.visibility = View.GONE } } } companion object { private const val ARG_SCHEDULE = "schedule" private const val ARG_SCHEDULE_TIMING = "scheduleTiming" @JvmStatic fun newInstance(schedule: Schedule, scheduleTiming: ScheduleTiming) = RightNowFragment().apply { arguments = Bundle().apply { putParcelable(ARG_SCHEDULE, schedule) putParcelable(ARG_SCHEDULE_TIMING, scheduleTiming) } } } }
0
Kotlin
0
0
1c371a063edb6ba014bc34e7195ee5d5aae7b10d
4,439
rose-schedule
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageadjudicationsapi/utils/MigrationEntityBuilder.kt
ministryofjustice
416,301,250
false
{"Kotlin": 1591749, "Dockerfile": 1411}
package uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.utils import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.AdjudicationMigrateDto import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.DisIssued import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateDamage import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateEvidence import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateHearing import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateHearingResult import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateOffence import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigratePrisoner import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigratePunishment import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateWitness import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.NomisGender import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.ReportingOfficer import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.DamageCode import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.EvidenceCode import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.WitnessCode import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.Finding import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.OicHearingType import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.OicSanctionCode import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.Plea import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.Status import java.math.BigDecimal import java.time.LocalDate import java.time.LocalDateTime import kotlin.random.Random class MigrationEntityBuilder { fun createAdjudication( agencyId: String = "MDI", agencyIncidentId: Long = 1, oicIncidentId: Long = Random.nextLong(10000, 999999), offenceSequence: Long = 1, prisoner: MigratePrisoner = createPrisoner(), offence: MigrateOffence = createOffence(), witnesses: List<MigrateWitness> = emptyList(), damages: List<MigrateDamage> = emptyList(), evidence: List<MigrateEvidence> = emptyList(), punishments: List<MigratePunishment> = emptyList(), hearings: List<MigrateHearing> = emptyList(), reportedDateTime: LocalDateTime = LocalDateTime.now(), disIssued: List<DisIssued> = emptyList(), ): AdjudicationMigrateDto = AdjudicationMigrateDto( agencyId = agencyId, agencyIncidentId = agencyIncidentId, oicIncidentId = oicIncidentId, offenceSequence = offenceSequence, bookingId = 1, incidentDateTime = LocalDateTime.now(), locationId = 1, statement = "some details", prisoner = prisoner, offence = offence, reportingOfficer = ReportingOfficer(username = "OFFICER_RO"), createdByUsername = "alo", witnesses = witnesses, damages = damages, evidence = evidence, punishments = punishments, hearings = hearings, reportedDateTime = reportedDateTime, disIssued = disIssued, ) fun createPrisoner( prisonerNumber: String = "AE12345", currentAgencyId: String? = "MDI", gender: String = NomisGender.M.name, ): MigratePrisoner = MigratePrisoner( prisonerNumber = prisonerNumber, currentAgencyId = currentAgencyId, gender = gender, ) fun createOffence(offenceCode: String = "51:17", offenceDescription: String = "description"): MigrateOffence = MigrateOffence(offenceCode = offenceCode, offenceDescription = offenceDescription) fun createWitness(): MigrateWitness = MigrateWitness(firstName = "first", lastName = "last", createdBy = "OFFICER_GEN", witnessType = WitnessCode.OFFICER, comment = "comment", dateAdded = LocalDate.now(), username = "AE12345") fun createDamage(details: String? = "something"): MigrateDamage = MigrateDamage(damageType = DamageCode.CLEANING, details = details, createdBy = "OFFICER_GEN", repairCost = BigDecimal(10.0)) fun createEvidence(): MigrateEvidence = MigrateEvidence(evidenceCode = EvidenceCode.PHOTO, details = "details", reporter = "OFFICER_GEN", dateAdded = LocalDate.now()) fun createPunishment( code: String = OicSanctionCode.CC.name, status: String = Status.IMMEDIATE.name, comment: String? = null, amount: BigDecimal? = null, days: Int? = 1, effectiveDate: LocalDate = LocalDate.now(), consecutiveChargeNumber: String? = null, ): MigratePunishment = MigratePunishment( sanctionCode = code, sanctionStatus = status, sanctionSeq = 1, comment = comment, compensationAmount = amount, consecutiveChargeNumber = consecutiveChargeNumber, days = days, effectiveDate = effectiveDate, createdBy = "NOMIS_USER", ) fun createHearing( comment: String? = null, adjudicator: String? = "ALO_GEN", hearingDateTime: LocalDateTime = LocalDateTime.now(), hearingResult: MigrateHearingResult? = null, oicHearingId: Long = 1, oicHearingType: OicHearingType = OicHearingType.GOV_ADULT, ): MigrateHearing = MigrateHearing( oicHearingId = oicHearingId, oicHearingType = oicHearingType, hearingDateTime = hearingDateTime, commentText = comment, locationId = 1, adjudicator = adjudicator, hearingResult = hearingResult, representative = "test", ) fun createHearingResult( plea: String = Plea.NOT_GUILTY.name, finding: String = Finding.PROVED.name, createdDateTime: LocalDateTime = LocalDateTime.now(), ): MigrateHearingResult = MigrateHearingResult( plea = plea, finding = finding, createdDateTime = createdDateTime, createdBy = "ALO_GEN", ) }
6
Kotlin
0
3
cd206a32c034551b38ba7b9a21e28711a9124127
5,875
hmpps-manage-adjudications-api
MIT License
kotlin-node/src/jsMain/generated/node/vm/MemoryMeasurementTotal.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package node.vm sealed external interface MemoryMeasurementTotal { var jsMemoryEstimate: Double var jsMemoryRange: js.array.JsTuple2<Double, Double> }
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
214
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/example/trendingtimes/ui/activity/ReadNewsActivity.kt
adityarai004
671,452,116
false
{"Kotlin": 142912}
package com.example.trendingtimes.ui.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.webkit.WebView import androidx.appcompat.widget.Toolbar import com.example.trendingtimes.R class ReadNewsActivity : AppCompatActivity() { companion object { const val EXTRA_URL = "extra_url" } private lateinit var webView : WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_read_news) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = "Read News" val url = intent.getStringExtra(EXTRA_URL) webView = findViewById(R.id.webView) if (url != null) { webView.loadUrl(url) } } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }
0
Kotlin
0
1
90b2b3f7330fd5368739d55c049760fdfeb4c76b
1,013
TrendingTimes
MIT License