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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xready/android/app/src/main/kotlin/xinlake/ready/MainActivity.kt | xinlake | 368,879,115 | false | null | package xinlake.ready
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity()
| 2 | C | 10 | 21 | 7fb3885ab868cc67d98041fe90d338ced5606383 | 114 | privch-client-flutter | MIT License |
app/src/main/kotlin/com/gurpreetsk/android_starter/greeting/GreetingState.kt | imGurpreetSK | 224,709,944 | false | {"Kotlin": 31526, "Java": 1371} | package com.gurpreetsk.android_starter.greeting
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class GreetingState(
val input: String
) : Parcelable
| 0 | Kotlin | 0 | 0 | a5ea5cfd3e18b9f56c85a2c4e74c7d790c4f9a67 | 197 | HelloUser | Apache License 2.0 |
app/src/main/java/id/aasumitro/easynote/ui/main/fragment/category/CategoryAdapter.kt | bakode | 126,250,753 | false | null | package id.aasumitro.easynote.ui.main.fragment.category
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import id.aasumitro.easynote.R
import id.aasumitro.easynote.data.local.model.Category
/**
* Created by Agus Adhi Sumitro on 21/02/2018.
* https://asmith.my.id
* [email protected]
*/
class CategoryAdapter (private val categoryList: ArrayList<Category>,
private val listener: RecyclerListener) :
RecyclerView.Adapter<AdapterHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AdapterHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_category_list, parent, false)
return AdapterHolder(view)
}
override fun getItemCount(): Int = categoryList.count()
override fun onBindViewHolder(holder: AdapterHolder, position: Int) =
holder.bind(categoryList[position], listener)
} | 0 | Kotlin | 0 | 0 | 1e0e1a0fa8e32c7c710c61730a674bed18cad243 | 991 | EasyNote | Apache License 2.0 |
app/src/main/java/com/didemeren/coffeeshopretrofitrx/model/OrderResponse.kt | didemeren | 290,844,176 | false | null | package com.didemeren.coffeeshopretrofitrx.model
import com.google.gson.annotations.SerializedName
data class OrderResponse (
@SerializedName("data")
var order: Order) | 0 | Kotlin | 0 | 0 | fdcace26d213c8ea30d6f75474de25bdfe3896d3 | 177 | CoffeeShopRetrofitRx | MIT License |
app/src/main/java/com/didemeren/coffeeshopretrofitrx/model/OrderResponse.kt | didemeren | 290,844,176 | false | null | package com.didemeren.coffeeshopretrofitrx.model
import com.google.gson.annotations.SerializedName
data class OrderResponse (
@SerializedName("data")
var order: Order) | 0 | Kotlin | 0 | 0 | fdcace26d213c8ea30d6f75474de25bdfe3896d3 | 177 | CoffeeShopRetrofitRx | MIT License |
wildfire1/android/app/src/main/kotlin/com/example/wildfire1/MainActivity.kt | thececilia | 389,446,665 | true | {"Dart": 5433, "HTML": 3697, "Swift": 404, "Kotlin": 126, "Objective-C": 38} | package com.example.wildfire1
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | null | 0 | 0 | d6a102cc55e8324537cd142290c7d9fac0e411e4 | 126 | Wildfire-Group1-Flutter | MIT License |
clikt-mordant/src/commonTest/kotlin/com/github/ajalt/clikt/completion/CompletionTestBase.kt | ajalt | 128,975,548 | false | {"Kotlin": 603162, "Shell": 1858, "Batchfile": 662} | package com.github.ajalt.clikt.completion
import com.github.ajalt.clikt.core.PrintCompletionMessage
import com.github.ajalt.clikt.core.context
import com.github.ajalt.clikt.core.subcommands
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.options.convert
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.testing.TestCommand
import com.github.ajalt.clikt.testing.parse
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.string.shouldContain
import kotlin.js.JsName
import kotlin.test.Test
import kotlin.test.assertEquals
@Suppress("unused")
abstract class CompletionTestBase(private val shell: String) {
private fun doTest(expected: String, command: TestCommand) {
val message = shouldThrow<PrintCompletionMessage> {
command.parse("--generate-completion=$shell")
}.message
assertEquals(expected.trimMargin(), message)
}
@JsName("custom_completions_expected")
protected abstract fun `custom completions expected`(): String
@Test
@JsName("custom_completions")
fun `custom completions`() {
class C : TestCommand(autoCompleteEnvvar = "TEST_COMPLETE") {
val o by option(completionCandidates = CompletionCandidates.Custom.fromStdout("echo foo bar"))
val a by argument(completionCandidates = CompletionCandidates.Custom {
when (shell) {
"fish" -> "\"(echo zzz xxx)\""
else -> """
WORDS=${'$'}(echo zzz xxx)
COMPREPLY=(${'$'}(compgen -W "${'$'}WORDS" -- "${'$'}{COMP_WORDS[${'$'}COMP_CWORD]}"))
""".trimIndent()
}
})
}
doTest(
`custom completions expected`(),
C().completionOption(hidden = true)
)
}
@JsName("subcommands_with_multi_word_names_expected")
protected abstract fun `subcommands with multi-word names expected`(): String
@Test
@JsName("subcommands_with_multi_word_names")
fun `subcommands with multi-word names`() {
class C : TestCommand(autoCompleteEnvvar = "TEST_COMPLETE")
class Sub : TestCommand()
class SubCommand : TestCommand(name = "sub-command")
class SubSub : TestCommand()
class LongSubCommand : TestCommand(name = "long-sub-command")
doTest(
`subcommands with multi-word names expected`(),
C().subcommands(
Sub(),
SubCommand().subcommands(SubSub(), LongSubCommand())
).completionOption(hidden = true)
)
}
@JsName("option_secondary_names_expected")
protected abstract fun `option secondary names expected`(): String
@Test
@JsName("option_secondary_names")
fun `option secondary names`() {
class C : TestCommand(autoCompleteEnvvar = "TEST_COMPLETE") {
val flag by option().flag("--no-flag")
}
doTest(
`option secondary names expected`(),
C().completionOption(hidden = true)
)
}
@JsName("explicit_completion_candidates_expected")
protected abstract fun `explicit completion candidates expected`(): String
@Test
@JsName("explicit_completion_candidates")
fun `explicit completion candidates`() {
class C : TestCommand(autoCompleteEnvvar = "TEST_COMPLETE") {
init {
context { helpOptionNames = emptySet() }
}
val none by option(completionCandidates = CompletionCandidates.None)
val path by option(completionCandidates = CompletionCandidates.Path)
val host by option(completionCandidates = CompletionCandidates.Hostname)
.convert(completionCandidates = CompletionCandidates.Path) { it }
val user by option(completionCandidates = CompletionCandidates.Username)
val fixed by option(completionCandidates = CompletionCandidates.Fixed("foo", "bar"))
val argUser by argument(completionCandidates = CompletionCandidates.Username)
val argFixed by argument(
completionCandidates = CompletionCandidates.Fixed(
"baz",
"qux"
)
)
}
doTest(
`explicit completion candidates expected`(),
C().completionOption(hidden = true)
)
}
@Test
@JsName("completion_command")
fun `completion command`() {
val message = shouldThrow<PrintCompletionMessage> {
TestCommand()
.subcommands(CompletionCommand(), TestCommand(name = "foo"))
.parse("generate-completion $shell")
}.message
message shouldContain shell
message shouldContain "foo"
}
}
| 18 | Kotlin | 94 | 2,507 | becce2e6b9ed85716469423719e7ef1dd86f953e | 4,943 | clikt | Apache License 2.0 |
kmp/features/settings/debugTools/src/commonMain/kotlin/com/egoriku/grodnoroads/settings/debugtools/domain/DebugToolsComponent.kt | BehindWheel | 485,026,420 | false | {"Kotlin": 1186756, "Ruby": 5708, "Swift": 1889, "Shell": 830} | package com.egoriku.grodnoroads.settings.debugtools.domain
import androidx.compose.runtime.Stable
@Stable
interface DebugToolsComponent {
fun showOnboarding()
}
| 17 | Kotlin | 1 | 18 | 966f0fb26df6c3f443e3b328b81f9938aaa9cac5 | 168 | BehindWheelKMP | Apache License 2.0 |
data/src/main/java/com/daniel/data/di/networkModule.kt | lluzalves | 661,433,078 | false | null | package com.daniel.workmanagerapp.data.di
import com.daniel.workmanagerapp.data.network.NetworkClient
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import org.koin.android.ext.koin.androidContext
import org.koin.core.qualifier.named
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
const val RETROFIT = "retrofit"
const val OK_HTTP_CLIENT = "ok_http_client"
val networkModule = module {
factory(named(OK_HTTP_CLIENT)) { NetworkClient(androidContext()).getNetworkClient() }
factory(named(RETROFIT)) {
Retrofit.Builder()
.client(get(named(OK_HTTP_CLIENT)))
.baseUrl("https://newsapi.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
}
} | 10 | Kotlin | 0 | 0 | 7edfa5d41831e1e2f523bed5a397b69216e05b9f | 892 | WorkmanagerApp | The Unlicense |
core/src/main/java/com/views/calendar/cosmocalendar/view/SlowdownRecyclerView.kt | tplloi | 126,578,283 | false | null | package com.views.calendar.cosmocalendar.view
import android.content.Context
import android.util.AttributeSet
import android.view.animation.Interpolator
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs
import kotlin.math.pow
class SlowdownRecyclerView : RecyclerView {
companion object {
// Change pow to control speed.
// Bigger = faster. RecyclerView default is 5.
private const val POW = 2
}
private var interpolator: Interpolator? = null
constructor(context: Context) : super(context) {
createInterpolator()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
createInterpolator()
}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
context,
attrs,
defStyle
) {
createInterpolator()
}
private fun createInterpolator() {
interpolator = Interpolator { t ->
@Suppress("NAME_SHADOWING")
var t = t
t = abs(t - 1.0f)
(1.0f - t.toDouble().pow(POW)).toFloat()
}
}
override fun smoothScrollBy(dx: Int, dy: Int) {
super.smoothScrollBy(dx, dy, interpolator)
}
}
| 0 | Kotlin | 0 | 6 | b6c11ccff814d25ff368013ea6dd8a6b5d987ff1 | 1,240 | basemaster | Apache License 2.0 |
AppCheck-ins/app/src/main/java/com/example/iram/check_ins/Interfaces/getRouteInterface.kt | IramML | 141,610,474 | false | null | package com.example.iram.check_ins.Interfaces
interface getRouteInterface{
fun getRoute(json:String)
} | 0 | Kotlin | 0 | 0 | 511b10c4207402c0ddd99efde5e8689f07b07fd0 | 107 | CheckinsApp | MIT License |
src/main/kotlin/de/megonno/cannibalkitchen/game/listeners/OnStopping.kt | Megonno | 822,249,651 | false | {"Kotlin": 60118} | package de.megonno.cannibalkitchen.game.listeners
import de.megonno.cannibalkitchen.CannibalKitchen
import de.megonno.cannibalkitchen.game.state.GameState
import de.megonno.cannibalkitchen.game.state.GameStateChangeEvent
import net.kyori.adventure.text.Component
import net.kyori.adventure.title.Title
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
class OnStopping(private val plugin: CannibalKitchen) : Listener {
@EventHandler(priority = EventPriority.HIGH)
fun onChangeGameState(event: GameStateChangeEvent) {
if (event.newGameState != GameState.Stopping) return
val gameManager = plugin.gameManager
gameManager.timer.pauseTimer()
gameManager.cropHandler.stop()
val winnerTeams = plugin.gameManager.orderHandler.winner()
.mapNotNull { plugin.gameManager.teamHandler.getTeamById(uuid = it) }
var winnerMessage = Component.text("Winner is ")
winnerTeams.forEachIndexed { index, currentTeam ->
winnerMessage = winnerMessage.append(currentTeam.name)
if (winnerTeams.size - 2 > index) {
winnerMessage = winnerMessage.append(Component.text(", "))
} else if (winnerTeams.size - 2 == index) {
winnerMessage = winnerMessage.append(Component.text(" & "))
}
}
plugin.server.onlinePlayers.forEach { player ->
player.showTitle(Title.title(winnerMessage, Component.empty()))
}
}
}
| 0 | Kotlin | 0 | 0 | 142780e92e341162492c67658afa427f8008c050 | 1,535 | CannibalKitchen | MIT License |
hexagon_core/src/main/kotlin/com/hexagonkt/injection/InjectionManager.kt | wanglaibao | 194,350,081 | true | {"Kotlin": 294183, "HTML": 22186, "Scala": 3558, "JavaScript": 2701, "Groovy": 2022, "Dockerfile": 1701, "CSS": 613} | package com.hexagonkt.injection
import kotlin.reflect.KClass
/**
* Generators registry and utilities.
*/
object InjectionManager {
private var registry: Map<Pair<KClass<*>, *>, () -> Any> = emptyMap()
fun <T : Any, R : T> bind(type: KClass<T>, parameter: Any, provider: () -> R) {
registry += (type to parameter) to provider
}
fun <T : Any, R : T> bind(type: KClass<T>, provider: () -> R) {
bind(type, Unit, provider)
}
fun <T : Any, R : T> bindObject(type: KClass<T>, parameter: Any, instance: R) {
bind(type, parameter) { instance }
}
fun <T : Any, R : T> bindObject(type: KClass<T>, instance: R) {
bindObject(type, Unit, instance)
}
inline fun <reified T : Any> bind(parameter: Any, noinline provider: () -> T) =
bind(T::class, parameter, provider)
inline fun <reified T : Any> bindObject(parameter: Any, instance: T) =
bindObject(T::class, parameter, instance)
inline fun <reified T : Any> bind(noinline provider: () -> T) =
bind(T::class, provider)
inline fun <reified T : Any> bindObject(instance: T) =
bindObject(T::class, instance)
@Suppress("UNCHECKED_CAST") // bind operation takes care of type matching
fun <T : Any> inject(type: KClass<T>, parameter: Any): T =
registry[type to parameter]?.invoke() as? T ?: error("${type.java.name} generator missing")
inline fun <reified T : Any> inject(parameter: Any): T = inject(T::class, parameter)
fun <T : Any> inject(type: KClass<T>): T = inject(type, Unit)
inline fun <reified T : Any> inject(): T = inject(T::class)
}
| 0 | Kotlin | 0 | 0 | 7f0e4b21a5d1be99525350af22719908323d3419 | 1,634 | hexagon | MIT License |
app/src/main/java/com/weatherxm/ui/devicesettings/UIModels.kt | WeatherXM | 728,657,649 | false | {"Kotlin": 1852713} | package com.weatherxm.ui.devicesettings
import androidx.annotation.Keep
import com.squareup.moshi.JsonClass
import com.weatherxm.data.models.Failure
import com.weatherxm.ui.common.DeviceAlert
import com.weatherxm.ui.common.RewardSplitsData
@Keep
@JsonClass(generateAdapter = true)
data class UIDeviceInfo(
val default: MutableList<UIDeviceInfoItem>,
val gateway: MutableList<UIDeviceInfoItem>,
val station: MutableList<UIDeviceInfoItem>,
var rewardSplit: RewardSplitsData?
)
@Keep
@JsonClass(generateAdapter = true)
data class UIDeviceInfoItem(
val title: String,
val value: String,
val deviceAlert: DeviceAlert? = null,
)
@JsonClass(generateAdapter = true)
data class RebootState(
var status: RebootStatus,
var failure: Failure? = null
)
enum class RebootStatus {
SCAN_FOR_STATION,
PAIR_STATION,
CONNECT_TO_STATION,
REBOOTING
}
@JsonClass(generateAdapter = true)
data class ChangeFrequencyState(
var status: FrequencyStatus,
var failure: Failure? = null
)
enum class FrequencyStatus {
SCAN_FOR_STATION,
PAIR_STATION,
CONNECT_TO_STATION,
CHANGING_FREQUENCY
}
| 2 | Kotlin | 1 | 13 | 7a9344ae336867dc5ea0366b856241ad331519e9 | 1,142 | wxm-android | Apache License 2.0 |
app/src/main/java/org/zlobste/spotter/features/analytics/view/AnalyticsFragment.kt | zlobste | 372,320,932 | false | null | package org.zlobste.spotter.features.analytics.view
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.annotation.RequiresApi
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fragment_analytics.*
import kotlinx.android.synthetic.main.layout_driver_analytics_dialog.view.*
import kotlinx.android.synthetic.main.toolbar_with_image.*
import kotlinx.android.synthetic.main.toolbar_with_image.view.*
import org.zlobste.spotter.R
import org.zlobste.spotter.databinding.FragmentAnalyticsBinding
import org.zlobste.spotter.features.analytics.logic.FilterDriversByDate
import org.zlobste.spotter.features.my_drivers.model.Driver
import org.zlobste.spotter.features.my_drivers.view.DriversAdapter
import org.zlobste.spotter.util.ScopedFragment
import org.kodein.di.KodeinAware
import org.kodein.di.android.x.closestKodein
import java.time.ZoneId
import java.time.temporal.ChronoUnit
import java.util.*
class AnalyticsFragment : ScopedFragment(), KodeinAware {
override val kodein by closestKodein()
private val driversAdapter: DriversAdapter by lazy {
DriversAdapter(requireContext())
}
val startDate = MutableLiveData<Date>()
val endDate = MutableLiveData<Date>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding =
FragmentAnalyticsBinding.inflate(inflater, container, false)
binding.fragment = this
binding.lifecycleOwner = this
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initToolbar()
initFields()
initRecyclerView()
}
private fun initToolbar() {
requireActivity().toolbar_with_image.title_text_view.text =
getString(R.string.analytics)
}
private fun initFields() {
start_date.setEndIconOnClickListener {
showCalendar(true)
}
end_date.setEndIconOnClickListener {
showCalendar(false)
}
}
private fun showCalendar(isStartDate: Boolean) {
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val pickerDialog = DatePickerDialog(
requireContext(),
{ _, chosenYear, monthOfYear, dayOfMonth ->
val date = GregorianCalendar(chosenYear, monthOfYear, dayOfMonth).time
if (isStartDate) startDate.value = date else endDate.value = date
updateDrivers()
},
year,
month,
day
)
pickerDialog.datePicker.maxDate = calendar.timeInMillis
pickerDialog.show()
}
private fun initRecyclerView() {
with(analytics_drivers) {
layoutManager =
LinearLayoutManager(
requireContext(),
LinearLayoutManager.VERTICAL,
false
)
adapter = driversAdapter
driversAdapter.onInfoIconClicked = { driver ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
showDialog(driver)
}
}
}
}
private fun getDriversInTimesBounds(): List<Driver> {
return if (startDate.value != null && endDate.value != null) {
FilterDriversByDate.getDrivers(
startDate.value!!,
endDate.value!!
).distinct()
} else {
emptyList()
}
}
private fun updateDrivers() {
val drivers = getDriversInTimesBounds()
driversAdapter.replace(drivers)
total.text = drivers.size.toString()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun showDialog(driver: Driver) {
val builder = AlertDialog.Builder(requireContext())
val view = layoutInflater.inflate(R.layout.layout_driver_analytics_dialog, null)
view.full_name.text = getString(R.string.full_name, driver.lastName, driver.firstName)
view.email.text = driver.email
view.b_day.text = driver.bDay
val count = FilterDriversByDate.getDriverLevelById(
driver.driverId, startDate.value!!,
endDate.value!!
)
view.incidents_count.text = count.toString()
view.drinking_level.text = chooseLevel(count).first
view.indicator.setImageResource(chooseLevel(count).second)
builder.setView(view)
builder.setCustomTitle(null)
val dialog: AlertDialog = builder.create()
val close = view.findViewById(R.id.close_info_button) as Button?
close!!.setOnClickListener {
dialog.dismiss()
}
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.show()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun chooseLevel(incidentsCount: Int): Pair<String, Int> {
val rate = incidentsCount / getMonthDiff()
val level: String
val drawable: Int
when {
rate < 2 -> {
level = "Low"
drawable = R.drawable.background_green_circle
}
rate < 10 -> {
level = "Middle"
drawable = R.drawable.background_yellow_circle
}
else -> {
level = "High"
drawable = R.drawable.background_red_circle
}
}
return level to drawable
}
@RequiresApi(Build.VERSION_CODES.O)
private fun getMonthDiff(): Long {
val difference = ChronoUnit.MONTHS.between(
startDate.value!!.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
endDate.value!!.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
)
return if(difference == 0L) 1 else difference
}
companion object {
fun getInstance() = AnalyticsFragment()
}
} | 0 | Kotlin | 0 | 0 | e5135d0da1c14abd2eba906022a3d6ecc3d473bf | 6,477 | spotter-android-client | MIT License |
src/main/kotlin/org/example/chitchatserver/domain/chat/persistence/repository/ChatRepository.kt | letsgochitchat | 727,956,889 | false | {"Kotlin": 29172} | package org.example.chitchatserver.domain.chat.persistence.repository
import org.example.chitchatserver.domain.chat.persistence.ChatEntity
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import java.util.UUID
interface ChatRepository : ReactiveMongoRepository<ChatEntity, UUID> {
} | 1 | Kotlin | 0 | 0 | e95600cbb8995140419276d724da8999cda7e3c2 | 310 | chitchat-server | Apache License 2.0 |
app/src/main/java/com/mateuszcholyn/wallet/frontend/domain/usecase/core/expense/AddExpenseUseCase.kt | mateusz-nalepa | 467,673,984 | false | {"Kotlin": 606018} | package com.mateuszcholyn.wallet.frontend.domain.usecase.core.expense
import com.mateuszcholyn.wallet.backend.api.core.expense.AddExpenseParameters
import com.mateuszcholyn.wallet.backend.api.core.expense.Expense
import com.mateuszcholyn.wallet.backend.api.core.expense.ExpenseCoreServiceAPI
import com.mateuszcholyn.wallet.frontend.domain.usecase.UseCase
interface AddExpenseUseCase : UseCase {
suspend fun invoke(addExpenseParameters: AddExpenseParameters): Expense
}
class DefaultAddExpenseUseCase(
private val expenseCoreService: ExpenseCoreServiceAPI,
) : AddExpenseUseCase {
override suspend fun invoke(addExpenseParameters: AddExpenseParameters): Expense =
expenseCoreService.add(addExpenseParameters)
} | 0 | Kotlin | 0 | 0 | 22fd86fbb5d9c360b1b86ab040a876b971a74d9a | 737 | wallet | Apache License 2.0 |
app/src/main/java/com/griffith/feedreeder_3061874/data/Category.kt | ahmedsaheed | 710,784,872 | false | {"Kotlin": 141086} | package com.griffith.feedreeder_3061874.data
import androidx.compose.runtime.Immutable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "categories",
indices = [
Index("name", unique = true)
]
)
@Immutable
data class Category(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Long = 0,
@ColumnInfo(name = "name") val name: String
)
| 0 | Kotlin | 0 | 0 | 9375ec20740a82b2e9f6ab4cd360c7bc37c52174 | 471 | feedreeder_3061874 | Creative Commons Zero v1.0 Universal |
web3/src/commonMain/kotlin/dev.icerock.moko.web3/EthereumAddress.kt | denmusic1992 | 390,233,891 | true | {"Kotlin": 61310} | /*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.web3
import com.soywiz.kbignum.BigInt
import com.soywiz.kbignum.bi
interface EthereumAddress {
val value: String
val bigInt: BigInt get() = value.removePrefix("0x").bi(16)
}
| 0 | Kotlin | 0 | 0 | 9bff0248ab317f14458853669ad75d96527a7a35 | 316 | moko-web3 | Apache License 2.0 |
checkout/src/test/java/com/checkout/tokenization/mapper/response/AddressEntityToAddressDataMapperTest.kt | checkout | 140,300,675 | false | {"Kotlin": 1048827, "Java": 19853, "Shell": 517} | package com.checkout.tokenization.mapper.response
import com.checkout.base.model.Country
import com.checkout.mock.TokenizationRequestTestData
import com.checkout.tokenization.model.Address
import org.amshove.kluent.internal.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class AddressEntityToAddressDataMapperTest {
private lateinit var addressEntityToAddressDataMapper: AddressEntityToAddressDataMapper
@BeforeEach
fun setUp() {
addressEntityToAddressDataMapper = AddressEntityToAddressDataMapper()
}
@Test
fun `mapping of AddressEntity to Address data`() {
// Given
val expectedAddressData = Address(
"Checkout.com",
"90 Tottenham Court Road",
"London",
"London",
"W1T 4TJ",
Country.from("GB"),
)
// When
val actualAddressData = addressEntityToAddressDataMapper.map(TokenizationRequestTestData.addressEntity)
// Then
assertEquals(expectedAddressData, actualAddressData)
}
}
| 14 | Kotlin | 36 | 51 | e1d99bff49067403a22f56bcb241cd4d014b269d | 1,096 | frames-android | MIT License |
picture_library/src/main/java/com/luck/picture/lib/immersive/ImmersiveManage.kt | MoustafaShahin | 365,029,122 | false | null | package com.luck.picture.lib.immersive
import android.graphics.*
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.view.*
import androidx.appcompat.app.AppCompatActivity
/**
* @author:luck
* @data:2018/3/28 下午1:00
* @描述: 沉浸式相关
*/
object ImmersiveManage {
/**
* 注意:使用最好将布局xml 跟布局加入 android:fitsSystemWindows="true" ,这样可以避免有些手机上布局顶边的问题
*
* @param baseActivity 这个会留出来状态栏和底栏的空白
* @param statusBarColor 状态栏的颜色
* @param navigationBarColor 导航栏的颜色
* @param isDarkStatusBarIcon 状态栏图标颜色是否是深(黑)色 false状态栏图标颜色为白色
*/
fun immersiveAboveAPI23(baseActivity: AppCompatActivity, statusBarColor: Int, navigationBarColor: Int, isDarkStatusBarIcon: Boolean) {
if (VERSION.SDK_INT >= VERSION_CODES.M) {
immersiveAboveAPI23(baseActivity, false, false, statusBarColor, navigationBarColor, isDarkStatusBarIcon)
}
}
/**
* @param baseActivity
* @param statusBarColor 状态栏的颜色
* @param navigationBarColor 导航栏的颜色
*/
fun immersiveAboveAPI23(baseActivity: AppCompatActivity, isMarginStatusBar: Boolean, isMarginNavigationBar: Boolean, statusBarColor: Int, navigationBarColor: Int, isDarkStatusBarIcon: Boolean) {
try {
val window = baseActivity.window
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT && VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
//4.4版本及以上 5.0版本及以下
window.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
} else if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
if (isMarginStatusBar && isMarginNavigationBar) {
//5.0版本及以上
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
LightStatusBarUtils.setLightStatusBar(baseActivity, isMarginStatusBar, isMarginNavigationBar, statusBarColor == Color.TRANSPARENT, isDarkStatusBarIcon)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
} else if (!isMarginStatusBar && !isMarginNavigationBar) {
window.requestFeature(Window.FEATURE_NO_TITLE)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
LightStatusBarUtils.setLightStatusBar(baseActivity, isMarginStatusBar, isMarginNavigationBar, statusBarColor == Color.TRANSPARENT, isDarkStatusBarIcon)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
} else if (!isMarginStatusBar && isMarginNavigationBar) {
window.requestFeature(Window.FEATURE_NO_TITLE)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
LightStatusBarUtils.setLightStatusBar(baseActivity, isMarginStatusBar, isMarginNavigationBar, statusBarColor == Color.TRANSPARENT, isDarkStatusBarIcon)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
} else {
//留出来状态栏 不留出来导航栏 没找到办法。。
return
}
window.statusBarColor = statusBarColor
window.navigationBarColor = navigationBarColor
}
} catch (e: Exception) {
}
}
} | 0 | Kotlin | 0 | 0 | 6cc5ff6a5c86c491a852304c58ce979ed42d6225 | 3,712 | InsGallery | Apache License 2.0 |
baseLib/src/main/java/com/dyn/base/ui/base/recycler/CenterLayoutManager.kt | dynsxyc | 420,926,305 | false | null | package com.dyn.base.ui.base.recycler
import android.content.Context
import android.util.AttributeSet
import android.util.DisplayMetrics
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.SmoothScroller
class CenterLayoutManager : LinearLayoutManager {
constructor(context: Context) : super(context) {}
constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(
context,
orientation,
reverseLayout
)
constructor(
context: Context?,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes) {
}
override fun smoothScrollToPosition(
recyclerView: RecyclerView,
state: RecyclerView.State,
position: Int
) {
val smoothScroller: SmoothScroller = CenterSmoothScroller(recyclerView.context)
smoothScroller.targetPosition = position
startSmoothScroll(smoothScroller)
}
private class CenterSmoothScroller(context: Context?) : LinearSmoothScroller(context) {
override fun calculateDtToFit(
viewStart: Int,
viewEnd: Int,
boxStart: Int,
boxEnd: Int,
snapPreference: Int
): Int {
return boxStart + (boxEnd - boxStart) / 2 - (viewStart + (viewEnd - viewStart) / 2)
}
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
return 100f / displayMetrics.densityDpi
}
}
} | 0 | Kotlin | 0 | 0 | 881f371dc87830d2c523ee6b70fc44b1db205165 | 1,688 | AndroidCommonProject | Apache License 2.0 |
app/src/sharedTest/java/org/fnives/test/showcase/testutils/doBlockinglyOnMainThread.kt | fknives | 356,982,481 | false | null | package org.fnives.test.showcase.testutils
import android.os.Handler
import android.os.Looper
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.runBlocking
fun doBlockinglyOnMainThread(action: () -> Unit) {
if (Looper.myLooper() === Looper.getMainLooper()) {
action()
} else {
val deferred = CompletableDeferred<Unit>()
Handler(Looper.getMainLooper()).post {
action()
deferred.complete(Unit)
}
runBlocking { deferred.await() }
}
}
| 8 | null | 1 | 3 | 041c721cc0e24f51df0e8bafe6e115016f4510d0 | 531 | AndroidTest-ShowCase | Apache License 2.0 |
android/quest/src/main/java/org/smartregister/fhircore/quest/ui/patient/register/components/RegisterListRow.kt | opensrp | 339,242,809 | false | null | /*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.quest.ui.patient.register.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.smartregister.fhircore.engine.ui.components.Separator
import org.smartregister.fhircore.engine.ui.theme.DefaultColor
import org.smartregister.fhircore.engine.ui.theme.DividerColor
import org.smartregister.fhircore.engine.ui.theme.InfoColor
import org.smartregister.fhircore.engine.ui.theme.OverdueColor
import org.smartregister.fhircore.quest.R
import org.smartregister.fhircore.quest.ui.shared.models.RegisterViewData
import org.smartregister.fhircore.quest.ui.shared.models.ServiceMember
@Composable
fun RegisterListRow(
modifier: Modifier = Modifier,
registerViewData: RegisterViewData,
onRowClick: (String) -> Unit
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth().height(IntrinsicSize.Min)
) {
Column(
modifier =
modifier
.clickable { onRowClick(registerViewData.logicalId) }
.weight(0.75f)
.padding(horizontal = 16.dp, vertical = 28.dp)
) {
if (registerViewData.serviceButtonActionable) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth()
) {
Column(modifier = modifier.wrapContentWidth(Alignment.Start)) {
Text(text = registerViewData.title)
RegisterListStatus(registerViewData, modifier)
}
}
} else {
Text(text = registerViewData.title)
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth()
) {
Column(modifier = modifier.wrapContentWidth(Alignment.Start).weight(0.7f)) {
if (!registerViewData.subtitle.isNullOrEmpty()) {
Text(
text = registerViewData.subtitle,
color = DefaultColor,
modifier = modifier.padding(top = 4.dp)
)
}
RegisterListStatus(registerViewData, modifier)
}
ServiceMemberIcons(
registerViewData,
modifier = modifier.wrapContentWidth(Alignment.End).weight(0.3f)
)
}
}
}
if (registerViewData.showDivider) {
Divider(
modifier =
modifier
.fillMaxHeight()
.padding(horizontal = 4.dp)
.width(1.dp)
.background(color = DividerColor)
)
}
Box(modifier = modifier.weight(0.25f), contentAlignment = Alignment.Center) {
if (registerViewData.showServiceButton) {
if (registerViewData.serviceButtonActionable) {
ServiceButton(
registerViewData = registerViewData,
modifier =
modifier
.wrapContentHeight(Alignment.CenterVertically)
.wrapContentWidth(Alignment.CenterHorizontally)
)
} else {
ServiceActionSection(
registerViewData = registerViewData,
modifier =
modifier.fillMaxHeight(0.6f).fillMaxWidth(0.9f).clip(RoundedCornerShape(4.dp))
)
}
}
}
}
}
@Composable
private fun ServiceButton(registerViewData: RegisterViewData, modifier: Modifier) {
val contentColor = remember { registerViewData.serviceButtonForegroundColor.copy(alpha = 0.85f) }
Row(
modifier =
modifier
.padding(horizontal = 8.dp)
.clip(RoundedCornerShape(8.dp))
.clickable { /*TODO Provide the given service*/}
.background(color = registerViewData.serviceButtonForegroundColor.copy(alpha = 0.1f)),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = null,
tint = contentColor,
modifier = modifier.size(16.dp).padding(horizontal = 1.dp)
)
Text(
text = registerViewData.serviceText ?: "",
color = contentColor,
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
modifier = modifier.padding(4.dp).wrapContentHeight(Alignment.CenterVertically),
overflow = TextOverflow.Visible,
maxLines = 1
)
}
}
@Composable
private fun RegisterListStatus(registerViewData: RegisterViewData, modifier: Modifier) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.padding(top = 4.dp),
) {
if (!registerViewData.status.isNullOrEmpty()) {
Text(
text = registerViewData.status,
color = DefaultColor,
modifier = modifier.wrapContentWidth(Alignment.Start)
)
}
if (!registerViewData.otherStatus.isNullOrEmpty()) {
Separator()
Text(
text = registerViewData.otherStatus,
color = DefaultColor,
modifier = modifier.wrapContentWidth(Alignment.Start)
)
}
}
}
@Composable
private fun ServiceActionSection(registerViewData: RegisterViewData, modifier: Modifier) {
if (registerViewData.serviceText != null && !registerViewData.serviceButtonActionable) {
if (registerViewData.borderedServiceButton) {
Box(modifier = modifier.background(registerViewData.serviceButtonBorderColor))
}
Column(
modifier =
modifier
.padding(if (registerViewData.borderedServiceButton) 1.4.dp else 0.dp)
.background(registerViewData.serviceButtonBackgroundColor),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
if (registerViewData.serviceTextIcon != null)
Icon(
painter = painterResource(id = registerViewData.serviceTextIcon),
contentDescription = null,
tint = registerViewData.serviceButtonForegroundColor
)
Text(
text = registerViewData.serviceText,
color = registerViewData.serviceButtonForegroundColor,
textAlign = TextAlign.Center
)
}
}
}
@Composable
private fun ServiceMemberIcons(registerViewData: RegisterViewData, modifier: Modifier) {
// Count member icons only show and display counter of the rest
val twoMemberIcons = remember { registerViewData.serviceMembers.take(2) }
if (!registerViewData.serviceButtonActionable) {
Row(modifier.padding(start = 4.dp)) {
twoMemberIcons.forEach {
if (it.icon != null)
Icon(
painter = painterResource(id = it.icon),
contentDescription = null,
modifier = modifier.size(20.dp).padding(0.dp),
tint = Color.Unspecified
)
}
if (twoMemberIcons.size == 2 && registerViewData.serviceMembers.size > 2) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier.clip(CircleShape).size(24.dp).background(DefaultColor.copy(0.1f))
) {
Text(
text = "+${registerViewData.serviceMembers.size - 2}",
fontSize = 12.sp,
color = Color.DarkGray
)
}
}
}
}
}
@Composable
@Preview(showBackground = true)
fun RegisterListRowForFamilyRegisterOverduePreview() {
RegisterListRow(
registerViewData =
RegisterViewData(
logicalId = "1234",
title = "<NAME>, Male, 40y",
subtitle = "#90129",
status = "Last visited on Thursday",
serviceText = "2",
serviceButtonBackgroundColor = OverdueColor,
serviceButtonForegroundColor = Color.White,
serviceButtonActionable = false,
showDivider = true,
serviceMembers =
listOf(
ServiceMember(R.drawable.ic_pregnant, "1920192"),
ServiceMember(R.drawable.ic_pregnant, "1920190"),
ServiceMember(R.drawable.ic_pregnant, "1920191"),
ServiceMember(R.drawable.ic_pregnant, "1920194")
)
),
onRowClick = {}
)
}
@Composable
@Preview(showBackground = true)
fun RegisterListRowForFamilyRegisterDuePreview() {
RegisterListRow(
registerViewData =
RegisterViewData(
logicalId = "1234",
title = "<NAME>, Male, 67y",
subtitle = "#90129",
status = "Last visited on 03-03-2022",
serviceText = "1",
serviceButtonActionable = false,
borderedServiceButton = true,
serviceButtonForegroundColor = InfoColor,
serviceButtonBorderColor = InfoColor,
showDivider = true,
),
onRowClick = {}
)
}
@Composable
@Preview(showBackground = true)
fun RegisterListRowForQuestRegisterPreview() {
RegisterListRow(
registerViewData =
RegisterViewData(logicalId = "1234", title = "<NAME>, 40y", subtitle = "Male"),
onRowClick = {}
)
}
@Composable
@Preview(showBackground = true)
fun RegisterListRowForRdtRegisterPreview() {
RegisterListRow(
registerViewData =
RegisterViewData(
logicalId = "1234",
title = "<NAME>, Female, 40y",
status = "Last test",
otherStatus = "04 Feb 2022"
),
onRowClick = {}
)
}
@Composable
@Preview(showBackground = true)
fun RegisterListRowForAncRegisterPreview() {
RegisterListRow(
registerViewData =
RegisterViewData(
logicalId = "121299",
title = "<NAME>, Female, 26Y",
status = "ID Number: 1929102",
otherStatus = "Kimulu village",
serviceButtonActionable = true,
serviceText = "ANC visit",
serviceButtonForegroundColor = InfoColor
),
onRowClick = {}
)
}
@Composable
@Preview(showBackground = true)
fun RegisterListRowForEirRegisterPreview() {
RegisterListRow(
registerViewData =
RegisterViewData(
logicalId = "1212299",
title = "<NAME>, Male, 26Y",
status = "Last test",
otherStatus = "04 Feb 2022",
serviceText = "Overdue",
serviceButtonForegroundColor = Color.White,
serviceButtonBackgroundColor = OverdueColor,
showDivider = true
),
onRowClick = {}
)
}
| 158 | Kotlin | 10 | 18 | 9d7044a12ef2726705a3019cb26ab03bc48bc28c | 12,309 | fhircore | Apache License 2.0 |
marketkit/src/main/java/io/horizontalsystems/marketkit/storage/TokenEntityDao.kt | horizontalsystems | 408,718,031 | false | {"Kotlin": 191982} | package io.horizontalsystems.marketkit.storage
import androidx.room.*
import io.horizontalsystems.marketkit.models.*
@Dao
interface TokenEntityDao {
@Query("SELECT * FROM TokenEntity")
fun getAll(): List<TokenEntity>
}
| 1 | Kotlin | 23 | 9 | 636ca4dc0ad54b16f913c287ac9ed302b8aff7fa | 231 | market-kit-android | MIT License |
app/src/main/java/com/lloyd/entersekt/data/models/cities/Shop.kt | doctorlloyd | 377,538,564 | false | null | package com.lloyd.entersekt.data.models.cities
import android.os.Parcelable
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import kotlinx.parcelize.Parcelize
@JsonClass(generateAdapter = true)
@Parcelize
data class Shop(
@Json(name = "id") val id: Int = 0,
@Json(name = "name") val name: String = ""
): Parcelable | 0 | Kotlin | 0 | 0 | cab67ecf4998c385e02ea9b084c2492fddc91fc2 | 343 | Entersekt | MIT License |
app/src/main/java/com/zachary_moore/moodlights/data/SpotifyFeature.kt | zsmoore | 355,370,229 | false | null | package com.zachary_moore.moodlights.data
import android.app.Activity
import android.app.AlertDialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.Transformations
import com.spotify.android.appremote.api.ConnectionParams
import com.spotify.android.appremote.api.Connector
import com.spotify.android.appremote.api.SpotifyAppRemote
import com.spotify.android.appremote.api.error.CouldNotFindSpotifyApp
import com.spotify.android.appremote.api.error.NotLoggedInException
import com.spotify.protocol.types.ImageUri
import com.spotify.protocol.types.Track
import com.zachary_moore.moodlights.BuildConfig
import com.zachary_moore.moodlights.R
class SpotifyFeature {
private val appRemote: MutableLiveData<SpotifyAppRemote> = MutableLiveData()
private val isPaused: MutableLiveData<Boolean> = MutableLiveData()
private val currentTrack: MutableLiveData<Track> = MutableLiveData()
private val currentPlayingAlbumBitmap: MutableLiveData<Bitmap> = MutableLiveData()
// Expose direct maps since they are immutable
private val currentPlayingAlbumImage = Transformations.distinctUntilChanged(
Transformations.map(currentTrack) {
it.imageUri
}
)
val currentTrackName = Transformations.distinctUntilChanged(
Transformations.map(currentTrack) {
it.name
}
)
val currentArtistName = Transformations.distinctUntilChanged(
Transformations.map(currentTrack) {
it.artist.name
}
)
val currentAlbumName = Transformations.distinctUntilChanged(
Transformations.map(currentTrack) {
it.album.name
}
)
private val connectionParams = ConnectionParams.Builder(BuildConfig.spotifyClientId)
.setRedirectUri(BuildConfig.spotifyRedirectUri)
.showAuthView(true)
.build()
private val appRemoteObserver: Observer<SpotifyAppRemote> = getSpotifyAppRemoteObserver()
private val currentAlbumImageObserver: Observer<ImageUri> =
getCurrentPlayingAlbumImageObserver()
init {
appRemote.observeForever(appRemoteObserver)
currentPlayingAlbumImage.observeForever(currentAlbumImageObserver)
}
fun cleanup() {
appRemote.removeObserver(appRemoteObserver)
currentPlayingAlbumImage.removeObserver(currentAlbumImageObserver)
}
fun isPaused(): LiveData<Boolean> = Transformations.distinctUntilChanged(isPaused)
fun currentPlayingAlbumImage(): LiveData<Bitmap> =
Transformations.distinctUntilChanged(currentPlayingAlbumBitmap)
/**
* Toggle pause / resume
*
* This method is assumed to be called after initial play instantiation and is not livedata
* aware
*/
fun togglePlay() {
isPaused.value?.let { isPausedValue ->
checkNotNull(appRemote.value) {
"Attempting to access AppRemote before it exists"
}.let { appRemote ->
if (isPausedValue) {
appRemote.playerApi.resume()
} else {
appRemote.playerApi.pause()
}
}
}
}
/**
* Start next song
*
* This method is assumed to be called after initial play instantiation and is not livedata
* aware
*/
fun next() {
checkNotNull(appRemote.value) {
"Attempting to access AppRemote before it exists"
}.playerApi.skipNext()
}
/**
* Start previous song
*
* This method is assumed to be called after initial play instantiation and is not livedata
* aware
*/
fun previous() {
checkNotNull(appRemote.value) {
"Attempting to access AppRemote before it exists"
}.playerApi.skipPrevious()
}
/**
* Initialize Spotify remote and setup connector callback
*/
fun initializeRemote(activity: Activity) {
SpotifyAppRemote.connect(
activity,
connectionParams,
object : Connector.ConnectionListener {
override fun onFailure(throwable: Throwable?) {
Log.e(
TAG,
throwable?.message,
throwable
)
handleSpotifyError(throwable, activity)
}
override fun onConnected(appRemote: SpotifyAppRemote) {
[email protected](appRemote)
}
}
)
}
fun disconnectRemote() {
appRemote.value?.let(SpotifyAppRemote::disconnect)
}
/**
* Observer for a [SpotifyAppRemote].
*
* This will subscribe to the spotify player api, and on state changed dispatch updates to
* [isPaused] for current pause state of user and [currentTrack] for the user's
* current playing track. This will trigger a bunch of side transformations to happen on
* chained livedatas
*/
private fun getSpotifyAppRemoteObserver() = Observer<SpotifyAppRemote> { appRemote ->
appRemote?.playerApi?.subscribeToPlayerState()?.setEventCallback { playerState ->
// We are on a background thread, need to post values
isPaused.postValue(playerState.isPaused)
playerState.track?.let { currentTrack.postValue(it) }
}
}
/**
* Observer for current playing album image.
*
* This will request down and get a bitmap based off of the uri.
*
* This function assumes app remote has a value rather than mediating with it
*/
private fun getCurrentPlayingAlbumImageObserver() =
Observer<ImageUri> { currentPlayingAlbumImage ->
checkNotNull(appRemote.value) {
"App remote doesn't exist after track found while trying to get bitmap for album image"
}.let {
it.imagesApi.getImage(currentPlayingAlbumImage).setResultCallback { resultBitmap ->
currentPlayingAlbumBitmap.postValue(resultBitmap)
}
}
}
companion object {
private const val TAG = "SpotifyFeature"
private const val appPackageName = "com.spotify.music"
private const val referrer =
"adjust_campaign=PACKAGE_NAME&adjust_tracker=ndjczk&utm_source=adjust_preinstall"
private fun promptSpotifyDownload(context: Context) {
try {
val uri: Uri = Uri.parse("market://details")
.buildUpon()
.appendQueryParameter("id", appPackageName)
.appendQueryParameter("referrer", referrer)
.build()
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
} catch (ignored: ActivityNotFoundException) {
val uri: Uri = Uri.parse("https://play.google.com/store/apps/details")
.buildUpon()
.appendQueryParameter("id", appPackageName)
.appendQueryParameter("referrer", referrer)
.build()
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
}
private fun launchSpotifyForLogin(context: Context) {
val uri: Uri = Uri.parse("spotify:")
.buildUpon()
.build()
context.startActivity(Intent(Intent.ACTION_VIEW, uri).apply {
putExtra(Intent.EXTRA_REFERRER, context.packageName)
})
}
private fun handleSpotifyError(
throwable: Throwable?,
activity: Activity
) {
when (throwable) {
is CouldNotFindSpotifyApp -> AlertDialog.Builder(activity)
.setTitle(R.string.moodlight_could_not_find_spotify_title)
.setMessage(R.string.moodlight_could_not_find_spotify_description)
.setPositiveButton(R.string.moodlight_could_not_find_spotify_go_to_download) { dialog, _ ->
dialog.dismiss()
promptSpotifyDownload(activity)
}
.setNegativeButton(R.string.moodlight_could_not_find_spotify_cancel) { dialog, _ ->
dialog.dismiss()
}
.show()
is NotLoggedInException -> AlertDialog.Builder(activity)
.setTitle(R.string.moodlight_spotify_login_fail_title)
.setMessage(R.string.moodlight_spotify_login_fail_description)
.setPositiveButton(R.string.moodlight_spotify_login_fail_launch_spotify) { dialog, _ ->
dialog.dismiss()
launchSpotifyForLogin(activity)
}
.setNegativeButton(R.string.moodlight_spotify_login_fail_cancel) { dialog, _ ->
dialog.dismiss()
}
.show()
}
}
}
} | 0 | Kotlin | 0 | 0 | 167530dd252f407da2caba66ef0fefc4ae71781c | 9,301 | MoodLights | Apache License 2.0 |
components/users/src/main/kotlin/io/barinek/continuum/users/UserRecord.kt | initialcapacity | 130,564,725 | false | {"Kotlin": 97259} | package io.barinek.continuum.users
data class UserRecord(val id: Long, val name: String) | 0 | Kotlin | 40 | 86 | c895096890c251b75d6f6f369890c89aaca83791 | 89 | application-continuum | Apache License 2.0 |
Lib/src/main/kotlin/screeps/api/Source.kt | P100sch | 189,650,418 | false | null | package screeps.api
abstract external class Source : RoomObjectNotNull, Harvestable, Identifiable {
val energy: Int
val energyCapacity: Int
} | 0 | Kotlin | 0 | 1 | 7b7992c316d8efe1bc9a48a474aa6b3d45d94bcf | 150 | screeps | MIT License |
core/src/main/java/com/hamster/core/inner/intercept/receive/impl/coroutine/CoroutineReceiverIntercept.kt | hamster-fly | 784,035,639 | false | {"Kotlin": 43537, "Java": 8276} | package com.hamster.core.inner.intercept.receive.impl.coroutine
import com.hamster.core.inner.intercept.receive.base.IReceiver
import com.hamster.core.inner.intercept.receive.protol.IReceiveIntercept
/**
* 协程包装拦截器
*/
internal class CoroutineReceiverIntercept<T> : IReceiveIntercept<T> {
override fun intercept(chain: IReceiveIntercept.IReceiverChain<T?>) : IReceiver<T?> {
val content = chain.getChainContent()
val proxy = ReceiverCoroutineProxy(content)
return chain.process(proxy)
}
} | 0 | Kotlin | 0 | 0 | 7a5d7ddedd9358851772773998d546b252328347 | 524 | CorBus | Apache License 2.0 |
lbcglance/src/main/kotlin/studio/lunabee/compose/glance/ui/GlanceTypefaceButton.kt | LunabeeStudio | 472,673,596 | false | {"Kotlin": 243135, "Java": 161408, "Python": 4873} | /*
* Copyright (c) 2024 Lunabee Studio
*
* 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.
*
* GlanceText.kt
* Lunabee Compose
*
* Created by Lunabee Studio / Date - 8/9/2024 - for the Lunabee Compose library.
*/
package studio.lunabee.compose.glance.ui
import android.graphics.Typeface
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
import androidx.glance.GlanceModifier
import androidx.glance.action.Action
import androidx.glance.action.clickable
import androidx.glance.layout.Alignment
import androidx.glance.layout.Box
import androidx.glance.layout.fillMaxWidth
import androidx.glance.text.TextAlign
/**
* Display a button with a custom font in a Glance widget.
* Custom font are not supported in a widget (even with the "old" XML API), so we need to draw the text and display an image instead.
* DO NOT USE [GlanceTypefaceButton] if you have a simple text without specific font to display, it will be a little over-kill!
*/
@Composable
fun GlanceTypefaceButton(
text: String,
color: Color,
fontSize: TextUnit,
typeface: Typeface,
action: Action,
modifier: GlanceModifier = GlanceModifier,
textAlign: TextAlign = TextAlign.Center,
letterSpacing: TextUnit = 0.sp,
lineHeight: TextUnit = 0.sp,
) {
Box(
modifier = modifier
.clickable(onClick = action),
contentAlignment = Alignment.Center,
) {
GlanceTypefaceText(
text = text,
color = color,
fontSize = fontSize,
typeface = typeface,
modifier = GlanceModifier
.fillMaxWidth(),
textAlign = textAlign,
letterSpacing = letterSpacing,
lineHeight = lineHeight,
)
}
}
| 0 | Kotlin | 0 | 10 | fc072c1ef6f67c83909352ce7660ec994bc13ec6 | 2,350 | Lunabee_Compose_Android | Apache License 2.0 |
app/src/main/java/edu/uw/acevedoj/sos/PlaceJSONParser.kt | amjadz | 161,661,449 | false | {"Kotlin": 63090} | package edu.uw.acevedoj.sos
import java.util.ArrayList
import java.util.HashMap
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
// Helper library that takes in a jsonobject formatted in
// google maps places that is then turned into a parcelable list
class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
fun parse(jObject: JSONObject): List<HashMap<String, String>> {
var jPlaces: JSONArray? = null
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results")
} catch (e: JSONException) {
e.printStackTrace()
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces!!)
}
private fun getPlaces(jPlaces: JSONArray): List<HashMap<String, String>> {
val placesCount = jPlaces.length()
val placesList = ArrayList<HashMap<String, String>>()
var place: HashMap<String, String>? = null
/** Taking each place, parses and adds to list object */
for (i in 0 until placesCount) {
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace(jPlaces.get(i) as JSONObject)
placesList.add(place)
} catch (e: JSONException) {
e.printStackTrace()
}
}
return placesList
}
/** Parsing the Place JSON object */
private fun getPlace(jPlace: JSONObject): HashMap<String, String> {
val place = HashMap<String, String>()
var placeName = "-NA-"
var vicinity = "-NA-"
var latitude = ""
var longitude = ""
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name")
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity")
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat")
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng")
place["place_name"] = placeName
place["vicinity"] = vicinity
place["lat"] = latitude
place["lng"] = longitude
} catch (e: JSONException) {
e.printStackTrace()
}
return place
}
} | 0 | Kotlin | 0 | 0 | b6092a1083f856828a20347f1543b8fc26f6a938 | 2,629 | SOS | MIT License |
auto-pipeline-examples/src/test/java/com/foldright/examples/grpc/pipeline/ChannelTest.kt | foldright | 439,208,400 | false | {"Kotlin": 39007, "Java": 17006, "Shell": 3973} | package com.foldright.examples.grpc.pipeline
import com.foldright.examples.grpc.CallOptions
import com.foldright.examples.grpc.ClientCall
import com.foldright.examples.grpc.MethodDescriptor
import com.foldright.examples.grpc.handler.DefaultChannelHandler
import com.foldright.examples.grpc.handler.TransformClientCallChannelHandler
import com.foldright.examples.grpc.handler.TransformClientCallChannelHandler.ClientCallWrapper
import com.foldright.examples.grpc.handler.WrapCallOptionsChannelHandler
import com.foldright.examples.grpc.handler.WrapCallOptionsChannelHandler.CallOptionsWrapper
import io.kotest.core.spec.style.AnnotationSpec
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.types.shouldBeTypeOf
class ChannelTest : AnnotationSpec() {
private lateinit var pipeline: ChannelPipeline
@Test
fun testNoneHandler() {
pipeline = ChannelPipeline()
val newCall = pipeline.newCall(
MethodDescriptor<String, String>("fullMethodName", "serviceName"),
CallOptions()
)
newCall.shouldBeNull()
}
@Test
fun testDefaultHandler() {
pipeline = ChannelPipeline()
.addLast(DefaultChannelHandler())
val newCall = pipeline.newCall(
MethodDescriptor<String, String>("fullMethodName", "serviceName"),
CallOptions()
)
newCall.shouldBeTypeOf<ClientCall<*, *>>()
}
@Test
fun testWrapperCallOptionsHandler() {
pipeline = ChannelPipeline()
.addLast(WrapCallOptionsChannelHandler())
.addLast(DefaultChannelHandler())
val newCall = pipeline.newCall(
MethodDescriptor<String, String>("fullMethodName", "serviceName"),
CallOptions()
)
newCall.callOptions.shouldBeTypeOf<CallOptionsWrapper>()
}
@Test
fun testTransformClientCallHandler() {
pipeline = ChannelPipeline()
.addLast(WrapCallOptionsChannelHandler())
.addLast(TransformClientCallChannelHandler())
.addLast(DefaultChannelHandler())
val newCall = pipeline.newCall(
MethodDescriptor<String, String>("fullMethodName", "serviceName"),
CallOptions()
)
newCall.shouldBeTypeOf<ClientCallWrapper<*, *>>()
}
}
| 8 | Kotlin | 31 | 142 | 5b7298553a09a2886256e3b2f59b928f30dd3325 | 2,325 | auto-pipeline | Apache License 2.0 |
crabzilla-core/src/main/java/io/github/crabzilla/core/crabzilla.kt | lukehuang | 131,502,776 | true | {"Kotlin": 103927, "Java": 65276, "Shell": 4897} | package io.github.crabzilla.core
import java.io.Serializable
import java.util.*
interface Entity : Serializable {
val id: EntityId
}
class CommandResult private constructor(val unitOfWork: UnitOfWork?,
val exception: Exception?) {
fun inCaseOfSuccess(uowFn: (UnitOfWork?) -> Unit) {
if (unitOfWork != null) {
uowFn.invoke(unitOfWork)
}
}
fun inCaseOfError(uowFn: (Exception) -> Unit) {
if (exception != null) {
uowFn.invoke(exception)
}
}
companion object {
fun success(uow: UnitOfWork?): CommandResult {
return CommandResult(uow, null)
}
fun error(e: Exception): CommandResult {
return CommandResult(null, e)
}
}
}
// command handling helper functions
fun resultOf(f: () -> UnitOfWork?): CommandResult {
return try {
CommandResult.success(f.invoke()) }
catch (e: Exception) {
CommandResult.error(e) }
}
fun uowOf(command: Command, events: List<DomainEvent>, currentVersion: Version): UnitOfWork {
return UnitOfWork(UUID.randomUUID(), command, currentVersion +1, events)
}
fun eventsOf(vararg event: DomainEvent): List<DomainEvent> {
return event.asList()
}
| 0 | Kotlin | 0 | 0 | d9f6123411c2b4ea03912c0d709d323cbb078a4c | 1,198 | crabzilla | Apache License 2.0 |
app/src/main/java/com/ohuji/cardsNmonsters/database/dao/CardsNDeckDao.kt | ohuji | 598,587,284 | false | null | package com.ohuji.cardsNmonsters.database.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.ohuji.cardsNmonsters.database.entities.Card
import com.ohuji.cardsNmonsters.database.CardNDeckCrossRef
import com.ohuji.cardsNmonsters.database.Deck
import com.ohuji.cardsNmonsters.database.FullDeck
@Dao
interface CardsNDeckDao {
// Card related
@Insert
fun addCard(vararg card: Card)
@Delete
fun deleteCard(vararg card: Card)
@Query("select * from Card")
fun getAllCards(): LiveData<List<Card>>
@Update
fun updateCard(card: Card)
// Deck related
@Query("SELECT * FROM Deck WHERE deckId = :deckId")
fun findDeckById(deckId: Long): LiveData<Deck>
@Query("SELECT * FROM Card WHERE cardId = :cardId")
fun findCardById(cardId: Long): LiveData<Card>
@Insert
fun addDeck(vararg deck: Deck)
@Delete
fun deleteDeck(deck: Deck)
@Query("DELETE FROM Deck WHERE deckId = :deckId")
fun deleteFullDeckById(deckId: Long)
@Query("select * from Deck")
fun getAllDecks(): LiveData<List<Deck>>
// Full deck related
@Insert
fun addCardToDeck(cardNDeckCrossRef: CardNDeckCrossRef)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun addCardNDeckCrossRefs(vararg cardNDeckCrossRef: CardNDeckCrossRef)
@Transaction
@Query("SELECT * FROM Deck")
fun getFullDeck(): LiveData<List<FullDeck>>
@Transaction
@Query("SELECT * FROM Deck WHERE deckId = :deckId")
fun getDeckWithCard(deckId: Long): LiveData<FullDeck>
} | 0 | Kotlin | 1 | 3 | 41f7c3e794d73b28582e3d0fde36f353083003ef | 1,735 | Cards-Monsters | MIT License |
ae-backend/src/main/java/eu/automateeverything/rest/instances/InstancesController.kt | tomaszbabiuk | 488,678,209 | false | {"Kotlin": 498866, "Vue": 138384, "JavaScript": 51377, "HTML": 795} | /*
* 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.rest.instances
import eu.automateeverything.data.Repository
import eu.automateeverything.data.instances.InstanceDto
import eu.automateeverything.domain.extensibility.PluginsCoordinator
import eu.automateeverything.rest.settings.ValidationResultMap
import eu.automateeverything.domain.configurable.ConfigurableWithFields
import eu.automateeverything.domain.configurable.FieldValidationResult
import eu.automateeverything.domain.dependencies.DependencyChecker
import jakarta.inject.Inject
import jakarta.ws.rs.*
import jakarta.ws.rs.core.MediaType
import kotlin.collections.HashMap
@Path("instances")
class InstancesController @Inject constructor(
private val pluginsCoordinator: PluginsCoordinator,
private val repository: Repository,
private val dependencyChecker: DependencyChecker
) {
private fun findConfigurable(clazz: String): ConfigurableWithFields? {
return pluginsCoordinator
.configurables
.filter { x -> x.javaClass.name.equals(clazz) }
.filterIsInstance<ConfigurableWithFields>()
.firstOrNull()
}
@POST
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Throws(Exception::class)
fun postInstances(instanceDto: InstanceDto): ValidationResultMap {
return validate(instanceDto) {
repository.saveInstance(instanceDto)
}
}
@PUT
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Throws(Exception::class)
fun putInstances(instanceDto: InstanceDto): ValidationResultMap {
return validate(instanceDto) {
repository.updateInstance(instanceDto)
}
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
fun getInstancesById(@PathParam("id") id: Long): InstanceDto {
return repository.getInstance(id)
}
@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
fun getInstances(@QueryParam("class") clazz: String?): List<InstanceDto> {
return if (clazz != null) {
repository.getInstancesOfClazz(clazz)
} else {
return repository.getAllInstances()
}
}
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
fun deleteInstance(@PathParam("id") id: Long): List<Long> {
val dependencies = dependencyChecker.checkInstance(id)
return if (dependencies.size > 0) {
val toRemove = dependencies.values.map { it.id } + listOf(id)
repository.deleteInstances(toRemove)
toRemove
} else {
repository.deleteInstance(id)
listOf(id)
}
}
private fun validate(instanceDto: InstanceDto, onValidCallback: () -> Unit):
MutableMap<String, FieldValidationResult> {
val configurable = findConfigurable(instanceDto.clazz)
return if (configurable != null) {
val validationResult: MutableMap<String, FieldValidationResult> = HashMap()
var isObjectValid = true
for (fieldDefinition in configurable.fieldDefinitions.values) {
val fieldValue = instanceDto.fields[fieldDefinition.name]
val isValid = fieldDefinition.validate(fieldValue, instanceDto.fields)
validationResult[fieldDefinition.name] = isValid
if (!isValid.valid) {
isObjectValid = false
}
}
if (isObjectValid) {
onValidCallback()
}
validationResult
} else {
throw Exception("Unsupported configurable class")
}
}
}
| 0 | Kotlin | 1 | 0 | 6508322d8b83553e18bdde8a3ebe7c0a37aed744 | 4,289 | automate-everything | Apache License 2.0 |
ospf-kotlin-utils/src/main/fuookami/ospf/kotlin/utils/parallel/FirstNotNullOfOrNull.kt | fuookami | 359,831,793 | false | {"Kotlin": 1866628, "Python": 6629} | package fuookami.ospf.kotlin.utils.parallel
import kotlinx.coroutines.*
import fuookami.ospf.kotlin.utils.math.*
import fuookami.ospf.kotlin.utils.error.*
import fuookami.ospf.kotlin.utils.functional.*
suspend inline fun <R, T> Iterable<T>.firstNotNullOfOrNullParallelly(
crossinline extractor: SuspendExtractor<R?, T>
): R? {
return this.firstNotNullOfOrNullParallelly(UInt64(Runtime.getRuntime().availableProcessors()), extractor)
}
suspend inline fun <R, T> Iterable<T>.firstNotNullOfOrNullParallelly(
concurrentAmount: UInt64,
crossinline extractor: SuspendExtractor<R?, T>
): R? {
var result: R? = null
return try {
coroutineScope {
val iterator = [email protected]()
while (iterator.hasNext()) {
val promises = ArrayList<Deferred<R?>>()
for (j in UInt64.zero until concurrentAmount) {
val v = iterator.next()
promises.add(async(Dispatchers.Default) {
extractor(v)
})
if (!iterator.hasNext()) {
break
}
}
for (promise in promises) {
result = promise.await()
if (result != null) {
cancel()
return@coroutineScope result
}
}
}
null
}
} catch (e: CancellationException) {
result
}
}
suspend inline fun <R, T> Iterable<T>.tryFirstNotNullOfOrNullParallelly(
crossinline extractor: SuspendTryExtractor<R?, T>
): Ret<R?> {
return this.tryFirstNotNullOfOrNullParallelly(UInt64(Runtime.getRuntime().availableProcessors()), extractor)
}
suspend inline fun <R, T> Iterable<T>.tryFirstNotNullOfOrNullParallelly(
concurrentAmount: UInt64,
crossinline extractor: SuspendTryExtractor<R?, T>
): Ret<R?> {
var result: R? = null
var error: Error? = null
return try {
coroutineScope {
val iterator = [email protected]()
while (iterator.hasNext()) {
val promises = ArrayList<Deferred<R?>>()
for (j in UInt64.zero until concurrentAmount) {
val v = iterator.next()
promises.add(async(Dispatchers.Default) {
when (val ret = extractor(v)) {
is Ok -> {
ret.value
}
is Failed -> {
error = ret.error
cancel()
null
}
}
})
if (!iterator.hasNext()) {
break
}
}
for (promise in promises) {
result = promise.await()
if (result != null) {
cancel()
return@coroutineScope result
}
}
}
null
}.let { Ok(it) }
} catch (e: CancellationException) {
result?.let { Ok(it) }
?: error?.let { Failed(it) }
?: Ok(null)
}
}
| 0 | Kotlin | 0 | 1 | a3cff7b2702baba923fcb0fa4a82ed4b84e3a0ff | 3,422 | ospf-kotlin | Apache License 2.0 |
nbridgekit/src/main/java/com/ntoworks/nbridgekit/view/common/DefaultDialogHandler.kt | samse | 494,270,806 | false | null | package com.ntoworks.nbridgekit.view.common
import android.R
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.webkit.JsResult
import android.webkit.WebView
class DefaultDialogHandler(val context: Context) : DialogHandler {
var mAlertDialog: AlertDialog? = null
override fun onJsAlert(
view: WebView?,
url: String?,
message: String?,
result: JsResult?
): Boolean {
if (mAlertDialog == null) {
mAlertDialog = AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton(R.string.ok, object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
result!!.confirm()
mAlertDialog?.dismiss()
mAlertDialog = null
}
})
.setCancelable(false)
.create()
}
mAlertDialog?.show()
return true
}
override fun onJsConfirm(
view: WebView?,
url: String?,
message: String?,
result: JsResult?
): Boolean {
if (mAlertDialog == null) {
mAlertDialog = AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton(R.string.ok, object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
result!!.confirm()
mAlertDialog?.dismiss()
mAlertDialog = null
}
})
.setNegativeButton(R.string.cancel, object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
result!!.cancel()
mAlertDialog?.dismiss()
mAlertDialog = null
}
})
.setCancelable(false)
.create()
}
mAlertDialog?.show()
return true
}
} | 0 | Kotlin | 0 | 0 | d58c768cf615b06942b33c894b697ea3933f18cd | 2,186 | NBridgeKit | MIT License |
generators/src/org/jetbrains/android/generator/test/TestGenerator.kt | leomindez | 32,422,065 | true | {"Kotlin": 601898, "Java": 5756, "Shell": 344, "HTML": 97} | package org.jetbrains.android.generator.test
import java.io.File
import org.jetbrains.android.dsl.KoanFile
import org.jetbrains.android.dsl.ConfigurationTune
import org.jetbrains.android.dsl.utils.Buffer
public fun Context.generate() {
functionalTest("ComplexListenerClassTest", KoanFile.LISTENERS) {
file(KoanFile.LISTENERS)
tune(ConfigurationTune.COMPLEX_LISTENER_CLASSES)
}
functionalTest("ComplexListenerSetterTest", KoanFile.LISTENERS) {
file(KoanFile.LISTENERS)
tune(ConfigurationTune.COMPLEX_LISTENER_SETTERS)
}
functionalTest("HelperConstructorTest", KoanFile.VIEWS) {
tune(ConfigurationTune.HELPER_CONSTRUCTORS)
}
functionalTest("LayoutsTest", KoanFile.LAYOUTS) {
file(KoanFile.LAYOUTS)
}
functionalTest("ViewTest", KoanFile.VIEWS) {
file(KoanFile.VIEWS)
tune(ConfigurationTune.TOP_LEVEL_DSL_ITEMS)
}
functionalTest("PropertyTest", KoanFile.PROPERTIES) {
file(KoanFile.PROPERTIES)
}
functionalTest("ServicesTest", KoanFile.SERVICES) {
file(KoanFile.SERVICES)
}
functionalTest("SimpleListenerTest", KoanFile.LISTENERS) {
file(KoanFile.LISTENERS)
tune(ConfigurationTune.SIMPLE_LISTENERS)
}
compileTests(ktFiles("robolectric"), "Robolectric")
compileTests(ktFiles("compile"), "Compile")
}
private fun ktFiles(category: String) = File("testData/$category")
.listFiles { it.name.endsWith(".kt") }?.map { it.name.replace(".kt", "") } ?: listOf() | 0 | Kotlin | 0 | 0 | a07d3ccefabcb3234d9a047fd988989203bff69b | 1,537 | koan | Apache License 2.0 |
lib/src/main/java/com/github/eklipse2k8/charting/highlight/HorizontalBarHighlighter.kt | eklipse2k8 | 403,391,938 | true | {"Kotlin": 945921, "Java": 57298} | package com.github.eklipse2k8.charting.highlight
import com.github.eklipse2k8.charting.data.Rounding
import com.github.eklipse2k8.charting.interfaces.dataprovider.BarDataProvider
import com.github.eklipse2k8.charting.interfaces.datasets.IDataSet
import com.github.eklipse2k8.charting.utils.MPPointD
import java.util.ArrayList
import kotlin.math.abs
/** Created by <NAME> on 22/07/15. */
class HorizontalBarHighlighter(chart: BarDataProvider) : BarHighlighter(chart) {
override fun getHighlight(x: Float, y: Float): Highlight? {
val barData = chartView.barData
val pos = getValsForTouch(y, x)
val high = getHighlightForX(pos.y.toFloat(), y, x) ?: return null
val set = barData?.getDataSetByIndex(high.dataSetIndex)
if (set?.isStacked == true) {
return getStackedHighlight(high, set, pos.y.toFloat(), pos.x.toFloat())
}
MPPointD.recycleInstance(pos)
return high
}
override fun buildHighlights(
set: IDataSet<*>,
dataSetIndex: Int,
xVal: Float,
rounding: Rounding?
): List<Highlight>? {
val highlights = ArrayList<Highlight>()
var entries = set.getEntriesForXValue(xVal)
if (entries?.size == 0) {
// Try to find closest x-value and take all entries for that x-value
val closest = set.getEntryForXValue(xVal, Float.NaN, rounding)
entries = closest?.let { set.getEntriesForXValue(it.x) }
}
if (entries.isNullOrEmpty()) return highlights
for (e in entries) {
val pixels = chartView.getTransformer(set.axisDependency).getPixelForValues(e.y, e.x)
highlights.add(
Highlight(
e.x, e.y, pixels.x.toFloat(), pixels.y.toFloat(), dataSetIndex, set.axisDependency))
}
return highlights
}
override fun getDistance(x1: Float, y1: Float, x2: Float, y2: Float): Float {
return abs(y1 - y2)
}
}
| 0 | Kotlin | 0 | 0 | 29d416f36d7fd1b6af13082c2ef6b7d6abe0cab8 | 1,845 | ComposeChart | Apache License 2.0 |
app/src/main/java/spam/blocker/ui/history/HistoryFabs.kt | aj3423 | 783,998,987 | false | {"Kotlin": 382407, "Go": 6080} | package spam.blocker.ui.history
import androidx.compose.foundation.layout.width
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import spam.blocker.G
import spam.blocker.R
import spam.blocker.def.Def
import spam.blocker.service.CleanerSchedule
import spam.blocker.ui.M
import spam.blocker.ui.setting.LabeledRow
import spam.blocker.ui.theme.LocalPalette
import spam.blocker.ui.theme.Salmon
import spam.blocker.ui.theme.SkyBlue
import spam.blocker.ui.widgets.BalloonQuestionMark
import spam.blocker.ui.widgets.Fab
import spam.blocker.ui.widgets.GreyLabel
import spam.blocker.ui.widgets.NumberInputBox
import spam.blocker.ui.widgets.PopupDialog
import spam.blocker.ui.widgets.PopupSize
import spam.blocker.ui.widgets.RowVCenterSpaced
import spam.blocker.ui.widgets.Str
import spam.blocker.ui.widgets.StrokeButton
import spam.blocker.ui.widgets.SwitchBox
import spam.blocker.util.SharedPref.HistoryOptions
@Composable
fun HistoryFabs(
modifier: Modifier,
visible: Boolean,
forType: Int,
) {
val ctx = LocalContext.current
val spf = HistoryOptions(ctx)
var showPassed by rememberSaveable { mutableStateOf(spf.getShowPassed()) }
var showBlocked by rememberSaveable { mutableStateOf(spf.getShowBlocked()) }
var historyTTL by rememberSaveable { mutableIntStateOf(spf.getHistoryTTL()) }
var logSmsContent by rememberSaveable { mutableStateOf(spf.isLogSmsContentEnabled()) }
val settingPopupTrigger = rememberSaveable { mutableStateOf(false) }
fun reloadVM() {
if (forType == Def.ForNumber)
G.callVM.reload(ctx)
else
G.smsVM.reload(ctx)
}
PopupDialog(
trigger = settingPopupTrigger,
popupSize = PopupSize(percentage = 0.8f, minWidth = 340, maxWidth = 500),
content = {
// TTL
LabeledRow(
labelId = R.string.expire,
helpTooltipId = R.string.help_history_ttl
) {
NumberInputBox(
intValue = historyTTL,
onValueChange = { newValue, hasError ->
if (!hasError) {
historyTTL = newValue!!
spf.setHistoryTTL(newValue)
CleanerSchedule.cancelPrevious(ctx)
if (newValue > 0) {
CleanerSchedule.scheduleNext(ctx)
} else if (newValue == 0) {
// it will not record data, no need to cleanup
} else {
// it will record data, but it will never expire, no need to cleanup
}
}
},
label = { Text(Str(R.string.days)) },
leadingIconId = R.drawable.ic_recycle_bin,
)
}
// Log SMS Content
if (forType == Def.ForSms) {
LabeledRow(
labelId = R.string.log_sms_content,
helpTooltipId = R.string.help_log_sms_content
) {
SwitchBox(checked = logSmsContent, onCheckedChange = { isTurningOn ->
logSmsContent = isTurningOn
spf.setLogSmsContentEnabled(isTurningOn)
})
}
}
HorizontalDivider(thickness = 1.dp, color = LocalPalette.current.disabled)
LabeledRow(labelId = R.string.show_passed) {
SwitchBox(checked = showPassed, onCheckedChange = { isOn ->
showPassed = isOn
spf.setShowPassed(isOn)
reloadVM()
})
}
LabeledRow(labelId = R.string.show_blocked) {
SwitchBox(checked = showBlocked, onCheckedChange = { isOn ->
showBlocked = isOn
spf.setShowBlocked(isOn)
reloadVM()
})
}
})
RowVCenterSpaced(space = 8, modifier = modifier) {
Fab(
visible = visible,
iconId = R.drawable.ic_display_filter,
bgColor = SkyBlue
) {
settingPopupTrigger.value = true
}
// Delete all
val deleteConfirm = remember { mutableStateOf(false) }
PopupDialog(
trigger = deleteConfirm,
buttons = {
StrokeButton(label = Str(R.string.delete), color = Salmon) {
deleteConfirm.value = false
when (forType) {
Def.ForNumber -> {
G.callVM.table.clearAll(ctx)
G.callVM.records.clear()
}
Def.ForSms -> {
G.smsVM.table.clearAll(ctx)
G.smsVM.records.clear()
}
}
}
}
) {
GreyLabel(Str(R.string.confirm_delete_all_records))
}
Fab(
visible = visible,
iconId = R.drawable.ic_recycle_bin,
bgColor = Salmon
) {
deleteConfirm.value = true
}
}
}
| 2 | Kotlin | 18 | 357 | 9a650076aa485bee8bb99653f3d7256b02ec8488 | 5,820 | SpamBlocker | MIT License |
app/src/main/java/spam/blocker/ui/history/HistoryFabs.kt | aj3423 | 783,998,987 | false | {"Kotlin": 382407, "Go": 6080} | package spam.blocker.ui.history
import androidx.compose.foundation.layout.width
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import spam.blocker.G
import spam.blocker.R
import spam.blocker.def.Def
import spam.blocker.service.CleanerSchedule
import spam.blocker.ui.M
import spam.blocker.ui.setting.LabeledRow
import spam.blocker.ui.theme.LocalPalette
import spam.blocker.ui.theme.Salmon
import spam.blocker.ui.theme.SkyBlue
import spam.blocker.ui.widgets.BalloonQuestionMark
import spam.blocker.ui.widgets.Fab
import spam.blocker.ui.widgets.GreyLabel
import spam.blocker.ui.widgets.NumberInputBox
import spam.blocker.ui.widgets.PopupDialog
import spam.blocker.ui.widgets.PopupSize
import spam.blocker.ui.widgets.RowVCenterSpaced
import spam.blocker.ui.widgets.Str
import spam.blocker.ui.widgets.StrokeButton
import spam.blocker.ui.widgets.SwitchBox
import spam.blocker.util.SharedPref.HistoryOptions
@Composable
fun HistoryFabs(
modifier: Modifier,
visible: Boolean,
forType: Int,
) {
val ctx = LocalContext.current
val spf = HistoryOptions(ctx)
var showPassed by rememberSaveable { mutableStateOf(spf.getShowPassed()) }
var showBlocked by rememberSaveable { mutableStateOf(spf.getShowBlocked()) }
var historyTTL by rememberSaveable { mutableIntStateOf(spf.getHistoryTTL()) }
var logSmsContent by rememberSaveable { mutableStateOf(spf.isLogSmsContentEnabled()) }
val settingPopupTrigger = rememberSaveable { mutableStateOf(false) }
fun reloadVM() {
if (forType == Def.ForNumber)
G.callVM.reload(ctx)
else
G.smsVM.reload(ctx)
}
PopupDialog(
trigger = settingPopupTrigger,
popupSize = PopupSize(percentage = 0.8f, minWidth = 340, maxWidth = 500),
content = {
// TTL
LabeledRow(
labelId = R.string.expire,
helpTooltipId = R.string.help_history_ttl
) {
NumberInputBox(
intValue = historyTTL,
onValueChange = { newValue, hasError ->
if (!hasError) {
historyTTL = newValue!!
spf.setHistoryTTL(newValue)
CleanerSchedule.cancelPrevious(ctx)
if (newValue > 0) {
CleanerSchedule.scheduleNext(ctx)
} else if (newValue == 0) {
// it will not record data, no need to cleanup
} else {
// it will record data, but it will never expire, no need to cleanup
}
}
},
label = { Text(Str(R.string.days)) },
leadingIconId = R.drawable.ic_recycle_bin,
)
}
// Log SMS Content
if (forType == Def.ForSms) {
LabeledRow(
labelId = R.string.log_sms_content,
helpTooltipId = R.string.help_log_sms_content
) {
SwitchBox(checked = logSmsContent, onCheckedChange = { isTurningOn ->
logSmsContent = isTurningOn
spf.setLogSmsContentEnabled(isTurningOn)
})
}
}
HorizontalDivider(thickness = 1.dp, color = LocalPalette.current.disabled)
LabeledRow(labelId = R.string.show_passed) {
SwitchBox(checked = showPassed, onCheckedChange = { isOn ->
showPassed = isOn
spf.setShowPassed(isOn)
reloadVM()
})
}
LabeledRow(labelId = R.string.show_blocked) {
SwitchBox(checked = showBlocked, onCheckedChange = { isOn ->
showBlocked = isOn
spf.setShowBlocked(isOn)
reloadVM()
})
}
})
RowVCenterSpaced(space = 8, modifier = modifier) {
Fab(
visible = visible,
iconId = R.drawable.ic_display_filter,
bgColor = SkyBlue
) {
settingPopupTrigger.value = true
}
// Delete all
val deleteConfirm = remember { mutableStateOf(false) }
PopupDialog(
trigger = deleteConfirm,
buttons = {
StrokeButton(label = Str(R.string.delete), color = Salmon) {
deleteConfirm.value = false
when (forType) {
Def.ForNumber -> {
G.callVM.table.clearAll(ctx)
G.callVM.records.clear()
}
Def.ForSms -> {
G.smsVM.table.clearAll(ctx)
G.smsVM.records.clear()
}
}
}
}
) {
GreyLabel(Str(R.string.confirm_delete_all_records))
}
Fab(
visible = visible,
iconId = R.drawable.ic_recycle_bin,
bgColor = Salmon
) {
deleteConfirm.value = true
}
}
}
| 2 | Kotlin | 18 | 357 | 9a650076aa485bee8bb99653f3d7256b02ec8488 | 5,820 | SpamBlocker | MIT License |
e6/movies/core/domain/src/main/java/ven/movies/core/domain/model/DummyMovies.kt | ernestosimionato6 | 584,044,832 | false | null | package ven.movies.core
import ven.movies.core.domain.model.Movie
import kotlin.Float.Companion
object DummyMovies {
fun getDomainMovies() = arrayListOf(
Movie(
0,
"The last us",
"",
"/last_us.png",
9.0f,
vote_average = 5.0f,
vote_count = 200
),
Movie(
0,
"Lord of rings",
"",
"/lord_rings.png",
9.5f,
vote_average = 9.8f,
vote_count = 1500
)
)
}
| 4 | Kotlin | 0 | 0 | 21b39b4b9dbd4273853fc3954f1f1fdafa056281 | 560 | e6-canasta | Apache License 2.0 |
src/example/kotlin/io/github/xstefanox/underkow/example/Utils.kt | xstefanox | 153,483,798 | false | null | package io.github.xstefanox.underkow.example
import io.undertow.server.HttpServerExchange
import io.undertow.util.AttachmentKey
import io.undertow.util.HttpString
import io.undertow.util.PathTemplateMatch
import kotlinx.serialization.ImplicitReflectionSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonConfiguration
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.contextual
import kotlinx.serialization.serializer
internal val CONTENT_TYPE = HttpString("Content-Type")
internal const val APPLICATION_JSON = "application/json"
internal val REQUEST_ID = AttachmentKey.create(RequestId::class.java)
internal val KOTLINX_JSON = Json(JsonConfiguration.Stable.copy(strictMode = false), SerializersModule {
contextual(PetIdSerializer)
})
internal fun String.toPetId(): PetId = PetId(this)
internal val HttpServerExchange.petId: PetId
get() = (getAttachment<PathTemplateMatch>(PathTemplateMatch.ATTACHMENT_KEY).parameters["id"]
?: throw RuntimeException()).toPetId()
internal fun HttpServerExchange.send(statusCode: Int) {
this.statusCode = statusCode
}
@UseExperimental(ImplicitReflectionSerializer::class)
internal inline fun <reified T : @Serializable Any> HttpServerExchange.send(statusCode: Int, body: T) {
this.statusCode = statusCode
this.responseHeaders.add(CONTENT_TYPE, APPLICATION_JSON)
this.responseSender.send(KOTLINX_JSON.stringify(T::class.serializer(), body))
}
@UseExperimental(ImplicitReflectionSerializer::class)
internal inline fun <reified T : Any> HttpServerExchange.send(statusCode: Int, body: CollectionResponse<T>) {
this.statusCode = statusCode
this.responseHeaders.add(CONTENT_TYPE, APPLICATION_JSON)
this.responseSender.send(KOTLINX_JSON.stringify(CollectionResponse.serializer(T::class.serializer()), body))
}
| 1 | Kotlin | 1 | 2 | c66269878122621f0b7533e4e036657997118076 | 1,910 | underkow | MIT License |
app/src/main/java/com/active/orbit/baseapp/core/database/tables/TableSeverities.kt | oakgroup | 629,001,920 | false | {"Kotlin": 504427} | package com.active.orbit.baseapp.core.database.tables
import android.content.Context
import androidx.annotation.WorkerThread
import com.active.orbit.baseapp.core.database.engine.Database
import com.active.orbit.baseapp.core.database.models.DBSeverity
import com.active.orbit.baseapp.core.utils.Logger
object TableSeverities {
@WorkerThread
fun getAll(context: Context, idSymptom: String): List<DBSeverity> {
try {
return Database.getInstance(context).getSeverities().getAllForSymptom(idSymptom)
} catch (e: Exception) {
e.printStackTrace()
Logger.e("Error on getting all options for symptom $idSymptom from database ${e.localizedMessage}")
}
return arrayListOf()
}
@WorkerThread
fun getById(context: Context, idSymptom: String, idSeverity: String): DBSeverity? {
try {
return Database.getInstance(context).getSeverities().getByIdForSymptom(idSymptom, idSeverity)
} catch (e: Exception) {
e.printStackTrace()
Logger.e("Error on getting option by id $idSeverity for symptom $idSymptom from database ${e.localizedMessage}")
}
return null
}
@WorkerThread
fun upsert(context: Context, model: DBSeverity) {
upsert(context, listOf(model))
}
@WorkerThread
fun upsert(context: Context, models: List<DBSeverity>) {
try {
Database.getInstance(context).getSeverities().upsert(models)
} catch (e: Exception) {
e.printStackTrace()
Logger.e("Error on upsert options to database ${e.localizedMessage}")
}
}
@WorkerThread
fun delete(context: Context, idSeverity: Long) {
try {
Database.getInstance(context).getSeverities().delete(idSeverity)
} catch (e: Exception) {
e.printStackTrace()
Logger.e("Error on delete option with id $idSeverity from database ${e.localizedMessage}")
}
}
@WorkerThread
fun truncate(context: Context) {
try {
Database.getInstance(context).getSeverities().truncate()
} catch (e: Exception) {
e.printStackTrace()
Logger.e("Error on truncate options from database ${e.localizedMessage}")
}
}
} | 0 | Kotlin | 0 | 0 | 19be5ff0abf754cd918b2d357f855cd73f8b9cd8 | 2,303 | android-bhf-doctors | MIT License |
app/src/main/java/com/example/jpmorgantest/data/sources/search/remote/SearchRemoteDataSource.kt | Sushanth12361 | 861,347,513 | false | {"Kotlin": 126062, "Java": 3448} | package com.example.jpmorgantest.data.sources.search.remote
import com.example.jpmorgantest.data.sources.search.entities.WeatherDetailResponse
import com.example.jpmorgantest.util.state.Result
interface SearchRemoteDataSource {
suspend fun search(
query: String? = null,
lat: Double? = null,
lon: Double? = null
): Result<WeatherDetailResponse>
}
| 0 | Kotlin | 0 | 0 | 6c0607adaba5018572237a7d51adcf0cd71a6540 | 381 | JPMC | Apache License 2.0 |
src/main/kotlin/com/vaadin/gradle/VaadinBuildFrontendTask.kt | vaadin | 222,452,521 | false | null | /**
* Copyright 2000-2020 Vaadin Ltd
*
* 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.vaadin.gradle
import com.vaadin.flow.server.Constants
import com.vaadin.flow.server.InitParameters
import com.vaadin.flow.server.frontend.CvdlProducts
import com.vaadin.flow.server.frontend.FrontendTools
import com.vaadin.flow.server.frontend.FrontendUtils
import com.vaadin.pro.licensechecker.BuildType
import com.vaadin.pro.licensechecker.LicenseChecker
import com.vaadin.pro.licensechecker.Product
import elemental.json.Json
import elemental.json.JsonObject
import elemental.json.impl.JsonUtil
import org.apache.commons.io.FileUtils
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.bundling.Jar
import java.io.File
import java.io.IOException
import java.util.*
import java.util.jar.Attributes
import java.util.jar.JarFile
/**
* Task that builds the frontend bundle.
*
* It performs the following actions when creating a package:
* * Update [Constants.PACKAGE_JSON] file with the [com.vaadin.flow.component.dependency.NpmPackage]
* annotations defined in the classpath,
* * Copy resource files used by flow from `.jar` files to the `node_modules`
* folder
* * Install dependencies by running `npm install`
* * Update the [FrontendUtils.IMPORTS_NAME] file imports with the
* [com.vaadin.flow.component.dependency.JsModule] [com.vaadin.flow.theme.Theme] and [com.vaadin.flow.component.dependency.JavaScript] annotations defined in
* the classpath,
* * Update [FrontendUtils.WEBPACK_CONFIG] file.
*
* @since 2.0
*/
public open class VaadinBuildFrontendTask : DefaultTask() {
init {
group = "Vaadin"
description = "Builds the frontend bundle with webpack"
// we need the flow-build-info.json to be created, which is what the vaadinPrepareFrontend task does
dependsOn("vaadinPrepareFrontend")
// Maven's task run in the LifecyclePhase.PREPARE_PACKAGE phase
// We need access to the produced classes, to be able to analyze e.g.
// @CssImport annotations used by the project.
dependsOn("classes")
// Make sure to run this task before the `war`/`jar` tasks, so that
// webpack bundle will end up packaged in the war/jar archive. The inclusion
// rule itself is configured in the VaadinPlugin class.
project.tasks.withType(Jar::class.java) { task: Jar ->
task.mustRunAfter("vaadinBuildFrontend")
}
}
@TaskAction
public fun vaadinBuildFrontend() {
val extension: VaadinFlowPluginExtension = VaadinFlowPluginExtension.get(project)
val tokenFile = File(extension.webpackOutputDirectory, FrontendUtils.TOKEN_FILE)
logger.info("Running the vaadinBuildFrontend task with effective configuration $extension")
updateBuildFile(tokenFile)
runNodeUpdater(extension, tokenFile)
if (extension.generateBundle) {
runWebpack(extension)
} else {
logger.info("Not running webpack since generateBundle is false")
}
}
private fun runWebpack(extension: VaadinFlowPluginExtension) {
if (!extension.oldLicenseChecker && !extension.compatibility) {
LicenseChecker.setStrictOffline(true)
}
val webpackCommand = "webpack/bin/webpack.js"
val webpackExecutable = File(extension.npmFolder, FrontendUtils.NODE_MODULES + webpackCommand)
check(webpackExecutable.isFile) {
"Unable to locate webpack executable by path '${webpackExecutable.absolutePath}'. Double check that the plugin is executed correctly"
}
val tools: FrontendTools = extension.createFrontendTools()
val nodePath: String = if (extension.requireHomeNodeExec) {
tools.forceAlternativeNodeExecutable()
} else {
tools.nodeExecutable
}
logger.info("Running webpack")
exec(project.logger, project.projectDir, tools.webpackNodeEnvironment, nodePath, webpackExecutable.absolutePath)
validateLicenses(extension)
}
private fun runNodeUpdater(extension: VaadinFlowPluginExtension, tokenFile: File) {
val jarFiles: Set<File> = getJarFiles()
logger.info("runNodeUpdater: npmFolder=${extension.npmFolder}, generatedPath=${extension.generatedFolder}, frontendDirectory=${extension.frontendDirectory}")
logger.info("runNodeUpdater: runNpmInstall=${extension.runNpmInstall}, enablePackagesUpdate=true, useByteCodeScanner=${extension.optimizeBundle}")
logger.info("runNodeUpdater: copyResources=${jarFiles.toPrettyFormat()}")
logger.info("runNodeUpdater: copyLocalResources=${extension.frontendResourcesDirectory}")
logger.info("runNodeUpdater: enableImportsUpdate=true, embeddableWebComponents=${extension.generateEmbeddableWebComponents}, tokenFile=${tokenFile}")
logger.info("runNodeUpdater: pnpm=${extension.pnpmEnable}, requireHomeNodeExec=${extension.requireHomeNodeExec}")
extension.createNodeTasksBuilder(project)
.runNpmInstall(extension.runNpmInstall)
.enablePackagesUpdate(true)
.useByteCodeScanner(extension.optimizeBundle)
.copyResources(jarFiles)
.copyLocalResources(extension.frontendResourcesDirectory)
.enableImportsUpdate(true)
.withEmbeddableWebComponents(extension.generateEmbeddableWebComponents)
.withTokenFile(tokenFile)
.enablePnpm(extension.pnpmEnable)
.build().execute()
logger.info("runNodeUpdater: done!")
}
private fun validateLicenses(extension: VaadinFlowPluginExtension) {
if (extension.oldLicenseChecker || extension.compatibility) {
return
}
val nodeModulesFolder = File(extension.npmFolder, FrontendUtils.NODE_MODULES)
val outputFolder: File = extension.webpackOutputDirectory!!
val statsFile = File(extension.webpackOutputDirectory!!, Constants.VAADIN_CONFIGURATION + "/stats.json")
check(statsFile.exists()) { "Stats file $statsFile does not exist" }
val commercialComponents: MutableList<Product> = findCommercialFrontendComponents(nodeModulesFolder, statsFile).toMutableList()
commercialComponents.addAll(findCommercialJavaComponents())
for (component in commercialComponents) {
try {
LicenseChecker.checkLicense(component.name, component.version, BuildType.PRODUCTION)
} catch (e: Exception) {
try {
logger.debug("License check for $component failed. Invalidating output")
FileUtils.deleteDirectory(outputFolder)
} catch (e1: IOException) {
logger.debug("Failed to remove $outputFolder", e1)
}
throw e
}
}
}
private fun findCommercialJavaComponents(): List<Product> {
val components: MutableList<Product> = ArrayList()
for (f in getJarFiles()) {
try {
JarFile(f).use { jarFile ->
val attributes: Attributes? = jarFile.manifest?.mainAttributes
val cvdlName: String? = attributes?.getValue("CvdlName")
if (cvdlName != null) {
val version = attributes.getValue("Bundle-Version")
val p = Product(cvdlName, version)
components.add(p)
}
}
} catch (e: IOException) {
logger.debug("Error reading manifest for jar $f", e)
}
}
return components
}
private fun getJarFiles() = project.configurations.getByName("runtimeClasspath")
.resolve()
.filter { it.name.endsWith(".jar") }
.toSet()
/**
* Add the devMode token to build token file so we don't try to start the
* dev server. Remove the abstract folder paths as they should not be used
* for prebuilt bundles.
*/
private fun updateBuildFile(tokenFile: File) {
check(tokenFile.isFile) { "$tokenFile is missing" }
val buildInfo: JsonObject = JsonUtil.parse(tokenFile.readText())
buildInfo.apply {
remove(Constants.NPM_TOKEN)
remove(Constants.GENERATED_TOKEN)
remove(Constants.FRONTEND_TOKEN)
remove(InitParameters.NODE_VERSION)
remove(InitParameters.NODE_DOWNLOAD_ROOT)
remove(Constants.SERVLET_PARAMETER_ENABLE_PNPM)
remove(Constants.REQUIRE_HOME_NODE_EXECUTABLE)
put(Constants.SERVLET_PARAMETER_ENABLE_DEV_SERVER, false)
}
buildInfo.writeToFile(tokenFile)
logger.info("Updated token file $tokenFile to $buildInfo")
}
public companion object {
private fun findCommercialFrontendComponents(
nodeModulesFolder: File, statsFile: File
): List<Product> {
val components: MutableList<Product> = mutableListOf()
try {
val contents = statsFile.readText()
val npmModules =
Json.parse(contents).getArray("npmModules")
for (i in 0 until npmModules.length()) {
val npmModule = npmModules.getString(i)
val product = CvdlProducts.getProductIfCvdl(nodeModulesFolder, npmModule)
if (product != null) {
components.add(product)
}
}
return components
} catch (e: Exception) {
throw RuntimeException("Error reading file $statsFile", e)
}
}
}
}
| 8 | Kotlin | 10 | 32 | 14f2cc36137dae32417c51425bf7207191c774c7 | 10,306 | vaadin-gradle-plugin | Apache License 2.0 |
styringsinfo/src/test/kotlin/db/migration/V36UkjentMottakerBlirNullTest.kt | navikt | 342,325,871 | false | {"Kotlin": 646155, "Dockerfile": 168} | package db.migration
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import no.nav.helse.rapids_rivers.isMissingOrNull
import no.nav.helse.spre.styringsinfo.db.AbstractDatabaseTest.Companion.dataSource
import no.nav.helse.spre.styringsinfo.teamsak.behandling.Versjon
import no.nav.helse.spre.styringsinfo.teamsak.hendelse.VedtakFattet
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.time.LocalDateTime
import java.util.*
internal class V35UkjentMottakerBlirNullTest: BehandlingshendelseJsonMigreringTest(
migrering = V36__ukjent_mottaker_blir_null(),
dataSource = dataSource
) {
@Test
fun `skal skrive om revurderinger av førstegangsbehandlinger skal ha periodetype førstebehandling`() {
val behandlingId = UUID.randomUUID()
val sakId = UUID.randomUUID()
val behandling = leggTilBehandlingshendelse(
sakId, behandlingId, true, Versjon.of("0.1.0"), false, data = {
it.put("mottaker", "UKJENT")
},
hendelse = VedtakFattet(
id = behandlingId,
opprettet = LocalDateTime.now(),
data = jacksonObjectMapper().createObjectNode() as JsonNode,
behandlingId = UUID.randomUUID(),
tags = emptyList()
)
)
migrer()
assertKorrigert(behandling) { _, ny ->
assertTrue(ny.path("mottaker").isMissingOrNull())
}
}
} | 0 | Kotlin | 2 | 0 | bdb426acb41c430f78bf232c148f6bd3aa126ad5 | 1,541 | helse-spre | MIT License |
design/src/main/java/little/goose/design/theme/Theme.kt | FnGoose | 789,832,100 | false | {"Kotlin": 72523} | package little.goose.design.theme
import android.graphics.Color
object Theme {
object Palette {
val Primary = Color.parseColor("#333333")
}
} | 0 | Kotlin | 0 | 0 | 0198209edf9f97451428899e9947db7a57088e28 | 161 | ViewNavigation | MIT License |
old/LinkedListJvmTest.kt | korlibs | 110,368,329 | false | null | package com.soywiz.kds
import org.junit.Test
import kotlin.test.assertEquals
class LinkedListJvmTest {
private fun <T> create() = LinkedList<T>(debug = true)
//private fun <T> create() = LinkedList<T>(debug = false)
private val <T> LinkedList<T>.str get() = this.joinToString(",")
@Test
fun simple() {
val l = create<String>()
assertEquals(0, l.size)
l += listOf("a", "b", "c", "d", "e", "f")
assertEquals("a,b,c,d,e,f", l.str)
assertEquals("a", l.first)
assertEquals("f", l.last)
assertEquals(6, l.size)
l.removeAt(1)
assertEquals(5, l.size)
l.removeAt(l.size - 2)
assertEquals(4, l.size)
assertEquals("a,c,d,f", l.str)
l.remove("d")
assertEquals(3, l.size)
assertEquals("a,c,f", l.str)
l.retainAll(listOf("a", "f"))
assertEquals(2, l.size)
assertEquals("a,f", l.str)
l.removeAll(listOf("a"))
assertEquals(1, l.size)
assertEquals("f", l.str)
}
@Test
fun grow() {
val l = create<String>()
for (n in 0 until 1000) l.add("$n")
for (n in 0 until 495) {
l.removeFirst()
l.removeLast()
}
assertEquals(10, l.size)
assertEquals("495,496,497,498,499,500,501,502,503,504", l.str)
}
@Test
fun grow2() {
val l = create<Boolean>()
for (n in 0 until 1000) l.addFirst(true)
for (n in 0 until 1000) l.removeFirst()
for (n in 0 until 1000) l.addFirst(true)
}
private fun simpleRemove(count: Int) {
val l = create<Boolean>()
for (n in 0 until count) l.addFirst(true); for (n in 0 until count) l.removeFirst()
for (n in 0 until count) l.addLast(true); for (n in 0 until count) l.removeFirst()
for (n in 0 until count) l.addFirst(true); for (n in 0 until count) l.removeLast()
for (n in 0 until count) l.addLast(true); for (n in 0 until count) l.removeLast()
}
@Test
fun simpleRemove1() = simpleRemove(1)
@Test
fun simpleRemove2() = simpleRemove(2)
@Test
fun simpleRemove4() = simpleRemove(4)
@Test
fun simpleRemove15() = simpleRemove(15)
@Test
fun simpleRemove16() = simpleRemove(16)
@Test
fun simpleRemove32() = simpleRemove(32)
@Test
fun mutableIteratorRemove() {
val l = create<Int>()
for (n in 0 until 10) l.addLast(n)
val it = l.iterator()
while (it.hasNext()) {
val item = it.next()
if (item % 2 == 0) {
it.remove()
}
}
assertEquals("1,3,5,7,9", l.str)
}
@Test
fun insertAfter() {
val l = create<String>()
val aSlot = l.addLast("a")
val cSlot = l.addLast("c")
l.addAfterSlot(aSlot, "b")
assertEquals("a,b,c", l.str)
}
@Test
fun insertAfterLast() {
val l = create<String>()
val aSlot = l.addLast("a")
val cSlot = l.addLast("c")
l.addAfterSlot(cSlot, "b")
assertEquals("a,c,b", l.str)
}
@Test
fun insertBefore() {
val l = create<String>()
val aSlot = l.addLast("a")
val cSlot = l.addLast("c")
l.addBeforeSlot(aSlot, "b")
assertEquals("b,a,c", l.str)
}
@Test
fun insertBeforeFirst() {
val l = create<String>()
val aSlot = l.addLast("a")
val cSlot = l.addLast("c")
l.addBeforeSlot(cSlot, "b")
assertEquals("a,b,c", l.str)
}
@Test
fun removeAt() {
val l = create<String>()
l.addAll(listOf("a", "b", "c", "d", "e", "f", "g"))
assertEquals("b", l.removeAt(1))
assertEquals("a,c,d,e,f,g", l.str)
assertEquals("f", l.removeAt(4))
assertEquals("a,c,d,e,g", l.str)
l.addAt(2, "*")
assertEquals("a,c,*,d,e,g", l.str)
l.addAt(0, "+")
assertEquals("+,a,c,*,d,e,g", l.str)
l.addAt(6, "-")
assertEquals("+,a,c,*,d,e,-,g", l.str)
l.addAt(8, "/")
assertEquals("+,a,c,*,d,e,-,g,/", l.str)
}
} | 1 | null | 8 | 50 | cc2397e7a575412dfa6e3850317c59b168356b76 | 4,145 | kds | Creative Commons Zero v1.0 Universal |
buildSrc/src/main/kotlin/Configuration.kt | sebastinto | 505,582,760 | false | {"Kotlin": 87790} | /*
* Copyright (C) 2022 tobianoapps
*
* 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.
*/
object Configuration {
const val compileSdk = 33
const val targetSdk = 33
const val minSdk = 21
private const val majorVersion = 1
private const val minorVersion = 0
private const val patchVersion = 3
private const val qualifier = ""
const val versionName = "$majorVersion.$minorVersion.$patchVersion$qualifier"
const val sampleVersionCode = 3
const val sampleVersionName = "$majorVersion.$minorVersion.$patchVersion"
const val groupId = "com.tobianoapps"
const val artifactId = "bulletin"
} | 0 | Kotlin | 0 | 48 | 4473ee4d117531295a0f5b31da12d7d5bf0fc2a1 | 1,135 | bulletin | Apache License 2.0 |
api/api/src/main/kotlin/nl/tno/federated/api/event/distribution/rules/SparqlEventDistributionRule.kt | federatedplatforms | 781,315,852 | false | {"Kotlin": 233863, "Java": 126363, "TypeScript": 10886, "HTML": 10475, "Svelte": 7001, "JavaScript": 5457, "Dockerfile": 1547, "CSS": 1017, "Python": 1014, "Makefile": 291} | package nl.tno.federated.api.event.distribution.rules
import org.eclipse.rdf4j.repository.Repository
import org.eclipse.rdf4j.repository.sail.SailRepository
import org.eclipse.rdf4j.rio.RDFFormat
import org.eclipse.rdf4j.sail.memory.MemoryStore
import java.io.StringReader
class SparqlEventDistributionRule(
private val sparql: String,
private val destinations: Set<String>
) : EventDistributionRule {
override fun getDestinations() = destinations
override fun appliesTo(ttl: String): Boolean {
val db: Repository = SailRepository(MemoryStore())
db.init()
try {
db.connection.use { conn ->
StringReader(ttl).use {
conn.add(it, "", RDFFormat.TURTLE)
}
val query = conn.prepareBooleanQuery(sparql)
return query.evaluate()
}
} finally {
db.shutDown()
}
}
override fun toString(): String {
return "SparqlEventDistributionRule(destinations='${getDestinations().joinToString(",")}'"
}
} | 0 | Kotlin | 0 | 0 | 55aa6b8f3e5faa32c378e3dc0e21b8c7fd57fa04 | 1,082 | FEDeRATED-BDI | Apache License 2.0 |
src/test/kotlin/org/drimachine/grakmat/LinesSplitingTest.kt | dmitmel | 69,173,049 | false | {"Kotlin": 83090} | /*
* Copyright (c) 2016 Drimachine.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drimachine.grakmat
import org.junit.*
import org.junit.Assert.*
class LinesSplitingTest {
@Test fun testLF() {
assertEquals(
listOf("a\n", "b\n", "c"),
"a\nb\nc".linesWithSeparators()
)
}
@Test fun testCR() {
assertEquals(
listOf("a\r", "b\r", "c"),
"a\rb\rc".linesWithSeparators()
)
}
@Test fun testCRLF() {
assertEquals(
listOf("a\r\n", "b\r\n", "c"),
"a\r\nb\r\nc".linesWithSeparators()
)
}
@Test fun testEmptyLinesAndLF() {
assertEquals(
listOf("a\n", "\n", "c"),
"a\n\nc".linesWithSeparators()
)
}
@Test fun testEmptyLinesAndCR() {
assertEquals(
listOf("a\r", "\r", "c"),
"a\r\rc".linesWithSeparators()
)
}
@Test fun testEmptyLinesAndCRLF() {
assertEquals(
listOf("a\r\n", "\r\n", "c"),
"a\r\n\r\nc".linesWithSeparators()
)
}
@Test fun testLastLF() {
assertEquals(
listOf("a\n", "b\n", "c\n"),
"a\nb\nc\n".linesWithSeparators()
)
}
@Test fun testLastCR() {
assertEquals(
listOf("a\r", "b\r", "c\r"),
"a\rb\rc\r".linesWithSeparators()
)
}
@Test fun testLastCRLF() {
assertEquals(
listOf("a\r\n", "b\r\n", "c\r\n"),
"a\r\nb\r\nc\r\n".linesWithSeparators()
)
}
}
| 0 | Kotlin | 0 | 0 | 88ef2ca5073201802126dd79bfc2945c7780edcb | 2,190 | grakmat | Apache License 2.0 |
app/src/main/java/com/example/neoticket/view/main/payment/ConfirmPageFragment.kt | rybakova-auca-2021 | 747,738,666 | false | {"Kotlin": 442862} | package com.example.neoticket.view.main.payment
import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.neoticket.R
import com.example.neoticket.adapters.ConcertTicketItem
import com.example.neoticket.adapters.MovieTicketItem
import com.example.neoticket.adapters.SportTicketItem
import com.example.neoticket.adapters.TheaterTicketItem
import com.example.neoticket.adapters.TicketConfirmAdapter
import com.example.neoticket.databinding.FragmentConfirmPageBinding
import com.example.neoticket.viewModel.cinema.GetMovieOrderDetailViewModel
import com.example.neoticket.viewModel.concerts.GetConcertOrderDetailViewModel
import com.example.neoticket.viewModel.sport.GetSportOrderDetailViewModel
import com.example.neoticket.viewModel.theater.GetTheaterOrderViewModel
class ConfirmPageFragment : Fragment() {
private lateinit var binding: FragmentConfirmPageBinding
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: TicketConfirmAdapter
private val viewModel: GetMovieOrderDetailViewModel by viewModels()
private val concertViewModel: GetConcertOrderDetailViewModel by viewModels()
private val sportViewModel: GetSportOrderDetailViewModel by viewModels()
private val theaterViewModel: GetTheaterOrderViewModel by viewModels()
private lateinit var countDownTimer: CountDownTimer
private lateinit var countdownTextView: TextView
private var timeRemainingMillis: Long = 1199000
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentConfirmPageBinding.inflate(inflater, container, false)
recyclerView = binding.rvTickets
countdownTextView = binding.timeLeft
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
startCountdown()
val order = arguments?.getInt("order", 0) ?: 0
val source = arguments?.getString("source")
setupRecyclerView()
when (source) {
"concertTicket" -> getConcertOrderData(order)
"movieTicket" -> getMovieOrderData(order)
"sportTicket" -> getSportOrderData(order)
"theaterTicket" -> getTheaterOrderData(order)
}
}
private fun setupRecyclerView() {
adapter = TicketConfirmAdapter(emptyList())
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(requireContext())
}
private fun getMovieOrderData(id: Int) {
viewModel.orderMovieLiveData.observe(viewLifecycleOwner, Observer { result ->
if (result != null) {
binding.textCinema.text = result.movie_cinema
binding.movieTitle.text = result.movie_title
binding.textMovieDate.text = result.tickets_movie[0].movie_data
binding.sumPayment.text = result.total_price
binding.btnPay.text = "Оплатить ${result.total_price} c"
Glide.with(binding.imageView8).load(result.movie_image).into(binding.imageView8)
val items = result.tickets_movie?.map { MovieTicketItem(it) }
if (items != null) {
adapter.updateData(items)
}
binding.btnPay.setOnClickListener {
val bundle = Bundle()
bundle.putString("ticket_type", "Кинотеатры")
bundle.putString("total_price", result.total_price)
bundle.putInt("order", result.id)
findNavController().navigate(R.id.paymentFragment, bundle)
}
}
})
viewModel.getMovieOrderDetail(id)
}
private fun getConcertOrderData(id: Int) {
concertViewModel.orderConcertLiveData.observe(viewLifecycleOwner, Observer { result ->
if (result != null) {
binding.textCinema.text = result.tickets_concert[0].concert_place
binding.movieTitle.text = result.tickets_concert[0].concert_title
binding.textMovieDate.text = result.tickets_concert[0].concert_date
binding.sumPayment.text = result.total_price
binding.btnPay.text = "Оплатить ${result.total_price} c"
Glide.with(binding.imageView8).load(result.tickets_concert[0].concert_images[0].image).into(binding.imageView8)
val items = result.tickets_concert?.map { ConcertTicketItem(it) }
if (items != null) {
adapter.updateData(items)
}
binding.btnPay.setOnClickListener {
val bundle = Bundle()
bundle.putString("ticket_type", "Концерты")
bundle.putString("total_price", result.total_price)
bundle.putInt("order", result.id)
findNavController().navigate(R.id.paymentFragment, bundle)
}
}
})
concertViewModel.getConcertOrderDetail(id)
}
private fun getSportOrderData(id: Int) {
sportViewModel.orderSportLiveData.observe(viewLifecycleOwner, Observer { result ->
if (result != null) {
binding.textCinema.text = result.tickets_sport[0].sport_place
binding.movieTitle.text = result.tickets_sport[0].sport_title
binding.textMovieDate.text = result.tickets_sport[0].sport_date
binding.sumPayment.text = result.total_price
binding.btnPay.text = "Оплатить ${result.total_price} c"
Glide.with(binding.imageView8).load(result.tickets_sport[0].sport_images[0].image).into(binding.imageView8)
val items = result.tickets_sport?.map { SportTicketItem(it) }
if (items != null) {
adapter.updateData(items)
}
binding.btnPay.setOnClickListener {
val bundle = Bundle()
bundle.putString("ticket_type", "Спорт")
bundle.putString("total_price", result.total_price)
bundle.putInt("order", result.id)
findNavController().navigate(R.id.paymentFragment, bundle)
}
}
})
sportViewModel.getSportOrderDetail(id)
}
private fun getTheaterOrderData(id: Int) {
theaterViewModel.orderTheaterLiveData.observe(viewLifecycleOwner, Observer { result ->
if (result != null) {
binding.textCinema.text = result.tickets_theater[0].theater_place
binding.movieTitle.text = result.tickets_theater[0].theater_title
binding.textMovieDate.text = result.tickets_theater[0].theater_date
binding.sumPayment.text = result.total_price
binding.btnPay.text = "Оплатить ${result.total_price} c"
Glide.with(binding.imageView8).load(result.tickets_theater[0].theater_images[0].image).into(binding.imageView8)
val items = result.tickets_theater?.map { TheaterTicketItem(it) }
if (items != null) {
adapter.updateData(items)
}
binding.btnPay.setOnClickListener {
val bundle = Bundle()
bundle.putString("ticket_type", "Театры")
bundle.putString("total_price", result.total_price)
bundle.putInt("order", result.id)
findNavController().navigate(R.id.paymentFragment, bundle)
}
}
})
theaterViewModel.getTheaterOrderDetail(id)
}
private fun startCountdown() {
countDownTimer = object : CountDownTimer(timeRemainingMillis, 1000) {
override fun onTick(millisUntilFinished: Long) {
timeRemainingMillis = millisUntilFinished
updateCountdownText()
}
override fun onFinish() {
countdownTextView.text = "00:00"
Toast.makeText(requireContext(), "Оплата больше недействительна", Toast.LENGTH_SHORT).show()
}
}.start()
}
private fun updateCountdownText() {
val minutes = (timeRemainingMillis / 1000) / 60
val seconds = (timeRemainingMillis / 1000) % 60
countdownTextView.text = String.format("%02d:%02d", minutes, seconds)
}
} | 0 | Kotlin | 0 | 0 | 7b7a198cc176704e613ee794176463935480b3aa | 8,980 | NeoTicket | MIT License |
android/src/main/kotlin/com/cloudwebrtc/webrtc/model/SignalingState.kt | krida2000 | 510,302,729 | false | null | package com.cloudwebrtc.webrtc.model
import org.webrtc.PeerConnection.SignalingState as WSignalingState
/**
* Representation of an [org.webrtc.PeerConnection.SignalingState].
*
* @property value [Int] representation of this enum which will be expected on the Flutter side.
*/
enum class SignalingState(val value: Int) {
/** Indicates that there is no ongoing exchange of offer and answer underway. */
STABLE(0),
/** Indicates that the local peer has called `RTCPeerConnection.setLocalDescription()`. */
HAVE_LOCAL_OFFER(1),
/**
* Indicates that the offer sent by the remote peer has been applied and an answer has been
* created.
*/
HAVE_LOCAL_PRANSWER(2),
/**
* Indicates that the remote peer has created an offer and used the signaling server to deliver it
* to the local peer, which has set the offer as the remote description by calling
* `PeerConnection.setRemoteDescription()`.
*/
HAVE_REMOTE_OFFER(3),
/**
* Indicates that the provisional answer has been received and successfully applied in response to
* the offer previously sent and established.
*/
HAVE_REMOTE_PRANSWER(4),
/** Indicates that the peer was closed. */
CLOSED(5);
companion object {
/**
* Converts the provided [org.webrtc.PeerConnection.SignalingState] into a [SignalingState].
*
* @return [SignalingState] created based on the provided
* [org.webrtc.PeerConnection.SignalingState].
*/
fun fromWebRtc(from: WSignalingState): SignalingState {
return when (from) {
WSignalingState.STABLE -> STABLE
WSignalingState.HAVE_LOCAL_OFFER -> HAVE_LOCAL_OFFER
WSignalingState.HAVE_LOCAL_PRANSWER -> HAVE_LOCAL_PRANSWER
WSignalingState.HAVE_REMOTE_OFFER -> HAVE_REMOTE_OFFER
WSignalingState.HAVE_REMOTE_PRANSWER -> HAVE_REMOTE_PRANSWER
WSignalingState.CLOSED -> CLOSED
}
}
}
}
| 0 | Rust | 0 | 0 | 146467b24dd16a2786c3843f773cd08da68bc83c | 1,907 | webrtc | MIT License |
app/src/main/java/es/ffgiraldez/comicsearch/comics/ComicRepository.kt | newsolf | 130,322,522 | true | {"Kotlin": 25488} | package es.ffgiraldez.comicsearch.comics
import android.util.Log
import es.ffgiraldez.comicsearch.comics.data.ComicVineApi
import es.ffgiraldez.comicsearch.comics.store.ComicDatabase
import es.ffgiraldez.comicsearch.comics.store.QueryEntity
import es.ffgiraldez.comicsearch.comics.store.SearchEntity
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
class ComicRepository(
private val api: ComicVineApi,
private val database: ComicDatabase
) {
fun findSuggestion(term: String): Flowable<List<String>> =
database.suggestionDao().findQueryByTerm(term)
.flatMap {
when (it.isEmpty()) {
true -> searchSuggestionsOnApi(term)
false -> searchSuggestionsOnDatabase(it.first())
}
}
fun findVolume(term: String): Flowable<List<Volume>> =
database.volumeDao().findQueryByTerm(term)
.flatMap {
when (it.isEmpty()) {
true -> searchVolumeOnApi(term)
false -> searchVolumeOnDatabase(it.first())
}
}
private fun searchSuggestionsOnApi(term: String): Flowable<List<String>> =
api.fetchSuggestedVolumes(term)
.subscribeOn(Schedulers.io())
.doOnSubscribe { Log.d("cambio", "pidiendo findSuggestion la api") }
.map { response ->
response.results
.distinctBy { it.name }
.map { it.name }
}
.flatMapCompletable { response ->
Completable.fromAction {
Log.d("cambio", "guardando query: $term en bd")
database.suggestionDao().insert(
term,
response
)
}
}.toFlowable<List<String>>()
private fun searchSuggestionsOnDatabase(query: QueryEntity): Flowable<List<String>> =
database.suggestionDao().findSuggestionByQuery(query.queryId)
.doOnSubscribe { Log.d("cambio", "devolviendo resultados") }
.subscribeOn(Schedulers.io())
.map { suggestions -> suggestions.map { it.title } }
private fun searchVolumeOnApi(term: String): Flowable<List<Volume>> =
api.fetchVolumes(term)
.subscribeOn(Schedulers.io())
.map { response ->
response.results
.filter { it.apiPublisher != null && it.apiImage != null }
.map {
Volume(it.name, it.apiPublisher!!.name, it.apiImage!!.url)
}
}
.subscribeOn(Schedulers.computation())
.flatMapCompletable { response ->
Completable.fromAction {
Log.d("cambio", "guardando query: $term en bd")
database.volumeDao().insert(
term,
response
)
}
}.toFlowable<List<Volume>>()
private fun searchVolumeOnDatabase(query: SearchEntity): Flowable<List<Volume>> =
database.volumeDao().findVolumeByQuery(query.queryId)
.doOnSubscribe { Log.d("cambio", "devolviendo resultados") }
.subscribeOn(Schedulers.io())
.map { volumeList -> volumeList.map { Volume(it.title, it.author, it.url) } }
} | 0 | Kotlin | 0 | 0 | 0b07cd9f52fa34469f12a3ebdc5dd52f8b343edf | 3,939 | rx-mvvm-android | Apache License 2.0 |
epifi/app/src/main/java/com/epifi/assignment/network/NetworkModule.kt | kunal26das | 673,585,943 | false | null | package com.epifi.assignment.network
import com.epifi.assignment.BuildConfig
import com.epifi.assignment.service.OmdbService
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
const val PAGE_SIZE = 10
const val FIRST_PAGE = 1
const val DEFAULT_FORMAT = "json"
private fun getGson(): Gson {
return GsonBuilder().create()
}
private fun getOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder().build()
}
private fun getRetrofit(): Retrofit {
return Retrofit.Builder().apply {
baseUrl(BuildConfig.BASE_URL)
client(getOkHttpClient())
addConverterFactory(GsonConverterFactory.create(getGson()))
}.build()
}
@Provides
fun getOmdbService(): OmdbService {
return getRetrofit().create(OmdbService::class.java)
}
} | 0 | Kotlin | 0 | 1 | de0811d69435da1b902a038848b8c52a9f9e165b | 1,156 | android-assignments | Apache License 2.0 |
data/RF01570/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF01570"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
1 to 5
44 to 48
}
value = "#2c633c"
}
color {
location {
7 to 8
31 to 32
}
value = "#0f3ced"
}
color {
location {
9 to 10
28 to 29
}
value = "#fb78d3"
}
color {
location {
11 to 14
22 to 25
}
value = "#695c2e"
}
color {
location {
49 to 51
55 to 57
}
value = "#625574"
}
color {
location {
61 to 62
282 to 283
}
value = "#18523e"
}
color {
location {
65 to 66
279 to 280
}
value = "#c3a663"
}
color {
location {
68 to 76
267 to 275
}
value = "#a6ab29"
}
color {
location {
80 to 86
257 to 263
}
value = "#3ecabe"
}
color {
location {
92 to 96
252 to 256
}
value = "#ec430a"
}
color {
location {
100 to 101
248 to 249
}
value = "#ff88fb"
}
color {
location {
104 to 109
242 to 247
}
value = "#cf7b39"
}
color {
location {
110 to 112
236 to 238
}
value = "#8ef731"
}
color {
location {
116 to 118
230 to 232
}
value = "#67ab8d"
}
color {
location {
120 to 126
221 to 227
}
value = "#0e1ef5"
}
color {
location {
127 to 132
164 to 169
}
value = "#f202d3"
}
color {
location {
134 to 137
159 to 162
}
value = "#98f597"
}
color {
location {
139 to 140
156 to 157
}
value = "#e33b13"
}
color {
location {
141 to 145
150 to 154
}
value = "#2e4320"
}
color {
location {
172 to 173
218 to 219
}
value = "#7bc305"
}
color {
location {
175 to 176
216 to 217
}
value = "#353ccf"
}
color {
location {
180 to 181
210 to 211
}
value = "#40fdf1"
}
color {
location {
185 to 187
206 to 208
}
value = "#0f2d34"
}
color {
location {
192 to 194
199 to 201
}
value = "#bb286a"
}
color {
location {
6 to 6
33 to 43
}
value = "#a7fe95"
}
color {
location {
9 to 8
30 to 30
}
value = "#dfd928"
}
color {
location {
11 to 10
26 to 27
}
value = "#8d4ac7"
}
color {
location {
15 to 21
}
value = "#963636"
}
color {
location {
52 to 54
}
value = "#50df13"
}
color {
location {
63 to 64
281 to 281
}
value = "#5d9b09"
}
color {
location {
67 to 67
276 to 278
}
value = "#26b359"
}
color {
location {
77 to 79
264 to 266
}
value = "#d44e16"
}
color {
location {
87 to 91
257 to 256
}
value = "#080b1a"
}
color {
location {
97 to 99
250 to 251
}
value = "#85321c"
}
color {
location {
102 to 103
248 to 247
}
value = "#4e23d4"
}
color {
location {
110 to 109
239 to 241
}
value = "#1e1eb7"
}
color {
location {
113 to 115
233 to 235
}
value = "#8671a2"
}
color {
location {
119 to 119
228 to 229
}
value = "#1360ff"
}
color {
location {
127 to 126
170 to 171
220 to 220
}
value = "#f1b430"
}
color {
location {
133 to 133
163 to 163
}
value = "#7bea09"
}
color {
location {
138 to 138
158 to 158
}
value = "#3f1b3e"
}
color {
location {
141 to 140
155 to 155
}
value = "#e1f49b"
}
color {
location {
146 to 149
}
value = "#3ab7a9"
}
color {
location {
174 to 174
218 to 217
}
value = "#b2dd65"
}
color {
location {
177 to 179
212 to 215
}
value = "#934c34"
}
color {
location {
182 to 184
209 to 209
}
value = "#d131c3"
}
color {
location {
188 to 191
202 to 205
}
value = "#b3a76c"
}
color {
location {
195 to 198
}
value = "#7086c8"
}
color {
location {
58 to 60
}
value = "#286377"
}
color {
location {
284 to 289
}
value = "#0d5d7d"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 7,527 | Rfam-for-RNArtist | MIT License |
src/main/java/io/github/lcriadof/atrevete/kotlin/capitulo4/c4p6.kt | lcriadof | 344,240,788 | false | null | /*
Atrévete con Kotlin
(un libro para programadores de back end)
ISBN: 9798596367164
Autor: http://luis.criado.online/index.html
*/
package io.github.lcriadof.atrevete.kotlin.capitulo4
import java.io.File
// ejemplo inspirado en
// https://jamie.mccrindle.org/posts/exploring-kotlin-standard-library-part-2/
fun main() {
try {
if (File("/tmp/kotlin/f6.txt").exists()) { // [1]
File("/tmp/kotlin/f6.txt").delete() // [2]
}
File("/tmp/kotlin/f3.txt").copyTo(File("/tmp/kotlin/f6.txt"))
}
catch (e: Exception) {
println(e)
}
} | 0 | Kotlin | 0 | 0 | 403586f25f549590efb1bfd7e28cb0678f5c90b5 | 580 | AtreveteConKotlin | MIT License |
mobile/src/main/java/rs/readahead/washington/mobile/data/entity/reports/ReportPostResponse.kt | Horizontal-org | 193,379,924 | false | {"Java": 1621257, "Kotlin": 1441445} | package rs.readahead.washington.mobile.data.entity.reports
import rs.readahead.washington.mobile.domain.entity.reports.Author
data class ReportPostResponse (
val id: String?, val title: String?, val description: String?,
val createdAt: String?, val author: Author?
) | 16 | Java | 17 | 55 | 5dd19f8c9a810c165d2d8ec8947cc9d5d4620bab | 284 | Tella-Android | Apache License 2.0 |
src/main/java/ru/hollowhorizon/hc/common/network/HollowPacketV3.kt | HollowHorizon | 450,852,365 | false | {"Kotlin": 427166, "Java": 142695, "GLSL": 2355, "HTML": 357} | package ru.hollowhorizon.hc.common.network
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.world.entity.player.Player
import net.minecraftforge.network.NetworkDirection
import net.minecraftforge.network.NetworkEvent
import net.minecraftforge.network.PacketDistributor
import org.jetbrains.kotlin.utils.addToStdlib.cast
import ru.hollowhorizon.hc.client.utils.HollowJavaUtils
import ru.hollowhorizon.hc.client.utils.JavaHacks
import ru.hollowhorizon.hc.client.utils.mc
import ru.hollowhorizon.hc.client.utils.nbt.NBTFormat
import ru.hollowhorizon.hc.client.utils.nbt.deserializeNoInline
import ru.hollowhorizon.hc.client.utils.nbt.serializeNoInline
import java.util.function.Supplier
interface HollowPacketV3<T> {
fun handle(player: Player, data: T)
fun send(dist: PacketDistributor.PacketTarget) {
NetworkHandler.HollowCoreChannel.send(dist, this)
}
fun send() {
NetworkHandler.sendMessageToServer(this)
}
}
fun <T> Class<T>.register() = JavaHacks.registerPacket(this)
fun <T : HollowPacketV3<T>> registerPacket(packetClass: Class<T>) {
NetworkHandler.PACKET_TASKS.add {
NetworkHandler.HollowCoreChannel.registerMessage(
NetworkHandler.PACKET_INDEX++,
packetClass,
{ packet: T, buffer: FriendlyByteBuf ->
val tag = NBTFormat.serializeNoInline(packet, packetClass)
if (tag is CompoundTag) buffer.writeNbt(tag)
else buffer.writeNbt(CompoundTag().apply { put("%%data", tag) })
},
{ buffer: FriendlyByteBuf ->
val tag = buffer.readNbt() ?: throw IllegalStateException("Can't decode ${packetClass.name} packet!")
if (tag.contains("%%data")) NBTFormat.deserializeNoInline(tag.get("%%data")!!, packetClass)
else NBTFormat.deserializeNoInline(tag, packetClass)
},
{ packet: T, ctx: Supplier<NetworkEvent.Context> ->
ctx.get().apply {
packetHandled = true
enqueueWork {
if (direction == NetworkDirection.PLAY_TO_CLIENT) packet.handle(mc.player!!, packet)
else packet.handle(sender!!, packet)
}
}
}
)
}
} | 0 | Kotlin | 2 | 9 | 09c6522f4b5b08a81c4ba1b935ac8b8a11eeecd0 | 2,347 | HollowCore | MIT License |
ohyeah/setreminder/src/main/java/com/ewingsa/ohyeah/setreminder/WheelType.kt | ewingsa | 258,544,034 | false | null | package com.ewingsa.ohyeah.setreminder
enum class WheelType { HOURS, MINUTES, MERIDIES }
| 0 | Kotlin | 0 | 1 | 5d824181721e74026ec2e36a08678d5bb95276ef | 90 | ohyeah | Apache License 2.0 |
app/src/main/java/net/hwyz/iov/mp/app/component/title/Title.kt | hwyzleo | 856,732,945 | false | {"Kotlin": 213230, "Java": 907} | package net.hwyz.iov.mp.app.component.title
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import com.google.accompanist.placeholder.material.placeholder
import net.hwyz.iov.mp.app.theme.AppTheme
@Composable
fun Title(
title: String,
modifier: Modifier = Modifier,
fontSize: TextUnit,
color: Color = AppTheme.colors.fontSecondary,
fontWeight: FontWeight = FontWeight.Normal,
maxLine: Int = 1,
textAlign: TextAlign = TextAlign.Start,
isLoading: Boolean = false
) {
Text(
text = title,
modifier = modifier
.placeholder(
visible = isLoading,
color = AppTheme.colors.fontPrimary
),
fontSize = fontSize,
color = color,
maxLines = maxLine,
overflow = TextOverflow.Ellipsis,
textAlign = textAlign
)
} | 0 | Kotlin | 0 | 0 | 6d6a22a9f6031384b62de7b1b383dd9446c6d822 | 1,147 | iov-mp-android-app | MIT License |
kotlin-antd/antd-samples/src/main/kotlin/samples/avatar/ToggleDebug.kt | LuoKevin | 341,311,901 | true | {"Kotlin": 1549697, "HTML": 1503} | package samples.avatar
import antd.*
import antd.avatar.*
import antd.button.button
import kotlinext.js.*
import react.*
import react.dom.*
import styled.*
interface ToggleDebugAppState : RState {
var hide: Boolean
var size: String
var scale: Number
}
class ToggleDebugApp : RComponent<RProps, ToggleDebugAppState>() {
private val toggle: MouseEventHandler<Any> = {
setState {
hide = !state.hide
}
}
private val toggleSize: MouseEventHandler<Any> = {
val sizes = arrayOf("small", "default", "large")
var current = sizes.indexOf(state.size) + 1
if (current > 2) {
current = 0
}
setState {
size = sizes[current]
}
}
private val changeScale: MouseEventHandler<Any> = {
setState {
scale = if (state.scale == 1) 2 else 1
}
}
override fun ToggleDebugAppState.init() {
hide = true
size = "large"
scale = 1
}
override fun RBuilder.render() {
div {
button {
attrs.onClick = toggle
+"Toggle Avatar visibility"
}
button {
attrs.onClick = toggleSize
+"Toggle Avatar size"
}
button {
attrs.onClick = changeScale
+"Toggle Avatar scale"
}
br {}
br {}
div {
attrs.jsStyle = js {
textAlign = "center"
transform = "scale(${state.scale})"
marginTop = 24
}
avatar {
attrs {
size = state.size
style = js {
background = "#7265e6"
display = if (state.hide) "none" else ""
}
}
+"Avatar"
}
avatar {
attrs {
size = state.size
src = "invalid"
style = js {
background = "#00a2ae"
display = if (state.hide) "none" else ""
}
}
+"Invalid"
}
div {
attrs.jsStyle = js { display = if (state.hide) "none" else "" }
avatar {
attrs {
size = state.size
style = js { background = "#7265e6" }
}
+"Avatar"
}
avatar {
attrs {
size = state.size
src = "invalid"
style = js { background = "#00a2ae" }
}
+"Invalid"
}
}
}
}
}
}
fun RBuilder.toggleDebugApp() = child(ToggleDebugApp::class) {}
fun RBuilder.toggleDebug() {
styledDiv {
css { +AvatarStyles.toggleDebug }
toggleDebugApp()
}
}
| 0 | null | 0 | 0 | 9f57507607c3dd5d5452f3cbeb966b6db3d60c76 | 3,284 | kotlin-js-wrappers | Apache License 2.0 |
components/data-collector/src/test/kotlin/test/goodboards/app/collector/DBMock.kt | CSCI-5828-Foundations-Sftware-Engr | 614,026,505 | false | null | package test.goodboards.app.collector
import com.goodboards.db.DBInterface
import com.goodboards.db.DriverManagerWrapper
import com.goodboards.db.Game
import com.goodboards.db.SystemWrapper
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import java.sql.Connection
object DBMock {
val VALUE_DATABASE_URL = "fakeURL"
val VALUE_DATABASE_USERNAME = "fakeUsername"
val VALUE_DATABASE_PASSWORD = "<PASSWORD>"
fun mockDBConnection(): Unit {
mockkObject(SystemWrapper)
every { SystemWrapper.getenv("JDBC_DATABASE_URL") } returns VALUE_DATABASE_URL
every { SystemWrapper.getenv("DATABASE_USERNAME") } returns VALUE_DATABASE_USERNAME
every { SystemWrapper.getenv("DATABASE_PASSWORD") } returns VALUE_DATABASE_PASSWORD
val mockedConnection: Connection = mockk(relaxed = true)
mockkObject(DriverManagerWrapper)
every {
DriverManagerWrapper.getConnection(
"jdbc:fakeURL",
"fakeUsername",
"fakePassword"
)
} returns mockedConnection
}
fun makeGameInfos(count: Int) = ( 1 .. count).map {
listOf(it.toString(), it.toString() + "Name", it.toString() + "Description")
}.toList()
fun mockGames(count: Int): List<Game> = makeGameInfos(count).map {
Game(it[0], it[1], it[2])
}
fun mockDBInterface() : DBInterface {
mockkObject(DBHelper)
val dbInterface = mockk<DBInterface>()
every { DBHelper.getDBInterface() } returns dbInterface
return dbInterface
}
} | 38 | Kotlin | 1 | 2 | 7b6f00de4f9bd906f1e2d12a414228bd67edbf58 | 1,593 | slackers | Apache License 2.0 |
app/src/main/java/org/mp/newsapp/component/AppComponent.kt | mprasad2510 | 191,714,898 | false | null | package org.mp.newsapp.component
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import org.mp.newsapp.MviApp
import org.mp.newsapp.module.ActivityBindingModule
import org.mp.newsapp.module.AppModule
import org.mp.newsapp.module.NetworkModule
import javax.inject.Singleton
@Singleton
@Component(modules = [
AndroidSupportInjectionModule::class,
AppModule::class,
NetworkModule::class,
ActivityBindingModule::class
])
interface AppComponent : AndroidInjector<MviApp> {
@Component.Builder
abstract class Builder : AndroidInjector.Builder<MviApp>() {
abstract fun appModule(appModule: AppModule): Builder
override fun seedInstance(instance: MviApp?) {
appModule(AppModule(instance!!))
}
}
} | 0 | Kotlin | 0 | 0 | 4162df644474222d1b6f356d092b40816b5ceec9 | 833 | NewsApp | The Unlicense |
comet-mirai-wrapper/src/main/kotlin/ren/natsuyuk1/comet/mirai/contact/Group.kt | StarWishsama | 173,288,057 | false | null | package ren.natsuyuk1.comet.mirai.contact
import kotlinx.datetime.Clock
import net.mamoe.mirai.contact.*
import ren.natsuyuk1.comet.api.event.broadcast
import ren.natsuyuk1.comet.api.event.events.comet.MessagePreSendEvent
import ren.natsuyuk1.comet.api.message.MessageReceipt
import ren.natsuyuk1.comet.api.message.MessageWrapper
import ren.natsuyuk1.comet.api.platform.LoginPlatform
import ren.natsuyuk1.comet.api.user.Group
import ren.natsuyuk1.comet.api.user.GroupMember
import ren.natsuyuk1.comet.api.user.group.GroupPermission
import ren.natsuyuk1.comet.mirai.MiraiComet
import ren.natsuyuk1.comet.mirai.util.toMessageChain
import ren.natsuyuk1.comet.mirai.util.toMessageSource
fun Member.toGroupMember(comet: MiraiComet): GroupMember {
return when (this) {
is NormalMember -> this.toGroupMember(comet)
is AnonymousMember -> this.toGroupMember(comet)
else -> error("Unsupported mirai side member (${this::class.simpleName})")
}
}
internal abstract class MiraiGroupMember : GroupMember() {
override val platform: LoginPlatform = LoginPlatform.MIRAI
}
internal class MiraiGroupMemberImpl(
private val contact: NormalMember,
override val comet: MiraiComet
) : MiraiGroupMember() {
override val group: Group
get() = contact.group.toCometGroup(comet)
override val id: Long
get() = contact.id
override val joinTimestamp: Int
get() = contact.joinTimestamp
override val lastActiveTimestamp: Int
get() = contact.lastSpeakTimestamp
override val remainMuteTime: Int
get() = contact.muteTimeRemaining
override suspend fun getGroupPermission(): GroupPermission = contact.permission.toGroupPermission()
override suspend fun mute(seconds: Int) {
contact.mute(seconds)
}
override suspend fun unmute() = contact.unmute()
override suspend fun kick(reason: String, block: Boolean) {
contact.kick(reason, block)
}
override suspend fun operateAdminPermission(operation: Boolean) {
contact.modifyAdmin(operation)
}
override suspend fun sendMessage(message: MessageWrapper): MessageReceipt? {
val event = MessagePreSendEvent(
comet,
this@MiraiGroupMemberImpl,
message,
Clock.System.now().epochSeconds
).also { it.broadcast() }
return if (!event.isCancelled) {
val receipt = contact.sendMessage(message.toMessageChain(contact))
return MessageReceipt(comet, receipt.source.toMessageSource())
} else {
null
}
}
override val name: String
get() = contact.nick
override var card: String
get() = contact.nameCard
set(value) {
contact.nameCard = value
}
}
fun MemberPermission.toGroupPermission(): GroupPermission = GroupPermission.values()[ordinal]
fun NormalMember.toGroupMember(comet: MiraiComet): GroupMember = MiraiGroupMemberImpl(this, comet)
internal class MiraiAnonymousMemberImpl(
private val contact: AnonymousMember,
override val comet: MiraiComet
) : ren.natsuyuk1.comet.api.user.AnonymousMember() {
override val group: Group
get() = contact.group.toCometGroup(comet)
override val platform: LoginPlatform
get() = LoginPlatform.MIRAI
override val anonymousId: String
get() = contact.anonymousId
override val id: Long
get() = contact.id
/**
* 匿名成员无此变量, 默认返回 -1
*/
override val joinTimestamp: Int
get() = -1
/**
* 匿名成员无此变量, 默认返回 -1
*/
override val lastActiveTimestamp: Int
get() = -1
/**
* 匿名成员无此变量, 默认返回 -1
*/
override val remainMuteTime: Int
get() = -1
override suspend fun getGroupPermission(): GroupPermission = GroupPermission.MEMBER
override suspend fun mute(seconds: Int) {
contact.mute(seconds)
}
override suspend fun unmute() = contact.mute(0)
override suspend fun kick(reason: String, block: Boolean) {
error("AnonymousMember cannot be kicked")
}
override suspend fun operateAdminPermission(operation: Boolean) {
error("AnonymousMember cannot be promoted")
}
override suspend fun sendMessage(message: MessageWrapper): MessageReceipt? {
error("Cannot send message to AnonymousMember")
}
override val name: String
get() = contact.nick
override var card: String
get() = contact.nameCard
set(_) {
error("Cannot modify namecard of AnonymousMember")
}
}
fun AnonymousMember.toGroupMember(comet: MiraiComet): GroupMember = MiraiAnonymousMemberImpl(this, comet)
fun ContactList<NormalMember>.toGroupMemberList(comet: MiraiComet): List<GroupMember> {
val converted = mutableListOf<GroupMember>()
for (normalMember in this) {
converted.add(normalMember.toGroupMember(comet))
}
return converted
}
| 14 | Kotlin | 19 | 188 | 61d85469adca9e49a8d012d3916dafd92a303d91 | 4,942 | Comet-Bot | MIT License |
MidiTools/src/main/kotlin/com/example/android/miditools/synth/EnvelopeADSR.kt | android | 525,124,832 | false | {"Kotlin": 206640} | /*
* 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.example.android.miditools.synth
/**
* Very simple Attack, Decay, Sustain, Release envelope with linear ramps.
*
* Times are in seconds.
*/
class EnvelopeADSR(private val mSampleRate: Int) : SynthUnit() {
private var mAttackRate = 0f
private var mReleaseRate = 0f
private var mSustainLevel = 0f
private var mDecayRate = 0f
private var mCurrent = 0f
private var mState = IDLE
private fun setAttackTime(inTime: Float) {
var time = inTime
if (time < MIN_TIME) time = MIN_TIME
mAttackRate = 1.0f / (mSampleRate * time)
}
private fun setDecayTime(inTime: Float) {
var time = inTime
if (time < MIN_TIME) time = MIN_TIME
mDecayRate = 1.0f / (mSampleRate * time)
}
private fun setSustainLevel(inLevel: Float) {
var level = inLevel
if (level < 0.0f) level = 0.0f
mSustainLevel = level
}
private fun setReleaseTime(inTime: Float) {
var time = inTime
if (time < MIN_TIME) time = MIN_TIME
mReleaseRate = 1.0f / (mSampleRate * time)
}
fun on() {
mState = ATTACK
}
fun off() {
mState = RELEASE
}
override fun render(): Float {
when (mState) {
ATTACK -> {
mCurrent += mAttackRate
if (mCurrent > 1.0f) {
mCurrent = 1.0f
mState = DECAY
}
}
DECAY -> {
mCurrent -= mDecayRate
if (mCurrent < mSustainLevel) {
mCurrent = mSustainLevel
mState = SUSTAIN
}
}
RELEASE -> {
mCurrent -= mReleaseRate
if (mCurrent < 0.0f) {
mCurrent = 0.0f
mState = FINISHED
}
}
}
return mCurrent
}
val isDone: Boolean
get() = mState == FINISHED
companion object {
private const val IDLE = 0
private const val ATTACK = 1
private const val DECAY = 2
private const val SUSTAIN = 3
private const val RELEASE = 4
private const val FINISHED = 5
private const val MIN_TIME = 0.001f
}
init {
setAttackTime(0.003f)
setDecayTime(0.08f)
setSustainLevel(0.3f)
setReleaseTime(1.0f)
}
} | 0 | Kotlin | 11 | 40 | f30bceee0b1257359088d8acec4a95248b5695be | 3,041 | midi-samples | Apache License 2.0 |
src/main/kotlin/top/vuhe/tool/Serialization.kt | vuhe | 495,647,196 | false | null | package top.vuhe.tool
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.slf4j.LoggerFactory
import top.vuhe.Context
import top.vuhe.model.Question
import java.io.File
import java.time.LocalDateTime
object Serialization {
private val log = LoggerFactory.getLogger(Serialization::class.java)
/** 生成习题文件 */
fun buildQuestionToFile() = runBlocking(Dispatchers.IO) {
val date = LocalDateTime.now()
val prefix = "${Context.FILE_PATH}/${date.year}_${date.monthValue}_${date.dayOfMonth}_"
// 混合生成
QuestionFactory.HalfHalf.produce() writeTo File(prefix + "混合算式")
// 全加法生成
QuestionFactory.AllPlus.produce() writeTo File(prefix + "全加法")
// 全减法生成
QuestionFactory.AllMinus.produce() writeTo File(prefix + "全减法")
}
/** 从文件读取习题数据 */
fun readQuestionFromFile(file: File) = runBlocking(Dispatchers.IO) {
log.info("读取文件")
// 检查是否是文件
require(file.isFile) { "传入文件错误" }
val json = file.readText()
Context.question = Json.decodeFromString(json)
log.info("读取完成")
}
fun writeQuestionToFile(question: Question) = runBlocking(Dispatchers.IO) {
val filePath = "${Context.FILE_PATH}/${Context.file}"
question writeTo File(filePath)
}
private infix fun Question.writeTo(file: File) {
file.writeText(Json.encodeToString(this))
}
}
| 0 | Kotlin | 0 | 0 | 6adaad885f230fe19683275bef79f4c7bb793cfa | 1,557 | arithmetic-homework | MIT License |
app/src/main/java/com/saharw/calculator/presentation/base/IPresenter.kt | SaharWeissman | 130,581,486 | false | {"Kotlin": 24434} | package com.saharw.calculator.presentation.base
/**
* Created by saharw on 22/04/2018.
*/
interface IPresenter {
fun onCreate()
fun onResume()
fun onDestroy()
} | 0 | Kotlin | 0 | 0 | c9e1d109e0157ce64836f21a790e0fc21688c970 | 175 | CalculatorApp | Apache License 2.0 |
app/src/main/java/com/dudu/ledger/ui/activities/MainActivity.kt | dudu-Dev0 | 545,372,565 | false | null | package com.dudu.ledger.ui.activities
import android.os.Bundle
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dudu.ledger.R
import com.dudu.ledger.adapters.LedgerAdapter
import com.dudu.ledger.bean.Ledger
import org.litepal.LitePal
import org.litepal.extension.findAll
import java.util.*
class MainActivity : AppCompatActivity() {
private var ledgerList: List<Ledger> = mutableListOf()
private lateinit var ledgerRecyclerView: RecyclerView //数据显示
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ledgerRecyclerView = findViewById(R.id.recycler_main_ledger)
initData()
}
private fun initData() {
LitePal.getDatabase()
val tmpList = LitePal.findAll<Ledger>()
tmpList.reverse()
if (ledgerList != tmpList ) {
ledgerList = LitePal.findAll<Ledger>()
Collections.reverse(ledgerList)
ledgerRecyclerView.layoutManager = LinearLayoutManager(this)
ledgerRecyclerView.adapter = LedgerAdapter(ledgerList)
}
}
override fun onResume() {
super.onResume()
initData()
}
} | 0 | Kotlin | 0 | 2 | 8f2b999233949e82583e4291a659ae57792aa81b | 1,370 | Ledger | Apache License 2.0 |
app/src/main/java/com/skylaski/android/wgm/wireguard/MyTunnel.kt | Skylaski-VPN | 353,005,586 | false | null | package com.skylaski.android.wgm.wireguard
import com.wireguard.android.backend.Tunnel
class MyTunnel(name: String): Tunnel {
private var mName = name
override fun getName(): String {
return mName
}
override fun onStateChange(newState: Tunnel.State) {
State
}
enum class State {
DOWN, TOGGLE, UP;
companion object {
/**
* Get the state of a [Tunnel]
*
* @param running boolean indicating if the tunnel is running.
* @return State of the tunnel based on whether or not it is running.
*/
fun of(running: Boolean): State {
return if (running) UP else DOWN
}
}
}
} | 0 | Kotlin | 0 | 1 | 5658121c6829d7ab07d700cd8565044421fe910d | 752 | skylaskivpn-android | MIT License |
LibDialog/src/main/java/com/mx/dialog/list/MXBaseListDialog.kt | zmx1990 | 862,220,171 | false | {"Kotlin": 92714} | package com.mx.dialog.list
import android.content.Context
import android.graphics.RectF
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ListAdapter
import android.widget.ListView
import android.widget.TextView
import com.mx.dialog.R
import com.mx.dialog.base.MXBaseDialog
import com.mx.dialog.tip.MXDialogPosition
import com.mx.dialog.utils.MXDrawableUtils
import com.mx.dialog.utils.MXTextProp
import com.mx.dialog.utils.MXUtils
import com.mx.dialog.views.MXRatioFrameLayout
open class MXBaseListDialog(context: Context) : MXBaseDialog(context) {
private var includeStatusBarHeight: Boolean = false
private var includeNavigationBarHeight: Boolean = false
private var titleStr: CharSequence? = null
private var dialogBackgroundColor: Int? = null
private var contentCornerRadiusDP = 12f
private var contentMaxHeightRatioDP = 0.8f
private var cardMarginDP = RectF(22f, 22f, 22f, 22f)
private var position = MXDialogPosition.BOTTOM
private var mxRootLay: LinearLayout? = null
private var mxCardLay: ViewGroup? = null
private var btnLay: ViewGroup? = null
private var contentLay: MXRatioFrameLayout? = null
private var btnDivider: View? = null
private var cancelBtn: TextView? = null
private var okBtn: TextView? = null
private var titleTxv: TextView? = null
private var titleLay: LinearLayout? = null
private var listView: ListView? = null
private val cancelProp = MXTextProp()
private val actionProp = MXTextProp()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.mx_dialog_list)
initView()
}
private fun initView() {
if (mxRootLay == null) mxRootLay = findViewById(R.id.mxRootLay)
if (mxCardLay == null) mxCardLay = findViewById(R.id.mxCardLay)
if (btnLay == null) btnLay = findViewById(R.id.mxBtnLay)
if (contentLay == null) contentLay = findViewById(R.id.mxContentLay)
if (btnDivider == null) btnDivider = findViewById(R.id.mxBtnDivider)
if (cancelBtn == null) cancelBtn = findViewById(R.id.mxCancelBtn)
if (okBtn == null) okBtn = findViewById(R.id.mxOkBtn)
if (titleTxv == null) titleTxv = findViewById(R.id.mxTitleTxv)
if (titleLay == null) titleLay = findViewById(R.id.mxTitleLay)
if (listView == null) listView = findViewById(R.id.listView)
}
override fun onStart() {
super.onStart()
initDialog()
}
protected open fun initDialog() {
if (listView == null) return
if (titleStr != null) {
titleTxv?.text = titleStr
titleLay?.visibility = View.VISIBLE
} else {
titleLay?.visibility = View.GONE
}
mxRootLay?.setOnClickListener {
if (isCanceledOnTouchOutside()) {
onBackPressed()
}
}
mxCardLay?.setOnClickListener { }
kotlin.run {
processCancelBtn()
processActionBtn()
if (cancelBtn?.visibility == View.VISIBLE && okBtn?.visibility == View.VISIBLE) {
btnDivider?.visibility = View.VISIBLE
} else {
btnDivider?.visibility = View.GONE
}
if (cancelBtn?.visibility != View.VISIBLE && okBtn?.visibility != View.VISIBLE) {
btnLay?.visibility = View.GONE
} else {
btnLay?.visibility = View.VISIBLE
}
}
if (contentCornerRadiusDP >= 0) {
mxCardLay?.background = MXDrawableUtils.buildGradientDrawable(
context, R.color.mx_dialog_color_background_content,
contentCornerRadiusDP
)
} else {
mxCardLay?.setBackgroundResource(R.drawable.mx_dialog_card_bg)
}
kotlin.run { // 位置设置
val marginLeft = MXUtils.dp2px(context, cardMarginDP.left)
val marginTop = MXUtils.dp2px(
context,
cardMarginDP.top
) + (if (includeStatusBarHeight) MXUtils.getStatusBarHeight(context) else 0)
val marginRight = MXUtils.dp2px(context, cardMarginDP.right)
val marginBottom = MXUtils.dp2px(
context,
cardMarginDP.bottom
) + (if (includeNavigationBarHeight) MXUtils.getNavigationBarHeight(context) else 0)
mxRootLay?.setPadding(marginLeft, marginTop, marginRight, marginBottom)
val screenWidth = MXUtils.getScreenWidth(context) - marginLeft - marginRight
mxCardLay?.layoutParams?.width = screenWidth
btnLay?.layoutParams?.width = screenWidth
}
kotlin.run {
val color = dialogBackgroundColor
?: context.resources.getColor(R.color.mx_dialog_color_background_root)
mxRootLay?.setBackgroundColor(color)
}
kotlin.run {
mxRootLay?.gravity = position.gravity
mxCardLay?.translationX =
MXUtils.dp2px(context, position.translationX ?: 0).toFloat()
mxCardLay?.translationY =
MXUtils.dp2px(context, position.translationY ?: 0).toFloat()
}
contentLay?.setMaxHeightRatio(contentMaxHeightRatioDP)
mxRootLay?.post {
calculatorListHeight()
}
}
/**
* 动态计算列表高度
*/
private fun calculatorListHeight() {
val mxRootLay = mxRootLay ?: return
var maxHeight = mxRootLay.height - mxRootLay.paddingTop - mxRootLay.paddingBottom
if (cancelBtn?.visibility == View.VISIBLE) {
maxHeight -= context.resources.getDimensionPixelOffset(R.dimen.mx_dialog_size_action_height)
maxHeight -= context.resources.getDimensionPixelOffset(R.dimen.mx_dialog_size_divider_normal)
}
if (titleLay?.visibility == View.VISIBLE) {
maxHeight -= context.resources.getDimensionPixelOffset(R.dimen.mx_dialog_size_list_item_height)
}
// maxHeight -= context.resources.getDimensionPixelOffset(R.dimen.mx_dialog_size_divider_space)
if (maxHeight > 0) {
contentLay?.setMaxHeight(maxHeight)
}
}
protected open fun showCancelBtn() = true
protected open fun showActionBtn() = false
private fun processCancelBtn() {
val button = cancelBtn ?: return
val visible = showCancelBtn() && isCancelable()
if (!visible) {
button.visibility = View.GONE
return
}
button.visibility = View.VISIBLE
button.text =
cancelProp.text ?: context.resources.getString(R.string.mx_dialog_button_cancel_text)
cancelProp.attachTextColor(cancelBtn, R.color.mx_dialog_color_text_cancel)
cancelProp.attachTextSize(cancelBtn, R.dimen.mx_dialog_text_size_button)
button.setOnClickListener { onBackPressed() }
if (contentCornerRadiusDP >= 0) {
button.background = MXDrawableUtils.buildGradientDrawable(
context, R.color.mx_dialog_color_background_content,
contentCornerRadiusDP
)
} else {
button.setBackgroundResource(R.drawable.mx_dialog_btn_bg_cancel_corner)
}
}
private fun processActionBtn() {
val button = okBtn ?: return
val visible = showActionBtn()
if (!visible) {
button.visibility = View.GONE
return
}
button.visibility = View.VISIBLE
button.text =
actionProp.text ?: context.resources.getString(R.string.mx_dialog_button_action_text)
actionProp.attachTextColor(okBtn, R.color.mx_dialog_color_text_action)
actionProp.attachTextSize(okBtn, R.dimen.mx_dialog_text_size_button)
button.setOnClickListener {
dismiss()
actionProp.onclick?.invoke()
}
if (contentCornerRadiusDP >= 0) {
button.background = MXDrawableUtils.buildGradientDrawable(
context, R.color.mx_dialog_color_action,
contentCornerRadiusDP
)
} else {
button.setBackgroundResource(R.drawable.mx_dialog_btn_bg_action_corner)
}
}
override fun setTitle(title: CharSequence?) {
titleStr = title
initDialog()
}
override fun setTitle(titleId: Int) {
titleStr = context.resources.getString(titleId)
initDialog()
}
override fun setCancelable(cancelable: Boolean) {
super.setCancelable(cancelable)
initDialog()
}
fun setAdapt(adapt: ListAdapter) {
listView?.adapter = adapt
}
fun setItemClick(call: (Int) -> Unit) {
listView?.setOnItemClickListener { _, _, position, _ ->
call.invoke(position)
}
}
/**
* 设置活动按钮
*/
fun setActionBtn(
text: CharSequence? = null,
textColor: Int? = null,
textSizeSP: Float? = null
) {
actionProp.text = text
actionProp.textColor = textColor
actionProp.textSizeSP = textSizeSP
initDialog()
}
/**
* 设置取消按钮
*/
fun setCancelBtn(
text: CharSequence? = null,
textColor: Int? = null,
textSizeSP: Float? = null
) {
cancelProp.text = text ?: context.resources.getString(R.string.mx_dialog_button_cancel_text)
cancelProp.textColor = textColor
cancelProp.textSizeSP = textSizeSP
initDialog()
}
protected fun setActionClick(click: (() -> Unit)? = null) {
actionProp.onclick = click
}
/**
* 设置弹窗背景颜色
*/
fun setDialogBackGroundColor(color: Int) {
dialogBackgroundColor = color
initDialog()
}
/**
* 设置内容ViewGroup 背景圆角半径
*/
fun setContentCornerRadius(radiusDP: Float) {
contentCornerRadiusDP = radiusDP
initDialog()
}
/**
* 设置内容最大宽高比
*/
fun setContentMaxHeightRatio(ratioDP: Float) {
contentMaxHeightRatioDP = ratioDP
initDialog()
}
/**
* 设置弹窗位置
*/
fun setContentPosition(position: MXDialogPosition) {
this.position = position
initDialog()
}
/**
* 设置内容外边距
* 单位:DP
* @param margin 左/右/上/下 边框宽度
* @param includeStatusBarHeight 上边框宽度是否加上状态栏高度
* @param includeNavigationBarHeight 下边框宽度是否加上导航栏高度
*/
fun setContentMargin(
margin: Float,
includeStatusBarHeight: Boolean = false,
includeNavigationBarHeight: Boolean = false
) {
cardMarginDP = RectF(margin, margin, margin, margin)
this.includeStatusBarHeight = includeStatusBarHeight
this.includeNavigationBarHeight = includeNavigationBarHeight
initDialog()
}
/**
* 设置内容外边距
* 单位:DP
* @param horizontal 左/右 边框宽度
* @param vertical 上/下 边框宽度
* @param includeStatusBarHeight 上边框宽度是否加上状态栏高度
* @param includeNavigationBarHeight 下边框宽度是否加上导航栏高度
*/
fun setContentMargin(
horizontal: Float, vertical: Float,
includeStatusBarHeight: Boolean = false,
includeNavigationBarHeight: Boolean = false
) {
cardMarginDP = RectF(horizontal, vertical, horizontal, vertical)
this.includeStatusBarHeight = includeStatusBarHeight
this.includeNavigationBarHeight = includeNavigationBarHeight
initDialog()
}
/**
* 设置内容外边距
* 单位:DP
* @param left 左 边框宽度
* @param top 上 边框宽度
* @param right 右 边框宽度
* @param bottom 下 边框宽度
* @param includeStatusBarHeight 上边框宽度是否加上状态栏高度
* @param includeNavigationBarHeight 下边框宽度是否加上导航栏高度
*/
fun setContentMargin(
left: Float, top: Float, right: Float, bottom: Float,
includeStatusBarHeight: Boolean = true,
includeNavigationBarHeight: Boolean = true
) {
cardMarginDP = RectF(left, top, right, bottom)
this.includeStatusBarHeight = includeStatusBarHeight
this.includeNavigationBarHeight = includeNavigationBarHeight
initDialog()
}
} | 0 | Kotlin | 0 | 0 | b52a8d5483bc0eaf1d1936f01a2c6a8a0a5e489f | 12,201 | MXDialog | Apache License 2.0 |
library/renetik-base/src/test/java/renetik/android/java/extensions/StringBuilderTest.kt | rene-dohan | 69,289,476 | false | null | package renetik.android.java.extensions
import org.junit.Assert.assertEquals
import org.junit.Test
import renetik.kotlin.text.StringBuilder
import renetik.kotlin.text.cutStart
import renetik.kotlin.text.deleteLast
import renetik.kotlin.text.remove
class StringBuilderTest {
@Test
fun deleteLast() =
assertEquals("123456", StringBuilder("12345678").deleteLast(2).toString())
@Test
fun cutStart() =
assertEquals("345678", StringBuilder("12345678").cutStart(2).toString())
@Test
fun removeStartLength() =
assertEquals("125678", StringBuilder("12345678").remove(2, 2).toString())
}
| 2 | Kotlin | 1 | 1 | 29735b81359911206fd16ce50f4d1fc687dae54c | 630 | renetik-library-android | Apache License 2.0 |
app/src/main/java/com/eatssu/android/data/usecase/AlarmUsecase.kt | EAT-SSU | 601,871,281 | false | {"Kotlin": 249990} | package com.eatssu.android.data.usecase
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.eatssu.android.util.NotificationReceiver
import java.util.Calendar
import javax.inject.Inject
class AlarmUseCase @Inject constructor(private val context: Context) {
fun scheduleAlarm() {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, NotificationReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val calendar = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 11)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
if (calendar.timeInMillis <= System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_YEAR, 1)
}
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent
)
}
fun cancelAlarm() {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, NotificationReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
alarmManager.cancel(pendingIntent)
}
}
| 26 | Kotlin | 0 | 9 | 751ca8534d3c65a56d88190d42b0711f8e66c822 | 1,600 | Android | MIT License |
src/main/kotlin/com/example/mongoreactivedemo/MongoReactiveDemoApplication.kt | yurickgomes | 809,421,797 | false | {"Kotlin": 12555} | package com.example.mongoreactivedemo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class MongoReactiveDemoApplication
fun main(args: Array<String>) {
runApplication<MongoReactiveDemoApplication>(*args)
}
| 0 | Kotlin | 0 | 0 | cf0262f1d61547ad4dd64a4826aa7df6c24ffa30 | 301 | spring-reactive-mongodb-demo | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/DoorEnter.kt | walter-juan | 868,046,028 | false | {"Kotlin": 20416825} | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.DoorEnter: ImageVector
get() {
if (_doorEnter != null) {
return _doorEnter!!
}
_doorEnter = Builder(name = "DoorEnter", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(13.0f, 12.0f)
verticalLineToRelative(0.01f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 21.0f)
horizontalLineToRelative(18.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(5.0f, 21.0f)
verticalLineToRelative(-16.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(6.0f)
moveToRelative(4.0f, 10.5f)
verticalLineToRelative(7.5f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(21.0f, 7.0f)
horizontalLineToRelative(-7.0f)
moveToRelative(3.0f, -3.0f)
lineToRelative(-3.0f, 3.0f)
lineToRelative(3.0f, 3.0f)
}
}
.build()
return _doorEnter!!
}
private var _doorEnter: ImageVector? = null
| 0 | Kotlin | 0 | 1 | b037895588c2f62d069c724abe624b67c0889bf9 | 2,898 | compose-icon-collections | MIT License |
app/src/main/java/com/vicky7230/tasker/data/network/ApiService.kt | Animesh-Barai | 253,386,503 | true | {"Kotlin": 97544, "Java": 40107} | package com.vicky7230.tasker.data.network
import com.google.gson.JsonElement
import com.vicky7230.tasker.worker.TaskSync
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
interface ApiService {
@FormUrlEncoded
@POST("api/LoginApi/generateOTP")
suspend fun generateOtp(
@Field("email") email: String
): Response<JsonElement>
@FormUrlEncoded
@POST("api/LoginApi/verifyOTP")
suspend fun verifyOtp(
@Field("email") email: String,
@Field("otp") otp: String
): Response<JsonElement>
@FormUrlEncoded
@POST("api/TaskApi/getUserTaskLists")
suspend fun getUserTaskLists(
@Field("userID") userId: String?,
@Field("token") token: String?
): Response<JsonElement>
@POST("api/TaskApi/syncSingleTask")
suspend fun syncSingleTask(
@Body taskSync: TaskSync
): Response<JsonElement>
@FormUrlEncoded
@POST("api/TaskApi/getUserTasks")
suspend fun getUserTasks(
@Field("userID") userId: String?,
@Field("token") token: String?
): Response<JsonElement>
} | 0 | null | 0 | 0 | 4073580268d01e18e26f10eab7d826cd145a7256 | 1,176 | Tasker | Apache License 2.0 |
custom-vu/src/main/kotlin/jces1209/vu/page/admin/workflow/browse/CloudBrowseWorkflowsPage.kt | dmewada-atlas | 290,410,294 | true | {"Kotlin": 235838} | package jces1209.vu.page.admin.workflow
import com.atlassian.performance.tools.jiraactions.api.WebJira
import jces1209.vu.page.FalliblePage
import jces1209.vu.wait
import org.openqa.selenium.By
import org.openqa.selenium.support.ui.ExpectedConditions.*
import java.time.Duration
class CloudBrowseWorkflowsPage(
private val jira: WebJira
) : BrowseWorkflowsPage(jira) {
private val falliblePage = FalliblePage.Builder(
jira.driver,
and(
visibilityOfElementLocated(By.className("aui-page-panel")),
visibilityOfElementLocated(By.id("active-workflows-module")),
presenceOfAllElementsLocatedBy(By.cssSelector(".workflow-name, .workflow-schemes, .workflow-operations")),
presenceOfElementLocated(By.id("inactive-workflows-module"))
)
)
.cloudErrors()
.timeout(Duration.ofSeconds(30))
.build()
override fun waitForBeingLoaded(): CloudBrowseWorkflowsPage {
falliblePage.waitForPageToLoad()
return this
}
}
| 0 | null | 0 | 0 | b036176c7c568f0e1f8e75e265c9008244c1a1a6 | 1,034 | jces-1209 | Apache License 2.0 |
bidding-service/src/main/kotlin/de/alxgrk/config/ConfigurationProperties.kt | alxgrk | 520,474,867 | false | {"Kotlin": 117999, "TypeScript": 71187, "CSS": 1456, "HTML": 365, "Shell": 105} | package de.alxgrk.config
import com.okta.jwt.JwtVerifiers
import io.ktor.server.application.*
import io.ktor.util.*
fun Application.loadConfigurationProperties(): ConfigurationProperties = ConfigurationProperties(
developmentMode = stringFromEnv("ktor.development").toBoolean(),
jwt = ConfigurationProperties.JWT(
secret = stringFromEnv("jwt.secret"),
audience = stringFromEnv("jwt.audience"),
realm = stringFromEnv("jwt.realm"),
issuer = stringFromEnv("jwt.issuer")
),
adminAuth = ConfigurationProperties.AdminAuth(
realm = stringFromEnv("admin.realm"),
username = stringFromEnv("admin.username"),
password = stringFromEnv("admin.password")
),
cookies = ConfigurationProperties.Cookies(
encryptionKey = hex(stringFromEnv("cookies.encryptionKey")),
signingKey = hex(stringFromEnv("cookies.signingKey"))
),
db = ConfigurationProperties.DB(stringFromEnv("db.redis")),
)
private fun Application.stringFromEnv(path: String) =
environment.config.property(path).getString()
data class ConfigurationProperties(
val developmentMode: Boolean,
val jwt: JWT,
val adminAuth: AdminAuth,
val cookies: Cookies,
val db: DB
) {
data class JWT(
val secret: String,
val audience: String,
val realm: String,
val issuer: String,
)
data class AdminAuth(
val realm: String,
val username: String,
val password: String
)
data class Cookies(
val encryptionKey: ByteArray,
val signingKey: ByteArray
)
data class DB(
val redis: String
)
}
| 0 | Kotlin | 0 | 0 | 4cf85dbead025ef0eae3e6f33dd9aaf6fe4a1ad5 | 1,663 | redis-dev-to-hackathon-auction-system | MIT License |
aoc-2015/src/test/kotlin/nl/jstege/adventofcode/aoc2015/days/Day15Test.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.utils.DayTester
/**
* Test for Day15
* @author <NAME>
*/
class Day15Test : DayTester(Day15()) | 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 182 | AdventOfCode | MIT License |
longball-model/src/test/kotlin/net/alexanderkahn/longball/model/RequestRosterPositionTest.kt | alexanderkahn | 129,308,181 | false | null | package net.alexanderkahn.longball.model
import net.alexanderkahn.service.commons.model.response.body.data.RelationshipObject
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.util.*
import javax.validation.Validation
import javax.validation.Validator
import javax.validation.constraints.Min
import kotlin.test.assertEquals
internal class RequestRosterPositionTest {
@Nested
inner class Validates {
private lateinit var validator: Validator
private val validPosition = RequestRosterPosition(
"rosterpositions",
RosterPositionAttributes(1, LocalDate.now()),
RosterPositionRelationships(RelationshipObject("teams", UUID.randomUUID()), RelationshipObject("people", UUID.randomUUID()))
)
@BeforeEach
internal fun setUp() {
val factory = Validation.buildDefaultValidatorFactory()
this.validator = factory.validator
}
@Test
internal fun validRequest() {
val violations = validator.validate(validPosition)
assertEquals(0, violations.size)
}
@Test
internal fun invalidType() {
val invalidType = "romperportions"
val position = RequestRosterPosition(
invalidType,
RosterPositionAttributes(1, LocalDate.now()),
RosterPositionRelationships(RelationshipObject("teams", UUID.randomUUID()), RelationshipObject("people", UUID.randomUUID()))
)
val violations = validator.validate(position)
assertEquals(1, violations.size)
}
@Test
internal fun invalidTeamType() {
val invalidType = "tram"
val position = RequestRosterPosition(
"rosterpositions",
RosterPositionAttributes(1, LocalDate.now()),
RosterPositionRelationships(RelationshipObject(invalidType, UUID.randomUUID()), RelationshipObject("people", UUID.randomUUID()))
)
val violations = validator.validate(position)
assertEquals(1, violations.size)
}
@Test
internal fun invalidPlayerType() {
val invalidType = "plural"
val position = RequestRosterPosition(
"rosterpositions",
RosterPositionAttributes(1, LocalDate.now()),
RosterPositionRelationships(RelationshipObject("teams", UUID.randomUUID()), RelationshipObject(invalidType, UUID.randomUUID()))
)
val violations = validator.validate(position)
assertEquals(1, violations.size)
}
@Test
internal fun invalidJerseyNumber() {
val invalidPosition = validPosition.copy(attributes = validPosition.attributes.copy(jerseyNumber = -1))
val violations = validator.validate(invalidPosition)
assertEquals(1, violations.size)
assertEquals(Min::class, violations.first().constraintDescriptor.annotation.annotationClass)
}
}
} | 0 | Kotlin | 0 | 0 | 447febebf1530e81532794c364155f914da418d9 | 3,195 | longball-service | MIT License |
src/test/kotlin/ru/hse/spb/sd/full_metal_rogue/logic/map/SerializationTest.kt | alefedor | 173,711,727 | false | null | package ru.hse.spb.sd.full_metal_rogue.logic.map
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import ru.hse.spb.sd.full_metal_rogue.logic.inventory.SimpleContentGenerator
import ru.hse.spb.sd.full_metal_rogue.logic.level.ActorGenerator
import ru.hse.spb.sd.full_metal_rogue.logic.level.StandardLevelGenerator
import ru.hse.spb.sd.full_metal_rogue.logic.level.TrivialActorGenerator
import ru.hse.spb.sd.full_metal_rogue.logic.objects.Chest
import ru.hse.spb.sd.full_metal_rogue.logic.objects.Player
import ru.hse.spb.sd.full_metal_rogue.view.ChestView
import ru.hse.spb.sd.full_metal_rogue.view.MutableMenu
import ru.hse.spb.sd.full_metal_rogue.view.View
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
class SerializationTest {
@Test
fun testChestView() {
val items = mutableListOf(
SimpleContentGenerator.generateItem(), SimpleContentGenerator.generateItem(), SimpleContentGenerator.generateItem()
)
val menu = MutableMenu(items)
testDeserializedEquals(ChestView(menu))
}
@Test
fun testMap() {
val map = StandardLevelGenerator().generateLevel(20, 20)
testDeserializedEquals(map)
}
@Test
fun testMapWithPlayer() {
val map = StandardLevelGenerator().generateLevel(20, 20)
map[0, 0] = TrivialActorGenerator(SimpleContentGenerator).generatePlayer("player")
testDeserializedEquals(map)
}
@Test
fun testMapWithChest() {
val map = StandardLevelGenerator().generateLevel(20, 20)
val items = mutableListOf(
SimpleContentGenerator.generateItem(), SimpleContentGenerator.generateItem(), SimpleContentGenerator.generateItem()
)
map[0, 0] = Chest(items)
testDeserializedEquals(map)
}
private fun testDeserializedEquals(obj: Any) {
val byteStream = ByteArrayOutputStream()
val objectStream = ObjectOutputStream(byteStream)
objectStream.writeObject(obj)
objectStream.flush()
val serializedObj = byteStream.toByteArray()
val deserializedObj = ObjectInputStream(ByteArrayInputStream(serializedObj)).readObject()
assertThat(obj).isEqualToComparingFieldByFieldRecursively(deserializedObj)
}
} | 0 | Kotlin | 0 | 0 | aa693d6d078083d9fedccd77a6e7c27205971335 | 2,348 | full_metal_rogue | MIT License |
buildSrc/src/main/kotlin/com/xfhy/asm/timecost/TimeCostPlugin.kt | xfhy | 258,978,567 | false | null | package com.xfhy.asm.timecost
import com.android.build.api.instrumentation.FramesComputationMode
import com.android.build.api.instrumentation.InstrumentationScope
import com.android.build.api.variant.AndroidComponentsExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
/**
* @author : xfhy
* Create time : 2023/2/20 21:20
* Description : 方法耗时统计 , ASM插桩
*
* Gradle 7.0 开始是通过 AndroidComponentsExtension来注册脚本的,之前的Transform被标记为废弃
*
*/
class TimeCostPlugin : Plugin<Project> {
override fun apply(project: Project) {
val androidComponents = project.extensions.getByType(AndroidComponentsExtension::class.java)
androidComponents.onVariants { variant ->
//不同的variant可以实现不同的处理
//InstrumentationScope控制扫描哪些代码
variant.instrumentation.transformClassesWith(
TimeCostTransform::class.java,
InstrumentationScope.PROJECT
) {}
//设置不同的栈帧计算模式
variant.instrumentation.setAsmFramesComputationMode(FramesComputationMode.COMPUTE_FRAMES_FOR_INSTRUMENTED_METHODS)
}
}
} | 1 | Kotlin | 5 | 6 | 294cd16f0549f97d13304d659e76c776189e44ff | 1,107 | AllInOne | Apache License 2.0 |
src/main/kotlin/no/nav/sosialhjelp/sosialhjelpfssproxy/tilgang/WellKnown.kt | navikt | 447,158,640 | false | {"Kotlin": 36042, "Dockerfile": 427} | package no.nav.sosialhjelp.sosialhjelpfssproxy.tilgang
import com.fasterxml.jackson.annotation.JsonProperty
data class WellKnown(
val issuer: String,
@JsonProperty("authorization_endpoint")
val authorizationEndpoint: String?,
@JsonProperty("token_endpoint")
val tokenEndpoint: String,
@JsonProperty("jwks_uri")
val jwksUri: String
)
| 0 | Kotlin | 0 | 0 | 08034f755564e5e5013891dd021ca33cc665dc87 | 363 | sosialhjelp-fss-proxy | MIT License |
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/brands/Bootstrap.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.fontawesomeicons.brands
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.fontawesomeicons.BrandsGroup
public val BrandsGroup.Bootstrap: ImageVector
get() {
if (_bootstrap != null) {
return _bootstrap!!
}
_bootstrap = Builder(name = "Bootstrap", defaultWidth = 448.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 448.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(292.3f, 311.93f)
curveToRelative(0.0f, 42.41f, -39.72f, 41.43f, -43.92f, 41.43f)
horizontalLineToRelative(-80.89f)
verticalLineToRelative(-81.69f)
horizontalLineToRelative(80.89f)
curveToRelative(42.56f, 0.0f, 43.92f, 31.9f, 43.92f, 40.26f)
close()
moveTo(242.15f, 238.8f)
curveToRelative(0.67f, 0.0f, 38.44f, 1.0f, 38.44f, -36.31f)
curveToRelative(0.0f, -15.52f, -3.51f, -35.87f, -38.44f, -35.87f)
horizontalLineToRelative(-74.66f)
verticalLineToRelative(72.18f)
horizontalLineToRelative(74.66f)
close()
moveTo(448.0f, 106.67f)
verticalLineToRelative(298.66f)
arcTo(74.89f, 74.89f, 0.0f, false, true, 373.33f, 480.0f)
lineTo(74.67f, 480.0f)
arcTo(74.89f, 74.89f, 0.0f, false, true, 0.0f, 405.33f)
lineTo(0.0f, 106.67f)
arcTo(74.89f, 74.89f, 0.0f, false, true, 74.67f, 32.0f)
horizontalLineToRelative(298.66f)
arcTo(74.89f, 74.89f, 0.0f, false, true, 448.0f, 106.67f)
close()
moveTo(338.05f, 317.86f)
curveToRelative(0.0f, -21.57f, -6.65f, -58.29f, -49.05f, -67.35f)
verticalLineToRelative(-0.73f)
curveToRelative(22.91f, -9.78f, 37.34f, -28.25f, 37.34f, -55.64f)
curveToRelative(0.0f, -7.0f, 2.0f, -64.78f, -77.6f, -64.78f)
horizontalLineToRelative(-127.0f)
verticalLineToRelative(261.33f)
curveToRelative(128.23f, 0.0f, 139.87f, 1.68f, 163.6f, -5.71f)
curveToRelative(14.21f, -4.42f, 52.71f, -17.98f, 52.71f, -67.12f)
close()
}
}
.build()
return _bootstrap!!
}
private var _bootstrap: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 3,115 | compose-icons | MIT License |
src/main/java/com/mallowigi/idea/MTStartup.kt | mallowigi | 177,159,235 | false | {"Kotlin": 50737, "JavaScript": 7011} | /*
* The MIT License (MIT)
*
* Copyright (c) 2021 Elior "Mallowigi" Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mallowigi.idea
import com.intellij.ide.AppLifecycleListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.registry.Registry
/** Runs at start. */
class MTStartup : StartupActivity {
/** Modify the registry at start. */
override fun runActivity(project: Project) {
modifyRegistry()
ApplicationManager.getApplication().messageBus.connect().also {
it.subscribe(
AppLifecycleListener.TOPIC,
object : AppLifecycleListener {
override fun appClosing() {
Registry.get(IDE_BALLOON_SHADOW_SIZE).setValue(15)
Registry.get(IDE_INTELLIJ_LAF_ENABLE_ANIMATION).setValue(false)
it.disconnect()
}
}
)
}
}
companion object {
private const val IDE_BALLOON_SHADOW_SIZE = "ide.balloon.shadow.size"
private const val IDE_INTELLIJ_LAF_ENABLE_ANIMATION = "ide.intellij.laf.enable.animation"
private fun modifyRegistry() {
Registry.get(IDE_BALLOON_SHADOW_SIZE).setValue(0)
Registry.get(IDE_INTELLIJ_LAF_ENABLE_ANIMATION).setValue(true)
}
}
}
| 8 | Kotlin | 9 | 45 | 211c016fdff8d797e884aa4e0e833cd34bd8f5ed | 2,377 | material-theme-ui-lite | MIT License |
app/src/main/java/com/github/fajaragungpramana/igit/module/search/SearchState.kt | fajaragungpramana | 759,898,833 | false | {"Kotlin": 114464} | package com.github.fajaragungpramana.igit.module.search
import androidx.paging.PagingData
import com.github.fajaragungpramana.igit.core.domain.user.model.User
sealed class SearchState {
data class UserData(val pagingData: PagingData<User>) : SearchState()
} | 0 | Kotlin | 0 | 2 | a9180669cf3a887207f6f41a4c558cba71e85c32 | 265 | android.igit | Apache License 2.0 |
app/src/main/java/mihon/core/migration/migrations/MoveCatalogueCoverOnlyGridSettingMigration.kt | komikku-app | 743,200,516 | false | {"Kotlin": 5951497} | package mihon.core.migration.migrations
import android.app.Application
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import mihon.core.migration.Migration
import mihon.core.migration.MigrationContext
import tachiyomi.core.common.util.lang.withIOContext
class MoveCatalogueCoverOnlyGridSettingMigration : Migration {
override val version: Float = 29f
override suspend fun invoke(migrationContext: MigrationContext): Boolean = withIOContext {
val context = migrationContext.get<Application>() ?: return@withIOContext false
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
if (prefs.getString("pref_display_mode_catalogue", null) == "NO_TITLE_GRID") {
prefs.edit(commit = true) {
putString("pref_display_mode_catalogue", "COMPACT_GRID")
}
}
return@withIOContext true
}
}
| 93 | Kotlin | 14 | 504 | bc460dd3b1edf67d095df0b15c6d1dc39444d5e6 | 915 | komikku | Apache License 2.0 |
bili-api/src/main/kotlin/dev/aaa1115910/biliapi/entity/pgc/PgcCarouselData.kt | aaa1115910 | 571,702,700 | false | {"Kotlin": 1683327} | package dev.aaa1115910.biliapi.entity.pgc
import dev.aaa1115910.biliapi.http.entity.pgc.PgcWebInitialStateData
import io.ktor.http.Url
data class PgcCarouselData(
val items: List<CarouselItem>
) {
companion object {
fun fromPgcWebInitialStateData(data: PgcWebInitialStateData): PgcCarouselData {
val result = mutableListOf<CarouselItem>()
var isMovie = false
// 电影板块里的轮播图数据里没有直接包含 episodeId 和 seasonId
if (data.modules.banner.moduleId == 1668) isMovie = true
data.modules.banner.items.filter {
it.episodeId != null || (isMovie && it.link.contains("bangumi/play/ep"))
}.forEach {
var cover = it.bigCover ?: it.cover
if (cover.startsWith("//")) cover = "https:$cover"
result.add(
CarouselItem(
cover = cover,
title = it.title,
seasonId = it.seasonId ?: -1,
episodeId = it.episodeId
?: Url(it.link).pathSegments.last().substring(2).toInt()
)
)
}
return PgcCarouselData(result)
}
}
data class CarouselItem(
val cover: String,
val title: String,
val seasonId: Int,
val episodeId: Int
)
}
| 22 | Kotlin | 161 | 1,429 | ac8c6ca424a99840e4073d7aa8fe71ea8a898388 | 1,394 | bv | MIT License |
src/main/kotlin/online/pizzacrust/kotlinroblox/xml/Element.kt | PizzaCrust | 143,601,164 | false | null | package online.pizzacrust.kotlinroblox.xml
interface Element : HasChildren {
fun attribute(attributeName: String): String?
val className: String?
get() = attribute("class")
val tagName: String
val text: String?
} | 0 | Kotlin | 0 | 1 | a556a7a2593f8fa89ebf00382413c0698fb62a67 | 242 | KotlinRoblox | MIT License |
quote/src/main/java/com/pyamsoft/tickertape/quote/dig/DigViewModeler.kt | pyamsoft | 371,196,339 | false | null | /*
* Copyright 2021 Peter Kenji Yamanaka
*
* 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.pyamsoft.tickertape.quote.dig
import com.pyamsoft.pydroid.arch.AbstractViewModeler
import com.pyamsoft.pydroid.core.ResultWrapper
import com.pyamsoft.tickertape.quote.Chart
import com.pyamsoft.tickertape.quote.Ticker
import com.pyamsoft.tickertape.stocks.api.StockChart
import kotlinx.coroutines.CoroutineScope
import timber.log.Timber
abstract class DigViewModeler<S : MutableDigViewState>
protected constructor(
private val state: S,
private val interactor: DigInteractor,
) : AbstractViewModeler<S>(state) {
protected suspend fun loadNews(force: Boolean) {
val s = state
interactor
.getNews(
force = force,
symbol = s.ticker.symbol,
)
.onSuccess { n ->
// Clear the error on load success
s.apply {
news = n
newsError = null
}
}
.onFailure { e ->
// Don't need to clear the ticker since last loaded state was valid
s.apply {
news = emptyList()
newsError = e
}
}
}
protected suspend fun loadTicker(
force: Boolean,
): ResultWrapper<Ticker> =
interactor
.getChart(
force = force,
symbol = state.ticker.symbol,
range = state.range,
)
.onSuccess { t -> state.apply { ticker = t } }
.onSuccess { ticker ->
ticker.chart?.also { c ->
if (c.dates().isEmpty()) {
Timber.w("No dates, can't pick currentDate and currentPrice")
return@also
}
state.apply {
onInitialLoad(c)
// Set the opening price based on the current chart
openingPrice = c.startingPrice()
// Clear the error on load success
chartError = null
}
}
}
.onFailure { Timber.e(it, "Failed to load Ticker") }
.onFailure { e ->
state.apply {
currentPrice = null
openingPrice = null
chartError = e
}
}
private fun MutableDigViewState.onInitialLoad(chart: StockChart) {
if (currentPrice != null) {
return
}
currentDate = chart.currentDate()
currentPrice = chart.currentPrice()
}
fun handleRangeSelected(
scope: CoroutineScope,
range: StockChart.IntervalRange,
) {
val oldRange = state.range
if (oldRange == range) {
return
}
state.range = range
handleLoadTicker(scope = scope, force = true)
}
fun handleDateScrubbed(data: Chart.Data?) {
if (data == null) {
return
}
state.apply {
currentDate = data.date
currentPrice = data.price
}
}
abstract fun handleLoadTicker(
scope: CoroutineScope,
force: Boolean,
)
}
| 2 | Kotlin | 0 | 1 | 77e90a764f7329e0ef1ee0c25f967f08d75234b4 | 3,507 | tickertape | Apache License 2.0 |
parser/src/main/java/com/jayasuryat/mendable/parser/model/ComposableSignaturesReport.kt | jayasuryat | 573,750,182 | false | {"Kotlin": 182007} | /*
* Copyright 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 com.jayasuryat.mendable.parser.model
import com.jayasuryat.mendable.metricsfile.Module
import dev.drewhamilton.poko.Poko
/**
* Represents a report containing information about composable functions within a module. This report includes details
* about each composable function's characteristics and parameters.
*
* Generally represents files with name in `<module-name>-classes.txt` format.
*
* @property module The module to which this composable signatures report pertains.
* @property composables The list of composables details in this report.
*/
@Poko
public class ComposableSignaturesReport(
public override val module: Module,
public val composables: List<ComposableDetails>,
) : ComposeCompilerMetrics {
/**
* Represents detailed information about a composable function.
*
* @property functionName The name of the composable function.
* @property isRestartable Indicates whether the composable function is restartable.
* @property isSkippable Indicates whether the composable function is skippable.
* @property isInline Indicates whether the composable function is inline.
* @property params The list of parameters for the composable function.
*/
@Poko
public class ComposableDetails(
public val functionName: String,
public val isRestartable: Boolean,
public val isSkippable: Boolean,
public val isInline: Boolean,
public val params: List<Parameter>,
) {
/**
* Represents a parameter of a composable function, including its condition and details.
*
* @property name The name of the parameter.
* @property condition The condition of the parameter.
* @property type The type of the parameter.
* @property defaultValue The default value of the parameter, if applicable.
*/
@Poko
public class Parameter(
public val name: String,
public val condition: Condition,
public val type: String,
public val defaultValue: String?,
) {
/**
* Represents the condition of a parameter.
*/
public enum class Condition {
STABLE,
UNSTABLE,
UNUSED,
UNKNOWN;
public companion object
}
public companion object
}
public companion object
}
public companion object
}
| 0 | Kotlin | 6 | 186 | 097de7c18987788ea7fd106e6ca551d073613df8 | 3,088 | mendable | Apache License 2.0 |
app/src/main/java/com/msomu/squareissues/util/DateUtil.kt | msomu | 371,398,075 | false | null | package com.msomu.squareissues.util
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* The string that is in this format "yyyy-MM-dd'T'hh:mm:ss'Z'"
* should be converted to this "MM-dd-yyyy" format
* ...should return null is the format is not right
* ...should return the string in correct format if its in the correct format
*/
fun String.toDate(): String? {
return try {
val date = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'", Locale.getDefault()).parse(this)
val toDateFormat = SimpleDateFormat("MM-dd-yyyy", Locale.getDefault())
date?.let { toDateFormat.format(date) }
} catch (parseException: ParseException) {
null
}
} | 0 | Kotlin | 1 | 0 | 3977a9c6c6f151b60b74a9e40f6434082151b6b7 | 715 | OkhttpIssues | Apache License 2.0 |
src/main/kotlin/dev/restate/sdktesting/tests/ProxyRequestSigning.kt | restatedev | 835,826,722 | false | {"Kotlin": 171136} | // Copyright (c) 2023 - Restate Software, Inc., Restate GmbH
//
// This file is part of the Restate SDK Test suite tool,
// which is released under the MIT license.
//
// You can find a copy of the license in file LICENSE in the root
// directory of this repository or package, or at
// https://github.com/restatedev/sdk-test-suite/blob/main/LICENSE
package dev.restate.sdktesting.tests
import dev.restate.sdk.client.Client
import dev.restate.sdktesting.contracts.CounterClient
import dev.restate.sdktesting.contracts.CounterDefinitions
import dev.restate.sdktesting.infra.InjectClient
import dev.restate.sdktesting.infra.RestateDeployerExtension
import dev.restate.sdktesting.infra.ServiceSpec
import java.util.*
import kotlinx.coroutines.test.runTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.parallel.Execution
import org.junit.jupiter.api.parallel.ExecutionMode
class ProxyRequestSigning {
companion object {
const val E2E_REQUEST_SIGNING_ENV = "E2E_REQUEST_SIGNING"
const val PRIVATE_KEY =
"""
-----BEGIN PRIVATE KEY-----
<KEY>-----END PRIVATE KEY-----
"""
const val SIGNING_KEY = "<KEY>"
@RegisterExtension
val deployerExt: RestateDeployerExtension = RestateDeployerExtension {
withCopyToContainer("/a.pem", PRIVATE_KEY)
withEnv("RESTATE_REQUEST_IDENTITY_PRIVATE_KEY_PEM_FILE", "/a.pem")
withServiceSpec(
ServiceSpec.builder("service-with-request-signing")
.withServices(CounterDefinitions.SERVICE_NAME)
.withEnv(E2E_REQUEST_SIGNING_ENV, SIGNING_KEY)
.build())
}
}
@Test
@Execution(ExecutionMode.CONCURRENT)
fun requestSigningPass(@InjectClient ingressClient: Client) = runTest {
val counterName = UUID.randomUUID().toString()
val client = CounterClient.fromClient(ingressClient, counterName)
client.add(1)
assertThat(client.get()).isEqualTo(1)
}
}
| 6 | Kotlin | 0 | 1 | 6d3600a3d7a2295766978059f6e6c9f5b27c9bc3 | 2,019 | sdk-test-suite | MIT License |
src/main/kotlin/yunas/template/TemplateEngine.kt | Bhanditz | 168,972,927 | true | {"Kotlin": 98222} | package yunas.template
import yunas.ModelAndView
/**
* TemplateEngine.
*
*/
interface TemplateEngine {
fun render(modelAndView: ModelAndView): String
}
| 0 | Kotlin | 0 | 0 | 6d21a668407e5703dc988115214d962d59e899e2 | 162 | yunas | Apache License 2.0 |
Samples/Android-Advanced-Kotlin/app/src/main/java/com/pushwoosh/sample/inbox/InboxNotificationFactory.kt | Pushwoosh | 15,434,764 | false | {"Java": 2695318, "Kotlin": 92394} | package com.pushwoosh.sample.inbox
import android.app.Notification
import android.app.PendingIntent
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import com.pushwoosh.notification.PushMessage
import com.pushwoosh.notification.PushwooshNotificationFactory
class InboxNotificationFactory : PushwooshNotificationFactory() {
companion object {
private const val GROUP_KEY = "PushwooshGroup"
}
private fun generateInboxStyle(pushData: PushMessage): NotificationCompat.Style? {
if (applicationContext == null) {
return null
}
MessageStorage.addMessage(applicationContext!!, Message(pushData.message, System.currentTimeMillis(), pushData.header))
val messages = MessageStorage.getHistory(applicationContext!!)
messages?. run {
val style = NotificationCompat.InboxStyle().setBigContentTitle(pushData.header + " Details")
for (message in messages) {
style.addLine(getContentFromHtml("<b>" + message.sender + "</b> " + message.text))
}
if (messages.size > 7) {
style.setSummaryText("+ " + (messages.size - 7) + " more")
}
return style
}
return null
}
private fun generateSummary(pushData: PushMessage) {
val notificationBuilder = NotificationCompat.Builder(applicationContext)
.setContentTitle(getContentFromHtml(pushData.header))
.setContentText(getContentFromHtml(pushData.message))
.setSmallIcon(pushData.smallIcon)
.setTicker(getContentFromHtml(pushData.ticker))
.setWhen(System.currentTimeMillis())
.setStyle(generateInboxStyle(pushData))
.setGroup(GROUP_KEY)
.setGroupSummary(true)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(applicationContext, 0, getNotificationIntent(pushData), PendingIntent.FLAG_CANCEL_CURRENT))
val notificationManager = NotificationManagerCompat.from(applicationContext!!)
notificationManager.notify(GROUP_KEY, 0, notificationBuilder.build())
}
override fun onGenerateNotification(pushData: PushMessage): Notification? {
// Summary will be displayed only on devices that do not support grouped notifications
generateSummary(pushData)
// This notification will be displayed only on devices that support grouped notifications
val notification = NotificationCompat.Builder(applicationContext)
.setContentTitle(getContentFromHtml(pushData.header))
.setContentText(getContentFromHtml(pushData.message))
.setSmallIcon(pushData.smallIcon)
.setTicker(getContentFromHtml(pushData.ticker))
.setWhen(System.currentTimeMillis())
.setGroup(GROUP_KEY)
.setAutoCancel(true)
.build()
addSound(notification, pushData.sound)
return notification
}
}
| 2 | Java | 44 | 55 | aa77bc545944ae509186dab810707e26f2d9f7c5 | 3,119 | pushwoosh-android-sdk | MIT License |
Samples/Android-Advanced-Kotlin/app/src/main/java/com/pushwoosh/sample/inbox/InboxNotificationFactory.kt | Pushwoosh | 15,434,764 | false | {"Java": 2695318, "Kotlin": 92394} | package com.pushwoosh.sample.inbox
import android.app.Notification
import android.app.PendingIntent
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import com.pushwoosh.notification.PushMessage
import com.pushwoosh.notification.PushwooshNotificationFactory
class InboxNotificationFactory : PushwooshNotificationFactory() {
companion object {
private const val GROUP_KEY = "PushwooshGroup"
}
private fun generateInboxStyle(pushData: PushMessage): NotificationCompat.Style? {
if (applicationContext == null) {
return null
}
MessageStorage.addMessage(applicationContext!!, Message(pushData.message, System.currentTimeMillis(), pushData.header))
val messages = MessageStorage.getHistory(applicationContext!!)
messages?. run {
val style = NotificationCompat.InboxStyle().setBigContentTitle(pushData.header + " Details")
for (message in messages) {
style.addLine(getContentFromHtml("<b>" + message.sender + "</b> " + message.text))
}
if (messages.size > 7) {
style.setSummaryText("+ " + (messages.size - 7) + " more")
}
return style
}
return null
}
private fun generateSummary(pushData: PushMessage) {
val notificationBuilder = NotificationCompat.Builder(applicationContext)
.setContentTitle(getContentFromHtml(pushData.header))
.setContentText(getContentFromHtml(pushData.message))
.setSmallIcon(pushData.smallIcon)
.setTicker(getContentFromHtml(pushData.ticker))
.setWhen(System.currentTimeMillis())
.setStyle(generateInboxStyle(pushData))
.setGroup(GROUP_KEY)
.setGroupSummary(true)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(applicationContext, 0, getNotificationIntent(pushData), PendingIntent.FLAG_CANCEL_CURRENT))
val notificationManager = NotificationManagerCompat.from(applicationContext!!)
notificationManager.notify(GROUP_KEY, 0, notificationBuilder.build())
}
override fun onGenerateNotification(pushData: PushMessage): Notification? {
// Summary will be displayed only on devices that do not support grouped notifications
generateSummary(pushData)
// This notification will be displayed only on devices that support grouped notifications
val notification = NotificationCompat.Builder(applicationContext)
.setContentTitle(getContentFromHtml(pushData.header))
.setContentText(getContentFromHtml(pushData.message))
.setSmallIcon(pushData.smallIcon)
.setTicker(getContentFromHtml(pushData.ticker))
.setWhen(System.currentTimeMillis())
.setGroup(GROUP_KEY)
.setAutoCancel(true)
.build()
addSound(notification, pushData.sound)
return notification
}
}
| 2 | Java | 44 | 55 | aa77bc545944ae509186dab810707e26f2d9f7c5 | 3,119 | pushwoosh-android-sdk | MIT License |
src/main/kotlin/org/move/lang/core/psi/ext/MvAssertBangExpr.kt | pontem-network | 279,299,159 | false | {"Kotlin": 2180391, "Move": 39421, "Lex": 5509, "HTML": 2114, "Java": 1275} | package org.move.lang.core.psi.ext
import com.intellij.psi.PsiElement
import org.move.lang.MvElementTypes.IDENTIFIER
import org.move.lang.core.psi.MvAssertMacroExpr
val MvAssertMacroExpr.identifier: PsiElement get() = this.findFirstChildByType(IDENTIFIER)!! | 3 | Kotlin | 29 | 69 | 063cb4e6e7cc0722d544fb6657ef6fd6d516743b | 259 | intellij-move | MIT License |
app/src/main/java/io/github/drumber/kitsune/domain/model/infrastructure/media/mediarelationship/MediaRelationship.kt | Drumber | 406,471,554 | false | {"Kotlin": 797542, "Ruby": 2045} | package io.github.drumber.kitsune.domain.model.infrastructure.media.mediarelationship
import android.os.Parcelable
import com.github.jasminb.jsonapi.annotations.Id
import com.github.jasminb.jsonapi.annotations.Relationship
import com.github.jasminb.jsonapi.annotations.Type
import io.github.drumber.kitsune.domain.model.infrastructure.media.BaseMedia
import kotlinx.parcelize.Parcelize
@Parcelize
@Type("mediaRelationships")
data class MediaRelationship(
@Id
val id: String?,
val role: MediaRelationshipRole?,
@Relationship("destination")
val media: BaseMedia?
) : Parcelable
| 5 | Kotlin | 4 | 61 | 6ab88cfacd8ee4daad23edbe4a134ab1f2b1f62c | 599 | Kitsune | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.