path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/github/dankinsoid/ideaswiftformat/actions/GenerateFile.kt | dankinsoid | 517,400,843 | false | {"Kotlin": 16417} | package com.github.dankinsoid.ideaswiftformat.actions
import com.github.dankinsoid.ideaswiftformat.services.SwiftformatCLI
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAware
class GenerateFile: AnAction(), DumbAware {
override fun actionPerformed(event: AnActionEvent) {
val files = event.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return
event.project?.let { pr ->
files.forEach {
SwiftformatCLI(pr).generate(it.path)
}
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.project != null
}
}
| 0 | Kotlin | 0 | 1 | 36f22c5d121f1bc26a831f12e180d9217c0568d3 | 765 | IdeaSwiftformat | Microsoft Public License |
app/src/main/java/com/github/albertopeam/spoktify/app/di/DispatcherIO.kt | albertopeam | 294,799,044 | false | null | package com.github.albertopeam.spoktify.app.di
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class DispatcherIO | 0 | Kotlin | 0 | 2 | 23e02f627a81d90b85eb03ab22824c56ff99c4ab | 158 | spoktify | MIT License |
src/main/kotlin/kotlinchennai/books/dto/SprintBItemDTO.kt | chennaijc | 771,301,483 | false | {"Kotlin": 11134, "HTML": 7967} | package kotlinchennai.books.dto
class SprintBItemDTO(
val itemId: String,
val summary: String,
val priority: String,
val assigned: String,
val status: String,
val storyPoints: String,
val id: Long=0,
val subTasks: List<SubTasksDTO>
) | 0 | Kotlin | 1 | 0 | 1eccd3a691b6c9bde51df078f3964f07069c65b3 | 266 | quarkus-kotlin-demo | MIT License |
src/main/kotlin/pro/batalin/coinkeeper/importer/Main.kt | kbatalin | 456,121,643 | false | {"Kotlin": 20632} | package pro.batalin.coinkeeper.importer
import kotlinx.coroutines.runBlocking
import pro.batalin.coinkeeper.importer.category.CategoryService
import pro.batalin.coinkeeper.importer.client.CoinKeeperClientFactory
import pro.batalin.coinkeeper.importer.data.SpendeeDataReader
import pro.batalin.coinkeeper.importer.dataimport.ImportService
import pro.batalin.coinkeeper.importer.mapper.ObjectMapperFactory
import pro.batalin.coinkeeper.importer.transaction.TransactionService
import java.io.File
import kotlin.system.exitProcess
fun main(args: Array<String>) {
try {
val filePath = args.firstOrNull() ?: "data/spendee.test.csv"
doMain(filePath)
} catch (e: Exception) {
println(e.message)
e.printStackTrace()
} finally {
exitProcess(0)
}
}
private fun doMain(filePath: String) {
val objectMapperFactory = ObjectMapperFactory()
val objectMapper = objectMapperFactory.objectMapper
val coinKeeperClientFactory = CoinKeeperClientFactory(objectMapper)
val coinKeeperClient = coinKeeperClientFactory.coinKeeperClient
val categoryService = CategoryService(coinKeeperClient, objectMapper)
val transactionService = TransactionService(coinKeeperClient)
val spendeeDataReader = SpendeeDataReader()
val importService = ImportService(spendeeDataReader, categoryService, transactionService, 5)
runBlocking {
importService.doImport(File(filePath))
}
}
| 0 | Kotlin | 0 | 0 | 6778933555323f25356cf28d38f6fb92ca17c61a | 1,447 | CoinKeeperImporter | Apache License 2.0 |
plugin/src/main/kotlin/spp/jetbrains/sourcemarker/icons/SourceMarkerIcons.kt | sourceplusplus | 173,253,271 | false | null | package spp.jetbrains.sourcemarker.icons
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.scale.ScaleContext
import com.intellij.util.SVGLoader
import com.intellij.util.ui.JBImageIcon
import spp.protocol.advice.ArtifactAdvice
import spp.protocol.advice.cautionary.RampDetectionAdvice
import spp.protocol.advice.informative.ActiveExceptionAdvice
import java.io.ByteArrayInputStream
import javax.swing.Icon
/**
* Defines the various visual icons SourceMarker may display.
*
* @since 0.1.0
* @author [Brandon Fergerson](mailto:[email protected])
*/
object SourceMarkerIcons {
val exclamationTriangle = IconLoader.getIcon("/icons/exclamation-triangle.svg")
val performanceRamp = IconLoader.getIcon("/icons/sort-amount-up.svg")
val activeException = IconLoader.getIcon("/icons/map-marker-exclamation.svg")
val LIVE_METER_COUNT_ICON = IconLoader.getIcon("/icons/count.svg")
val LIVE_METER_GAUGE_ICON = IconLoader.getIcon("/icons/gauge.svg")
val LIVE_METER_HISTOGRAM_ICON = IconLoader.getIcon("/icons/histogram.svg")
val LIVE_BREAKPOINT_ACTIVE_ICON = IconLoader.getIcon("/icons/breakpoint/live-breakpoint-active.svg")
val LIVE_BREAKPOINT_DISABLED_ICON = IconLoader.getIcon("/icons/breakpoint/live-breakpoint-disabled.svg")
val LIVE_BREAKPOINT_COMPLETE_ICON = IconLoader.getIcon("/icons/breakpoint/live-breakpoint-complete.svg")
val LIVE_BREAKPOINT_PENDING_ICON = IconLoader.getIcon("/icons/breakpoint/live-breakpoint-pending.svg")
val LIVE_BREAKPOINT_ERROR_ICON = IconLoader.getIcon("/icons/breakpoint/live-breakpoint-error.svg")
fun getGutterMarkIcon(advice: ArtifactAdvice): Icon? {
return when (advice) {
is ActiveExceptionAdvice -> exclamationTriangle
is RampDetectionAdvice -> performanceRamp
else -> null
}
}
fun getNumericGutterMarkIcon(value: Int, color: String = "#182d34"): Icon {
return JBImageIcon(
SVGLoader.loadHiDPI(
null,
ByteArrayInputStream(NumericSvgIcon(value, color).toString().toByteArray()),
ScaleContext.create()
)
)
}
}
| 35 | Kotlin | 7 | 79 | 37bb6a3a67fb56bf31371d9933ab056d9d4483a1 | 2,170 | SourceMarker | Apache License 2.0 |
src/main/kotlin/com/developerphil/adbidea/ObjectGraph.kt | tiwiz | 247,727,891 | true | {"Kotlin": 76384} | package com.developerphil.adbidea
import com.developerphil.adbidea.accessor.preference.ProjectPreferenceAccessor
import com.developerphil.adbidea.adb.BridgeImpl
import com.developerphil.adbidea.adb.DeviceResultFetcher
import com.developerphil.adbidea.adb.UseSameDevicesHelper
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.project.Project
// This is more of a service locator than a proper DI framework.
// It's not used often enough in the codebase to warrant the complexity of a DI solution like dagger.
class ObjectGraph(private val project: Project) : ProjectComponent {
val deviceResultFetcher by lazy { DeviceResultFetcher(project, useSameDevicesHelper, bridge) }
val pluginPreferences: PluginPreferences by lazy { PluginPreferencesImpl(preferenceAccessor) }
private val useSameDevicesHelper by lazy { UseSameDevicesHelper(pluginPreferences, bridge) }
private val preferenceAccessor by lazy { ProjectPreferenceAccessor(project) }
private val bridge by lazy { BridgeImpl(project) }
// Project Component Boilerplate
override fun projectOpened() = Unit
override fun projectClosed() = Unit
override fun initComponent() = Unit
override fun disposeComponent() = Unit
override fun getComponentName(): String = "InjectionObjectGraph"
}
| 0 | Kotlin | 0 | 0 | ecfdaf19b79225044e9fbb7c8df595096e0f0b89 | 1,322 | adb-idea | Apache License 2.0 |
src/main/kotlin/ch09/4_3_DestructuringDeclarations2.kt | draganglumac | 843,717,905 | false | {"Kotlin": 114145, "Java": 878} | package ch09.exkt
data class NameComponents(
val name: String,
val extension: String,
)
fun splitFilename(fullName: String): NameComponents {
val (name, extension) = fullName.split('.', limit = 2)
return NameComponents(name, extension)
}
| 0 | Kotlin | 0 | 0 | ba8291a209fb7c6bae4997c1c9da2e7910788aed | 256 | kotlin-in-action-2e-main | MIT License |
app/src/main/java/es/upm/bienestaremocional/core/ui/theme/Color.kt | Emotional-Wellbeing | 531,973,820 | false | null | package es.upm.bienestaremocional.core.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF006C53)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFF82F8D0)
val md_theme_light_onPrimaryContainer = Color(0xFF002117)
val md_theme_light_secondary = Color(0xFF775A00)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFFFDF9A)
val md_theme_light_onSecondaryContainer = Color(0xFF251A00)
val md_theme_light_tertiary = Color(0xFF904D00)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFDCC3)
val md_theme_light_onTertiaryContainer = Color(0xFF2F1500)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFBFDF9)
val md_theme_light_onBackground = Color(0xFF191C1B)
val md_theme_light_surface = Color(0xFFFBFDF9)
val md_theme_light_onSurface = Color(0xFF191C1B)
val md_theme_light_surfaceVariant = Color(0xFFDBE5DE)
val md_theme_light_onSurfaceVariant = Color(0xFF404944)
val md_theme_light_outline = Color(0xFF707974)
val md_theme_light_inverseOnSurface = Color(0xFFEFF1EE)
val md_theme_light_inverseSurface = Color(0xFF2E312F)
val md_theme_light_inversePrimary = Color(0xFF64DBB4)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF006C53)
val md_theme_light_outlineVariant = Color(0xFFBFC9C3)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFF64DBB4)
val md_theme_dark_onPrimary = Color(0xFF00382A)
val md_theme_dark_primaryContainer = Color(0xFF00513D)
val md_theme_dark_onPrimaryContainer = Color(0xFF82F8D0)
val md_theme_dark_secondary = Color(0xFFF5BF2C)
val md_theme_dark_onSecondary = Color(0xFF3F2E00)
val md_theme_dark_secondaryContainer = Color(0xFF5A4300)
val md_theme_dark_onSecondaryContainer = Color(0xFFFFDF9A)
val md_theme_dark_tertiary = Color(0xFFFFB77D)
val md_theme_dark_onTertiary = Color(0xFF4D2600)
val md_theme_dark_tertiaryContainer = Color(0xFF6E3900)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDCC3)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF191C1B)
val md_theme_dark_onBackground = Color(0xFFE1E3E0)
val md_theme_dark_surface = Color(0xFF191C1B)
val md_theme_dark_onSurface = Color(0xFFE1E3E0)
val md_theme_dark_surfaceVariant = Color(0xFF404944)
val md_theme_dark_onSurfaceVariant = Color(0xFFBFC9C3)
val md_theme_dark_outline = Color(0xFF89938D)
val md_theme_dark_inverseOnSurface = Color(0xFF191C1B)
val md_theme_dark_inverseSurface = Color(0xFFE1E3E0)
val md_theme_dark_inversePrimary = Color(0xFF006C53)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFF64DBB4)
val md_theme_dark_outlineVariant = Color(0xFF404944)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF005843)
| 0 | Kotlin | 0 | 1 | e45d8969c9cd1a89f53777fcc671a4196177b7e3 | 3,211 | App | Apache License 2.0 |
app/src/main/java/fingerfire/com/overwatch/features/heroes/ui/adapter/AbilitiesAdapter.kt | marlonsantini | 595,391,286 | false | null | package fingerfire.com.overwatch.features.heroes.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.load
import fingerfire.com.overwatch.R
import fingerfire.com.overwatch.databinding.ItemAbilitiesBinding
import fingerfire.com.overwatch.features.heroes.data.response.AbilitiesResponse
class AbilitiesAdapter(
private val abilitiesList: List<AbilitiesResponse>,
private val itemClick: (AbilitiesResponse) -> Unit,
private var selectedItemIndex: Int = RecyclerView.NO_POSITION
) : RecyclerView.Adapter<AbilitiesAdapter.AbilitiesViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AbilitiesViewHolder {
val binding =
ItemAbilitiesBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return AbilitiesViewHolder(binding)
}
override fun onBindViewHolder(holder: AbilitiesViewHolder, position: Int) {
val item = abilitiesList[position]
holder.bind(item, position == selectedItemIndex)
}
override fun getItemCount(): Int {
return abilitiesList.size
}
inner class AbilitiesViewHolder(private val binding: ItemAbilitiesBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: AbilitiesResponse, isSelected: Boolean) {
with(binding) {
imAbilities.load(item.displayIcon)
if (isSelected) {
binding.imAbilities.setBackgroundResource(R.drawable.circle_background_orange)
} else {
binding.imAbilities.setBackgroundResource(R.drawable.circle_background)
}
cvAbilities.setOnClickListener {
itemClick.invoke(item)
val previousSelectedItemIndex = selectedItemIndex
selectedItemIndex = bindingAdapterPosition
// Notificar a atualização nos itens afetados
notifyItemChanged(previousSelectedItemIndex)
notifyItemChanged(selectedItemIndex)
}
}
}
}
fun setSelectedItem(index: Int) {
val previousSelectedItemIndex = selectedItemIndex
selectedItemIndex = index
notifyItemChanged(previousSelectedItemIndex)
notifyItemChanged(selectedItemIndex)
}
} | 0 | Kotlin | 0 | 2 | 34e7026565fd689cac549f493369fc9ff80c201e | 2,411 | OverGuide | Apache License 2.0 |
ECommerceTrainingProject/app/src/main/java/com/training/ecommerce/data/models/products/ProductModel.kt | eslamfaisal | 757,328,403 | false | {"Kotlin": 153908, "Dart": 60034, "JavaScript": 10092, "HTML": 6764, "CSS": 1066} | package com.training.ecommerce.data.models.products
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.firebase.firestore.PropertyName
import kotlinx.parcelize.Parcelize
@Keep
@Parcelize
data class ProductModel(
var id: String? = null,
var name: String? = null,
var description: String? = null,
@get:PropertyName("categories_ids")
@set:PropertyName("categories_ids")
var categoriesIDs: List<String>? = null,
var images: List<String>? = null,
var price: Int? = null,
var rate: Float? = null,
@get:PropertyName("sale_percentage")
@set:PropertyName("sale_percentage")
var salePercentage: Int? = null,
@get:PropertyName("sale_type")
@set:PropertyName("sale_type")
var saleType: String? = null,
var colors: List<ProductColorModel>? = null,
var sizes: List<ProductSizeModel>? = null,
) : Parcelable
@Keep
@Parcelize
data class ProductColorModel(
var size: String? = null,
var stock: Int? = null,
var color: String? = null
) : Parcelable
@Keep
@Parcelize
data class ProductSizeModel(
var size: String? = null,
var stock: Int? = null
) : Parcelable
enum class ProductSaleType(val type: String) {
FLASH_SALE("flash_sale"),
MEGA_SALE("mega_sale")
} | 2 | Kotlin | 15 | 52 | 3348446527ef3c1e23c0ac0a9346792f3fba7c41 | 1,273 | android-development-training | MIT License |
app/src/main/java/com/mycompany/advioo/viewmodels/CampaignStatsViewModel.kt | demirelarda | 609,874,629 | false | {"Kotlin": 330942} | package com.mycompany.advioo.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.auth.FirebaseAuth
import com.mycompany.advioo.models.tripdata.UserTripData
import com.mycompany.advioo.repo.local.LocalDriverRepositoryInterface
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.util.Calendar
import javax.inject.Inject
@HiltViewModel
class CampaignStatsViewModel @Inject constructor(
private val localRepo : LocalDriverRepositoryInterface,
private val firebaseAuth: FirebaseAuth
) : ViewModel() {
private val _dailyTripDataList = MutableLiveData<List<UserTripData>>()
private val _weeklyTripDataList = MutableLiveData<List<UserTripData>>()
private val _monthlyTripDataList = MutableLiveData<List<UserTripData>>()
private val _yearlyTripDataList = MutableLiveData<List<UserTripData>>()
private val _earningsList = MutableLiveData<ArrayList<Triple<Int,Double,Double>>>()
val earningsList : LiveData<ArrayList<Triple<Int,Double,Double>>>
get() = _earningsList
private val _dailyEarnings = MutableLiveData<Double>()
val dailyEarnings : LiveData<Double>
get() = _dailyEarnings
private val _weeklyEarnings = MutableLiveData<Double>()
val weeklyEarnings : LiveData<Double>
get() = _weeklyEarnings
private val _monthlyEarnings = MutableLiveData<Double>()
val monthlyEarnings : LiveData<Double>
get() = _monthlyEarnings
private val _yearlyEarnings = MutableLiveData<Double>()
val yearlyEarnings : LiveData<Double>
get() = _yearlyEarnings
private val _loadingState = MutableLiveData<Boolean>()
val loadingState: LiveData<Boolean>
get() = _loadingState
private val _successState = MutableLiveData<Boolean>()
val successState: LiveData<Boolean>
get() = _successState
private val _failState = MutableLiveData<Boolean>()
val failState: LiveData<Boolean>
get() = _failState
private val _errorMessage = MutableLiveData<String>()
val errorMessage: LiveData<String>
get() = _errorMessage
fun getAllPayments(campaignId: String){
println("main calculation function ran")
getDailyTripData(campaignId)
getWeeklyTripData(campaignId)
getMonthlyTripData(campaignId)
getYearlyTripData(campaignId)
}
private fun getDailyTripData(campaignId: String){
println("daily function")
_loadingState.value = true
viewModelScope.launch{
try {
_dailyTripDataList.value = localRepo.getAllTripDataFromToday(getStartAndEndOfToday().first,getStartAndEndOfToday().second,firebaseAuth.uid!!,campaignId)
calculateEarnings(_dailyTripDataList.value!!, 0)
}
catch (e:Exception){
_loadingState.value = false
_failState.value = true
_errorMessage.value = e.localizedMessage
}
}
}
private fun getWeeklyTripData(campaignId: String){
_loadingState.value = true
viewModelScope.launch{
try {
_weeklyTripDataList.value = localRepo.getAllTripDataFromThisWeek(getStartAndEndOfThisWeek().first,getStartAndEndOfThisWeek().second,firebaseAuth.uid!!,campaignId)
calculateEarnings(_weeklyTripDataList.value!!, 1)
}
catch (e:Exception){
_loadingState.value = false
_failState.value = true
_errorMessage.value = e.localizedMessage
}
}
}
private fun getMonthlyTripData(campaignId: String){
_loadingState.value = true
viewModelScope.launch{
try {
_monthlyTripDataList.value = localRepo.getAllTripDataFromThisMonth(getStartAndEndOfThisMonth().first,getStartAndEndOfThisMonth().second,firebaseAuth.uid!!,campaignId)
calculateEarnings(_monthlyTripDataList.value!!, 2)
}
catch (e:Exception){
_loadingState.value = false
_failState.value = true
_errorMessage.value = e.localizedMessage
}
}
}
private fun getYearlyTripData(campaignId: String){
_loadingState.value = true
viewModelScope.launch{
try {
_yearlyTripDataList.value = localRepo.getAllTripDataFromThisYear(getStartAndEndOfThisYear().first,getStartAndEndOfThisYear().second,firebaseAuth.uid!!,campaignId)
calculateEarnings(_yearlyTripDataList.value!!, 3)
}
catch (e:Exception){
_loadingState.value = false
_failState.value = true
_errorMessage.value = e.localizedMessage
}
}
}
private fun getStartAndEndOfToday(): Pair<Long, Long> {
val cal = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
val dayStart = cal.timeInMillis
cal.add(Calendar.DAY_OF_MONTH, 1)
val dayEnd = cal.timeInMillis - 1
return Pair(dayStart, dayEnd)
}
private fun getStartAndEndOfThisWeek(): Pair<Long, Long> {
val cal = Calendar.getInstance().apply {
set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
val weekStart = cal.timeInMillis
cal.add(Calendar.WEEK_OF_YEAR, 1)
val weekEnd = cal.timeInMillis - 1
return Pair(weekStart, weekEnd)
}
private fun getStartAndEndOfThisMonth(): Pair<Long, Long> {
val cal = Calendar.getInstance().apply {
set(Calendar.DAY_OF_MONTH, 1)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
val monthStart = cal.timeInMillis
cal.add(Calendar.MONTH, 1)
val monthEnd = cal.timeInMillis - 1
return Pair(monthStart, monthEnd)
}
private fun getStartAndEndOfThisYear(): Pair<Long, Long> {
val cal = Calendar.getInstance().apply {
set(Calendar.DAY_OF_YEAR, 1)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
val yearStart = cal.timeInMillis
cal.add(Calendar.YEAR, 1)
val yearEnd = cal.timeInMillis - 1
return Pair(yearStart, yearEnd)
}
private fun calculateEarnings(tripDataList : List<UserTripData>, timePeriod: Int){
var totalPayment = 0.0
var totalDistanceDriven = 0.0
val paymentList = ArrayList<Triple<Int,Double,Double>>()
for(tripData in tripDataList){
totalPayment += tripData.earnedPayment
totalDistanceDriven += tripData.kmDriven
println("total payment = $totalPayment")
println("total distance driven = $totalDistanceDriven")
}
when(timePeriod){
0 -> paymentList.add(Triple(0,totalPayment,totalDistanceDriven))
1 -> paymentList.add(Triple(1,totalPayment,totalDistanceDriven))
2 -> paymentList.add(Triple(2,totalPayment,totalDistanceDriven))
3 -> paymentList.add(Triple(3,totalPayment,totalDistanceDriven))
}
_earningsList.value = paymentList
}
} | 0 | Kotlin | 0 | 0 | b27390784a5903d4ba81249f7b3535ff49c08ab1 | 7,764 | AdTracker | FSF All Permissive License |
meistercharts-demos/meistercharts-demos/src/commonMain/kotlin/com/meistercharts/demo/descriptors/NeckarITFlowDemoDescriptor.kt | Neckar-IT | 599,079,962 | false | null | /**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.demo.descriptors
import com.meistercharts.algorithms.axis.AxisOrientationY
import com.meistercharts.algorithms.layers.AbstractLayer
import com.meistercharts.algorithms.layers.FillBackgroundLayer
import com.meistercharts.algorithms.layers.LayerPaintingContext
import com.meistercharts.algorithms.layers.LayerType
import com.meistercharts.canvas.saved
import com.meistercharts.canvas.strokeBoundingBox
import com.meistercharts.demo.ChartingDemo
import com.meistercharts.demo.ChartingDemoDescriptor
import com.meistercharts.demo.DemoCategory
import com.meistercharts.demo.PredefinedConfiguration
import com.meistercharts.demo.configurableBoolean
import com.meistercharts.demo.configurableDouble
import com.meistercharts.design.neckarit.NeckarItFlowPaintable
import com.meistercharts.model.Size
/**
*
*/
class NeckarITFlowDemoDescriptor : ChartingDemoDescriptor<Nothing> {
override val name: String = "Neckar IT Flow"
override val category: DemoCategory = DemoCategory.NeckarIT
override fun createDemo(configuration: PredefinedConfiguration<Nothing>?): ChartingDemo {
return ChartingDemo {
meistercharts {
configure {
chartSupport.rootChartState.axisOrientationY = AxisOrientationY.OriginAtBottom
layers.addLayer(FillBackgroundLayer() {
dark()
})
val layer = object : AbstractLayer() {
var translateX: Double = 0.0
var translateY: Double = 0.0
var width = 900.0
var height = 300.0
var showBoundingBox: Boolean = true
override val type: LayerType = LayerType.Content
override fun paint(paintingContext: LayerPaintingContext) {
val gc = paintingContext.gc
val chartCalculator = paintingContext.chartCalculator
val size = Size.of(width, height)
val paintable = NeckarItFlowPaintable(size)
gc.saved {
paintable.paint(paintingContext, translateX, translateY)
}
if (showBoundingBox) {
paintable.strokeBoundingBox(paintingContext, translateX, translateY, true)
}
markAsDirty()
}
}
layers.addLayer(layer)
configurableBoolean("Show bounding box", layer::showBoundingBox)
configurableDouble("Translation X", layer::translateX) {
max = 1000.0
}
configurableDouble("Translation Y", layer::translateY) {
max = 1000.0
}
configurableDouble("Width", layer::width) {
max = 2000.0
}
configurableDouble("Height Y", layer::height) {
max = 1500.0
}
declare {
button("Optimal height") {
layer.height = NeckarItFlowPaintable.optimalHeight(layer.width)
markAsDirty()
}
}
}
}
}
}
}
| 0 | Kotlin | 0 | 4 | af73f0e09e3e7ac9437240e19974d0b1ebc2f93c | 3,594 | meistercharts | Apache License 2.0 |
core/core/src/jvmMain/kotlin/zakadabar/core/server/ktor/convenience.kt | spxbhuhb | 290,390,793 | false | null | /*
* Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.core.server.ktor
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.routing.*
import zakadabar.core.server.Server
interface KtorConfigBuilder
class KtorAuthConfig(
val build : (Authentication.Configuration.() -> Unit)
) : KtorConfigBuilder {
fun runBuild(config : Authentication.Configuration) {
config.build()
}
}
class KtorRouteConfig(
val build : (Route.() -> Unit)
) : KtorConfigBuilder {
fun runBuild(config : Route) {
config.build()
}
}
class KtorFeatureWithConfig<B : Any>(
val feature : ApplicationFeature<Application, B, *>,
val config : (B.() -> Unit)?
)
operator fun Server.plusAssign(feature : ApplicationFeature<Application, Any, *>) {
features += KtorFeatureWithConfig(feature) { }
}
operator fun Server.plusAssign(feature : KtorFeatureWithConfig<*>) {
features += feature
}
operator fun Server.plusAssign(configBuilder :KtorConfigBuilder) {
configBuilders += configBuilder
}
operator fun <B : Any, F : ApplicationFeature<Application, B, *>> F.invoke(config : B.() -> Unit) =
KtorFeatureWithConfig(this, config) | 12 | Kotlin | 3 | 24 | 2e0d94b6a77f79566c6cf0d0cff17b3ba6a9c6a1 | 1,256 | zakadabar-stack | Apache License 2.0 |
app/src/main/java/com/triobot/chatbot/ChatActivityPresenter.kt | ilkeryildirim | 244,383,296 | true | {"Kotlin": 13296, "JavaScript": 2188} | package com.triobot.chatbot
import android.app.Activity
import android.os.Handler
import com.triobot.chatbot.ChatTypes.ACTIONS
import com.triobot.chatbot.ChatTypes.ACTIONS.*
class ChatActivityPresenter(var view: ChatActivityContract.View, var context: Activity) : ChatActivityContract.Presenter {
var controlledDevice = arrayListOf<String>()
fun createAction(action: ACTIONS) {
when (action) {
PROBLEM_WITH_DEVICE -> {
problemWithDevices()
}
CANT_LOGIN -> {
}
PASSWORD -> {
}
NEW_PRODUCT -> {
}
ACTION_YES -> TODO()
ACTION_NO -> TODO()
}
}
override fun problemWithDevices() {
view.appendTextMessage("Hangi cihaz ile ilgili sorun yaşamaktasınız?", ChatTypes.MESSAGE_OWNER.BOT)
view.appendDialog(StockDialogs.getDevicesDummy()) {
//needs api response
var isControlled = false
val handler = Handler()
handler.postDelayed({
controlledDevice.forEach { device ->
if (device == it.text) {
isControlled = true
}
}
if (!isControlled) {
view.appendTextMessage(
"Cihazınızdan son güncel veri 5 saat önce alınmış, uzaktan müdahale sağlandı. 10 dakika sonra tekrar kontrol edebilir misiniz?",
ChatTypes.MESSAGE_OWNER.BOT
)
controlledDevice.add(it.text)
view.appendEndText("")
view.appendNeedHelpAgain()
} else {
view.stillGoingSolution()
}
}, 2000)
}
}
} | 0 | Kotlin | 0 | 0 | 8b8e53544a084bf19dd17476a90df7026d4a41ca | 1,824 | dialogflow-voice-assistant | Apache License 2.0 |
app/src/main/java/com/triobot/chatbot/ChatActivityPresenter.kt | ilkeryildirim | 244,383,296 | true | {"Kotlin": 13296, "JavaScript": 2188} | package com.triobot.chatbot
import android.app.Activity
import android.os.Handler
import com.triobot.chatbot.ChatTypes.ACTIONS
import com.triobot.chatbot.ChatTypes.ACTIONS.*
class ChatActivityPresenter(var view: ChatActivityContract.View, var context: Activity) : ChatActivityContract.Presenter {
var controlledDevice = arrayListOf<String>()
fun createAction(action: ACTIONS) {
when (action) {
PROBLEM_WITH_DEVICE -> {
problemWithDevices()
}
CANT_LOGIN -> {
}
PASSWORD -> {
}
NEW_PRODUCT -> {
}
ACTION_YES -> TODO()
ACTION_NO -> TODO()
}
}
override fun problemWithDevices() {
view.appendTextMessage("Hangi cihaz ile ilgili sorun yaşamaktasınız?", ChatTypes.MESSAGE_OWNER.BOT)
view.appendDialog(StockDialogs.getDevicesDummy()) {
//needs api response
var isControlled = false
val handler = Handler()
handler.postDelayed({
controlledDevice.forEach { device ->
if (device == it.text) {
isControlled = true
}
}
if (!isControlled) {
view.appendTextMessage(
"Cihazınızdan son güncel veri 5 saat önce alınmış, uzaktan müdahale sağlandı. 10 dakika sonra tekrar kontrol edebilir misiniz?",
ChatTypes.MESSAGE_OWNER.BOT
)
controlledDevice.add(it.text)
view.appendEndText("")
view.appendNeedHelpAgain()
} else {
view.stillGoingSolution()
}
}, 2000)
}
}
} | 0 | Kotlin | 0 | 0 | 8b8e53544a084bf19dd17476a90df7026d4a41ca | 1,824 | dialogflow-voice-assistant | Apache License 2.0 |
adaptive-lib-ui/src/commonMain/kotlin/fun/adaptive/ui/checkbox/api/checkbox.kt | spxbhuhb | 788,711,010 | false | {"Kotlin": 2371371, "Java": 25297, "HTML": 7875, "JavaScript": 3880, "Shell": 687} | package `fun`.adaptive.ui.checkbox.api
import `fun`.adaptive.foundation.Adaptive
import `fun`.adaptive.foundation.AdaptiveFragment
import `fun`.adaptive.foundation.binding.AdaptiveStateVariableBinding
import `fun`.adaptive.foundation.binding.PropertySelector
import `fun`.adaptive.foundation.fragment
import `fun`.adaptive.foundation.instruction.AdaptiveInstruction
import `fun`.adaptive.foundation.rangeTo
import `fun`.adaptive.graphics.svg.api.svg
import `fun`.adaptive.graphics.svg.api.svgHeight
import `fun`.adaptive.graphics.svg.api.svgWidth
import `fun`.adaptive.ui.api.box
import `fun`.adaptive.ui.api.noSelect
import `fun`.adaptive.ui.api.onClick
import `fun`.adaptive.ui.api.position
import `fun`.adaptive.ui.api.row
import `fun`.adaptive.ui.builtin.Res
import `fun`.adaptive.ui.builtin.check
import `fun`.adaptive.ui.instruction.dp
import `fun`.adaptive.ui.theme.iconColors
@Adaptive
fun checkbox(
vararg instructions: AdaptiveInstruction,
binding: AdaptiveStateVariableBinding<Boolean>? = null,
@PropertySelector
selector: () -> Boolean
): AdaptiveFragment {
checkNotNull(binding)
row(*instructions) {
onClick { binding.setValue(! binding.value, true) }
if (binding.value) {
box(*checkboxTheme.active) {
svg(Res.drawable.check) .. noSelect .. position(1.dp, 1.dp) .. svgHeight(17.dp) .. svgWidth(17.dp) .. iconColors.onPrimary
}
} else {
box(*checkboxTheme.inactive) {
}
}
}
return fragment()
} | 36 | Kotlin | 0 | 3 | 065cbee981afd131472e41a4ba33d9220ad9e8c3 | 1,539 | adaptive | Apache License 2.0 |
modules/db/impl/src/main/kotlin/nasa/db/NasaDatabaseDelegate.kt | jonapoul | 794,260,725 | false | {"Kotlin": 505595} | package nasa.db
import java.io.File
class NasaDatabaseDelegate(private val impl: RoomNasaDatabase) : NasaDatabase {
override fun close() = impl.close()
override fun clearAllTables() = impl.clearAllTables()
override fun file() = impl.openHelper.readableDatabase.path
?.let(::File) ?: error("Null file for database $impl")
}
| 0 | Kotlin | 0 | 1 | 3f22cd526c253a9489d87ef96e5b076da0e7068a | 337 | nasa-android | Apache License 2.0 |
core/data/src/test/kotlin/es/marcrdz/data/repositories/ItemsRepositoryTest.kt | marcRDZ | 806,552,312 | false | {"Kotlin": 49665} | package es.marcrdz.data.repositories
import arrow.core.Either
import es.marcrdz.data.DataContract
import es.marcrdz.domain.DomainContract
import es.marcrdz.domain.models.Fail
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.coVerifySequence
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class ItemsRepositoryTest {
@MockK
lateinit var cacheDataSource: DataContract.ItemDataSource.Cache
@MockK
lateinit var remoteDataSource: DataContract.ItemDataSource.Remote
private val repository: DomainContract.ItemsRepository by lazy {
ItemsRepository(
remoteDataSource,
cacheDataSource
)
}
@Before
fun setUp() = MockKAnnotations.init(this, relaxUnitFun = true)
@Test
fun `When items are cached fetchItems returns data`() = runTest {
//given
coEvery { cacheDataSource.getItems() } returns Either.right(emptyList())
//when
val result = repository.fetchItems()
//then
Assert.assertTrue(result.isRight())
coVerify { cacheDataSource.getItems() }
}
@Test
fun `When no items are cached, loadItems is successful, saveItem executed and fetchItems returns data`() =
runTest {
//given
coEvery { cacheDataSource.getItems() } returns Either.left(Fail.NoData)
coEvery { remoteDataSource.loadItems() } returns Either.right(emptyList())
coEvery { cacheDataSource.saveItems(any()) } returns Either.right(true)
//when
val result = repository.fetchItems()
//then
Assert.assertTrue(result.isRight())
coVerifySequence {
cacheDataSource.getItems()
remoteDataSource.loadItems()
cacheDataSource.saveItems(any())
}
}
@Test
fun `When no items are cached, loadItems is unsuccessful, saveItem is not executed and fetchItems returns fail`() =
runTest {
//given
coEvery { cacheDataSource.getItems() } returns Either.left(Fail.NoData)
coEvery { remoteDataSource.loadItems() } returns Either.left(Fail.Network)
//when
val result = repository.fetchItems()
//then
Assert.assertTrue((result as? Either.Left)?.a is Fail.Network)
coVerifySequence {
cacheDataSource.getItems()
remoteDataSource.loadItems()
}
}
@Test
fun `When clearItems is executed returns data`() = runTest {
//given
coEvery { cacheDataSource.clearItems() } returns Either.right(true)
//when
val result = repository.clearItems()
//then
Assert.assertTrue(result.isRight())
coVerify { cacheDataSource.clearItems() }
}
}
| 0 | Kotlin | 0 | 0 | 0886fa08b73047eaed6f9d53f44315beca80bb6d | 2,993 | MondlyApp | Apache License 2.0 |
app/src/main/kotlin/no/nav/navnosearchadminapi/rest/aspect/ApiKeyProtectedAspect.kt | navikt | 710,261,054 | false | {"Kotlin": 71834, "Dockerfile": 248} | package no.nav.navnosearchadminapi.rest.aspect
import no.nav.navnosearchadminapi.exception.InvalidApiKeyException
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
@Aspect
@Component
class HeaderCheckAspect(@Value("\${api-key}") val apiKey: String) {
@Before("@annotation(apiKeyProtected)")
fun checkHeader(apiKeyProtected: ApiKeyProtected) {
val request = (RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes).request
val actualValue = request.getHeader(API_KEY_HEADER)
if (actualValue != apiKey) {
throw InvalidApiKeyException()
}
}
companion object {
const val API_KEY_HEADER = "api-key"
}
} | 0 | Kotlin | 0 | 0 | 91c18672dc252dbb94b24164391406fe46887267 | 978 | navno-search-admin-api | MIT License |
app/src/main/java/com/hsilva/ungathering/domain/model/types/Direction.kt | higoorc | 581,670,582 | false | null | package com.hsilva.ungathering.domain.model.types
enum class Direction {
NORTH,
SOUTH,
EAST,
WEST
} | 0 | Kotlin | 0 | 1 | 206127cabc352691c00482c1cc3dd17d5088455a | 116 | ungathering-app | MIT License |
livenesscamerax/src/main/java/com/schaefer/livenesscamerax/domain/model/StorageType.kt | arturschaefer | 412,866,499 | false | null | package com.schaefer.livenesscamerax.domain.model
import com.schaefer.domain.model.StorageTypeDomain
enum class StorageType {
INTERNAL,
EXTERNAL
}
fun StorageType.toDomain(): StorageTypeDomain {
return when (this) {
StorageType.INTERNAL -> StorageTypeDomain.INTERNAL
StorageType.EXTERNAL -> StorageTypeDomain.EXTERNAL
}
}
| 0 | Kotlin | 5 | 7 | ed9bbdaf766209f640a0b9fc28a123b2d65fb4b6 | 357 | liveness-camerax-android | Apache License 2.0 |
app/src/main/java/com/example/veterinary/db/helpers/DatabaseHelper.kt | diegovarias | 696,524,395 | false | {"Kotlin": 11431} | package com.example.veterinary.db.helpers
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseHelper(context: Context?) :
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(CREATE_USERS_TABLE)
db.execSQL(CREATE_PETS_TABLE)
db.execSQL(CREATE_APPOINTMENTS_TABLE)
insertInitialData(db)
}
private fun insertInitialData(db: SQLiteDatabase) {
// Inserta datos en la tabla de usuarios
insertUser(db, "Diego", "Vasquez", "owner", "[email protected]", "12345678")
insertUser(db, "Juan", "Torres", "doctor", "[email protected]", "12345678")
insertUser(db, "Leo", "Saravia", "admin", "[email protected]", "12345678")
// Inserta datos en la tabla de mascotas
insertPet(db, 1, "Phillipa")
// Inserta datos en la tabla de citas
insertAppointment(db, 1, 1, 2, "2023-01-17", "Consulta general")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Aquí puedes manejar actualizaciones de la base de datos
}
companion object {
private const val DATABASE_NAME = "VeterinaryDatabase.db"
private const val DATABASE_VERSION = 1
private const val CREATE_USERS_TABLE = "CREATE TABLE users (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
"last_name TEXT," +
"type TEXT," +
"email TEXT," +
"password TEXT)"
private const val CREATE_PETS_TABLE = "CREATE TABLE pets (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"user_id INTEGER," +
"name TEXT," +
"FOREIGN KEY(user_id) REFERENCES users(id))"
private const val CREATE_APPOINTMENTS_TABLE = "CREATE TABLE appointments (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"owner_id INTEGER," +
"pet_id INTEGER," +
"doctor_id INTEGER," +
"date TEXT," +
"notes TEXT," +
"FOREIGN KEY(owner_id) REFERENCES users(id)," +
"FOREIGN KEY(pet_id) REFERENCES pets(id)," +
"FOREIGN KEY(doctor_id) REFERENCES users(id))"
}
fun addUser(name: String, lastName: String, type: String, email: String, password: String): Boolean {
return try {
val db = this.writableDatabase
val contentValues = ContentValues().apply {
put("name", name)
put("last_name", lastName)
put("type", type)
put("email", email)
put("password", password)
}
val result = db.insert("users", null, contentValues)
db.close()
result != -1L
} catch (e: Exception) {
false
}
}
private fun insertUser(db: SQLiteDatabase, name: String, lastName: String, type: String, email: String, password: String) {
val contentValues = ContentValues().apply {
put("name", name)
put("last_name", lastName)
put("type", type)
put("email", email)
put("password", password)
}
db.insert("users", null, contentValues)
}
private fun insertPet(db: SQLiteDatabase, userId: Int, name: String) {
val contentValues = ContentValues().apply {
put("user_id", userId)
put("name", name)
}
db.insert("pets", null, contentValues)
}
private fun insertAppointment(db: SQLiteDatabase, ownerId: Int, petId: Int, doctorId: Int, date: String, notes: String) {
val contentValues = ContentValues().apply {
put("owner_id", ownerId)
put("pet_id", petId)
put("doctor_id", doctorId)
put("date", date)
put("notes", notes)
}
db.insert("appointments", null, contentValues)
}
fun checkUser(email: String, password: String): Boolean {
val db = this.readableDatabase
val cursor = db.query(
"users",
arrayOf("id"),
"email = ? AND password = ?",
arrayOf(email, password),
null,
null,
null
)
val userExists = cursor.count > 0
cursor.close()
db.close()
return userExists
}
}
| 0 | Kotlin | 1 | 0 | 05fb8ec9cf0a86d6c64ab16b61b32d2479fed8e8 | 4,588 | proyecto-dsm | Creative Commons Attribution 3.0 Unported |
app/src/main/java/com/korol/myweather/db/ViewedCityWithInfo.kt | AndreyKoroliov1981 | 456,469,102 | false | {"Kotlin": 59456} | package com.korol.myweather.db
class ViewedCityWithInfo {
var viewedCity=ViewedCity()
var infoAboutData="empty"
} | 0 | Kotlin | 0 | 0 | a6074efac0ea6d9c945a2b9edcff5d3b6eec1e44 | 122 | My-Weather | The Unlicense |
shared/src/commonMain/third/app/cash/sqldelight/paging3/OffsetQueryPagingSource.kt | qdsfdhvh | 650,389,325 | false | {"Kotlin": 266749, "Ruby": 1100, "Swift": 628, "Shell": 228} | package app.cash.sqldelight.paging3
import androidx.paging.PagingState
import app.cash.sqldelight.Query
import app.cash.sqldelight.SuspendingTransacter
import app.cash.sqldelight.Transacter
import app.cash.sqldelight.TransacterBase
import app.cash.sqldelight.TransactionCallbacks
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
internal class OffsetQueryPagingSource<RowType : Any>(
private val queryProvider: (limit: Int, offset: Int) -> Query<RowType>,
private val countQuery: Query<Int>,
private val transacter: TransacterBase,
private val context: CoroutineContext,
private val initialOffset: Int,
) : QueryPagingSource<Int, RowType>() {
override val jumpingSupported get() = true
override suspend fun load(
params: LoadParams<Int>,
): LoadResult<Int, RowType> = withContext(context) {
val key = params.key ?: initialOffset
val limit = when (params) {
is LoadParams.Prepend<*> -> minOf(key, params.loadSize)
else -> params.loadSize
}
val getPagingSourceLoadResult: TransactionCallbacks.() -> LoadResult.Page<Int, RowType> = {
val count = countQuery.executeAsOne()
val offset = when (params) {
is LoadParams.Prepend<*> -> maxOf(0, key - params.loadSize)
is LoadParams.Append<*> -> key
is LoadParams.Refresh<*> -> if (key >= count) maxOf(0, count - params.loadSize) else key
else -> error("Unknown PagingSourceLoadParams ${params::class}")
}
val data = queryProvider(limit, offset)
.also { currentQuery = it }
.executeAsList()
val nextPosToLoad = offset + data.size
LoadResult.Page(
data = data,
prevKey = offset.takeIf { it > 0 && data.isNotEmpty() },
nextKey = nextPosToLoad.takeIf { data.isNotEmpty() && data.size >= limit && it < count },
itemsBefore = offset,
itemsAfter = maxOf(0, count - nextPosToLoad),
)
}
val loadResult = when (transacter) {
is Transacter -> transacter.transactionWithResult(bodyWithReturn = getPagingSourceLoadResult)
is SuspendingTransacter -> transacter.transactionWithResult(bodyWithReturn = getPagingSourceLoadResult)
}
if (invalid) LoadResult.Invalid() else loadResult
}
override fun getRefreshKey(state: PagingState<Int, RowType>) =
state.anchorPosition?.let { maxOf(0, it - (state.config.initialLoadSize / 2)) }
}
| 6 | Kotlin | 0 | 3 | d670b93173a89306f511000bab1a195fc1ff090d | 2,616 | green-qrscanner | Apache License 2.0 |
src/seadustry/Seadustry.kt | Slava0135 | 354,625,440 | false | null | package seadustry
import mindustry.mod.Mod
import seadustry.content.SeaBlocks
class Seadustry : Mod() {
override fun loadContent() {
SeaBlocks().load()
}
} | 1 | Kotlin | 2 | 5 | ba42b9110dab5406024fb55371dd2ab8e7b04d2c | 174 | Seadustry | MIT License |
airbyte-cdk/java/airbyte-cdk/dependencies/src/main/kotlin/io/airbyte/commons/protocol/DefaultProtocolSerializer.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.commons.protocol
import io.airbyte.commons.json.Jsons
import io.airbyte.protocol.models.ConfiguredAirbyteCatalog
class DefaultProtocolSerializer : ProtocolSerializer {
override fun serialize(configuredAirbyteCatalog: ConfiguredAirbyteCatalog): String {
return Jsons.serialize(configuredAirbyteCatalog)
}
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 408 | airbyte | MIT License |
Android/RIAID/app/src/main/java/com/kwaishou/ad/riaid/service/DefaultContainer.kt | kwai | 660,007,483 | false | {"Text": 1, "Ignore List": 10, "Markdown": 4, "Ruby": 1, "Objective-C": 184, "C": 2, "XML": 28, "Protocol Buffer": 1, "Gradle": 9, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 7, "Kotlin": 18, "Java": 218, "INI": 6} | package com.kwaishou.ad.riaid.service
import android.annotation.SuppressLint
import android.content.Context
import com.kuaishou.riaid.render.service.base.IDataBindingService
import com.kuaishou.riaid.render.service.base.ILoadImageService
import com.kuaishou.riaid.render.service.base.IMediaPlayerService
import com.kuaishou.riaid.render.service.base.IRIAIDLogReportService
import com.kuaishou.riaid.render.service.base.IResumeActionService
import com.kuaishou.riaid.render.service.base.render.IRenderService
import com.kwaishou.riaid_adapter.glide.GlideImageService
import com.kwaishou.riaid_adapter.media.AndroidMediaServiceImpl
class DefaultContainer(var context: Context) : IRenderService {
override fun getResumeActionService(): IResumeActionService {
return IResumeActionService { _, _, _ -> }
}
override fun getLoadImageService(): ILoadImageService {
return GlideImageService()
}
override fun getRIAIDLogReportService(): IRIAIDLogReportService {
return IRIAIDLogReportService { key, value -> }
}
@SuppressLint("UseRequireInsteadOfGet")
override fun getMediaService(): IMediaPlayerService {
return AndroidMediaServiceImpl()
}
override fun getDataBindingService(): IDataBindingService {
return DemoDataBindingService()
}
} | 0 | Java | 0 | 31 | f421c52eb5218cae42408ef4b42b724809398317 | 1,277 | RIAID | Apache License 2.0 |
heart-rate-app/core/src/main/java/titsch/guilherme/heartratemonitor/core/date/DateProvider.kt | titsch-guilherme | 568,068,598 | false | {"Kotlin": 134173, "JavaScript": 16582} | package titsch.guilherme.heartratemonitor.core.date
import java.time.Instant
import java.time.ZoneId
import java.time.ZoneOffset
class DateProvider {
fun now(): Instant = Instant.now()
fun getZoneOffset(): ZoneOffset {
return ZoneId
.systemDefault().rules
.getOffset(Instant.now())
}
} | 0 | Kotlin | 0 | 0 | 7647c459186696b3b0675aeb289b5a59e1864cf5 | 332 | heart-rate-monitor-android | MIT License |
platform/src/main/kotlin/uk/gov/gdx/datashare/models/CreateAcquirerResponse.kt | alphagov | 549,031,617 | false | null | package uk.gov.gdx.datashare.models
import io.swagger.v3.oas.annotations.media.Schema
import uk.gov.gdx.datashare.enums.RegExConstants
@Schema(description = "Create Acquirer Response")
class CreateAcquirerResponse(
@Schema(
description = "URL of SQS queue that events will be sent to. Either the oauth client details or the queue url will be present, but not both",
required = false,
example = "https://sqs.eu-west-2.amazonaws.com/000000000000/acq_example-queue",
)
val queueUrl: String?,
@Schema(
description = "Cognito client name",
required = true,
example = "hmpo",
maxLength = 80,
pattern = RegExConstants.CLIENT_NAME_REGEX,
)
val clientName: String?,
@Schema(
description = "Cognito client id",
required = true,
example = "1234abc",
maxLength = 50,
pattern = RegExConstants.CLIENT_ID_REGEX,
)
val clientId: String?,
@Schema(
description = "Cognito client secret",
required = true,
example = "1234abc",
maxLength = 80,
pattern = RegExConstants.CLIENT_SECRET_REGEX,
)
val clientSecret: String?,
)
| 7 | Kotlin | 4 | 14 | 42bd225b144d39176a81995bdafdb4da203c79f3 | 1,099 | di-data-life-events-platform | MIT License |
uwmediapicker/src/main/java/com/anilokcun/uwmediapicker/enum/Enums.kt | chimzycash | 173,022,302 | true | {"Kotlin": 53498} | package com.anilokcun.uwmediapicker.enum
/**
* Author : <NAME>
* Author mail : <EMAIL>
* Create Date : 30.08.2018
*/
internal enum class Enums {
MissingViewTypeException {
override fun toString(): String {
return "UW Media Picker, Missing view type exception"
}
},
UWMediaPickerSettingsKey
} | 0 | Kotlin | 0 | 0 | 3cba7570c1ffe9df8087f1dc48102d27437eea2f | 312 | UWMediaPicker-Android | Apache License 2.0 |
src/main/kotlin/org/sdi/domain/model/ApplicationContext.kt | LuismiBarcos | 600,857,845 | false | {"Kotlin": 43161, "Java": 3869} | package org.sdi.domain.model
/**
* @author <NAME>
*/
data class ApplicationContext(
private var components: Components
) {
fun addComponent(component: Component) {
components = Components(components.values.plus(component))
}
fun getComponents() = components.copy(values = components.values)
}
| 0 | Kotlin | 0 | 0 | 7b74b015949c753784efbf289fdba90e6efbc35f | 321 | SDI | Apache License 2.0 |
app/src/main/java/com/truiton/mergedlivedata/model/Icon.kt | Truiton | 202,845,940 | false | {"Kotlin": 26232} | package com.truiton.mergedlivedata.model
import com.google.gson.annotations.SerializedName
data class Icon (
@SerializedName("prefix") val prefix : String,
@SerializedName("suffix") val suffix : String
) | 0 | Kotlin | 4 | 9 | 96ff74a376b848211b10dfda755068b58c56d56e | 208 | MergedLiveData | Apache License 2.0 |
app/src/main/java/com/megaulorder/illcalculator/ResultMapperController.kt | megaulorder | 562,401,450 | false | null | package com.megaulorder.illcalculator
import java.math.BigInteger
class ResultMapperController(
private val base: Base,
private val result: BooleanArray,
) {
fun mapResult(): String = mapNumber(result, base)
private fun mapNumber(number: BooleanArray, base: Base): String =
BigInteger(toBinaryString(number), 2).toString(base.num)
private fun toBinaryString(number: BooleanArray): String =
number.map { if (it) 1 else 0 }.toIntArray().joinToString("")
} | 0 | Kotlin | 0 | 0 | cccd4cfa87760448db3373755c08aad79c34b187 | 466 | IllCalculator | MIT License |
plugins/korge-build/src/main/kotlin/com/soywiz/korge/build/util/KryptoExt.kt | cybernetics | 183,833,774 | true | {"Kotlin": 1966103, "Java": 182026, "ActionScript": 7114, "HTML": 2081, "Shell": 1547, "Batchfile": 698} | package com.soywiz.korge.build.util
import com.soywiz.korio.async.*
import com.soywiz.korio.file.*
import com.soywiz.korio.stream.*
import com.soywiz.krypto.*
suspend fun AsyncInputStream.hash(factory: HashFactory): ByteArray {
val hash = factory.create()
val temp = ByteArray(64 * 1024)
while (true) {
val read = read(temp)
if (read <= 0) break
hash.update(temp, 0, read)
}
return hash.digest()
}
suspend fun VfsFile.hash(factory: HashFactory): ByteArray = openInputStream().use { this.hash(factory) }
| 0 | Kotlin | 0 | 0 | 1d7632525260b115ff7cfabb3631519736986676 | 517 | korge | Apache License 2.0 |
src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/CodedDataSection.kt | juzraai | 78,370,453 | false | null | package hu.juzraai.ted.xml.model.tedexport
import hu.juzraai.ted.xml.model.tedexport.coded.CodifData
import hu.juzraai.ted.xml.model.tedexport.coded.NoticeData
import hu.juzraai.ted.xml.model.tedexport.coded.RefOjs
import org.simpleframework.xml.Element
import org.simpleframework.xml.Root
/**
* Model of CODED_DATA_SECTION element.
*
* @author <NAME>
*/
@Root(name = "CODED_DATA_SECTION")
data class CodedDataSection(
@field:Element(name = "REF_OJS")
var refOjs: RefOjs = RefOjs(),
@field:Element(name = "NOTICE_DATA")
var noticeData: NoticeData = NoticeData(),
@field:Element(name = "CODIF_DATA")
var codifData: CodifData = CodifData()
) | 1 | Kotlin | 1 | 0 | c1dca6b095e76085d2fc7449c8769aeb693a618e | 659 | ted-xml-model | Apache License 2.0 |
src/data/model/PostSnippet.kt | Hymn-Qin | 200,554,890 | false | null | package com.geely.gic.hmi.data.model
data class PostSnippet(val snippet: PostSnippet.Text) {
data class Text(val text: String)
} | 0 | Kotlin | 0 | 0 | 2843ff5dcbf5aeaf3d04dad29ffed78003ab7779 | 133 | KtorWebAndServer | Apache License 2.0 |
site/src/jsMain/kotlin/com/caleb/k/sections/MainSection.kt | Mzazi25 | 738,193,866 | false | {"Kotlin": 91254, "HTML": 69009} | package com.caleb.k.sections
import androidx.compose.runtime.Composable
import com.caleb.k.components.Header
import com.caleb.k.components.SocialBar
import com.caleb.k.models.Section
import com.caleb.k.models.Theme
import com.caleb.k.styles.MainButtonStyle
import com.caleb.k.styles.MainImageStyle
import com.caleb.k.utils.Constants.FONT_FAMILY
import com.caleb.k.utils.Constants.SECTION_WIDTH
import com.caleb.k.utils.Constants.SHORT_INTRO
import com.caleb.k.utils.Res
import com.varabyte.kobweb.compose.css.*
import com.varabyte.kobweb.compose.foundation.layout.Arrangement
import com.varabyte.kobweb.compose.foundation.layout.Box
import com.varabyte.kobweb.compose.foundation.layout.Column
import com.varabyte.kobweb.compose.foundation.layout.Row
import com.varabyte.kobweb.compose.ui.Alignment
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.graphics.Colors
import com.varabyte.kobweb.compose.ui.modifiers.*
import com.varabyte.kobweb.compose.ui.toAttrs
import com.varabyte.kobweb.silk.components.graphics.Image
import com.varabyte.kobweb.silk.components.layout.SimpleGrid
import com.varabyte.kobweb.silk.components.layout.numColumns
import com.varabyte.kobweb.silk.components.navigation.Link
import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint
import com.varabyte.kobweb.silk.components.style.toModifier
import com.varabyte.kobweb.silk.theme.breakpoint.rememberBreakpoint
import org.jetbrains.compose.web.css.percent
import org.jetbrains.compose.web.css.px
import org.jetbrains.compose.web.dom.Button
import org.jetbrains.compose.web.dom.P
import org.jetbrains.compose.web.dom.Text
@Composable
fun MainSection(onMenuClicked: () -> Unit) {
Box(
modifier = Modifier
.id(Section.Home.id)
.maxWidth(SECTION_WIDTH.px),
contentAlignment = Alignment.TopCenter
) {
MainBackground()
MainContent(onMenuClicked = onMenuClicked)
}
}
@Composable
fun MainBackground() {
Image(
modifier = Modifier
.fillMaxSize()
.objectFit(ObjectFit.Cover),
src = Res.Image.background,
description = "Background Image"
)
}
@Composable
fun MainContent(onMenuClicked: () -> Unit) {
val breakpoint = rememberBreakpoint()
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceBetween,
horizontalAlignment = Alignment.CenterHorizontally
) {
Header(onMenuClicked = onMenuClicked)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Bottom,
horizontalAlignment = Alignment.CenterHorizontally
) {
SimpleGrid(
modifier = Modifier.fillMaxWidth(
if (breakpoint >= Breakpoint.MD) 80.percent
else 90.percent
),
numColumns = numColumns(base = 1, md = 2)
) {
MainText(breakpoint = breakpoint)
MainImage()
}
}
}
}
@Composable
fun MainText(breakpoint: Breakpoint) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
if (breakpoint > Breakpoint.MD) {
SocialBar()
}
Column {
P(
attrs = Modifier
.margin(topBottom = 0.px)
.fontFamily(FONT_FAMILY)
.fontSize(if(breakpoint >= Breakpoint.LG) 45.px else 20.px)
.fontWeight(FontWeight.Normal)
.color(Theme.Primary.rgb)
.toAttrs()
) {
Text("Hello, I'm")
}
P(
attrs = Modifier
.margin(top = 20.px, bottom = 0.px)
.fontFamily(FONT_FAMILY)
.fontSize(if(breakpoint >= Breakpoint.LG) 68.px else 40.px)
.fontWeight(FontWeight.Bolder)
.color(Theme.Secondary.rgb)
.toAttrs()
) {
Text("Caleb Langat")
}
P(
attrs = Modifier
.margin(top = 10.px, bottom = 5.px)
.fontFamily(FONT_FAMILY)
.fontSize(20.px)
.fontWeight(FontWeight.Bold)
.color(Theme.Secondary.rgb)
.toAttrs()
) {
Text("Android Engineer and Open Source Enthusiast")
}
P(
attrs = Modifier
.margin(bottom = 25.px)
.maxWidth(400.px)
.fontFamily(FONT_FAMILY)
.fontSize(15.px)
.fontStyle(FontStyle.Italic)
.fontWeight(FontWeight.Normal)
.color(Theme.Secondary.rgb)
.toAttrs()
) {
Text(SHORT_INTRO)
}
Button(
attrs = MainButtonStyle.toModifier()
.height(40.px)
.border(width = 0.px)
.borderRadius(r = 5.px)
.backgroundColor(Theme.Primary.rgb)
.color(Colors.White)
.cursor(Cursor.Pointer)
.toAttrs()
) {
Link(
modifier = Modifier
.color(Colors.White)
.textDecorationLine(TextDecorationLine.None),
text = "Contact me",
path = Section.Contact.path
)
}
}
}
}
@Composable
fun MainImage() {
Column(
modifier = Modifier.fillMaxSize(80.percent).fillMaxHeight(),
verticalArrangement = Arrangement.Bottom
) {
Image(
modifier = MainImageStyle.toModifier().fillMaxWidth(),
src = Res.Image.main,
description = "Main Image"
)
}
} | 0 | Kotlin | 0 | 6 | 8e71decd4aabee4c7534a196944015f9294d9d9a | 6,086 | Caleb-Portfolio | The Unlicense |
src/main/kotlin/com/nogeeksbrewing/graphql/repositories/Repositories.kt | nogeeksbrewing | 192,024,864 | false | null | package com.nogeeksbrewing.graphql.repositories
import com.nogeeksbrewing.graphql.domains.Brewery
import com.nogeeksbrewing.graphql.domains.Recipe
import org.socialsignin.spring.data.dynamodb.repository.EnableScan
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
@Repository
@EnableScan
interface BreweryRepository: CrudRepository<Brewery, String>
@Repository
@EnableScan
interface RecipeRepository: CrudRepository<Recipe, String>
| 1 | Kotlin | 0 | 0 | d0333cc3433d9b499b1008c511bd49ebeb524a0d | 492 | graphql-api | Apache License 2.0 |
src/test/kotlin/com/qomolangma/usecase/iam/UserLoginTest.kt | highsoft-shanghai | 386,574,483 | false | null | package com.qomolangma.usecase.iam
import com.qomolangma.ApiTest
import com.qomolangma.frameworks.test.web.Documentation
import com.qomolangma.frameworks.test.web.Documentation.Companion.doc
import com.qomolangma.frameworks.test.web.PathVariables.Companion.variables
import com.qomolangma.iam.domain.AccessToken
import com.qomolangma.iam.domain.User
import com.qomolangma.iam.domain.Users
import com.qomolangma.usecase.iam.TestUsers.Companion.system
import org.assertj.core.api.Assertions.assertThat
import org.hamcrest.Matchers.`is`
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.restdocs.payload.PayloadDocumentation.*
import java.time.Instant
import javax.annotation.Resource
class UserLoginTest : ApiTest() {
@Resource
private val users: Users? = null
@Resource
private val accessTokens: User.AccessTokens? = null
@BeforeEach
internal fun setUp() {
users!!.add(system())
accessTokens!!.add(AccessToken(system().id(), "previous-token", Instant.now()))
accessTokens.add(AccessToken(system().id(), "previous-token", Instant.now()))
accessTokens.add(AccessToken("", "previous-token", Instant.now()))
}
@Test
internal fun should_user_login_successfully() {
val post = post(
"/user/login", variables(mapOf<String, Any>()), mapOf(
Pair("userName", "Neil"),
Pair("password", "<PASSWORD>"),
), document()
)
val accessToken = system().accessToken(accessTokens!!).display()
assertThat(accessToken).isNotEqualTo("previous-token")
post.statusCode(`is`(200))
.body("code", `is`("0"))
.body("data.token", `is`(accessToken))
assertThat(system().accessToken(accessTokens).display()).isNotEqualTo("")
}
@AfterEach
internal fun tearDown() {
users!!.clear()
accessTokens!!.clear()
}
override fun document(): Documentation {
return doc(
"iam.user.login", requestFields(
fieldWithPath("userName").description("Name of new user"),
fieldWithPath("password").description("Password of new user"),
), responseFields(
fieldWithPath("code").description("response code"),
fieldWithPath("msg").description("response msg"),
fieldWithPath("data.token").description("Token of this user")
)
)
}
}
| 0 | Kotlin | 2 | 4 | d2622ea653baccd9a68cedc0b3daf60957f00dae | 2,534 | qomolangma | MIT License |
android/engine/src/test/java/org/smartregister/fhircore/engine/configuration/UpdateWorkflowValueConfigTest.kt | opensrp | 339,242,809 | false | {"Kotlin": 3034140, "Java": 4967, "JavaScript": 3548, "CSS": 459} | /*
* Copyright 2021-2024 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.engine.configuration
import android.os.Parcel
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import org.hl7.fhir.r4.model.ResourceType
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.smartregister.fhircore.engine.configuration.event.UpdateWorkflowValueConfig
@RunWith(AndroidJUnit4::class)
class UpdateWorkflowValueConfigTest {
@Test
fun testWriteToParcel() {
val config =
UpdateWorkflowValueConfig(
jsonPathExpression = "$.example",
value = Json.decodeFromString("{ \"key\": \"value\" }"),
resourceType = ResourceType.Task,
)
val parcel = Parcel.obtain()
config.writeToParcel(parcel, config.describeContents())
parcel.setDataPosition(0)
val createdConfig = UpdateWorkflowValueConfig.CREATOR.createFromParcel(parcel)
assertEquals(config, createdConfig)
}
@Test
fun testCreateFromParcel() {
// Create a sample UpdateWorkflowValueConfig instance
val config =
UpdateWorkflowValueConfig(
jsonPathExpression = "$.example",
value = Json.decodeFromString("{ \"key\": \"value\" }"),
resourceType = ResourceType.Task,
)
val parcel = Parcel.obtain()
config.writeToParcel(parcel, config.describeContents())
parcel.setDataPosition(0)
val createdConfig = UpdateWorkflowValueConfig.CREATOR.createFromParcel(parcel)
assertEquals("$.example", createdConfig.jsonPathExpression)
assertEquals(Json.decodeFromString<JsonElement>("{ \"key\": \"value\" }"), createdConfig.value)
assertEquals(ResourceType.Task, createdConfig.resourceType)
}
}
| 192 | Kotlin | 56 | 56 | 64a55e6920cb6280cf02a0d68152d9c03266518d | 2,357 | fhircore | Apache License 2.0 |
definitions/src/main/kotlin-gen/xyz/urbanmatrix/mavlink/definitions/ardupilotmega/GoproGetRequest.kt | urbanmatrix | 484,943,163 | false | null | package xyz.urbanmatrix.mavlink.definitions.ardupilotmega
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.ByteArray
import kotlin.Int
import kotlin.Unit
import xyz.urbanmatrix.mavlink.api.GeneratedMavField
import xyz.urbanmatrix.mavlink.api.GeneratedMavMessage
import xyz.urbanmatrix.mavlink.api.MavDeserializer
import xyz.urbanmatrix.mavlink.api.MavEnumValue
import xyz.urbanmatrix.mavlink.api.MavMessage
import xyz.urbanmatrix.mavlink.serialization.decodeEnumValue
import xyz.urbanmatrix.mavlink.serialization.decodeUint8
import xyz.urbanmatrix.mavlink.serialization.encodeEnumValue
import xyz.urbanmatrix.mavlink.serialization.encodeUint8
import xyz.urbanmatrix.mavlink.serialization.truncateZeros
/**
* Request a GOPRO_COMMAND response from the GoPro.
*/
@GeneratedMavMessage(
id = 216,
crc = 50,
)
public data class GoproGetRequest(
/**
* System ID.
*/
@GeneratedMavField(type = "uint8_t")
public val targetSystem: Int = 0,
/**
* Component ID.
*/
@GeneratedMavField(type = "uint8_t")
public val targetComponent: Int = 0,
/**
* Command ID.
*/
@GeneratedMavField(type = "uint8_t")
public val cmdId: MavEnumValue<GoproCommand> = MavEnumValue.fromValue(0),
) : MavMessage<GoproGetRequest> {
public override val instanceMetadata: MavMessage.Metadata<GoproGetRequest> = METADATA
public override fun serializeV1(): ByteArray {
val outputBuffer = ByteBuffer.allocate(SIZE_V1).order(ByteOrder.LITTLE_ENDIAN)
outputBuffer.encodeUint8(targetSystem)
outputBuffer.encodeUint8(targetComponent)
outputBuffer.encodeEnumValue(cmdId.value, 1)
return outputBuffer.array()
}
public override fun serializeV2(): ByteArray {
val outputBuffer = ByteBuffer.allocate(SIZE_V2).order(ByteOrder.LITTLE_ENDIAN)
outputBuffer.encodeUint8(targetSystem)
outputBuffer.encodeUint8(targetComponent)
outputBuffer.encodeEnumValue(cmdId.value, 1)
return outputBuffer.array().truncateZeros()
}
public companion object {
private const val ID: Int = 216
private const val CRC: Int = 50
private const val SIZE_V1: Int = 3
private const val SIZE_V2: Int = 3
private val DESERIALIZER: MavDeserializer<GoproGetRequest> = MavDeserializer { bytes ->
val inputBuffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val targetSystem = inputBuffer.decodeUint8()
val targetComponent = inputBuffer.decodeUint8()
val cmdId = inputBuffer.decodeEnumValue(1).let { value ->
val entry = GoproCommand.getEntryFromValueOrNull(value)
if (entry != null) MavEnumValue.of(entry) else MavEnumValue.fromValue(value)
}
GoproGetRequest(
targetSystem = targetSystem,
targetComponent = targetComponent,
cmdId = cmdId,
)
}
private val METADATA: MavMessage.Metadata<GoproGetRequest> = MavMessage.Metadata(ID, CRC,
DESERIALIZER)
public val classMetadata: MavMessage.Metadata<GoproGetRequest> = METADATA
public fun builder(builderAction: Builder.() -> Unit): GoproGetRequest =
Builder().apply(builderAction).build()
}
public class Builder {
public var targetSystem: Int = 0
public var targetComponent: Int = 0
public var cmdId: MavEnumValue<GoproCommand> = MavEnumValue.fromValue(0)
public fun build(): GoproGetRequest = GoproGetRequest(
targetSystem = targetSystem,
targetComponent = targetComponent,
cmdId = cmdId,
)
}
}
| 1 | Kotlin | 4 | 9 | 8f480256eeaac5755a2ce5582c338a4b30c7e178 | 3,470 | mavlink-kotlin | Apache License 2.0 |
fieldmask-core/src/test/kotlin/ma/ju/fieldmask/core/FieldMatcherTest.kt | stevejuma | 363,915,990 | false | null | package ma.ju.fieldmask.core
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class FieldMatcherTest {
@Test
fun `matches the requested fields`() {
mapOf(
"a/b(c/x,d(*(f,g)))" to mapOf(
"a/b/d/zz/y" to false,
"a/b/d/zz" to true,
"x" to false,
"a/b/c/x/y/z" to true,
"a/b/c" to true,
"a/*/c" to true,
"a/b/d/f" to true,
"a/b/d/zz/f" to true
),
"name,albums/*/id" to mapOf(
"name" to true,
"albums/songs/id" to true,
"albums/id" to true
)
).forEach { (q, expected) ->
val matcher = FieldMask.matcherFor(q)
expected.forEach { (k, v) ->
assertEquals(v, matcher.matches(k).paths.isNotEmpty(), "$q MATCHES $k => $v")
}
}
}
}
| 0 | Kotlin | 1 | 0 | 7445611b65657d26f33e0811b1668da8a43a01f6 | 971 | fieldmask | MIT License |
feature/product/src/main/java/com/peonlee/product/ui/CategoryFilterBottomSheetFragment.kt | YAPP-Github | 634,125,265 | false | null | package com.peonlee.product.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.peonlee.core.ui.base.BaseBottomSheetFragment
import com.peonlee.core.ui.designsystem.selector.SmallSelector
import com.peonlee.model.product.ProductSearchConditionUiModel
import com.peonlee.model.type.Category
import com.peonlee.model.type.CategoryFilter
import com.peonlee.product.databinding.ItemFilterChipBinding
import com.peonlee.product.databinding.ItemSelectorFilterBinding
import com.peonlee.product.databinding.LayoutSelectorFilterBinding
class CategoryFilterBottomSheetFragment(
private val onCategorySelect: (List<Category>) -> Unit
) : BaseBottomSheetFragment("카테고리") {
private var selectedCategory = mutableListOf<Category>()
override fun getFilterLayout(
layoutInflater: LayoutInflater,
parent: ViewGroup
): View {
val listLayout = LayoutSelectorFilterBinding.inflate(layoutInflater, parent, false).root
CategoryFilter.values().forEach { categoryFilter ->
listLayout.addView(
ItemSelectorFilterBinding.inflate(layoutInflater, listLayout, false).apply {
tvTitle.text = categoryFilter.title
categoryFilter.filters.forEach { category ->
flexEventChip.addView(
ItemFilterChipBinding.inflate(layoutInflater).apply {
root.text = category.categoryName
if (category in selectedCategory) root.setFillColor() else root.setCancelColor()
root.setOnClickListener { onSelectCategory(root, category) }
}.root
)
}
}.root
)
}
return listLayout
}
override fun onClickComplete() {
onCategorySelect(selectedCategory)
}
override fun setChangedFilter(productSearchCondition: ProductSearchConditionUiModel): BaseBottomSheetFragment {
selectedCategory = productSearchCondition.categories?.toMutableList() ?: mutableListOf()
return this
}
private fun onSelectCategory(
selector: SmallSelector,
category: Category
) {
if (category in selectedCategory) {
selector.setCancelColor()
selectedCategory.remove(category)
} else {
selector.setFillColor()
selectedCategory.add(category)
}
}
}
| 4 | Kotlin | 0 | 8 | 648ee3f13682367a7c8d7966d056e4047bb9ce23 | 2,536 | pyeonlee-aos | Apache License 2.0 |
src/main/kotlin/logic/document/operations/media/modules/IDownloadModule.kt | DareFox | 470,665,006 | false | {"Kotlin": 107574, "HTML": 683} | package logic.document.operations.media.modules
import logic.document.operations.media.BinaryMedia
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
/**
* Module of [MediaProcessor] that downloads binary media.
*/
sealed interface IDownloadModule {
/**
* If folder is null, [MediaProcessor] will save media to folder with html
*/
val folder: String?
/**
* On error, replace with this media
*/
val onErrorMedia: BinaryMedia?
/**
* Convert and filter elements which need to be downloaded.
* @return pair of [Element] and it's media url
*/
fun filter(document: Document): List<Pair<Element, String>>
/**
* Transform element to use relativePath instead of url
*/
fun transform(element: Element, relativePath: String)
/**
* What processor will download, e.g: Image, Video. Used in UI to show what media is downloading
*/
val downloadingContentType: String
} | 1 | Kotlin | 1 | 18 | c4201e612951f2756337a78e028e1fc8c069881f | 971 | SaveDTF-Compose | MIT License |
src/main/kotlin/model/graph/WeightedGraph.kt | spbu-coding-2023 | 802,501,813 | false | {"Kotlin": 69457} | package model.graph
class WeightedGraph : UndirectedGraph() {
override fun addEdge(first: Int, second: Int, weight: Long): Edge? {
val vertex1 = _vertices[first] ?: return null
val vertex2 = _vertices[second] ?: return null
val edgesVertex1 = _adjacencyList[vertex1]
val edgesVertex2 = _adjacencyList[vertex2]
if (edgesVertex1 == null || edgesVertex2 == null)
return addNewEdge(vertex1, vertex2, weight)
val edge1 = edgesVertex1.find { it.second.key == second }
val edge2 = edgesVertex2.find { it.second.key == first }
if (edge1 == null || edge2 == null) return addNewEdge(vertex1, vertex2, weight)
if (edge1.weight == weight) return null
edge1.weight = weight
edge2.weight = weight
return edge1
}
private fun addNewEdge(vertex1: Vertex, vertex2: Vertex, weight: Long): Edge? {
_adjacencyList[vertex1]?.add(WeightedEdge(vertex1, vertex2, weight))
_adjacencyList[vertex2]?.add(WeightedEdge(vertex2, vertex1, weight))
return _adjacencyList[vertex1]?.last()
}
private data class WeightedEdge(
override val first: Vertex, override val second: Vertex,
override var weight: Long
) : Edge
}
| 1 | Kotlin | 0 | 2 | 087b51aafcdbb4484e2c72d616cd5f1d72569816 | 1,272 | graphs-graphs-3 | MIT License |
shared/src/commonMain/kotlin/com/bunjne/bbit/data/remote/plugin/DefaultBearerAuthProvider.kt | Bunjne | 676,815,886 | false | {"Kotlin": 111845, "Swift": 954} | package com.bunjne.bbit.data.remote.plugin
import io.github.aakira.napier.Napier
import io.ktor.client.plugins.auth.AuthProvider
import io.ktor.client.plugins.auth.providers.BearerTokens
import io.ktor.client.plugins.auth.providers.RefreshTokensParams
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.headers
import io.ktor.client.statement.HttpResponse
import io.ktor.http.HttpHeaders
import io.ktor.http.auth.AuthScheme
import io.ktor.http.auth.HttpAuthHeader
/**
* A wrapper class of [BearerAuthProvider] to support refresh token handling
* when getting an API response with status code 401 and www-authenticate: OAuth realm="Bitbucket.org HTTP"
* Note that, every APIs use Bearer authorization but, auth scheme = OAuth is not supported by [BearerAuthProvider]
* */
class DefaultBearerAuthProvider(
private val refreshTokens: suspend RefreshTokensParams.() -> BearerTokens?,
private val loadTokens: suspend () -> BearerTokens?,
private val sendWithoutRequestCallback: (HttpRequestBuilder) -> Boolean = { true },
private val realm: String?
) : AuthProvider {
@Suppress("OverridingDeprecatedMember")
@Deprecated("Please use sendWithoutRequest function instead")
override val sendWithoutRequest: Boolean
get() = error("Deprecated")
override fun sendWithoutRequest(request: HttpRequestBuilder): Boolean =
sendWithoutRequestCallback(request)
/**
* Checks if current provider is applicable to the request.
*/
override fun isApplicable(auth: HttpAuthHeader): Boolean {
if (auth.authScheme != AuthScheme.Bearer
&& auth.authScheme != AuthScheme.OAuth
&& auth.authScheme != "BitbucketCustom"
) {
println("Bearer Auth Provider is not applicable for $auth")
Napier.i("Bearer Auth Provider is not applicable for $auth")
return false
}
val isSameRealm = when {
realm == null -> true
auth !is HttpAuthHeader.Parameterized -> false
else -> auth.parameter("realm") == realm
}
if (!isSameRealm) {
Napier.i("Bearer Auth Provider is not applicable for this realm")
}
println("isSameRealm $isSameRealm")
return isSameRealm
}
/**
* Adds an authentication method headers and credentials.
*/
override suspend fun addRequestHeaders(
request: HttpRequestBuilder,
authHeader: HttpAuthHeader?
) {
val token = loadTokens() ?: return
request.headers {
val tokenValue = "Bearer ${token.accessToken}"
if (contains(HttpHeaders.Authorization)) {
remove(HttpHeaders.Authorization)
}
append(HttpHeaders.Authorization, tokenValue)
}
}
override suspend fun refreshToken(response: HttpResponse): Boolean {
val newToken = refreshTokens(
RefreshTokensParams(
response.call.client,
response,
loadTokens()
)
)
return newToken != null
}
} | 0 | Kotlin | 0 | 1 | 88c6e511d22756925a478bc1d77de3f892bfd765 | 3,124 | BBit | Apache License 2.0 |
cesium-kotlin/src/jsMain/kotlin/cesium/engine/LabelGraphics.factory.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6214094} | // Automatically generated - do not modify!
package cesium.engine
inline fun LabelGraphics(
block: LabelGraphics.() -> Unit,
): LabelGraphics =
LabelGraphics().apply(block)
| 0 | Kotlin | 7 | 35 | ac6d96e24eb8d07539990dc2d88cbe85aa811312 | 183 | types-kotlin | Apache License 2.0 |
src/main/kotlin/michi/bot/commands/MichiCommand.kt | slz-br | 598,900,844 | false | null | package michi.bot.commands
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent
abstract class MichiCommand(val name: String, val description: String, val scope: CommandScope) {
protected open val userPermissions = listOf<Permission>()
protected open val botPermisions = listOf<Permission>()
protected open val ownerOnly = false
protected open val usage = ""
open val arguments = listOf<MichiArgument>()
/**
* Executes the command.
* @param context The interaction to retrieve info from.
* @author Slz
* @see canHandle
*/
abstract fun execute(context: SlashCommandInteractionEvent)
/**
* Checks if it's possible to handle the command.
* @param context The interaction to check if it's possible to handle.
* @return True if it's possible to handle, false otherwise.
* @author Slz
* @see execute
*/
protected abstract fun canHandle(context: SlashCommandInteractionEvent): Boolean
} | 1 | Kotlin | 0 | 1 | ff23bfd4b6fc62409b300e865b2bc24bdab7db5d | 1,042 | Michi | Apache License 2.0 |
src/th/mangamoon/src/eu/kanade/tachiyomi/extension/th/mangamoon/MangaMoon.kt | komikku-app | 720,497,299 | false | {"Kotlin": 6646856, "JavaScript": 2160} | package eu.kanade.tachiyomi.extension.th.mangamoon
import eu.kanade.tachiyomi.multisrc.mangathemesia.MangaThemesia
import java.text.SimpleDateFormat
import java.util.Locale
class MangaMoon : MangaThemesia(
"Manga-Moon",
"https://manga-moons.net",
"th",
dateFormat = SimpleDateFormat("MMMM d, yyyy", Locale("th")),
)
| 12 | Kotlin | 5 | 36 | 840b65c8ab7f68e2a5719c9078c631bf8dc84cc1 | 334 | komikku-extensions | Apache License 2.0 |
src/main/kotlin/com/github/hugohomesquita/htmxjetbrains/AttributesProvider.kt | hugohomesquita | 574,459,366 | false | {"Kotlin": 17394} | package com.github.hugohomesquita.htmxjetbrains
import com.intellij.psi.impl.source.html.dtd.HtmlElementDescriptorImpl
import com.intellij.psi.xml.XmlTag
import com.intellij.xml.XmlAttributeDescriptor
import com.intellij.xml.XmlAttributeDescriptorsProvider
class AttributesProvider : XmlAttributeDescriptorsProvider {
override fun getAttributeDescriptors(xmlTag: XmlTag): Array<XmlAttributeDescriptor> {
return emptyArray()
}
@Suppress("ReturnCount")
override fun getAttributeDescriptor(name: String, xmlTag: XmlTag): XmlAttributeDescriptor? {
if (xmlTag.descriptor !is HtmlElementDescriptorImpl) return null
val info = AttributeInfo(name)
if (info.isHtmx()) {
return HtmxAttributeDescriptor(name, xmlTag)
}
return null
}
}
| 1 | Kotlin | 10 | 31 | 5e0d0e6c1ec096f6a4fa5ca4575d47176db7aff2 | 809 | htmx-jetbrains | Apache License 2.0 |
mui-kotlin/src/jsMain/kotlin/mui/base/MenuUnstyled.classes.kt | karakum-team | 387,062,541 | false | null | // Automatically generated - do not modify!
package mui.base
import web.cssom.ClassName
external interface MenuUnstyledClasses {
/** Class name applied to the root element. */
var root: ClassName
/** Class name applied to the listbox element. */
var listbox: ClassName
/** State class applied to the root `PopperUnstyled` element and the listbox `ul` element if `open={true}`. */
var expanded: ClassName
}
| 0 | Kotlin | 3 | 31 | 7a08a2b9c40774b5d98b6fe896e7d70578d372e7 | 435 | mui-kotlin | Apache License 2.0 |
app/src/main/java/com/wsg/up/entity/CommunityRecommend.kt | wushaoge | 299,235,402 | false | null | package com.wsg.up.entity
import android.annotation.SuppressLint
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
/**
* ================================================
* 作 者:wushaoge
* 版 本:1.0
* 创建日期:2020-08-18 09:50
* 描 述:
* 修订历史:
* ================================================
*/
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class RecommendData(
@SerializedName("adExist")
val adExist: Boolean?,
@SerializedName("count")
val count: Int?,
@SerializedName("itemList")
val itemList: List<RecommendItem>?,
@SerializedName("nextPageUrl")
val nextPageUrl: String?,
@SerializedName("total")
val total: Int?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class RecommendItem(
@SerializedName("adIndex")
val adIndex: Int?,
@SerializedName("data")
val `data`: DataRx?,
@SerializedName("id")
val id: Long?,
@SerializedName("type")
val type: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class DataRx(
@SerializedName("content")
val content: Content?,
@SerializedName("count")
val count: Int?,
@SerializedName("dataType")
val dataType: String?,
@SerializedName("header")
val header: Header?,
@SerializedName("itemList")
val itemList: List<ItemX>?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class Content(
@SerializedName("adIndex")
val adIndex: Int?,
@SerializedName("data")
val `data`: DataX?,
@SerializedName("id")
val id: Long?,
@SerializedName("type")
val type: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class Header(
@SerializedName("actionUrl")
val actionUrl: String?,
@SerializedName("followType")
val followType: String?,
@SerializedName("icon")
val icon: String?,
@SerializedName("iconType")
val iconType: String?,
@SerializedName("id")
val id: Long?,
@SerializedName("issuerName")
val issuerName: String?,
@SerializedName("showHateVideo")
val showHateVideo: Boolean?,
@SerializedName("tagId")
val tagid: Long?,
@SerializedName("time")
val time: Long?,
@SerializedName("topShow")
val topShow: Boolean?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class ItemX(
@SerializedName("adIndex")
val adIndex: Int?,
@SerializedName("data")
val `data`: DataXX?,
@SerializedName("id")
val id: Long?,
@SerializedName("type")
val type: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class DataX(
@SerializedName("addWatermark")
val addWatermark: Boolean?,
@SerializedName("area")
val area: String?,
@SerializedName("checkStatus")
val checkStatus: String?,
@SerializedName("city")
val city: String?,
@SerializedName("collected")
val collected: Boolean?,
@SerializedName("consumption")
val consumption: Consumption?,
@SerializedName("cover")
val cover: Cover?,
@SerializedName("createTime")
val createTime: Long?,
@SerializedName("dataType")
val dataType: String?,
@SerializedName("description")
val description: String?,
@SerializedName("height")
val height: Int?,
@SerializedName("id")
val id: Long?,
@SerializedName("ifMock")
val ifMock: Boolean?,
@SerializedName("latitude")
val latitude: Double?,
@SerializedName("library")
val library: String?,
@SerializedName("longitude")
val longitude: Double?,
@SerializedName("owner")
val owner: Owner?,
@SerializedName("reallyCollected")
val reallyCollected: Boolean?,
@SerializedName("recentOnceReply")
val recentOnceReply: RecentOnceReply?,
@SerializedName("releaseTime")
val releaseTime: Long?,
@SerializedName("resourceType")
val resourceType: String?,
@SerializedName("selectedTime")
val selectedTime: Long?,
@SerializedName("status")
val status: String?,
@SerializedName("tags")
val tags: List<TagRx>?,
@SerializedName("title")
val title: String?,
@SerializedName("uid")
val uid: Long?,
@SerializedName("updateTime")
val updateTime: Long?,
@SerializedName("url")
val url: String?,
@SerializedName("urls")
val urls: List<String>?,
@SerializedName("urlsWithWatermark")
val urlsWithWatermark: List<String>?,
@SerializedName("validateResult")
val validateResult: String?,
@SerializedName("validateStatus")
val validateStatus: String?,
@SerializedName("width")
val width: Int?,
@SerializedName("playUrl")
val playUrl: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class Consumption(
@SerializedName("collectionCount")
val collectionCount: Int?,
@SerializedName("realCollectionCount")
val realCollectionCount: Int?,
@SerializedName("replyCount")
val replyCount: Int?,
@SerializedName("shareCount")
val shareCount: Int?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class Cover(
@SerializedName("detail")
val detail: String?,
@SerializedName("feed")
val feed: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class Owner(
@SerializedName("actionUrl")
val actionUrl: String?,
@SerializedName("avatar")
val avatar: String?,
@SerializedName("birthday")
val birthday: Long?,
@SerializedName("city")
val city: String?,
@SerializedName("country")
val country: String?,
@SerializedName("cover")
val cover: String?,
@SerializedName("description")
val description: String?,
@SerializedName("expert")
val expert: Boolean?,
@SerializedName("followed")
val followed: Boolean?,
@SerializedName("gender")
val gender: String?,
@SerializedName("ifPgc")
val ifPgc: Boolean?,
@SerializedName("job")
val job: String?,
@SerializedName("library")
val library: String?,
@SerializedName("limitVideoOpen")
val limitVideoOpen: Boolean?,
@SerializedName("nickname")
val nickname: String?,
@SerializedName("registDate")
val registDate: Long?,
@SerializedName("releaseDate")
val releaseDate: Long?,
@SerializedName("uid")
val uid: Long?,
@SerializedName("university")
val university: String?,
@SerializedName("userType")
val userType: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class RecentOnceReply(
@SerializedName("actionUrl")
val actionUrl: String?,
@SerializedName("dataType")
val dataType: String?,
@SerializedName("message")
val message: String?,
@SerializedName("nickname")
val nickname: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class TagRx(
@SerializedName("actionUrl")
val actionUrl: String?,
@SerializedName("bgPicture")
val bgPicture: String?,
@SerializedName("communityIndex")
val communityIndex: Int?,
@SerializedName("desc")
val desc: String?,
@SerializedName("haveReward")
val haveReward: Boolean?,
@SerializedName("headerImage")
val headerImage: String?,
@SerializedName("id")
val id: Long?,
@SerializedName("ifNewest")
val ifNewest: Boolean?,
@SerializedName("name")
val name: String?,
@SerializedName("tagRecType")
val tagRecType: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class DataXX(
@SerializedName("actionUrl")
val actionUrl: String?,
@SerializedName("adTrack")
val adTrack: List<AdTrack>?,
@SerializedName("autoPlay")
val autoPlay: Boolean?,
@SerializedName("bgPicture")
val bgPicture: String?,
@SerializedName("dataType")
val dataType: String?,
@SerializedName("description")
val description: String?,
@SerializedName("header")
val header: HeaderX?,
@SerializedName("id")
val id: Long?,
@SerializedName("image")
val image: String?,
@SerializedName("label")
val label: Label?,
@SerializedName("labelList")
val labelList: List<LabelX>?,
@SerializedName("shade")
val shade: Boolean?,
@SerializedName("subTitle")
val subTitle: String?,
@SerializedName("title")
val title: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class AdTrack(
@SerializedName("clickUrl")
val clickUrl: String?,
@SerializedName("id")
val id: Long?,
@SerializedName("monitorPositions")
val monitorPositions: String?,
@SerializedName("needExtraParams")
val needExtraParams: List<String>?,
@SerializedName("organization")
val organization: String?,
@SerializedName("playUrl")
val playUrl: String?,
@SerializedName("viewUrl")
val viewUrl: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class HeaderX(
@SerializedName("id")
val id: Long?,
@SerializedName("textAlign")
val textAlign: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class Label(
@SerializedName("card")
val card: String?,
@SerializedName("text")
val text: String?
) : Parcelable
@SuppressLint("ParcelCreator")
@Parcelize
@Keep
data class LabelX(
@SerializedName("text")
val text: String?
) : Parcelable | 0 | Kotlin | 16 | 53 | d5c8722ecc013f17ae8a7d0419abb6daec8c7def | 9,493 | WsgMvvm | Apache License 2.0 |
app/src/main/kotlin/me/nkly/applicanti/App.kt | nkly | 624,831,420 | false | null | package me.nkly.applicanti
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.*
@Configuration
class WebMvcConfig : WebMvcConfigurer {
override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/")
}
}
@SpringBootApplication class Application
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
| 0 | Kotlin | 0 | 0 | e5a645fe0cc06172e65ccb1f1612a7aa1f857c79 | 601 | applicanti | MIT License |
Common/src/main/kotlin/journeymap_webmap/common/kotlin/extensions/resources.kt | TeamJM | 585,745,533 | false | {"Kotlin": 29720, "Java": 862} | package journeymap_webmap.common.kotlin.extensions
import net.minecraft.client.Minecraft
import net.minecraft.resources.ResourceLocation
import java.io.InputStream
fun ResourceLocation.getResourceAsStream(): InputStream {
return Minecraft.getInstance().resourceManager.open(this)
}
| 1 | Kotlin | 1 | 0 | d835afd2ea89d7aa8c9ba0b3005585206941c7a7 | 288 | journeymap-webmap | Apache License 1.1 |
plugin/annotations/src/main/kotlin/shapeTyping/annotations/Annotations.kt | facebookresearch | 498,810,868 | false | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package shapeTyping.annotations
/**
* If used on a type, denotes the shape data of the instance of that type.
* The shape is computed from its argument string, which is a list of shape arguments (currently dimensions or shapes).
*
* Example type usages:
* val a: @SType("[Batches, 2, 3]") Tensor // Generic dimension vals (like Batches) are supported (also see Declare below)
* val a: @SType("[1, 2, _]") Tensor // _ is used to denote an unknown dimension value
* val a: @SType("[___]") Tensor // [___] is used to denote an unknown shape value
* val a: @SType("matmul([1, 2], [2, 1])") // get the shape of a shape function call. Shape function calls can be nested.
* val layer: @SType("[Batches, 3], 3") Layer // multiple arguments may describe the shape of an object with several shaped arguments
*
* If used on a class or function declaration, it declares new generic shapes or dimensions.
*
* _ is used to denote an unknown dimension; [___] is used to denote an unknown shape.
* Example usage:
* @SType("D: _", "S1: [D, 10]", "S2: [10, D]", "S3: [___]") // D is a generic dimension; the rest are generic shapes
* fun foo(a: @SType("S1") Tensor, b: @SType("S2") Tensor, c: @SType("S3") Tensor, d: @SType("[D, D]") Tensor) { ... }
*/
@Target(AnnotationTarget.TYPE, AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.CONSTRUCTOR)
@Retention(AnnotationRetention.RUNTIME)
annotation class SType(val value: String)
/**
* Applied to a scope, this allows the SType checker to accept incomplete evaluation of STypes - usually in cases where
* one or more SType variables cannot be resolved to a concrete value.
*
* For example, a user might write an identity function:
*
* @AllowUnreduced
* @SType("S: Shape")
* fun id(t: @SType("S") Tensor): @SType("S") Tensor = t
*
* The value of S cannot be further reduced at compile time, but we'd want to allow this usage.
*
* NOTE: This annotation is processed by [STypeChecker]. If the default parameter or usage is changed, make sure to
* update it there.
*/
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.FILE,
AnnotationTarget.FIELD,
AnnotationTarget.CONSTRUCTOR
)
@Retention(AnnotationRetention.RUNTIME)
annotation class AllowUnreduced(val allow: Boolean = true)
/**
* This disables any SType checking on functions defined inside the annotated scope.
*/
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.FILE,
AnnotationTarget.FIELD,
AnnotationTarget.CONSTRUCTOR,
)
@Retention(AnnotationRetention.RUNTIME)
annotation class NoSType | 15 | Kotlin | 2 | 8 | b80b7484b8f1033fbef3e76a401b7a0237a35e05 | 2,811 | shapekt | MIT License |
src/test/resources/examples/okHttpClientPostWithoutRequestBody/client/ApiClient.kt | cjbooms | 229,844,927 | false | {"Kotlin": 874094, "Handlebars": 4874} | package examples.okHttpClientPostWithoutRequestBody.client
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.Map
import kotlin.jvm.Throws
@Suppress("unused")
public class ExampleClient(
private val objectMapper: ObjectMapper,
private val baseUrl: String,
private val client: OkHttpClient,
) {
/**
*
*/
@Throws(ApiException::class)
public fun putExample(
additionalHeaders: Map<String, String> = emptyMap(),
additionalQueryParameters: Map<String, String> = emptyMap(),
): ApiResponse<Unit> {
val httpUrl: HttpUrl = "$baseUrl/example"
.toHttpUrl()
.newBuilder()
.also { builder -> additionalQueryParameters.forEach { builder.queryParam(it.key, it.value) } }
.build()
val headerBuilder = Headers.Builder()
additionalHeaders.forEach { headerBuilder.header(it.key, it.value) }
val httpHeaders: Headers = headerBuilder.build()
val request: Request = Request.Builder()
.url(httpUrl)
.headers(httpHeaders)
.put(ByteArray(0).toRequestBody())
.build()
return request.execute(client, objectMapper, jacksonTypeRef())
}
/**
*
*/
@Throws(ApiException::class)
public fun postExample(
additionalHeaders: Map<String, String> = emptyMap(),
additionalQueryParameters: Map<String, String> = emptyMap(),
): ApiResponse<Unit> {
val httpUrl: HttpUrl = "$baseUrl/example"
.toHttpUrl()
.newBuilder()
.also { builder -> additionalQueryParameters.forEach { builder.queryParam(it.key, it.value) } }
.build()
val headerBuilder = Headers.Builder()
additionalHeaders.forEach { headerBuilder.header(it.key, it.value) }
val httpHeaders: Headers = headerBuilder.build()
val request: Request = Request.Builder()
.url(httpUrl)
.headers(httpHeaders)
.post(ByteArray(0).toRequestBody())
.build()
return request.execute(client, objectMapper, jacksonTypeRef())
}
/**
*
*/
@Throws(ApiException::class)
public fun patchExample(
additionalHeaders: Map<String, String> = emptyMap(),
additionalQueryParameters: Map<String, String> = emptyMap(),
): ApiResponse<Unit> {
val httpUrl: HttpUrl = "$baseUrl/example"
.toHttpUrl()
.newBuilder()
.also { builder -> additionalQueryParameters.forEach { builder.queryParam(it.key, it.value) } }
.build()
val headerBuilder = Headers.Builder()
additionalHeaders.forEach { headerBuilder.header(it.key, it.value) }
val httpHeaders: Headers = headerBuilder.build()
val request: Request = Request.Builder()
.url(httpUrl)
.headers(httpHeaders)
.patch(ByteArray(0).toRequestBody())
.build()
return request.execute(client, objectMapper, jacksonTypeRef())
}
}
| 33 | Kotlin | 41 | 154 | b95cb5bd8bb81e59eca71e467118cd61a1848b3f | 3,377 | fabrikt | Apache License 2.0 |
src/test/resources/examples/okHttpClientPostWithoutRequestBody/client/ApiClient.kt | cjbooms | 229,844,927 | false | {"Kotlin": 874094, "Handlebars": 4874} | package examples.okHttpClientPostWithoutRequestBody.client
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.Map
import kotlin.jvm.Throws
@Suppress("unused")
public class ExampleClient(
private val objectMapper: ObjectMapper,
private val baseUrl: String,
private val client: OkHttpClient,
) {
/**
*
*/
@Throws(ApiException::class)
public fun putExample(
additionalHeaders: Map<String, String> = emptyMap(),
additionalQueryParameters: Map<String, String> = emptyMap(),
): ApiResponse<Unit> {
val httpUrl: HttpUrl = "$baseUrl/example"
.toHttpUrl()
.newBuilder()
.also { builder -> additionalQueryParameters.forEach { builder.queryParam(it.key, it.value) } }
.build()
val headerBuilder = Headers.Builder()
additionalHeaders.forEach { headerBuilder.header(it.key, it.value) }
val httpHeaders: Headers = headerBuilder.build()
val request: Request = Request.Builder()
.url(httpUrl)
.headers(httpHeaders)
.put(ByteArray(0).toRequestBody())
.build()
return request.execute(client, objectMapper, jacksonTypeRef())
}
/**
*
*/
@Throws(ApiException::class)
public fun postExample(
additionalHeaders: Map<String, String> = emptyMap(),
additionalQueryParameters: Map<String, String> = emptyMap(),
): ApiResponse<Unit> {
val httpUrl: HttpUrl = "$baseUrl/example"
.toHttpUrl()
.newBuilder()
.also { builder -> additionalQueryParameters.forEach { builder.queryParam(it.key, it.value) } }
.build()
val headerBuilder = Headers.Builder()
additionalHeaders.forEach { headerBuilder.header(it.key, it.value) }
val httpHeaders: Headers = headerBuilder.build()
val request: Request = Request.Builder()
.url(httpUrl)
.headers(httpHeaders)
.post(ByteArray(0).toRequestBody())
.build()
return request.execute(client, objectMapper, jacksonTypeRef())
}
/**
*
*/
@Throws(ApiException::class)
public fun patchExample(
additionalHeaders: Map<String, String> = emptyMap(),
additionalQueryParameters: Map<String, String> = emptyMap(),
): ApiResponse<Unit> {
val httpUrl: HttpUrl = "$baseUrl/example"
.toHttpUrl()
.newBuilder()
.also { builder -> additionalQueryParameters.forEach { builder.queryParam(it.key, it.value) } }
.build()
val headerBuilder = Headers.Builder()
additionalHeaders.forEach { headerBuilder.header(it.key, it.value) }
val httpHeaders: Headers = headerBuilder.build()
val request: Request = Request.Builder()
.url(httpUrl)
.headers(httpHeaders)
.patch(ByteArray(0).toRequestBody())
.build()
return request.execute(client, objectMapper, jacksonTypeRef())
}
}
| 33 | Kotlin | 41 | 154 | b95cb5bd8bb81e59eca71e467118cd61a1848b3f | 3,377 | fabrikt | Apache License 2.0 |
app/src/main/java/com/telen/easylineup/utils/ImagePickerUtils.kt | kaygenzo | 177,859,247 | false | null | package com.telen.easylineup.utils
import android.app.Activity
import android.content.Context
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.nguyenhoanglam.imagepicker.ui.imagepicker.ImagePicker
import com.telen.easylineup.R
class ImagePickerUtils {
companion object {
open fun launchPicker(fragment: Fragment) {
fragment.context?.let {
ImagePicker.with(fragment) // Initialize ImagePicker with activity or fragment context
.setToolbarColor(colorToHexString(ContextCompat.getColor(it, R.color.colorPrimary))) // Toolbar color
.setStatusBarColor(colorToHexString(ContextCompat.getColor(it, R.color.colorPrimaryVariant))) // StatusBar color (works with SDK >= 21 )
.setToolbarTextColor(colorToHexString(ContextCompat.getColor(it, R.color.white))) // Toolbar text color (Title and Done button)
.setToolbarIconColor(colorToHexString(ContextCompat.getColor(it, R.color.white))) // Toolbar icon color (Back and Camera button)
.setProgressBarColor("#4CAF50") // ProgressBar color
.setBackgroundColor(colorToHexString(ContextCompat.getColor(it, R.color.white))) // Background color
.setCameraOnly(false) // Camera mode
.setMultipleMode(false) // Select multiple images or single image
.setFolderMode(true) // Folder mode
.setShowCamera(false) // Show camera button
.setFolderTitle(it.getString(R.string.gallery_picker_default_title)) // Folder title (works with FolderMode = true)
.setMaxSize(1) // Max images can be selected
.setSavePath(it.getString(R.string.app_name)) // Image capture folder name
.setAlwaysShowDoneButton(true) // Set always show done button in multiple mode
.setKeepScreenOn(false) // Keep screen on when selecting images
.start() // Start ImagePicker
}
}
private fun colorToHexString(color: Int): String {
return String.format("#%06X", (0xFFFFFF and color))
}
}
} | 0 | Kotlin | 0 | 0 | 3941fb10aee593332bc942f96734971ab3e68600 | 2,484 | EasyLineUp | Apache License 2.0 |
app/src/main/java/com/arjun/connect/viewmodel/NetworkViewModel.kt | ArjunJadeja | 527,292,695 | false | null | package com.arjun.connect.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class NetworkViewModel : ViewModel() {
private val _isNetworkConnected = MutableLiveData<Boolean>()
val isNetworkConnected: LiveData<Boolean> = _isNetworkConnected
fun getNetwork(isNetworkConnected: Boolean) {
_isNetworkConnected.value = isNetworkConnected
}
} | 0 | Kotlin | 0 | 0 | a7d26ebc5e49661ca849351ceac1eab650989a48 | 437 | Connect | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Bread.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.Bread: ImageVector
get() {
if (_bread != null) {
return _bread!!
}
_bread = Builder(name = "Bread", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(6.3f, 23.989f)
arcToRelative(6.279f, 6.279f, 0.0f, false, true, -4.578f, -1.712f)
curveTo(-1.69f, 18.863f, 0.15f, 11.675f, 5.913f, 5.913f)
reflectiveCurveToRelative(12.949f, -7.6f, 16.364f, -4.19f)
reflectiveCurveToRelative(1.573f, 10.6f, -4.19f, 16.364f)
curveTo(14.281f, 21.894f, 9.853f, 23.989f, 6.3f, 23.989f)
close()
moveTo(17.689f, 3.013f)
curveToRelative(-2.548f, 0.0f, -6.26f, 1.625f, -9.655f, 5.021f)
curveTo(3.228f, 12.84f, 1.968f, 18.28f, 3.844f, 20.156f)
reflectiveCurveToRelative(7.316f, 0.617f, 12.122f, -4.19f)
reflectiveCurveTo(22.032f, 5.72f, 20.156f, 3.844f)
arcTo(3.41f, 3.41f, 0.0f, false, false, 17.689f, 3.013f)
close()
moveTo(14.0f, 5.0f)
verticalLineTo(8.0f)
arcToRelative(1.8f, 1.8f, 0.0f, false, true, 2.0f, 2.0f)
horizontalLineToRelative(3.0f)
arcTo(4.784f, 4.784f, 0.0f, false, false, 14.0f, 5.0f)
close()
moveTo(10.0f, 9.0f)
verticalLineToRelative(3.0f)
arcToRelative(1.8f, 1.8f, 0.0f, false, true, 2.0f, 2.0f)
horizontalLineToRelative(3.0f)
arcTo(4.784f, 4.784f, 0.0f, false, false, 10.0f, 9.0f)
close()
moveTo(6.0f, 13.0f)
verticalLineToRelative(3.0f)
arcToRelative(1.8f, 1.8f, 0.0f, false, true, 2.0f, 2.0f)
horizontalLineToRelative(3.0f)
arcTo(4.784f, 4.784f, 0.0f, false, false, 6.0f, 13.0f)
close()
}
}
.build()
return _bread!!
}
private var _bread: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,938 | icons | MIT License |
application/src/main/kotlin/com/lomeone/application/seucirty/config/SecurityConfig.kt | lomeone | 583,942,276 | false | {"Kotlin": 105805, "Smarty": 1861} | package com.lomeone.application.seucirty.config
import com.lomeone.application.seucirty.filter.EmailPasswordAuthenticationFilter
import com.lomeone.application.seucirty.handler.OAuthAuthenticationSuccessHandler
import com.lomeone.domain.authentication.entity.AuthProvider
import com.lomeone.domain.authentication.exception.OAuth2ProviderNotSupportedException
import com.lomeone.domain.authentication.service.AuthRegisterProvider
import com.lomeone.domain.authentication.service.JwtTokenProvider
import com.lomeone.domain.authentication.service.OAuth2UserService
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.SecurityFilterChain
@Configuration
@EnableWebSecurity
class SecurityConfig(
private val oAuth2UserService: OAuth2UserService,
private val oAuthAuthenticationSuccessHandler: OAuthAuthenticationSuccessHandler
) {
@Bean
fun filterChain(
http: HttpSecurity,
authenticationConfiguration: AuthenticationConfiguration,
jwtTokenProvider: JwtTokenProvider
): SecurityFilterChain {
http.httpBasic { it.disable() }
.csrf { it.disable() }
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.formLogin { it.disable() }
.authorizeHttpRequests {
it.anyRequest().permitAll()
}
.addFilter(EmailPasswordAuthenticationFilter(
authenticationManager = authenticationConfiguration.authenticationManager,
jwtTokenProvider = jwtTokenProvider
))
.oauth2Login { oAuth2LoginConfigure ->
oAuth2LoginConfigure
.userInfoEndpoint { userInfoEndpointConfig ->
userInfoEndpointConfig
.userService { userRequest ->
when (val registrationId = userRequest.clientRegistration.registrationId) {
AuthProvider.GOOGLE.value,
AuthProvider.FACEBOOK.value,
AuthProvider.APPLE.value,
AuthProvider.GITHUB.value,
AuthProvider.KAKAO.value,
AuthProvider.NAVER.value,
AuthProvider.LINE.value -> oAuth2UserService.loadUser(userRequest)
AuthRegisterProvider.GOOGLE.value,
AuthRegisterProvider.FACEBOOK.value,
AuthRegisterProvider.APPLE.value,
AuthRegisterProvider.GITHUB.value,
AuthRegisterProvider.KAKAO.value,
AuthRegisterProvider.NAVER.value,
AuthRegisterProvider.LINE.value -> TODO("Not yet implemented")
else -> throw OAuth2ProviderNotSupportedException(mapOf("oauth2" to registrationId))
}
}
}
.successHandler(oAuthAuthenticationSuccessHandler)
}
return http.build()
}
}
| 4 | Kotlin | 0 | 0 | 480a369035240983e71db4144cddd343b46dc1d5 | 3,701 | lomeone-server | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/cleanroomsml/GlueDataSourcePropertyDsl.kt | F43nd1r | 643,016,506 | false | {"Kotlin": 5279682} | package com.faendir.awscdkkt.generated.services.cleanroomsml
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.cleanroomsml.CfnTrainingDataset
@Generated
public fun buildGlueDataSourceProperty(initializer: @AwsCdkDsl
CfnTrainingDataset.GlueDataSourceProperty.Builder.() -> Unit = {}):
CfnTrainingDataset.GlueDataSourceProperty =
CfnTrainingDataset.GlueDataSourceProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 4 | 32fa5734909e4f7f3bf59b80bd6d4d0bfb2d0dd8 | 504 | aws-cdk-kt | Apache License 2.0 |
sample/src/main/java/com/aqrlei/bannerview/sample/holder/SimpleBannerViewHolder.kt | AqrLei | 288,323,192 | false | null | package com.aqrlei.bannerview.sample.holder
import android.view.View
import android.widget.TextView
import com.aqrlei.bannerview.sample.R
import com.aqrlei.bannerview.widget.BannerViewHolder
/**
* created by AqrLei on 2020/10/20
*/
class SimpleBannerViewHolder(private val list: ArrayList<Int>) : BannerViewHolder() {
override fun getLayoutId(viewType: Int): Int = R.layout.layout_banner_item
override fun getListSize(): Int = list.size
override fun onBindView(position: Int, view: View) {
val tvBanner = view.findViewById<TextView>(R.id.tvBanner)
tvBanner.setBackgroundColor(list[position])
tvBanner.text = "${position+1}"
}
} | 0 | Kotlin | 0 | 1 | cc59f744432fe7ec1b5b72d8ee2ddc2e21745e1a | 674 | BannerView | Apache License 2.0 |
app/src/main/java/com/mujapps/navicomposedrawer/Navigation.kt | aMujeeb | 762,199,041 | false | {"Kotlin": 58006} | package com.mujapps.navicomposedrawer
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.mujapps.navicomposedrawer.presentation.add_note.AddEditNotesScreen
import com.mujapps.navicomposedrawer.presentation.login.LoginScreen
import com.mujapps.navicomposedrawer.presentation.notes.NotesScreen
import com.mujapps.navicomposedrawer.presentation.register.UserRegisterScreen
import com.mujapps.navicomposedrawer.presentation.settings.SettingsScreen
import com.mujapps.navicomposedrawer.utils.ScreenRoute
@Composable
fun Navigation(mNavController: NavHostController) {
NavHost(navController = mNavController, startDestination = ScreenRoute.LoginScreen.route) {
composable(ScreenRoute.LoginScreen.route) {
LoginScreen(navController = mNavController)
}
composable(ScreenRoute.RegisterScreen.route) {
UserRegisterScreen(navController = mNavController)
}
composable(ScreenRoute.NotesScreen.route) {
NotesScreen(navController = mNavController)
}
composable(ScreenRoute.AddEditNotesScreen.route+"?noteId={noteID}¬eTitle={noteTitle}¬eText={noteText}") { backStackEntry ->
AddEditNotesScreen(navController = mNavController,
noteId = backStackEntry.arguments?.getString("noteId"),
title = backStackEntry.arguments?.getString("noteTitle"),
text = backStackEntry.arguments?.getString("noteText"))
}
composable(ScreenRoute.SettingsScreen.route) {
SettingsScreen(navController = mNavController)
}
}
} | 0 | Kotlin | 0 | 0 | 6e295b506abc092ea058a075a02656045b9eb82f | 1,825 | jetpack_compose_navigation_drawer | Apache License 2.0 |
camera/integration-tests/viewtestapp/src/main/java/androidx/camera/integration/view/Media3EffectsFragment.kt | androidx | 256,589,781 | false | {"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019} | /*
* Copyright 2024 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 androidx.camera.integration.view
import android.annotation.SuppressLint
import android.content.ContentValues
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.SeekBar
import android.widget.Toast
import android.widget.ToggleButton
import androidx.annotation.OptIn
import androidx.annotation.RequiresApi
import androidx.camera.core.CameraEffect.IMAGE_CAPTURE
import androidx.camera.core.CameraEffect.PREVIEW
import androidx.camera.core.CameraEffect.VIDEO_CAPTURE
import androidx.camera.core.CameraSelector
import androidx.camera.core.DynamicRange
import androidx.camera.core.impl.utils.executor.CameraXExecutors.directExecutor
import androidx.camera.core.impl.utils.executor.CameraXExecutors.mainThreadExecutor
import androidx.camera.media3.effect.Media3Effect
import androidx.camera.video.MediaStoreOutputOptions
import androidx.camera.video.Recording
import androidx.camera.video.VideoRecordEvent
import androidx.camera.video.VideoRecordEvent.Finalize.ERROR_DURATION_LIMIT_REACHED
import androidx.camera.video.VideoRecordEvent.Finalize.ERROR_FILE_SIZE_LIMIT_REACHED
import androidx.camera.video.VideoRecordEvent.Finalize.ERROR_INSUFFICIENT_STORAGE
import androidx.camera.video.VideoRecordEvent.Finalize.ERROR_SOURCE_INACTIVE
import androidx.camera.view.CameraController
import androidx.camera.view.LifecycleCameraController
import androidx.camera.view.PreviewView
import androidx.camera.view.video.AudioConfig
import androidx.fragment.app.Fragment
import androidx.media3.common.util.UnstableApi
import androidx.media3.effect.Brightness
/** Fragment for testing effects integration. */
@OptIn(UnstableApi::class)
@Suppress("RestrictedApiAndroidX")
class Media3EffectsFragment : Fragment() {
private lateinit var media3Effect: Media3Effect
lateinit var cameraController: LifecycleCameraController
lateinit var previewView: PreviewView
lateinit var slider: SeekBar
private lateinit var hdrToggle: ToggleButton
private lateinit var cameraToggle: ToggleButton
private lateinit var recordButton: Button
private var recording: Recording? = null
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment.
val view = inflater.inflate(R.layout.media3_effect_view, container, false)
previewView = view.findViewById(R.id.preview_view)
slider = view.findViewById(R.id.slider)
hdrToggle = view.findViewById(R.id.hdr)
cameraToggle = view.findViewById(R.id.flip)
recordButton = view.findViewById(R.id.record)
cameraController = LifecycleCameraController(requireContext())
cameraController.bindToLifecycle(viewLifecycleOwner)
cameraController.setEnabledUseCases(CameraController.VIDEO_CAPTURE)
previewView.controller = cameraController
slider.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
media3Effect.setEffects(listOf(Brightness(progress / 100f)))
}
override fun onStartTrackingTouch(seekBar: SeekBar) = Unit
override fun onStopTrackingTouch(seekBar: SeekBar) = Unit
}
)
cameraToggle.setOnClickListener { updateCameraOrientation() }
hdrToggle.setOnClickListener {
cameraController.videoCaptureDynamicRange =
if (hdrToggle.isChecked) {
DynamicRange.HDR_UNSPECIFIED_10_BIT
} else {
DynamicRange.SDR
}
}
recordButton.setOnClickListener {
if (recording == null) {
startRecording()
} else {
stopRecording()
}
}
media3Effect =
Media3Effect(
requireContext(),
PREVIEW or VIDEO_CAPTURE or IMAGE_CAPTURE,
mainThreadExecutor(),
) {
toast("Error in CameraFiltersAdapterProcessor")
}
cameraController.setEffects(setOf(media3Effect))
// Set up UI events.
return view
}
private fun updateCameraOrientation() {
cameraController.cameraSelector =
if (cameraToggle.isChecked) {
CameraSelector.DEFAULT_FRONT_CAMERA
} else {
CameraSelector.DEFAULT_BACK_CAMERA
}
}
override fun onDestroyView() {
super.onDestroyView()
media3Effect.close()
}
private fun toast(message: String?) {
requireActivity().runOnUiThread {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
@SuppressLint("MissingPermission")
private fun startRecording() {
recordButton.text = "Stop recording"
val outputOptions: MediaStoreOutputOptions = getNewVideoOutputMediaStoreOptions()
val audioConfig = AudioConfig.create(true)
recording =
cameraController.startRecording(outputOptions, audioConfig, directExecutor()) {
if (it is VideoRecordEvent.Finalize) {
val uri = it.outputResults.outputUri
when (it.error) {
VideoRecordEvent.Finalize.ERROR_NONE,
ERROR_FILE_SIZE_LIMIT_REACHED,
ERROR_DURATION_LIMIT_REACHED,
ERROR_INSUFFICIENT_STORAGE,
ERROR_SOURCE_INACTIVE -> toast("Video saved to: $uri")
else -> toast("Failed to save video: uri $uri with code (${it.error})")
}
}
}
}
private fun stopRecording() {
recordButton.text = "Record"
recording?.stop()
recording = null
}
private fun getNewVideoOutputMediaStoreOptions(): MediaStoreOutputOptions {
val videoFileName = "video_" + System.currentTimeMillis()
val resolver = requireContext().contentResolver
val contentValues = ContentValues()
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4")
contentValues.put(MediaStore.Video.Media.TITLE, videoFileName)
contentValues.put(MediaStore.Video.Media.DISPLAY_NAME, videoFileName)
return MediaStoreOutputOptions.Builder(
resolver,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
)
.setContentValues(contentValues)
.build()
}
}
| 29 | Kotlin | 1011 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 7,466 | androidx | Apache License 2.0 |
src/main/java/com/tang/intellij/lua/codeInsight/inspection/UnreachableStatement.kt | Benjamin-Dobell | 231,814,734 | false | null | /*
* Copyright (c) 2020
*
* 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.tang.intellij.lua.codeInsight.inspection
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import com.tang.intellij.lua.lang.LuaFileType
import com.tang.intellij.lua.psi.LuaReturnStat
import com.tang.intellij.lua.psi.LuaStatement
import com.tang.intellij.lua.psi.LuaVisitor
class UnreachableStatement : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
if (session.file.name.matches(LuaFileType.DEFINITION_FILE_REGEX)) {
return PsiElementVisitor.EMPTY_VISITOR
}
return object : LuaVisitor() {
override fun visitStatement(o: LuaStatement) {
var sibling = o.prevSibling
var found = false
while (sibling != null && !found) {
if (sibling is LuaReturnStat) {
found = true
holder.registerProblem(o, "Unreachable statement", object : LocalQuickFix {
override fun getName() = "Remove unreachable statement"
override fun getFamilyName() = name
override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) {
o.delete()
}
})
}
sibling = sibling.prevSibling
}
if (!found) super.visitStatement(o)
}
}
}
}
| 61 | Kotlin | 9 | 83 | 68b0a63d3ddd5bc7be9ed304534b601fedcc8319 | 2,220 | IntelliJ-Luanalysis | Apache License 2.0 |
app/src/main/java/com/tjcoding/funtimer/data/local/type_converter/Converters.kt | TimJeric1 | 650,984,348 | false | {"Kotlin": 135265} | package com.tjcoding.funtimer.data.local.type_converter
import androidx.room.TypeConverter
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
class Converters {
@TypeConverter
fun fromLocalDateTime(time: LocalDateTime): Long {
return time.atZone(ZoneId.systemDefault()).toEpochSecond()
}
@TypeConverter
fun toLocalDateTime(unixTime: Long): LocalDateTime {
return Instant.ofEpochSecond(unixTime).atZone(ZoneId.systemDefault()).toLocalDateTime()
}
} | 0 | Kotlin | 0 | 0 | 89e9a8450e6f1394d8810fa317e2001f06c94e50 | 519 | FunTimer | Apache License 2.0 |
android/src/test/java/com/uwconnect/android/domain/usecase/CreateEventUseCaseTest.kt | IbrahimKashif1 | 817,739,177 | false | {"Kotlin": 410352} | package com.uwconnect.android.domain.usecase
import androidx.compose.ui.graphics.Color
import com.uwconnect.android.domain.repository.EventRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.datetime.LocalDateTime
import org.uwconnect.models.CreateEventRequest
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@ExperimentalCoroutinesApi
class CreateEventUseCaseTest {
private lateinit var repository: EventRepository
private lateinit var createEventUseCase: CreateEventUseCase
@Before
fun setUp() {
repository = mock()
createEventUseCase = CreateEventUseCaseImpl(repository)
}
@Test
fun `invoke calls repository createEvent and returns success`() = runBlockingTest {
val eventRequest = CreateEventRequest(
title = "Sample Event Title",
description = "This is a sample description for our event.",
location = "123 Main St, Anytown, AN 12345",
link = "https://example.com/event",
start = LocalDateTime(2024, 4, 5, 14, 30),
end = LocalDateTime(2024, 4, 5, 17, 0),
color = Color.Blue.toString()
)
val expectedResult = Result.success(Unit)
whenever(repository.createEvent(eventRequest)).thenReturn(expectedResult)
val result = createEventUseCase(eventRequest)
verify(repository).createEvent(eventRequest)
assert(result.isSuccess)
}
@Test
fun `invoke calls repository createEvent and returns failure`() = runBlockingTest {
val eventRequest = CreateEventRequest(
title = "Sample Event Title",
description = "This is a sample description for our event.",
location = "123 Main St, Anytown, AN 12345",
link = "https://example.com/event",
start = LocalDateTime(2024, 4, 5, 14, 30),
end = LocalDateTime(2024, 4, 5, 17, 0),
color = Color.Green.toString()
)
val expectedResult = Result.failure<Unit>(RuntimeException("Error creating event"))
whenever(repository.createEvent(eventRequest)).thenReturn(expectedResult)
val result = createEventUseCase(eventRequest)
verify(repository).createEvent(eventRequest)
assert(result.isFailure)
assert(result.exceptionOrNull()?.message == "Error creating event")
}
} | 0 | Kotlin | 0 | 0 | 336e842ca45c5d747bf162f3a7d55ca562591fb0 | 2,515 | UWConnect | MIT License |
app/src/main/java/pl/smcebi/recipeme/App.kt | Seba0855 | 616,026,534 | false | {"Kotlin": 89067} | package pl.smcebi.recipeme
import android.app.Application
import androidx.emoji2.text.EmojiCompat
import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber
import javax.inject.Inject
@HiltAndroidApp
class App : Application() {
@Inject
lateinit var initializersContainer: AppInitializersContainer
override fun onCreate() {
super.onCreate()
initializersContainer.init(this)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
EmojiCompat.init(this)
}
}
| 0 | Kotlin | 0 | 0 | 04a9966a50929063f3f85c2c270c91ce3133575e | 540 | recipe.me | Apache License 2.0 |
feature/inquiry/src/main/java/com/bitgoeul/inquiry/navigation/InquiryNavigation.kt | School-of-Company | 700,744,250 | false | {"Kotlin": 724178} | package com.bitgoeul.inquiry.navigation
| 6 | Kotlin | 1 | 22 | 358bf40188fa2fc2baf23aa6b308b039cb3fbc8c | 41 | Bitgoeul-Android | MIT License |
core/src/test/kotlin/com/messengerk/core/MessageBusTest.kt | tsantos84 | 441,781,910 | false | {"Kotlin": 40278} | package com.messengerk.core
import com.messengerk.core.handler.MessageHandler
import com.messengerk.core.stamp.HandledStamp
import org.junit.jupiter.api.Test
import strikt.api.expectThat
internal class CommandBusTest {
class FooMessage
class FooHandler : MessageHandler<FooMessage> {
override fun handle(envelope: Envelope<FooMessage>): Boolean {
return true
}
}
@Test
fun `It should handle the message`() {
val messageBus = MessageBusBuilder("foo").build {
withHandler(FooHandler())
}
val envelope = messageBus.dispatch(FooMessage())
expectThat(envelope).contains<HandledStamp>()
}
} | 0 | Kotlin | 0 | 0 | 5358365033dfb76db9d021f7e2b12aa568e2c22d | 686 | messengerk | MIT License |
verifiable-credentials-library/src/test/java/org/idp/wallet/verifiable_credentials_library/util/sdjwt/SdJwtTest.kt | hirokazu-kobayashi-koba-hiro | 752,660,337 | false | {"Kotlin": 339200, "Mermaid": 497} | package org.idp.wallet.verifiable_credentials_library.util.sdjwt
import com.nimbusds.jose.crypto.*
import com.nimbusds.jose.jwk.JWK
import eu.europa.ec.eudi.sdjwt.*
import kotlinx.coroutines.runBlocking
import org.idp.wallet.verifiable_credentials_library.util.jose.toRsaPublicKey
import org.junit.Test
class SdJwtTest {
@Test
fun `create and verify`() = runBlocking {
val issuerKeyPair =
"""
{
"p": "<KEY>",
"kty": "RSA",
"q": "<KEY>",
"d": "<KEY>",
"e": "AQAB",
"qi": "<KEY>",
"dp": "<KEY>",
"dq": "<KEY>",
"n": "<KEY>"
}
"""
.trimIndent()
val jwk = JWK.parse(issuerKeyPair)
val rsaKey = jwk.toRSAKey()
val plainPayload =
listOf(
SdJwtElement(
"@context",
listOf("https://www.w3.org/2018/credentials/v1", "https://w3id.org/vaccination/v1"),
true),
SdJwtElement("type", listOf("VerifiableCredential", "VaccinationCertificate"), true),
SdJwtElement("issuer", "https://example.com/issuer", true),
SdJwtElement("issuanceDate", "2023-02-09T11:01:59Z", true),
SdJwtElement("expirationDate", "2028-02-08T11:01:59Z", true),
SdJwtElement("name", "Vaccination Certificate", false),
SdJwtElement("description", "Vaccination Certificate", false),
SdJwtElement(
"cnf",
mapOf(
"jwk" to
mapOf(
"kty" to "EC",
"crv" to "P-256",
"x" to "<KEY>",
"y" to "<KEY>")),
true))
val structuredPayload =
mapOf(
"credentialSubject" to
listOf(
SdJwtElement("type", "VaccinationEvent", false),
),
"vaccine" to
listOf(
SdJwtElement("type", "Vaccine", false),
),
"recipient" to
listOf(
SdJwtElement("type", "VaccineRecipient", false),
))
val payload = SdJwtPayload(plainPayload, structuredPayload)
val sdkJwt = SdJwtUtils.issue(payload, issuerKeyPair)
val rawJwt = sdkJwt.serialize()
println(rawJwt)
val publicKey = jwk.toRsaPublicKey()
val jwtSignatureVerifier = RSASSAVerifier(publicKey).asJwtVerifier()
val verifiedSdJwt = SdJwtVerifier.verifyIssuance(jwtSignatureVerifier, rawJwt).getOrThrow()
println(verifiedSdJwt.jwt.second)
val recreateClaims = verifiedSdJwt.recreateClaims(claimsOf = { jwt -> jwt.second })
print(recreateClaims)
}
}
| 0 | Kotlin | 0 | 0 | a10dacf1ded9df6a6552440060eadb97e59d11ae | 2,867 | vc-wallet-android-app | Apache License 2.0 |
api/src/main/java/com/applakazam/androidmvvmtemplate/api/error/NetworkException.kt | BisiPaul | 642,722,484 | false | {"Kotlin": 62813} | package com.applakazam.androidmvvmtemplate.api.error
import java.io.IOException
/**
* Created by paulbisioc on 23.05.2023
*/
open class NetworkException : IOException() | 2 | Kotlin | 0 | 0 | 16aa0b890a4982f51bf53e89f429a8803923190c | 174 | AndroidMvvmTemplate | MIT License |
src/commonMain/kotlin/io/revenuemonster/sdk/model/common/MemberProfile.kt | RevenueMonster | 370,565,536 | false | {"Kotlin": 76091} | package io.revenuemonster.sdk.model.common
import kotlinx.datetime.Instant
import kotlinx.serialization.Serializable
@Serializable
data class MemberProfile(
val id: String,
val key: String,
val name: String,
val email: String,
val nric: String,
val birthDate: String,
val gender: String,
val address: Address,
val memberTier: String?,
val totalLoyaltyPoint: Int,
val hasPinCode: Boolean,
val loyaltyPointBalance: Int,
val spendingPoint: Int,
val creditBalance: Int,
val status: String,
val createdAt: Instant,
val updatedAt: Instant
) | 5 | Kotlin | 0 | 2 | 36342cd8d0f19b14ffcafa2103e3801e6ff67093 | 604 | rm-kotlin-sdk | MIT License |
fortis/src/main/kotlin/cmu/isr/ts/lts/LTSParallelComposition.kt | cmu-soda | 598,835,734 | false | {"Kotlin": 194808, "Python": 13138, "Shell": 1979} | package cmu.isr.ts.lts
import cmu.isr.ts.DetLTS
import cmu.isr.ts.LTS
import cmu.isr.ts.alphabet
import cmu.isr.ts.nfa.NFAParallelComposition
import net.automatalib.automata.fsa.impl.compact.CompactDFA
import net.automatalib.automata.fsa.impl.compact.CompactNFA
import net.automatalib.util.ts.copy.TSCopy
import net.automatalib.util.ts.traversal.TSTraversal
import net.automatalib.util.ts.traversal.TSTraversalMethod
import net.automatalib.words.impl.Alphabets
class LTSParallelComposition<S1, S2, I>(
private val lts1: LTS<S1, I>,
private val lts2: LTS<S2, I>
) : NFAParallelComposition<S1, S2, I>(lts1, lts2) {
override fun getSuccessor(transition: Pair<S1, S2>): Pair<S1, S2> {
return if (getStateProperty(transition)) transition else Pair(lts1.errorState, lts2.errorState)
}
}
fun <I> parallelComposition(lts1: LTS<*, I>, lts2: LTS<*, I>): LTS<Int, I> {
val inputs = Alphabets.fromCollection(lts1.alphabet() union lts2.alphabet())
val out = CompactNFA(inputs)
val composition = LTSParallelComposition(lts1, lts2)
TSCopy.copy(TSTraversalMethod.DEPTH_FIRST, composition, TSTraversal.NO_LIMIT, inputs, out)
return out.asLTS()
}
fun <I> parallelComposition(lts1: DetLTS<*, I>, lts2: DetLTS<*, I>): DetLTS<Int, I> {
val inputs = Alphabets.fromCollection(lts1.alphabet() union lts2.alphabet())
val out = CompactDFA(inputs)
val composition = LTSParallelComposition(lts1, lts2)
TSCopy.copy(TSTraversalMethod.DEPTH_FIRST, composition, TSTraversal.NO_LIMIT, inputs, out)
return out.asLTS()
} | 1 | Kotlin | 0 | 1 | 63e6a839589614bb309d9415f6fc28f2a8e37abc | 1,525 | Fortis | MIT License |
app/src/main/java/com/apaluk/wsplayer/data/stream_cinema/remote/dto/tv_show/episodes/TvShowSeasonEpisodesResponseDto.kt | apaluk | 576,009,487 | false | null | package com.apaluk.wsplayer.data.stream_cinema.remote.dto.tv_show.episodes
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class TvShowSeasonEpisodesResponseDto(
@Json(name = "hits")
val hits: HitsDto,
@Json(name = "_shards")
val shards: ShardsDto,
@Json(name = "timed_out")
val timedOut: Boolean,
@Json(name = "took")
val took: Int
) | 0 | Kotlin | 0 | 0 | 551703a932d3659f5dadd058d4e3083cbff25534 | 428 | ws-player-android | MIT License |
app/shared/auth/impl/src/commonMain/kotlin/build/wallet/auth/LiteToFullAccountUpgraderImpl.kt | proto-at-block | 761,306,853 | false | null | package build.wallet.auth
import build.wallet.bitkey.account.FullAccount
import build.wallet.bitkey.account.LiteAccount
import build.wallet.bitkey.keybox.KeyCrossDraft
import build.wallet.bitkey.keybox.Keybox
import build.wallet.bitkey.spending.SpendingKeyset
import build.wallet.compose.collections.emptyImmutableList
import build.wallet.f8e.onboarding.UpgradeAccountService
import build.wallet.keybox.KeyboxDao
import build.wallet.notifications.DeviceTokenManager
import build.wallet.platform.random.UuidGenerator
import com.github.michaelbull.result.Result
import com.github.michaelbull.result.coroutines.binding.binding
import com.github.michaelbull.result.mapError
class LiteToFullAccountUpgraderImpl(
private val accountAuthenticator: AccountAuthenticator,
private val authTokenDao: AuthTokenDao,
private val deviceTokenManager: DeviceTokenManager,
private val keyboxDao: KeyboxDao,
private val upgradeAccountService: UpgradeAccountService,
private val uuidGenerator: UuidGenerator,
) : LiteToFullAccountUpgrader {
override suspend fun upgradeAccount(
liteAccount: LiteAccount,
keyCrossDraft: KeyCrossDraft.WithAppKeysAndHardwareKeys,
): Result<FullAccount, AccountCreationError> =
binding {
val fullAccountConfig = keyCrossDraft.config
// Upgrade the account on the server and get a server key back.
val (f8eSpendingKeyset, accountId) =
upgradeAccountService
.upgradeAccount(liteAccount, keyCrossDraft)
.mapError { AccountCreationError.AccountCreationF8eError(it) }
.bind()
val spendingKeyset =
SpendingKeyset(
localId = uuidGenerator.random(),
appKey = keyCrossDraft.appKeyBundle.spendingKey,
networkType = fullAccountConfig.bitcoinNetworkType,
hardwareKey = keyCrossDraft.hardwareKeyBundle.spendingKey,
f8eSpendingKeyset = f8eSpendingKeyset
)
// Store the [Global] scope auth tokens (we don't need to do the [Recovery] scope because
// the Lite Account already has those stored.
val authTokens =
accountAuthenticator
.appAuth(
f8eEnvironment = liteAccount.config.f8eEnvironment,
appAuthPublicKey = keyCrossDraft.appKeyBundle.authKey,
authTokenScope = AuthTokenScope.Global
)
.mapError { AccountCreationError.AccountCreationAuthError(it) }
.bind()
.authTokens
authTokenDao
.setTokensOfScope(accountId, authTokens, AuthTokenScope.Global)
.mapError { AccountCreationError.AccountCreationDatabaseError.FailedToSaveAuthTokens(it) }
.bind()
// Don't bind the error so we don't block account creation on the success of adding
// the device token because it won't yet be available on iOS until push notification
// permissions are requested (which happens after full account creation).
deviceTokenManager
.addDeviceTokenIfPresentForAccount(
fullAccountId = accountId,
f8eEnvironment = fullAccountConfig.f8eEnvironment,
authTokenScope = AuthTokenScope.Global
)
// Retain previous recovery auth key.
val adjustedKeyCross = keyCrossDraft.appKeyBundle
.copy(recoveryAuthKey = liteAccount.recoveryAuthKey)
// We now have everything we need for our Keyset (app/hw/server spending keys)
val keybox =
Keybox(
localId = uuidGenerator.random(),
fullAccountId = accountId,
activeSpendingKeyset = spendingKeyset,
activeAppKeyBundle = adjustedKeyCross,
activeHwKeyBundle = keyCrossDraft.hardwareKeyBundle,
inactiveKeysets = emptyImmutableList(),
appGlobalAuthKeyHwSignature = keyCrossDraft.appGlobalAuthKeyHwSignature,
config = fullAccountConfig
)
// Save our keybox, but do NOT set as active.
// Once onboarding completes, it will be activated
keyboxDao.saveKeyboxAndBeginOnboarding(keybox)
.mapError { AccountCreationError.AccountCreationDatabaseError.FailedToSaveKeybox(it) }
.bind()
FullAccount(accountId, keybox.config, keybox)
}
}
| 3 | null | 16 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 4,175 | bitkey | MIT License |
app/src/main/java/br/com/tarcisiofl/bookshelf/data/local/BookshelfDatabase.kt | Tarcisiofl | 659,526,176 | false | null | package br.com.tarcisiofl.bookshelf.data.local
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import br.com.tarcisiofl.bookshelf.data.local.dao.BookDao
import br.com.tarcisiofl.bookshelf.data.local.dao.RemoteKeysDao
import br.com.tarcisiofl.bookshelf.data.local.entities.BookEntity
import br.com.tarcisiofl.bookshelf.data.local.entities.RemoteKeysEntity
@Database(
entities = [BookEntity::class, RemoteKeysEntity::class],
version = 1
)
@TypeConverters(Converters::class)
abstract class BookshelfDatabase : RoomDatabase() {
abstract val bookDao: BookDao
abstract val remoteKeysDao: RemoteKeysDao
companion object {
const val DB_NAME = "bookshelf_db"
}
} | 0 | Kotlin | 0 | 0 | 3484f05d562678fad5f884165956ba57c3409c55 | 740 | bookshelf-gutendex | MIT License |
src/main/java/com/redmagic/undefinedapi/menu/presets/UndefinedDefaultPageMenu.kt | UndefinedCreation | 756,316,697 | false | {"Kotlin": 90374} | package com.redmagic.undefinedapi.menu.presets
import com.redmagic.undefinedapi.builders.ItemBuilder
import com.redmagic.undefinedapi.extension.string.translateColor
import com.redmagic.undefinedapi.menu.MenuSize
import com.redmagic.undefinedapi.menu.normal.button.ClickData
import com.redmagic.undefinedapi.menu.page.UndefinedPageMenu
import com.redmagic.undefinedapi.menu.page.button.PageButton
import com.redmagic.undefinedapi.menu.setRow
import org.bukkit.Material
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.ItemStack
class UndefinedDefaultPageMenu(name: String, list: MutableList<ItemStack>, private val createInventoryCon: Inventory.() -> Unit,
override var clickData: ClickData.() -> Unit
): UndefinedPageMenu(name, MenuSize.LARGE, list) {
override fun generateInventory(): Inventory = createPageInventory {
setBackButton(
PageButton(45, ItemBuilder(Material.RED_STAINED_GLASS_PANE)
.setName("<reset><#d92323>ʙᴀᴄᴋ ᴀ ᴘᴀɢᴇ".translateColor())
.addLine(" ")
.addLine("<reset><gray>ᴄʟɪᴄᴋ ᴛᴏ ɢᴏ ʙᴀᴄᴋ ᴀɴ ᴘᴀɢᴇ".translateColor()).build(),
ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName(" ").build())
)
setNextButton(
PageButton(53, ItemBuilder(Material.LIME_STAINED_GLASS_PANE)
.setName("<reset><#32e67d>ɴᴇxᴛ ᴘᴀɢᴇ".translateColor())
.addLine(" ")
.addLine("<reset><gray>ᴄʟɪᴄᴋ ᴛᴏ ɢᴏ ᴛᴏ ᴛʜᴇ ɴᴇxᴛ ᴘᴀɢᴇ".translateColor()).build(), ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName(" ").build())
)
setRow(5, ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName(" ").build())
createInventoryCon.invoke(this)
}
} | 0 | Kotlin | 0 | 2 | 85693bd4718f4039fd7b868cec4092aad868a7d4 | 1,769 | UndefinedAPI | MIT License |
app/src/main/java/io/github/airdaydreamers/homebuttonhandler/HomeActivity.kt | vladislav-smirnov | 297,154,534 | false | null | package io.github.airdaydreamers.homebuttonhandler
import android.app.UiModeManager
import android.content.Context
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.SavedStateViewModelFactory
import androidx.lifecycle.ViewModelProvider
import io.github.airdaydreamers.homebuttonhandler.viewmodels.HomeViewModel
import io.github.airdaydreamers.homebuttonhandler.viewmodels.SavedStateViewModel
class HomeActivity : AppCompatActivity() {
private var mSavedStateViewModel: SavedStateViewModel? = null
private var mHomeViewModel: HomeViewModel? = null
private lateinit var mUiModeManager: UiModeManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
//region work with view
findViewById<Button>(R.id.disable_mode_button).setOnClickListener { disableMode() }
//endregion
// Obtain the ViewModel
//region is not google way
//Notes: jsut for show how to use savedState with ViewModelStoreOwner
mSavedStateViewModel =
ViewModelProvider(
application as HomeApplication,
SavedStateViewModelFactory(application, this)
).get(SavedStateViewModel::class.java)
//endregion
//region Google way.
mHomeViewModel = ViewModelProvider(
this,
HomeViewModelFactory.getInstance(application)
).get(HomeViewModel::class.java)
//endregion
//Enable car mode
mUiModeManager = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
mUiModeManager.enableCarMode(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME)
}
override fun onResume() {
super.onResume()
mSavedStateViewModel?.saveActivityState(1)//TODO: change to const or emum or
mHomeViewModel?.setActiveState(1)//TODO: change to const or emum or
}
override fun onStop() {
super.onStop()
mSavedStateViewModel?.saveActivityState(0) //TODO: change to const or emum or
mHomeViewModel?.setActiveState(0) //TODO: change to const or emum or
}
fun disableMode() {
//disable car mode
mUiModeManager.disableCarMode(UiModeManager.DISABLE_CAR_MODE_GO_HOME)
}
} | 0 | Kotlin | 0 | 1 | 6ec9046f8b260f293dd8c354e00ad82818cf290c | 2,364 | homebuttonhandler | Apache License 2.0 |
app/src/main/java/com/cykod/cabinar/SpaceViewActivity.kt | CabinAR | 191,037,036 | false | null | package com.cykod.cabinar
import android.content.Context
import android.content.Intent
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity;
import com.google.ar.core.*
import com.google.ar.sceneform.AnchorNode
import com.google.ar.sceneform.FrameTime
import com.google.ar.sceneform.Scene
import com.google.ar.sceneform.ux.ArFragment
import kotlinx.android.synthetic.main.activity_space_view.*
import java.io.IOException
import java.util.HashMap
import android.webkit.WebViewClient
import androidx.appcompat.app.AlertDialog
import com.google.ar.core.exceptions.ImageInsufficientQualityException
import com.squareup.picasso.Picasso
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.net.HttpURLConnection
import java.net.URL
class SpaceViewActivity : AppCompatActivity() {
private lateinit var arFragment: AugmentedImageFragment
private lateinit var arWebview: WebView
private var spaceId: Int = 0
private var cabinSpace:CabinSpace? = null
private var activePieces:HashMap<String,CabinPiece> = HashMap<String,CabinPiece>()
private lateinit var apiClient: ApiClient
private var showScan = true
private val augmentedImageMap: MutableMap<AugmentedImage, AnchorNode> = mutableMapOf()
companion object {
const val EXTRA_TITLE = "title"
const val EXTRA_ID = "id"
fun newIntent(context: Context, space: CabinSpace): Intent {
val detailIntent = Intent(context, SpaceViewActivity::class.java)
detailIntent.putExtra(EXTRA_TITLE, space.name)
detailIntent.putExtra(EXTRA_ID, space.id)
return detailIntent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_space_view)
//setSupportActionBar(toolbar)
/*
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}*/
arFragment = supportFragmentManager.findFragmentById(R.id.ux_fragment) as AugmentedImageFragment
arFragment.arSceneView.scene.addOnUpdateListener(Scene.OnUpdateListener { this.onUpdateFrame(it) })
// Turn off the plane discovery since we're only looking for images
arFragment.getPlaneDiscoveryController().hide()
arFragment.getPlaneDiscoveryController().setInstructionView(null)
arFragment.getArSceneView().getPlaneRenderer().setEnabled(false)
val action: String? = intent?.action
val intentData: Uri? = intent?.data
var apiToken:String? = null;
// Query params from the intent link
if(intentData != null && intentData.host == "space") {
spaceId = intentData!!.getQueryParameter("space_id")!!.toInt()
apiToken = intentData!!.getQueryParameter("cabin_key")
} else {
spaceId = intent.extras!!.getInt(EXTRA_ID)
var sharedPref = this.getSharedPreferences("cabinar",Context.MODE_PRIVATE)
apiToken = sharedPref.getString("api_token",null)
}
apiClient = ApiClient(applicationContext,apiToken)
arWebview = findViewById(R.id.webview) as WebView
arWebview.setBackgroundColor(0)
arWebview.setLayerType(WebView.LAYER_TYPE_HARDWARE, null)
val webSettings = arWebview.settings
webSettings.allowUniversalAccessFromFileURLs = true
webSettings.javaScriptEnabled = true
arWebview.setWebViewClient(object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
getSpace(spaceId)
}
})
arWebview.loadUrl("file:///android_asset/WebAssets/index.html")
refresh_button.setOnClickListener {
resetTracking()
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//WebView.setWebContentsDebuggingEnabled(true);
}
}
fun errorOut(title:String, message:String) {
AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("ok") { _, _ ->
this.finish()
}.show();
}
fun getSpace(spaceId: Int) {
apiClient.getSpace(spaceId) { space, message ->
if(space != null) {
cabinSpace = space
setupSpace()
} else {
errorOut("Could not load space", "Check your network connection and retry")
}
}
}
fun setupSpace() {
setAssets()
val future = doAsync {
// do your background thread task
val markerPieces = cabinSpace!!.pieces.filter { it.markerUrl != null && it.markerUrl != "" }
val context = applicationContext
var bitmaps: MutableList<Bitmap?> = mutableListOf()
var piecesWithBitmaps: MutableList<CabinPiece> = mutableListOf()
markerPieces.map { piece ->
val url = URL(piece.markerUrl)
val connection = url.openConnection() as HttpURLConnection
val s = connection.getInputStream()
val img = BitmapFactory.decodeStream(s )
piecesWithBitmaps.add(piece)
bitmaps.add(img)
}
uiThread {
// use result here if you want to update ui
loadBitmaps(piecesWithBitmaps, bitmaps)
}
}
// asfd
// get all the images
}
fun resetTracking() {
// This is stupid but currently seems to be the best option
// for sceneForm
// https://github.com/google-ar/sceneform-android-sdk/issues/253
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
/*
arWebview.evaluateJavascript("resetTracking()", { })
augmentedImageMap.forEach { (key, value) ->
arFragment.arSceneView.scene.removeChild(value)
value.anchor?.detach()
value.setParent(null)
}
augmentedImageMap.clear()
fit_to_scan.visibility = View.VISIBLE
showScan = true
*/
}
fun setFocusMode() {
var config = arFragment.arSceneView.session!!.config
config.focusMode = Config.FocusMode.AUTO
config.updateMode = Config.UpdateMode.LATEST_CAMERA_IMAGE
arFragment.arSceneView.session!!.configure(config)
}
fun loadBitmaps(pieces: MutableList<CabinPiece>, bitmaps: MutableList<Bitmap?>) {
setFocusMode();
if(arFragment.imageDatabase != null) {
var config = arFragment.arSceneView.session!!.config
var imageDatabase = AugmentedImageDatabase(arFragment.arSceneView.session!!)
for ((index, bitmap) in bitmaps.withIndex()) {
if(bitmap != null) {
try {
var pos = imageDatabase!!.addImage(
pieces[index].id.toString(),
bitmap
)
activePieces[pieces[index].id.toString()] = pieces[index]
Log.e("CabinAR", "Added images $pos")
} catch(e: ImageInsufficientQualityException) {
errorOut("Space has bad Markers", "The markers are of insufficient quality. Please upload better markers.")
}
}
}
config.augmentedImageDatabase = imageDatabase
config.focusMode = Config.FocusMode.AUTO
config.updateMode = Config.UpdateMode.LATEST_CAMERA_IMAGE
arFragment.arSceneView.session!!.configure(config)
Log.e("CabinAR", "Added images")
Log.e("CabinAR", arFragment.arSceneView.session!!.config.augmentedImageDatabase.numImages.toString())
}
}
fun setAssets() {
arWebview.evaluateJavascript(assetString(), { })
}
fun assetString() : String {
var allAssets = ""
for (piece in cabinSpace!!.pieces) {
if (piece.assets != null) {
val assets = (piece.assets ?: "").replace("\"/ar-file", "\"https://www.cabin-ar.com/ar-file")
allAssets = allAssets + assets + "\n"
}
}
return "addAssets(`$allAssets`);"
}
fun addPieceToWebview(piece:CabinPiece) {
arWebview.evaluateJavascript(pieceString(piece), { })
}
fun addPiecesToWebview() {
var allStr = "";
for (piece in cabinSpace!!.pieces) {
allStr = allStr + pieceString(piece)
}
//allStr += ";hideAllPieces();"
arWebview.evaluateJavascript(allStr, {});
}
fun pieceString(piece: CabinPiece) : String {
return "setPieceEntity(${piece.id}, ${piece.markerMeterWidth ?: 1.0}, `${piece.scene}`);"
}
fun printMatrix(mat:FloatArray) : String {
return "[${mat[0]}, ${mat[4]}, ${mat[8]}, ${mat[12]}," +
"${mat[1]}, ${mat[5]}, ${mat[9]}, ${mat[13]}," +
"${mat[2]}, ${mat[6]}, ${mat[10]}, ${mat[14]}," +
"${mat[3]}, ${mat[7]}, ${mat[11]}, ${mat[15]} ]"
}
private fun onUpdateFrame(frameTime: FrameTime) {
val frame = arFragment.arSceneView.arFrame
// If there is no frame or ARCore is not tracking yet, just return.
if (frame == null || frame.camera.trackingState != TrackingState.TRACKING) {
return
}
var objectTransforms = "{"
var camMat:FloatArray = FloatArray(16)
frame.camera.getDisplayOrientedPose().toMatrix(camMat,0)
var projMat:FloatArray = FloatArray(16)
frame.camera.getProjectionMatrix(projMat,0,0.005f,10000.0f)
var cameraTransform = printMatrix(camMat)
var projectionTransform = printMatrix(projMat)
val updatedAugmentedImages = frame.getUpdatedTrackables(AugmentedImage::class.java)
for (augmentedImage in updatedAugmentedImages) {
when (augmentedImage.trackingState) {
TrackingState.PAUSED -> {
// When an image is in PAUSED state, but the camera is not PAUSED, it has been detected,
// but not yet tracked.
val text = "Detected Image " + augmentedImage.index
//SnackbarHelper.getInstance().showMessage(this, text)
Log.e("CabinAR", text)
}
TrackingState.TRACKING -> {
if(showScan) {
fit_to_scan.visibility = View.GONE
showScan = false
}
// Have to switch to UI Thread to update View.
//fitToScanView.setVisibility(View.GONE)
// Create a new anchor for newly found images.
var node:AugmentedImageNode?
if (!augmentedImageMap.containsKey(augmentedImage)) {
node = AugmentedImageNode(this)
node.image = augmentedImage
augmentedImageMap[augmentedImage] = node
arFragment.arSceneView.scene.addChild(node)
val piece = activePieces[augmentedImage.name]
if(piece != null) {
addPieceToWebview(piece)
}
} else {
node = augmentedImageMap[augmentedImage]!! as AugmentedImageNode
}
var mat:FloatArray = FloatArray(16)
if(node.anchor != null) {
node.anchor!!.pose.toMatrix(mat, 0)
objectTransforms += "\n${augmentedImage.name}: ${printMatrix(mat)},"
}
}
TrackingState.STOPPED -> augmentedImageMap.remove(augmentedImage)
}
}
objectTransforms += "\n}"
val str = "setScenePostParams(${objectTransforms},${cameraTransform},${projectionTransform});"
arWebview.evaluateJavascript(str, { })
}
}
| 0 | Kotlin | 0 | 0 | f10e69455a8cc6880f3f15e3dd0188e5b1537292 | 12,866 | CabinArAndroid | MIT License |
feature-timeline/src/main/java/com/rumosoft/feature_timeline/presentation/viewmodel/DetailsViewModel.kt | Rviewer-Challenges | 498,898,253 | false | {"Kotlin": 140139} | package com.rumosoft.feature_timeline.presentation.viewmodel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.rumosoft.feature_timeline.domain.usecase.GetCommentsUseCase
import com.rumosoft.feature_timeline.domain.usecase.GetTweetUseCase
import com.rumosoft.feature_timeline.presentation.navigation.destination.PicturesDestination
import com.rumosoft.feature_timeline.presentation.screen.model.toTweetUI
import com.rumosoft.feature_timeline.presentation.viewmodel.state.CommentsState
import com.rumosoft.feature_timeline.presentation.viewmodel.state.DetailsState
import com.rumosoft.feature_timeline.presentation.viewmodel.state.TweetState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class DetailsViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val getTweetUseCase: GetTweetUseCase,
private val getCommentsUseCase: GetCommentsUseCase,
) : ViewModel() {
val uiState: StateFlow<DetailsState> get() = _uiState
private val _uiState = MutableStateFlow(DetailsState())
private val tweetId: Long = checkNotNull(savedStateHandle[PicturesDestination.tweetArg])
fun retrieveTweetDetails() {
viewModelScope.launch {
val tweet = getTweetUseCase(tweetId)
_uiState.update {
it.copy(tweet = TweetState.Ready(tweet = tweet.toTweetUI()))
}
loadComments()
}
}
private fun loadComments() {
viewModelScope.launch {
val comments = getCommentsUseCase(tweetId)
_uiState.update { detailsState ->
detailsState.copy(comments = CommentsState.Ready(
comments = comments.map { it.toTweetUI() }
))
}
}
}
} | 0 | Kotlin | 0 | 0 | e72e5c622f73263fa64377bdbcbc9be277693e0e | 2,022 | rbnbRT74TEkpXOeVjjxy | MIT License |
zircon.core/src/main/kotlin/org/codetome/zircon/internal/color/DefaultTextColor.kt | jayece09 | 123,382,162 | true | {"Kotlin": 703071, "Java": 73204} | package org.codetome.zircon.internal.color
import org.codetome.zircon.api.color.TextColor
import org.codetome.zircon.api.color.TextColorFactory
import java.awt.Color
data class DefaultTextColor(private val red: Int,
private val green: Int,
private val blue: Int,
private val alpha: Int = TextColorFactory.DEFAULT_ALPHA) : TextColor {
private val cacheKey = "$red$green$blue$alpha"
override fun generateCacheKey() = cacheKey
private val color: Color = Color(red, green, blue, alpha)
override fun toAWTColor() = color
override fun getRed() = red
override fun getGreen() = green
override fun getBlue() = blue
override fun getAlpha() = alpha
override fun tint(): TextColor {
val c = color.brighter()
return DefaultTextColor(c.red, c.green, c.blue, c.alpha)
}
override fun shade(): TextColor {
val c = color.darker()
return DefaultTextColor(c.red, c.green, c.blue, c.alpha)
}
override fun invert(): TextColor {
return DefaultTextColor(255-color.red, 255-color.green, 255-color.blue, color.alpha)
}
}
| 0 | Kotlin | 0 | 0 | bf4afe40710789aa22c7934e9f3029fce386f0ab | 1,188 | zircon | MIT License |
src/main/kotlin/components/DrawableTextListContainer.kt | LukynkaCZE | 832,858,584 | false | {"Kotlin": 7336} | package cz.lukynka.components
import cz.lukynka.AutoSizeAxis
import cz.lukynka.BindableList
import cz.lukynka.Drawable
import cz.lukynka.util.Vector2
class DrawableTextListContainer : Drawable() {
var list: BindableList<String> = BindableList()
var autoSizeAxis: AutoSizeAxis? = null
override fun drawContent() {
var longestLine = 0
list.values.forEach {
if(it.length > longestLine) longestLine = it.length
}
if(autoSizeAxis != null) {
size = when(autoSizeAxis!!) {
AutoSizeAxis.BOTH -> Vector2(longestLine +2, list.size + 1)
AutoSizeAxis.Y -> Vector2(size.x, list.size + 1)
AutoSizeAxis.X -> Vector2(longestLine +2, size.y)
}
}
list.values.forEachIndexed { index: Int, s: String ->
s.forEachIndexed { charIndex: Int, char ->
buffer[index][charIndex +1] = char
}
}
}
} | 0 | Kotlin | 0 | 2 | 0182a7c005eb16d80f51da37c46269cc7a892323 | 968 | lazy-kotlin-tui | MIT License |
src/main/kotlin/io/api/bloxy/executor/impl/HttpClient.kt | XMaxZone | 170,307,546 | true | {"Kotlin": 241425} | package io.api.bloxy.executor.impl
import io.api.bloxy.executor.IHttpClient
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.stream.Collectors
import java.util.zip.GZIPInputStream
import java.util.zip.InflaterInputStream
/**
* @see IHttpClient
*
* Supports GZIP and deflate decoding
*
* @author GoodforGod
* @since 16.11.2018
*/
class HttpClient @JvmOverloads constructor(
private val connectTimeout: Int = 8000,
private val readTimeout: Int = 0
) : IHttpClient {
companion object {
private val headers: Map<String, String> = hashMapOf(
"Accept-Language" to "en",
"Accept-Encoding" to "deflate, gzip",
"Accept-Charset" to "UTF-8",
"User-Agent" to "Chrome/68.0.3440.106",
"Content-Type" to "application/x-www-form-urlencoded"
)
}
private fun HttpURLConnection.getReader(): InputStreamReader {
return when (contentEncoding) {
"deflate" -> InputStreamReader(InflaterInputStream(this.inputStream), "UTF-8")
"gzip" -> InputStreamReader(GZIPInputStream(this.inputStream), "UTF-8")
else -> InputStreamReader(this.inputStream, "UTF-8")
}
}
override fun get(url: String): String {
(URL(url).openConnection().apply {
readTimeout = [email protected]
connectTimeout = [email protected]
HttpClient.headers.forEach { e -> setRequestProperty(e.key, e.value) }
getHeaderField("Location")?.let { return get(it) }
} as HttpURLConnection).getReader().use {
return BufferedReader(it).lines().collect(Collectors.joining())
}
}
} | 0 | Kotlin | 0 | 0 | 522df5a60a3a11a806656df0c7a6799a776c6eca | 1,772 | bloxy-api | MIT License |
app/src/main/java/ru/barinov/obdroid/ui/utils/LocationSource.kt | PavelB24 | 546,869,778 | false | {"Kotlin": 232443} | package ru.barinov.obdroid.ui.utils
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import androidx.core.app.ActivityCompat
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
object LocationSource {
private val _locationFlow: MutableSharedFlow<Location> = MutableSharedFlow()
val locationFlow: SharedFlow<Location> = _locationFlow
private val gpsListener = GpsLocationListener()
private val netListener = NetLocationListener()
private var locationManager: LocationManager? = null
private val localScope = CoroutineScope(Job() + Dispatchers.IO)
private fun initialize(context: Context) {
if (locationManager == null) {
locationManager = context.getSystemService(LocationManager::class.java)
}
}
fun startListening(context: Context): Boolean {
return if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
initialize(context)
locationManager?.let {
it.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, gpsListener)
it.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, netListener)
}
true
} else false
}
fun getBestLocation(): Location?{
val currGps = gpsListener.currentLocation
val currNet = netListener.currentLocation
return when{
currGps != null && currNet == null -> currGps
currGps == null && currNet != null -> currNet
currGps != null && currNet != null -> {
if(currGps.accuracy < currNet.accuracy){
currGps
} else {
currNet
}
}
else -> null
}
}
class GpsLocationListener : LocationListener {
var currentLocation: Location? = null
override fun onLocationChanged(location: Location) {
currentLocation = location
localScope.launch {
_locationFlow.emit(location)
}
}
}
class NetLocationListener : LocationListener {
var currentLocation: Location? = null
override fun onLocationChanged(location: Location) {
currentLocation = location
localScope.launch {
_locationFlow.emit(location)
}
}
}
} | 0 | Kotlin | 0 | 0 | 4d0947565037ebe03d74adcba115858128f58e92 | 2,893 | OBDroid | Creative Commons Zero v1.0 Universal |
src/main/kotlin/org/swordess/common/vitool/ext/slf4j/CmdLogger.kt | swordess | 206,268,650 | false | {"Kotlin": 103664, "Smalltalk": 54} | /*
* Copyright (c) 2019-2022 Swordess
*
* Distributed under MIT license.
* See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.swordess.common.vitool.ext.slf4j
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.reflect.KProperty
object CmdLogger {
val db by LoggerDelegate()
val docker by LoggerDelegate()
val jib by LoggerDelegate()
}
private class LoggerDelegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Logger =
LoggerFactory.getLogger("cmd.${property.name}")
}
| 10 | Kotlin | 0 | 3 | 8e13f5e6a194a28ea9346b384e95d4f921910924 | 577 | vitool | MIT License |
oppgave-endret/src/main/kotlin/no/nav/helse/sparkel/oppgaveendret/Hendelse.kt | navikt | 341,650,641 | false | null | package no.nav.helse.sparkel.oppgaveendret
import com.fasterxml.jackson.databind.JsonNode
data class Hendelse(
private val hendelsestype: Hendelsetype
) {
internal fun erRelevant() = hendelsestype in Hendelsetype.RELEVANTE_HENDELSER
companion object {
fun fromJson(jsonNode: JsonNode): Hendelse {
return Hendelse(
enumValueOf(jsonNode.path("hendelse").path("hendelsestype").asText())
)
}
}
}
enum class Hendelsetype {
OPPGAVE_OPPRETTET, OPPGAVE_ENDRET, OPPGAVE_FERDIGSTILT, OPPGAVE_FEILREGISTRERT;
companion object {
internal val RELEVANTE_HENDELSER = listOf(OPPGAVE_OPPRETTET, OPPGAVE_FERDIGSTILT, OPPGAVE_FEILREGISTRERT)
}
} | 1 | Kotlin | 1 | 2 | 4127ee4f6d528da5009699dfcc4c6af2c2b83598 | 723 | helse-sparkelapper | MIT License |
app/src/main/java/com/engineerfred/kotlin/ktor/ui/use_case/ValidateNameInputUseCase.kt | EngFred | 763,078,300 | false | {"Kotlin": 375304} | package com.engineerfred.kotlin.ktor.ui.use_case
import com.engineerfred.kotlin.ktor.ui.model.NameInputValidationType
class ValidateNameInputUseCase() {
operator fun invoke(name: String) : NameInputValidationType {
return when {
name.isEmpty() -> NameInputValidationType.EmptyField
name.length < 3 -> NameInputValidationType.Invalid
else -> NameInputValidationType.Valid
}
}
} | 0 | Kotlin | 0 | 0 | bf9031db3581709d5de44181361e1246850b6092 | 438 | quiz-quest | MIT License |
app/src/main/java/com/example/youngster_bmi_app/model/Gender.kt | MaciejPawlik | 228,154,627 | false | null | package com.example.youngster_bmi_app.model
enum class Gender {
GIRL,
BOY
} | 0 | Kotlin | 0 | 0 | e3bcb08180414143e107e872c2ee08eb44e4d469 | 84 | Youngster_BMI_App | MIT License |
app/src/main/java/com/donkor/gank4camp/utils/NetworkUtils.kt | ChenYXin | 114,641,791 | false | null | package com.donkor.gank4camp.utils
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
/**
*
* Created by Donkor on 2017/12/19.
*/
object NetworkUtils {
fun isNetConneted(context: Context):Boolean{
val connectManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo : NetworkInfo?= connectManager.activeNetworkInfo
return if(networkInfo==null){
false
}else{
networkInfo.isAvailable&& networkInfo.isConnected
}
}
} | 0 | Kotlin | 1 | 8 | a4ec18b702ee892a7467dcaef5acf21b8f7d53b1 | 586 | Gank4Camp-in-kotlin | Apache License 2.0 |
app/src/main/java/com/gabor/cleanarchitecture/presentation/utils/dialogs/DialogFactory.kt | gyorgygabor | 440,453,398 | false | {"Kotlin": 109509} | /*
* Copyright 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gabor.cleanarchitecture.presentation.utils.dialogs
import android.app.AlertDialog
import android.content.Context
import com.gabor.cleanarchitecture.R
/**
* Responsible for creating the dialogs.
*/
object DialogFactory {
fun showSessionExpiredDialog(context: Context, function: () -> Unit) {
AlertDialog.Builder(context).apply {
setTitle(context.getString(R.string.title_alert))
setMessage(context.getString(R.string.label_session_expired))
setNeutralButton(
context.getString(R.string.label_login)
) { dialog, _ ->
dialog.cancel()
function.invoke()
}
create()
}.show()
}
fun showServerErrorDialog(context: Context) {
AlertDialog.Builder(context).apply {
setTitle(context.getString(R.string.title_alert))
setMessage(context.getString(R.string.label_server_unreachable))
setNeutralButton(
context.getString(R.string.label_ok)
) { dialog, _ ->
dialog.cancel()
}
create()
}.show()
}
fun showNetworkErrorDialog(context: Context) {
AlertDialog.Builder(context).apply {
setTitle(context.getString(R.string.title_alert))
setMessage(context.getString(R.string.label_no_internet_connection))
setNeutralButton(
context.getString(R.string.label_ok)
) { dialog, _ ->
dialog.cancel()
}
create()
}.show()
}
}
| 0 | Kotlin | 0 | 0 | 9f5828f70c6cfa21741b452f803b205ea1c4c6d3 | 2,228 | clean_architecture | Apache License 2.0 |
app/src/main/java/com/itscatalano/capstonenewsapp/models/Article.kt | TonyCat | 528,997,166 | false | null | package com.itscatalano.capstonenewsapp.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
/***
* Author: Anthony Catalano
* Data class to hold the articles
*
*/
@Parcelize
data class Article(val author: String? = null, var title: String?, var content: String?, var description: String? = null, var publishedAt: String?, var source: Source?, var url: String?, var urlToImage: String? = null ) :
Parcelable
| 3 | Kotlin | 0 | 0 | 0b9dbff9f71c3bd716dcbc1f10e18ca2bc84bff8 | 437 | CapstoneNewsApp | MIT License |
src/main/kotlin/me/moeszyslak/taboo/commands/ConfigurationCommands.kt | hhhapz | 308,037,549 | true | {"Kotlin": 30733, "Dockerfile": 256, "Shell": 63} | package me.moeszyslak.taboo.commands
import com.gitlab.kordlib.common.entity.Snowflake
import me.jakejmattson.discordkt.api.arguments.*
import me.jakejmattson.discordkt.api.dsl.commands
import me.moeszyslak.taboo.data.Configuration
import me.moeszyslak.taboo.data.MimeConfiguration
import me.moeszyslak.taboo.extensions.requiredPermissionLevel
import me.moeszyslak.taboo.services.Permission
import java.awt.Color
fun configurationCommands(configuration: Configuration) = commands("Configuration") {
guildCommand("IgnoredRoles") {
description = "List ignored roles and ignore/unignore roles from the exclusion list"
requiredPermissionLevel = Permission.STAFF
execute(ChoiceArg("ignore/unignore/list", "ignore", "unignore", "list").makeOptional("list"),
RoleArg.makeNullableOptional(null)) {
val (choice, role) = args
val config = configuration[(guild.id.longValue)] ?: return@execute
when (choice) {
"ignore" -> {
if (role == null) {
respond("Received less arguments than expected. Expected: `(Role)`")
return@execute
}
if (config.ignoredRoles.contains(role.id.longValue)) {
respond("${role.name} is already being ignored")
return@execute
}
config.ignoredRoles.add(role.id.longValue)
configuration.save()
respond("${role.name} added to the ignore list")
}
"unignore" -> {
if (role == null) {
respond("Received less arguments than expected. Expected: `(Role)`")
return@execute
}
if (!config.ignoredRoles.contains(role.id.longValue)) {
respond("${role.name} is not being ignored")
return@execute
}
config.ignoredRoles.remove(role.id.longValue)
configuration.save()
respond("${role.name} removed from the ignore list")
}
"list" -> {
respond {
title = "Currently ignored roles"
if (config.ignoredRoles.isEmpty()) {
color = Color(0xE10015)
field {
value = "There are currently no ignored roles."
}
} else {
color = Color(0xDB5F96)
val roles = config.ignoredRoles.map { ignoredRole ->
guild.getRole(Snowflake(ignoredRole)).mention
}
field {
value = roles.joinToString("\n")
}
}
}
}
else -> {
respond("Invalid choice")
}
}
}
}
guildCommand("Mime") {
description = "List mimes and add/remove mimes from the ignore list"
requiredPermissionLevel = Permission.STAFF
execute(ChoiceArg("add/remove/list", "add", "remove", "list").makeOptional("list"),
MultipleArg(AnyArg).makeNullableOptional(null)) {
val (choice, mime) = args
val config = configuration[guild.id.longValue] ?: return@execute
when (choice) {
"add" -> {
if (mime == null) {
respond("Received less arguments than expected. Expected: `(Mime)`")
return@execute
}
mime.forEach {
if (config.ignoredMimes.contains(it)) {
respond("$it is already being ignored")
return@execute
}
}
mime.forEach { config.ignoredMimes.add(it) }
configuration.save()
respond("${mime.joinToString()} added to the ignore list")
}
"remove" -> {
if (mime == null) {
respond("Received less arguments than expected. Expected: `(Mime)`")
return@execute
}
mime.forEach {
if (!config.ignoredMimes.contains(it)) {
respond("$it is not being ignored")
return@execute
}
}
mime.forEach { config.ignoredMimes.remove(it) }
configuration.save()
respond("${mime.joinToString()} removed to the ignore list")
}
"list" -> {
respond {
title = "Currently ignored mimes"
if (config.ignoredMimes.isEmpty()) {
color = Color(0xE10015)
field {
value = "There are currently no ignored mimes."
}
} else {
color = Color(0xDB5F96)
field {
value = config.ignoredMimes.joinToString("\n")
}
}
}
}
else -> {
respond("Invalid choice")
}
}
}
}
guildCommand("MimeRules") {
description = "List mime Rules and add/remove mime rules from the ignore list"
requiredPermissionLevel = Permission.STAFF
execute(ChoiceArg("add/remove/list", "add", "remove", "list").makeOptional("list"),
AnyArg.makeNullableOptional(null), BooleanArg.makeOptional(false), EveryArg.makeNullableOptional()) {
val (choice, mime, upload, warningMessage) = args
val config = configuration[guild.id.longValue] ?: return@execute
when (choice) {
"add" -> {
if (mime == null) {
respond("Received less arguments than expected. Expected: `(Mime)`")
return@execute
}
if (warningMessage == null) {
respond("Received less arguments than expected. Expected: `(Text)`")
return@execute
}
if (config.mimeRules.containsKey(mime)) {
respond("$mime already has a rule attached to it.")
return@execute
}
config.mimeRules[mime] = MimeConfiguration(warningMessage, upload)
configuration.save()
respond("$mime's rules have been updated")
}
"remove" -> {
if (mime == null) {
respond("Received less arguments than expected. Expected: `(Mime)`")
return@execute
}
if (!config.mimeRules.containsKey(mime)) {
respond("$mime doesn't have a rule attached to it.")
return@execute
}
config.mimeRules.remove(mime)
configuration.save()
respond("$mime's rule has been deleted")
}
"list" -> {
if (config.mimeRules.isEmpty()) {
respond {
title = "Current mime rules"
color = Color(0xE10015)
field {
value = "There are currently no mime rules"
}
}
} else {
val chunks = config.mimeRules.toList().chunked(25)
respondMenu {
chunks.map {
page {
title = "Current mime rules"
color = Color(0xDB5F96)
it.map { (mime, mimeconfig) ->
field {
name = "**$mime**"
value = "```\nUpload: ${mimeconfig.uploadText}\n" +
"Delete message: ${mimeconfig.message}```"
}
}
}
}
}
}
}
else -> {
respond("Invalid choice")
}
}
}
}
} | 0 | null | 0 | 0 | 7c2def7e0ec5a90406803fe878ac4c98e695bfd6 | 9,285 | Taboo | MIT License |
pandora/src/main/java/com/lodz/android/pandora/picker/preview/PreviewBuilder.kt | LZ9 | 137,967,291 | false | {"Kotlin": 2174504} | package com.lodz.android.pandora.picker.preview
import android.content.Context
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.IntRange
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.lodz.android.corekt.anko.getColorCompat
import com.lodz.android.pandora.picker.preview.vh.AbsPreviewAgent
/**
* 图片预览构建器
* Created by zhouL on 2018/12/15.
*/
class PreviewBuilder<T, VH : RecyclerView.ViewHolder> {
/** 预览数据 */
private val previewBean = PreviewBean<T, VH>()
/** 设置默认展示图片的位置[position] */
fun setPosition(@IntRange(from = 0) position: Int): PreviewBuilder<T, VH> {
previewBean.showPosition = position
return this
}
/** 设置背景色[color] */
fun setBackgroundColor(@ColorInt color: Int): PreviewBuilder<T, VH> {
previewBean.backgroundColor = color
return this
}
/** 设置背景色[color] */
fun setBackgroundColor(context: Context, @ColorRes color: Int): PreviewBuilder<T, VH> =
setBackgroundColor(context.getColorCompat(color))
/** 设置顶部状态栏颜色[color] */
fun setStatusBarColor(@ColorInt color: Int): PreviewBuilder<T, VH> {
previewBean.statusBarColor = color
return this
}
/** 设置顶部状态栏颜色[color] */
fun setStatusBarColor(context: Context, @ColorRes color: Int): PreviewBuilder<T, VH> =
setStatusBarColor(context.getColorCompat(color))
/** 设置底部导航栏颜色[color] */
fun setNavigationBarColor(@ColorInt color: Int): PreviewBuilder<T, VH> {
previewBean.navigationBarColor = color
return this
}
/** 设置底部导航栏颜色[color] */
fun setNavigationBarColor(context: Context, @ColorRes color: Int): PreviewBuilder<T, VH> =
setNavigationBarColor(context.getColorCompat(color))
/** 设置页码文字颜色[color] */
fun setPagerTextColor(@ColorInt color: Int): PreviewBuilder<T, VH> {
previewBean.pagerTextColor = color
return this
}
/** 设置页码文字颜色[color] */
fun setPagerTextColor(context: Context, @ColorRes color: Int): PreviewBuilder<T, VH> =
setPagerTextColor(context.getColorCompat(color))
/** 设置页码文字大小[sp] */
fun setPagerTextSize(sp: Int): PreviewBuilder<T, VH> {
previewBean.pagerTextSize = sp
return this
}
/** 设置是否显示[isShow]页码文字 */
fun setShowPagerText(isShow: Boolean): PreviewBuilder<T, VH> {
previewBean.isShowPagerText = isShow
return this
}
/** 设置控件[view] */
fun setImageView(view: AbsPreviewAgent<T, VH>): PreviewBuilder<T, VH> {
previewBean.view = view
return this
}
/** 设置VP2的动画[pageTransformer] */
fun setPageTransformer(pageTransformer: ViewPager2.PageTransformer?): PreviewBuilder<T, VH> {
previewBean.pageTransformer = pageTransformer
return this
}
/** 完成单张图片[source]构建 */
fun build(source: T): PreviewManager<T, VH> {
previewBean.sourceList = arrayListOf(source)
return PreviewManager(previewBean)
}
/** 完成图片列表[sourceList]构建 */
fun build(sourceList: List<T>): PreviewManager<T, VH> {
previewBean.sourceList = sourceList
return PreviewManager(previewBean)
}
/** 完成图片数组[sourceArray]构建 */
fun build(sourceArray: Array<T>): PreviewManager<T, VH> {
previewBean.sourceList = sourceArray.toList()
return PreviewManager(previewBean)
}
} | 0 | Kotlin | 3 | 11 | 91c1f5697ab83e18b2f5531b590ed44f0a382568 | 3,421 | AgileDevKt | Apache License 2.0 |
shared/src/commonMain/kotlin/com/qiaoyuang/kmmnews/shared/Platform.kt | qiaoyuang | 342,540,149 | false | null | package com.qiaoyuang.kmmnews.shared
expect class Platform() {
val platform: String
} | 0 | Kotlin | 0 | 0 | 0df803517fb18d9be3e45aa2a679c7956fdefc06 | 90 | KMMNews | Apache License 2.0 |
src/main/kotlin/com/nexsabre/hardwarereservationtool/cmd/helpers/reservations/Reservations.kt | NexSabre | 304,905,839 | false | null | package com.nexsabre.hardwarereservationtool.cmd.helpers.reservations
import com.nexsabre.hardwarereservationtool.cmd.models.Hart
import com.nexsabre.hardwarereservationtool.server.models.Element
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
fun getAllReservations(): List<Element>? {
val response = Hart().reservations() ?: return null
return Json.decodeFromString<List<Element>>(response)
} | 2 | Kotlin | 0 | 0 | 120f5f8049fcec11e4de2805518bf838eab0b8c4 | 441 | hardware-reservation-tool | Apache License 2.0 |
library/src/main/java/com/smartmobilefactory/epubreader/InternalEpubViewSettings.kt | smartmobilefactory | 83,435,122 | false | null | package com.smartmobilefactory.epubreader
import android.os.Handler
import android.os.Looper
import com.smartmobilefactory.epubreader.model.EpubFont
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.PublishSubject
internal class InternalEpubViewSettings(
private val settings: EpubViewSettings
) {
private val settingsChangedSubject = PublishSubject.create<EpubViewSettings.Setting>()
private val mainThreadHandler = Handler(Looper.getMainLooper())
private val disposables = mutableMapOf<EpubViewPlugin, Disposable>()
private val plugins = mutableListOf<EpubViewPlugin>()
val fontSizeSp: Int
get() = settings.fontSizeSp
val font: EpubFont
get() = settings.font
val customChapterCss: List<String>
get() = mutableSetOf<String>().apply {
addAll(settings.customChapterCss)
plugins.forEach { plugin ->
addAll(plugin.customChapterCss)
}
}.toList()
val customChapterScripts: List<String>
get() = mutableSetOf<String>().apply {
addAll(settings.customChapterScripts)
plugins.forEach { plugin ->
addAll(plugin.customChapterScripts)
}
}.toList()
val javascriptBridges: List<EpubJavaScriptBridge>
get() = mutableListOf<EpubJavaScriptBridge>().apply {
if (settings.javascriptBridge != null) {
add(EpubJavaScriptBridge("bridge", settings.javascriptBridge))
}
plugins.forEach { plugin ->
plugin.javascriptBridge?.let { add(it) }
}
}
fun addPlugin(epubPlugin: EpubViewPlugin) {
if (!plugins.contains(epubPlugin)) {
plugins.add(epubPlugin)
val disposable = epubPlugin
.dataChanged()
.subscribe {
onSettingHasChanged(setting = EpubViewSettings.Setting.CUSTOM_FILES)
}
disposables[epubPlugin] = disposable
}
}
fun removePlugin(epubPlugin: EpubViewPlugin) {
plugins.remove(epubPlugin)
disposables[epubPlugin]?.dispose()
disposables.remove(epubPlugin)
}
private fun onSettingHasChanged(setting: EpubViewSettings.Setting) {
// make sure the values only updates on the main thread but avoid delaying events
if (Looper.getMainLooper().thread === Thread.currentThread()) {
settingsChangedSubject.onNext(setting)
} else {
mainThreadHandler.post({ settingsChangedSubject.onNext(setting) })
}
}
fun anySettingHasChanged(): Observable<EpubViewSettings.Setting> {
return settingsChangedSubject.mergeWith(settings.anySettingHasChanged())
}
}
| 5 | Kotlin | 7 | 22 | e89d3523ce3876e0dc44e9a0d5dec8f78909d325 | 2,826 | EpubReaderAndroid | MIT License |
auth/src/main/java/org/futo/circles/auth/utils/UserIdUtils.kt | circles-project | 615,347,618 | false | {"Kotlin": 1307644, "C": 137821, "C++": 12364, "Shell": 3202, "CMake": 1680, "Ruby": 922} | package org.futo.circles.auth.utils
import org.futo.circles.auth.model.EmptyUserId
import org.futo.circles.auth.model.InvalidUserId
import org.futo.circles.auth.model.SuggestedUserId
import org.futo.circles.auth.model.ValidUserId
import org.futo.circles.auth.model.ValidateUserIdStatus
import org.futo.circles.core.base.CirclesAppConfig
import org.matrix.android.sdk.api.MatrixPatterns
object UserIdUtils {
private val defaultDomain = CirclesAppConfig.usDomain
fun getNameAndDomainFromId(userId: String): Pair<String, String> {
if (!MatrixPatterns.isUserId(userId)) throw IllegalArgumentException("Invalid userId $userId")
return userId.split(":").takeIf { it.size == 2 }?.let {
val userName = it.first().replace("@", "")
val domain = it[1]
userName to domain
} ?: throw IllegalArgumentException("Invalid userId $userId")
}
fun validateUserId(input: String): ValidateUserIdStatus {
if (input.isEmpty()) return EmptyUserId
if (MatrixPatterns.isUserId(input)) return ValidUserId(input)
return if (!input.contains("@")) handleMissingLeadingAtSymbol(input)
else if (!input.startsWith("@")) handleEmailToUserIdTransform(input)
else if (input.contains(":")) handleNoDomainInput(input)
else InvalidUserId
}
private fun handleMissingLeadingAtSymbol(input: String): ValidateUserIdStatus {
val suggestion = if (input.contains(":")) "@$input"
else "@$input:$defaultDomain"
return SuggestedUserId(suggestion)
}
private fun handleEmailToUserIdTransform(input: String): ValidateUserIdStatus {
val parts = input.split("@")
.takeIf { it.size == 2 && !it.first().contains(":") }
?: return InvalidUserId
return SuggestedUserId("@${parts.first()}:${parts[1]}")
}
private fun handleNoDomainInput(input: String): ValidateUserIdStatus {
return SuggestedUserId("$input$defaultDomain")
}
} | 8 | Kotlin | 4 | 29 | 7edec708f9c491a7b6f139fc2f2aa3e2b7149112 | 2,003 | circles-android | Apache License 2.0 |
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/normal/PencilSquare.kt | wiryadev | 380,639,096 | false | null | package com.wiryadev.bootstrapiconscompose.bootstrapicons.normal
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.wiryadev.bootstrapiconscompose.bootstrapicons.NormalGroup
public val NormalGroup.PencilSquare: ImageVector
get() {
if (_pencilSquare != null) {
return _pencilSquare!!
}
_pencilSquare = Builder(name = "PencilSquare", defaultWidth = 16.0.dp, defaultHeight =
16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.502f, 1.94f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, 0.706f)
lineTo(14.459f, 3.69f)
lineToRelative(-2.0f, -2.0f)
lineTo(13.502f, 0.646f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.707f, 0.0f)
lineToRelative(1.293f, 1.293f)
close()
moveTo(13.752f, 4.396f)
lineTo(11.752f, 2.396f)
lineTo(4.939f, 9.21f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.121f, 0.196f)
lineToRelative(-0.805f, 2.414f)
arcToRelative(0.25f, 0.25f, 0.0f, false, false, 0.316f, 0.316f)
lineToRelative(2.414f, -0.805f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.196f, -0.12f)
lineToRelative(6.813f, -6.814f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(1.0f, 13.5f)
arcTo(1.5f, 1.5f, 0.0f, false, false, 2.5f, 15.0f)
horizontalLineToRelative(11.0f)
arcToRelative(1.5f, 1.5f, 0.0f, false, false, 1.5f, -1.5f)
verticalLineToRelative(-6.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -1.0f, 0.0f)
verticalLineToRelative(6.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -0.5f, 0.5f)
horizontalLineToRelative(-11.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -0.5f, -0.5f)
verticalLineToRelative(-11.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, -0.5f)
horizontalLineTo(9.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -1.0f)
horizontalLineTo(2.5f)
arcTo(1.5f, 1.5f, 0.0f, false, false, 1.0f, 2.5f)
verticalLineToRelative(11.0f)
close()
}
}
.build()
return _pencilSquare!!
}
private var _pencilSquare: ImageVector? = null
| 0 | Kotlin | 0 | 2 | 1c199d953dc96b261aab16ac230dc7f01fb14a53 | 3,602 | bootstrap-icons-compose | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.