path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/msvalandro/wishlistapp/data/Wish.kt
msvalandro
872,113,498
false
{"Kotlin": 22779}
package com.msvalandro.wishlistapp.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "wishes") data class Wish( @PrimaryKey(autoGenerate = true) val id: Long = 0L, @ColumnInfo(name = "title") val title: String = "", @ColumnInfo(name = "description") val description: String = "" )
0
Kotlin
0
0
1df574d3f2d95b3b5d07812013facff4965d3b13
376
WishlistApp
MIT License
verik-compiler/src/main/kotlin/io/verik/compiler/transform/mid/StringTemplateExpressionTransformerStage.kt
frwang96
269,980,078
false
null
/* * Copyright (c) 2021 Francis Wang * * 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 io.verik.compiler.transform.mid import io.verik.compiler.ast.element.common.EExpression import io.verik.compiler.ast.element.kt.EKtCallExpression import io.verik.compiler.ast.element.kt.EStringTemplateExpression import io.verik.compiler.ast.element.sv.EStringExpression import io.verik.compiler.ast.property.ExpressionStringEntry import io.verik.compiler.ast.property.LiteralStringEntry import io.verik.compiler.common.TreeVisitor import io.verik.compiler.core.common.Core import io.verik.compiler.main.ProjectContext import io.verik.compiler.main.ProjectStage import io.verik.compiler.message.Messages import io.verik.compiler.target.common.Target object StringTemplateExpressionTransformerStage : ProjectStage() { override fun process(projectContext: ProjectContext) { projectContext.project.accept(StringTemplateExpressionTransformerVisitor) } private fun getFormatSpecifier(expression: EExpression): String { val type = expression.type return when (type.reference) { Core.Kt.C_Boolean -> "%b" Core.Kt.C_Int -> "%0d" Core.Kt.C_String -> "%s" Core.Vk.C_Ubit, Core.Vk.C_Sbit -> { val width = type.asBitWidth(expression) "%0${(width + 3) / 4}h" } Core.Vk.C_Time -> "%0t" else -> { Messages.INTERNAL_ERROR.on(expression, "Unable to get format specifier of type: ${expression.type}") } } } private object StringTemplateExpressionTransformerVisitor : TreeVisitor() { override fun visitStringTemplateExpression(stringTemplateExpression: EStringTemplateExpression) { super.visitStringTemplateExpression(stringTemplateExpression) val isStringExpression = stringTemplateExpression.entries.all { it is LiteralStringEntry } val builder = StringBuilder() val valueArguments = ArrayList<EExpression>() for (entry in stringTemplateExpression.entries) { when (entry) { is LiteralStringEntry -> { entry.text.toCharArray().forEach { val text = when (it) { '\n' -> "\\n" '\t' -> "\\t" '\\' -> "\\\\" '\"' -> "\\\"" '\'' -> "\\\'" '%' -> if (isStringExpression) "%" else "%%" else -> it } builder.append(text) } } is ExpressionStringEntry -> { builder.append(getFormatSpecifier(entry.expression)) valueArguments.add(entry.expression) } } } val stringExpression = EStringExpression( stringTemplateExpression.location, builder.toString() ) if (isStringExpression) { stringTemplateExpression.replace(stringExpression) } else { valueArguments.add(0, stringExpression) val callExpression = EKtCallExpression( stringTemplateExpression.location, stringTemplateExpression.type, Target.F_sformatf, null, valueArguments, arrayListOf() ) stringTemplateExpression.replace(callExpression) } } } }
0
Kotlin
0
3
70f9d58061350ca01db0e7c226de50d3b532229e
4,280
verik
Apache License 2.0
MomoPlantsUser/app/src/main/java/com/johndev/momoplants/ui/detailModule/view/DetailsFragment.kt
Johnmorales26
614,629,687
false
null
package com.johndev.momoplants.ui.detailModule.view import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.viewModels import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.airbnb.lottie.LottieAnimationView import com.bumptech.glide.Glide import com.johndev.momoplants.R import com.johndev.momoplants.common.entities.PlantEntity import com.johndev.momoplants.common.utils.Constants import com.johndev.momoplants.databinding.FragmentDetailsBinding import com.johndev.momoplants.ui.detailModule.viewModel.DetailViewModel import com.johndev.momoplants.ui.trackModule.view.TrackFragmentArgs import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class DetailsFragment : Fragment() { private var _binding: FragmentDetailsBinding? = null private val binding get() = _binding!! private lateinit var detailViewModel: DetailViewModel private var plantEntity: PlantEntity? = null private val args : DetailsFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDetailsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViewModels() setupObservers() setupButtons() receiveValues() var like = false //val corazon = findViewById<View>(R.id.likeImageView) binding.likeImageView.setOnClickListener { like = likeAnimation(binding.likeImageView as LottieAnimationView, R.raw.black_joy, like) } } private fun receiveValues() { args.idPlant?.let { detailViewModel.onSearchPlantRealtime(it) } } private fun likeAnimation(imageView: LottieAnimationView, animation: Int, like: Boolean) : Boolean { if (!like) { imageView.setAnimation(animation) imageView.playAnimation() } else { imageView.animate() .alpha(0f) .setDuration(200) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animator: Animator) { imageView.setImageResource(R.drawable.corazon) imageView.alpha = 1f } }) } return !like } private fun setupViewModels() { val vm: DetailViewModel by viewModels() detailViewModel = vm } private fun setupObservers() { detailViewModel.plantEntity.observe(viewLifecycleOwner) { plantEntity -> plantEntity?.let { this.plantEntity = it updateUI(this.plantEntity) } } } private fun setupButtons() { binding.ibReturn.setOnClickListener { findNavController().popBackStack() } binding.bottomOptions.fabAddCart.setOnClickListener { detailViewModel.onSave(plantEntity!!) } } private fun updateUI(plantEntity: PlantEntity?) { plantEntity?.let { with(binding) { tvPlantName.text = it.name.toString().trim() tvDescription.text = it.description.toString().trim() bottomOptions.tvPrice.text = it.price.toString().trim() if (plantEntity.quantity > 0) { cardStock.containerCard.setBackgroundColor(requireContext().getColor(R.color.md_theme_light_primaryContainer)) cardStock.tvStock.text = getString(R.string.msg_stock_with_stock) bottomOptions.fabAddCart.isEnabled = true } else { cardStock.containerCard.setBackgroundColor(requireContext().getColor(R.color.md_theme_light_error)) cardStock.tvStock.text = getString(R.string.msg_stock_without_stock) bottomOptions.fabAddCart.isEnabled = false } Glide .with(requireContext()) .load(plantEntity.imageUrl) .centerCrop() .circleCrop() .placeholder(R.drawable.ic_broken_image) .into(imgPlant) } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
3b887bfd6ad6b12abde152b5cafbabfe38d65183
4,832
Momo_Plants
W3C Software Notice and License (2002-12-31)
src/main/kotlin/com/gmail/williammingardi/hobbykeeping/exception/NotFoundException.kt
wilboron
453,335,562
false
null
package com.gmail.williammingardi.hobbykeeping.exception class NotFoundException( class_name: String, id: Long ) : RuntimeException() { override var message = "$class_name not found with id '$id'" }
0
Kotlin
0
1
0a68427bcc4d3bb5b2aad53a476164df0ea48abe
211
hobby-keeping
Apache License 2.0
data/repo/src/main/java/com/kafka/data/feature/recommendation/RecommendationRepository.kt
vipulyaara
612,950,214
false
{"Kotlin": 689879, "JavaScript": 447669, "HTML": 11959, "CSS": 7888, "Shell": 2974}
package com.kafka.data.feature.recommendation import com.kafka.data.feature.recommendation.network.RecommendationService import com.kafka.data.model.recommendation.RecommendationRequestBody import com.kafka.data.model.recommendation.RecommendationRequestBody.RecommendationEvent import com.kafka.data.model.recommendation.RecommendationRequestBody.RecommendationEvent.EndObject import com.kafka.data.model.recommendation.RecommendationRequestBody.RecommendationEvent.Relationship import com.kafka.data.model.recommendation.RecommendationRequestBody.RecommendationEvent.StartObject import com.kafka.data.resultApiCall import org.kafka.base.CoroutineDispatchers import org.threeten.bp.LocalDateTime import org.threeten.bp.format.DateTimeFormatter import java.util.Locale import javax.inject.Inject import javax.inject.Singleton @Singleton class RecommendationRepository @Inject constructor( private val recommendationService: RecommendationService, private val dispatchers: CoroutineDispatchers ) { suspend fun getRecommendedContent(userId: String) = resultApiCall(dispatchers.io) { val requestBody = ContentRecommendationRequestBody.fromUser(userId) recommendationService.getRecommendedContent(pipelessAppId, requestBody) } suspend fun getRelatedContent(contentId: String) = resultApiCall(dispatchers.io) { val requestBody = RelatedContentRequestBody.fromContent(contentId) recommendationService.getRelatedContent(pipelessAppId, requestBody) } suspend fun postEvent( recommendationObjectFrom: RecommendationObject, recommendationRelationship: RecommendationRelationship, recommendationObjectTo: RecommendationObject ) = resultApiCall(dispatchers.io) { val event = RecommendationEvent( StartObject( createdOn = currentDate(), id = recommendationObjectFrom.id, type = recommendationObjectFrom.key ), Relationship( createdOn = currentDate(), type = recommendationRelationship.name.lowercase() ), EndObject( createdOn = currentDate(), id = recommendationObjectTo.id, type = recommendationObjectTo.key ), ) recommendationService.postEvent( appId = pipelessAppId, body = RecommendationRequestBody(event) ) } private val pipelessAppId = 1763 private fun currentDate(): String { val outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH) val date: LocalDateTime = LocalDateTime.now() return outputFormatter.format(date).orEmpty() } }
5
Kotlin
18
247
f660cb0a45102cdc7af119e418252dee6274bdc6
2,749
Kafka
Apache License 2.0
shared/src/wasmJsMain/kotlin/com/kgurgul/cpuinfo/data/provider/OsDataProvider.wasm.kt
kamgurgul
105,620,694
false
{"Kotlin": 468649, "C": 167973, "Swift": 5197, "C++": 4834, "JavaScript": 834, "CMake": 622, "HTML": 472, "CSS": 102, "Objective-C": 82}
package com.kgurgul.cpuinfo.data.provider import com.kgurgul.cpuinfo.utils.toList import kotlinx.browser.window import org.koin.core.component.KoinComponent actual class OsDataProvider actual constructor() : IOsDataProvider, KoinComponent { actual override suspend fun getData(): List<Pair<String, String>> { return buildList { if (window.navigator.platform.isNotEmpty()) { add("Platform" to window.navigator.platform) } if (window.navigator.appCodeName.isNotEmpty()) { add("App code name" to window.navigator.appCodeName) } if (window.navigator.appName.isNotEmpty()) { add("App name" to window.navigator.appName) } if (window.navigator.appVersion.isNotEmpty()) { add("App version" to window.navigator.appVersion) } if (window.navigator.product.isNotEmpty()) { add("Product" to window.navigator.product) } if (window.navigator.productSub.isNotEmpty()) { add("Product sub" to window.navigator.productSub) } if (window.navigator.userAgent.isNotEmpty()) { add("User agent" to window.navigator.userAgent) } if (window.navigator.vendor.isNotEmpty()) { add("Vendor" to window.navigator.vendor) } if (window.navigator.vendorSub.isNotEmpty()) { add("Vendor sub" to window.navigator.vendorSub) } if (window.navigator.language.isNotEmpty()) { add("Language" to window.navigator.language) } val languages = window.navigator.languages.toList() if (languages.isNotEmpty()) { add("Languages" to languages.joinToString()) } } } }
30
Kotlin
103
658
ea3ec63943992cc457faeeaf52d0a451fad49f5a
1,894
cpu-info
Apache License 2.0
src/jvmTest/kotlin/io/smallibs/aktor/MassiveThreadedActorTest.kt
Smallibs
159,055,361
false
null
package io.smallibs.aktor import io.smallibs.aktor.Aktor.Companion.new import io.smallibs.utils.Await import kotlinx.atomicfu.atomic import org.awaitility.Duration.FIVE_SECONDS import org.junit.Test import java.text.DecimalFormat import java.time.Duration private const val actors = 1000 private const val messages = 1000 class MassiveThreadedActorTest { private val format = DecimalFormat.getIntegerInstance() private fun Int.format() = format.format(this) private inline fun <T> stopWatch(label: () -> String, block: () -> T): T { val start = System.nanoTime() val result = block() val duration = Duration.ofNanos(System.nanoTime() - start) println("${label()} done in ${duration.toMillis()} ms") return result } @Test fun shouldDoOneMillionTellsUsingThreads() { val system = new("test", execution = ActorRunner.threaded()) val called = atomic(0) val references = (0 until actors).map { system.actorFor<Boolean> { a, _ -> called.incrementAndGet(); a.same() } } stopWatch({ "Execution of ${called.value.format()} messages using Threads" }) { stopWatch({ "Submission" }) { repeat(messages) { references.forEach { a -> a tell true } } } Await() atMost FIVE_SECONDS.valueInMS until { called.value == messages * actors } } } }
2
Kotlin
1
7
e8276ac9dcc8cf14ef253e7c32a74bf9f7af6a2b
1,478
aktor
Apache License 2.0
app/src/main/java/com/sachin/app/storyapp/data/repository/CommunityRepository.kt
sachinkumar53
684,631,959
false
{"Kotlin": 138151}
package com.sachin.app.storyapp.data.repository import android.icu.text.RelativeDateTimeFormatter import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.Query import com.sachin.app.storyapp.data.di.PublicationCollectionRef import com.sachin.app.storyapp.data.di.UserCollectionRef import com.sachin.app.storyapp.data.model.Story import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.tasks.await import javax.inject.Inject import kotlin.time.Duration import kotlin.time.DurationUnit import kotlin.time.toDuration class CommunityRepository @Inject constructor( @PublicationCollectionRef private val publications: CollectionReference, @UserCollectionRef private val users: CollectionReference, private val reviewRepository: ReviewRepository ) { suspend fun getRecentPublications(): List<Story> { return publications.orderBy( "published_on", Query.Direction.DESCENDING ).get().await().documents .map { snapshot -> val authorName = users.document(snapshot["author_id"].toString()).get() .await() .data ?.get("name") .toString() val millisDiff = System.currentTimeMillis() .toDuration(DurationUnit.MILLISECONDS) - (snapshot.get("published_on") as? Long ?: 0L).toDuration(DurationUnit.MILLISECONDS) getRelativeTimeSpanString(millisDiff) Story( coverUrl = snapshot.get("cover_url").toString(), title = snapshot.get("title").toString(), description = snapshot.get("description").toString(), content = snapshot.get("content").toString(), publishedDate = getRelativeTimeSpanString(millisDiff).toString() /*DateUtils.getRelativeTimeSpanString( snapshot.get("published_on") as? Long ?: 0L, System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS ).toString()*/, authorName = authorName, id = snapshot.id, rating = reviewRepository.getTotalRating(snapshot.id).firstOrNull()?.totalRating ?: 0f, genre = snapshot["genre"].toString() ) } } private fun getRelativeTimeSpanString(millisDiff: Duration): String? { val formatter = RelativeDateTimeFormatter.getInstance() return when { millisDiff.inWholeSeconds == 0L -> { "moments ago" } millisDiff.inWholeMinutes == 0L -> { formatter.format( millisDiff.inWholeSeconds.toDouble(), RelativeDateTimeFormatter.Direction.LAST, RelativeDateTimeFormatter.RelativeUnit.SECONDS ) } millisDiff.inWholeHours == 0L -> { formatter.format( millisDiff.inWholeMinutes.toDouble(), RelativeDateTimeFormatter.Direction.LAST, RelativeDateTimeFormatter.RelativeUnit.MINUTES ) } millisDiff.inWholeDays == 0L -> { formatter.format( millisDiff.inWholeHours.toDouble(), RelativeDateTimeFormatter.Direction.LAST, RelativeDateTimeFormatter.RelativeUnit.HOURS ) } else -> { val days = millisDiff.inWholeDays val months = (days / 30.417).toInt() formatter.format( days.toDouble(), RelativeDateTimeFormatter.Direction.LAST, RelativeDateTimeFormatter.RelativeUnit.DAYS ) val t = if (months == 0) { formatter.format( millisDiff.inWholeDays.toDouble(), RelativeDateTimeFormatter.Direction.LAST, RelativeDateTimeFormatter.RelativeUnit.DAYS ) } else if (months < 12) { formatter.format( months.toDouble(), RelativeDateTimeFormatter.Direction.LAST, RelativeDateTimeFormatter.RelativeUnit.MONTHS ) } else { formatter.format( (months.toDouble() / 12).toInt().toDouble(), RelativeDateTimeFormatter.Direction.LAST, RelativeDateTimeFormatter.RelativeUnit.MONTHS ) } t } } } }
0
Kotlin
0
0
2e5edc23ec66e27ae1054b8236bcbc728bcbaeee
4,923
StoryApp
MIT License
src/main/kotlin/br/com/zup/edu/chaves/TipoContaEntity.kt
ArtMedeiros
408,417,459
true
{"Kotlin": 105504}
package br.com.zup.edu.chaves import br.com.zup.edu.utils.services.bcb.TipoContaBCB enum class TipoContaEntity { CONTA_CORRENTE { override fun converterBcb(): TipoContaBCB { return TipoContaBCB.CACC } }, CONTA_POUPANCA { override fun converterBcb(): TipoContaBCB { return TipoContaBCB.SVGS } }; abstract fun converterBcb(): TipoContaBCB }
0
Kotlin
0
0
7abfed286ae95d3a02f6a1ca669aec34c9f6d463
417
orange-talents-07-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/com/tripletres/platformscience/data/db/driver/DriverDao.kt
daniel553
540,959,283
false
null
package com.tripletres.platformscience.data.db.driver import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface DriverDao { @Query("SELECT * FROM driver_table") suspend fun getAll(): List<DriverEntity> @Query("SELECT * FROM driver_table WHERE driver_id = :id") suspend fun getById(id: Long): DriverEntity @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(driverEntity: DriverEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(driverEntity: List<DriverEntity>) @Query("DELETE FROM driver_table") suspend fun deleteAll() }
0
Kotlin
0
0
2ea5962dc0ad349ae97b277ab4ecf9e9a0aee1e6
689
PlatformScience
FSF All Permissive License
src/main/java/net/lab0/treasure/structure/Step.kt
ununhexium
136,074,171
false
{"Kotlin": 8568}
package net.lab0.treasure.structure data class Step( val actionKey: String, val title: String, val goto: String )
0
Kotlin
0
0
abd53230930a4ff9ace11a3432e46d0998a76225
127
treasureisland
The Unlicense
src/main/kotlin/backloggd/models/api/request/AppGameRateRequest.kt
videogreg93
605,215,068
false
null
package backloggd.models.api.request import kotlinx.serialization.Serializable @Serializable data class AppGameRateRequest(val gameId: String, val rating: Int)
0
Kotlin
0
0
db5dcfaee48abb4f968ec09a5b5da95cd7e24f04
162
backloggd-api
MIT License
android/app/src/main/kotlin/com/mwalagho/ferdinand/covid_19/MainActivity.kt
ferdinandmwal123
307,099,886
false
{"Dart": 18360, "Swift": 404, "Kotlin": 136, "Objective-C": 38}
package com.mwalagho.ferdinand.covid_19 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
6f9db97314f5251777b73b6d83754242fa50ea89
136
covid_19_flutter
MIT License
app/src/main/java/ru/vdv/filmexpert/model/api/IApiTmdbService.kt
stdimensiy
457,918,889
false
{"Kotlin": 54623}
package ru.vdv.filmexpert.model.api import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query import ru.vdv.filmexpert.domain.CreditsResponseTmdb import ru.vdv.filmexpert.domain.MovieDetailTmdb import ru.vdv.filmexpert.domain.MoviesResponseTmdb interface IApiTmdbService { /** * Раздел API: Movies * Режим standards lists (согласно документации есть только 4 стандартных листа now_playing, popular, top_rated и upcoming * @param apiVersion версия API с которой приято решение работать * @param key базовый ключ пользователя API key * @param page номер запрашиваемой страницы ( >=1 ) * @param region регион поиска (пока отключен) код ISO 3166-1 * @param language установка базового языка ответа * @param standardList указатель стандартной выборки результатов (адрес относительно /movie/) * @param includeAdult флаг включения в выборку фиильмов для взрослых * @return возвращает список фиьмов с самым высоким рейтонгом по версии TMDB. */ @GET("{api_version}/movie/{standard_list}") fun sectionMoviesGetStandardsLists( @Path("api_version") apiVersion: Int, @Path("standard_list") standardList: String, @Query("api_key") key: String, @Query("page") page: Int, @Query("language") language: String, @Query("include_adult") includeAdult: Boolean //@Query("region") region: String ): Call<MoviesResponseTmdb> /** * Раздел API: Movies Получить список участников (актеров и съемочной группы) * Режим полечения дополнительной информации * @param apiVersion версия API с которой приято решение работать * @param key базовый ключ пользователя API key * @param language установка базового языка ответа * @return возвращает список актеров и участников съемочного процесса отсортированный * согласно рейтингу по версии TMDB. */ @GET("{api_version}/movie/{movie_id}/casts") fun sectionMoviesGetCredits( @Path("api_version") apiVersion: Int, @Path("movie_id") movieId: String, @Query("api_key") key: String, @Query("language") language: String, ): Call<CreditsResponseTmdb> /** * Раздел API - Movies Получить детализированную информацию о фильме * Режим полечения дополнительной информации * @param apiVersion версия API с которой приято решение работать * @param key базовый ключ пользователя API key * @param language установка базового языка ответа * @return возвращает расширенный набор полей для объекта фильма по версии TMDB. */ @GET("{api_version}/movie/{movie_id}") fun sectionMoviesGetDetailInfo( @Path("api_version") apiVersion: Int, @Path("movie_id") movieId: String, @Query("api_key") key: String, @Query("language") language: String, ): Call<MovieDetailTmdb> }
7
Kotlin
1
2
331c26bcdd9a73ad0028e213505181fb1cfacda1
2,904
Film_Expert
MIT License
app/src/main/java/com/thinkalvb/sensorstorm/Location.kt
ThinkalVB
369,485,915
false
null
package com.thinkalvb.sensorstorm import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.location.LocationManager import android.os.Looper import com.google.android.gms.location.* import java.nio.ByteBuffer import java.nio.ByteOrder private const val GPS_SENSOR_CODE = 120 class Location(activity: Activity) { var isAvailable = false var isRunning = false private lateinit var mFusedLocationProviderClient: FusedLocationProviderClient private lateinit var mLocationRequest: LocationRequest private lateinit var mLocationCallback: LocationCallback private var mBroadcastBuffer = ByteBuffer.allocate((Double.SIZE_BYTES * 3) + Int.SIZE_BYTES).order(ByteOrder.LITTLE_ENDIAN) init { if(activity.packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) { isAvailable = true mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity) mLocationRequest = LocationRequest.create().apply { interval = 2000 fastestInterval = 1000 priority = LocationRequest.PRIORITY_HIGH_ACCURACY } mLocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { super.onLocationResult(locationResult) mBroadcastBuffer.clear() mBroadcastBuffer.putInt(GPS_SENSOR_CODE) mBroadcastBuffer.putDouble(locationResult.lastLocation.latitude) mBroadcastBuffer.putDouble(locationResult.lastLocation.longitude) mBroadcastBuffer.putDouble(locationResult.lastLocation.altitude) Broadcaster.sendData(mBroadcastBuffer.array()) } } } } fun startService() { if(!isAvailable) return isRunning = try { mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper()) true }catch (e: SecurityException) { false } } fun stopService() { if(isRunning){ mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback) isRunning = false } } fun isEnabled(activity: Activity): Boolean { val locationManager = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) } }
0
Kotlin
0
1
7c7d0932d225b028fc5e5305a49d798b04b6ed2d
2,603
SensorStorm
MIT License
src/main/kotlin/com/github/vlsi/gradle/license/PomLicenseLoader.kt
pombredanne
191,727,436
true
{"Kotlin": 55726}
/* * Copyright 2019 <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.github.vlsi.gradle.license import groovy.util.XmlSlurper import groovy.util.slurpersupport.GPathResult import kotlinx.coroutines.runBlocking import org.gradle.api.Project import org.gradle.api.artifacts.component.ComponentIdentifier import org.gradle.api.artifacts.result.ResolvedArtifactResult import org.gradle.api.internal.artifacts.DefaultModuleIdentifier import org.gradle.internal.component.external.model.DefaultModuleComponentIdentifier import org.gradle.kotlin.dsl.getArtifacts import org.gradle.kotlin.dsl.withArtifacts import org.gradle.maven.MavenModule import org.gradle.maven.MavenPomArtifact import java.io.File data class LicenseTag(val name: String, val url: String) data class PomContents( val parentId: ComponentIdentifier?, val id: ComponentIdentifier, val licenses: List<LicenseTag> ) typealias PomParser = suspend (ComponentIdentifier) -> PomContents class LicenseDetector( private val parser: PomParser ) { suspend fun detect(id: ComponentIdentifier): LicenseTag? { val pom = parser(id) val licenses = pom.licenses if (licenses.isNotEmpty()) { if (licenses.size > 1) { throw IllegalStateException("Multiple licenses declared for $id. Please clarify which should be used") } return licenses.first() } val parentId = pom.parentId ?: return null return detect(parentId) } } operator fun GPathResult.get(name: String) = getProperty(name) as GPathResult fun GPathResult.getList(name: String) = getProperty(name) as Iterable<GPathResult> private fun File.parseXml(): GPathResult = XmlSlurper().parse(this) fun GPathResult.parsePom(): PomContents { fun GPathResult.parseId(parentGroup: String = "") = DefaultModuleComponentIdentifier.newId( DefaultModuleIdentifier.newId( this["groupId"].text().ifEmpty { parentGroup }, this["artifactId"].text() ), this["version"].text() ) val licenses = this["licenses"].getList("license") .map { LicenseTag(it["name"].text(), it["url"].text()) } val parentTag = getList("parent").firstOrNull()?.parseId() return PomContents(parentTag, this.parseId(parentTag?.group ?: ""), licenses) } fun loadLicenses(ids: List<ComponentIdentifier>, project: Project) = runBlocking { batch<ComponentIdentifier, File, LicenseTag?> { handleBatch { requests -> val artifactResolutionResult = project.dependencies.createArtifactResolutionQuery() .forComponents(requests.map { it.first }) .withArtifacts(MavenModule::class, MavenPomArtifact::class) .execute() val results = artifactResolutionResult.resolvedComponents .associate { it.id to it.getArtifacts(MavenPomArtifact::class) } for (req in requests) { val result = results[req.first]?.firstOrNull() if (result == null) { req.second.completeExceptionally(IllegalStateException("${req.first} was not downloaded")) continue } req.second.complete((result as ResolvedArtifactResult).file) } } for (id in ids) { task { loader -> LicenseDetector { id -> loader(id).parseXml().parsePom() }.detect(id) } } } }
0
Kotlin
0
0
3372bcb707354101ea002dbe9aaa1526f67a7346
4,152
license-gather-plugin
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Walker.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.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.rounded.Icons public val Icons.Bold.Walker: ImageVector get() { if (_walker != null) { return _walker!! } _walker = Builder(name = "Walker", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(22.0f, 17.337f) verticalLineTo(5.5f) curveToRelative(0.0f, -3.032f, -2.468f, -5.5f, -5.5f, -5.5f) horizontalLineToRelative(-4.681f) curveToRelative(-2.319f, 0.0f, -4.4f, 1.467f, -5.181f, 3.649f) lineTo(0.087f, 21.995f) curveToRelative(-0.278f, 0.78f, 0.129f, 1.639f, 0.908f, 1.918f) curveToRelative(0.167f, 0.06f, 0.337f, 0.087f, 0.505f, 0.087f) curveToRelative(0.616f, 0.0f, 1.193f, -0.382f, 1.413f, -0.995f) lineToRelative(3.93f, -11.005f) horizontalLineToRelative(12.157f) verticalLineToRelative(5.337f) curveToRelative(-1.182f, 0.562f, -2.0f, 1.767f, -2.0f, 3.163f) curveToRelative(0.0f, 1.933f, 1.567f, 3.5f, 3.5f, 3.5f) reflectiveCurveToRelative(3.5f, -1.567f, 3.5f, -3.5f) curveToRelative(0.0f, -1.396f, -0.818f, -2.601f, -2.0f, -3.163f) close() moveTo(7.914f, 9.0f) lineToRelative(1.55f, -4.342f) curveToRelative(0.354f, -0.991f, 1.3f, -1.658f, 2.354f, -1.658f) horizontalLineToRelative(4.681f) curveToRelative(1.379f, 0.0f, 2.5f, 1.121f, 2.5f, 2.5f) verticalLineToRelative(3.5f) horizontalLineTo(7.914f) close() } } .build() return _walker!! } private var _walker: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,626
icons
MIT License
src/test/kotlin/com/github/monosoul/git/updateindex/extended/ExtendedUpdateIndexTaskTest.kt
monosoul
151,694,127
false
{"Kotlin": 53449}
package com.github.monosoul.git.updateindex.extended import com.github.monosoul.git.updateindex.extended.ExtendedUpdateIndexTaskTest.FilesAndCommandArgumentsSource.NoVcsRoot import com.github.monosoul.git.updateindex.extended.ExtendedUpdateIndexTaskTest.FilesAndCommandArgumentsSource.WithVcsRoot import com.intellij.mock.MockApplication import com.intellij.mock.MockProject import com.intellij.openapi.application.ApplicationManager.setApplication import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.Disposer.dispose import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vfs.VirtualFile import git4idea.commands.Git import git4idea.commands.GitCommandResult import git4idea.commands.GitLineHandler import io.mockk.Called import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.junit5.MockKExtension import io.mockk.mockk import io.mockk.verify import io.mockk.verifyAll import io.mockk.verifyOrder import org.apache.commons.lang3.RandomStringUtils import org.apache.commons.lang3.RandomUtils.nextInt import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ArgumentsSource import strikt.api.expectThat import strikt.assertions.containsExactlyInAnyOrder @ExtendWith(MockKExtension::class) internal class ExtendedUpdateIndexTaskTest { private lateinit var parent: TestDisposable private lateinit var application: MockApplication private lateinit var project: MockProject @MockK private lateinit var git: Git @MockK private lateinit var vcsManager: ProjectLevelVcsManager @MockK(relaxUnitFun = true) private lateinit var dirtyScopeManager: VcsDirtyScopeManager @MockK private lateinit var updateIndexLineHandlerFactory: UpdateIndexLineHandlerFactory @MockK private lateinit var gitLineHandler: GitLineHandler @MockK private lateinit var gitCommandResult: GitCommandResult @BeforeEach fun setUp() { parent = TestDisposable() application = MockApplication(parent) setApplication(application, parent) application.registerService(git, parent) project = MockProject(null, parent) project.registerService(vcsManager, parent) project.registerService(dirtyScopeManager, parent) project.registerService(updateIndexLineHandlerFactory, parent) every { updateIndexLineHandlerFactory.invoke(any(), any(), any()) } returns gitLineHandler every { git.runCommand(any<GitLineHandler>()) } returns gitCommandResult } @AfterEach fun tearDown() { dispose(parent) } @ParameterizedTest @ArgumentsSource(NoVcsRoot::class) fun `should do nothing if a file has no VCS root`( files: List<VirtualFile>, command: ExtendedUpdateIndexCommand, @MockK indicator: ProgressIndicator ) { every { vcsManager.getVcsRootFor(any<VirtualFile>()) } returns null ExtendedUpdateIndexTask(project, files, command).run(indicator) verifyOrder { vcsManager.getVcsRootFor(files[0]) } verifyAll { git wasNot Called updateIndexLineHandlerFactory wasNot Called gitLineHandler wasNot Called dirtyScopeManager wasNot Called } } @ParameterizedTest @ArgumentsSource(WithVcsRoot::class) internal fun `should execute a command and log nothing if it was successful`( files: List<VirtualFile>, command: ExtendedUpdateIndexCommand, @MockK indicator: ProgressIndicator ) { val root = mockk<VirtualFile>() every { vcsManager.getVcsRootFor(any<VirtualFile>()) } returns root every { gitCommandResult.success() } returns true ExtendedUpdateIndexTask(project, files, command).run(indicator) verify(exactly = files.size) { vcsManager.getVcsRootFor(any<VirtualFile>()) } verifyOrder { updateIndexLineHandlerFactory.invoke(command, root, withArg { expectThat(it) containsExactlyInAnyOrder files }) git.runCommand(gitLineHandler) gitCommandResult.success() } verify(exactly = files.size) { dirtyScopeManager.fileDirty(any<VirtualFile>()) } } @ParameterizedTest @ArgumentsSource(WithVcsRoot::class) internal fun `should execute a command and log errors if it was unsuccessful`( files: List<VirtualFile>, command: ExtendedUpdateIndexCommand, @MockK indicator: ProgressIndicator ) { val root = mockk<VirtualFile>() every { vcsManager.getVcsRootFor(any<VirtualFile>()) } returns root every { gitCommandResult.success() } returns false val error = RandomStringUtils.randomAlphabetic(LIMIT) every { gitCommandResult.errorOutput } returns listOf(error) ExtendedUpdateIndexTask(project, files, command).run(indicator) verify(exactly = files.size) { vcsManager.getVcsRootFor(any<VirtualFile>()) } verifyOrder { updateIndexLineHandlerFactory.invoke(command, root, withArg { expectThat(it) containsExactlyInAnyOrder files }) git.runCommand(gitLineHandler) gitCommandResult.success() gitCommandResult.errorOutput } verify(exactly = files.size) { dirtyScopeManager.fileDirty(any<VirtualFile>()) } } private sealed class FilesAndCommandArgumentsSource( vararg generators: () -> Any? ) : AbstractMultiArgumentsSource(*generators) { class NoVcsRoot : FilesAndCommandArgumentsSource( { listOf(mockk<VirtualFile>()) }, { randomEnum<ExtendedUpdateIndexCommand>() } ) class WithVcsRoot : FilesAndCommandArgumentsSource( { virtualFileList() }, { randomEnum<ExtendedUpdateIndexCommand>() } ) companion object { private fun virtualFileList() = generateSequence { mockk<VirtualFile>() } .take(nextInt(1, LIMIT)) .toList() } } }
3
Kotlin
2
5
3dbb3154f620d17d661e76c4c0d16df9095a277b
6,408
git-extended-update-index-plugin
Apache License 2.0
modules/tests/src/main/kotlin/com/github/davenury/tests/strategies/peersets/GetPeersStrategy.kt
kjarosh
782,141,241
false
{"Kotlin": 745167, "Java": 206433, "Go": 61106, "Python": 33653, "Shell": 21551, "JavaScript": 3419, "Dockerfile": 1387, "Ruby": 835}
package com.github.davenury.tests.strategies.peersets import com.github.davenury.common.Notification import com.github.davenury.common.PeersetId interface GetPeersStrategy { suspend fun getPeersets( numberOfPeersets: Int, changeId: String, ): List<PeersetId> suspend fun freePeersets( peersetsId: List<PeersetId>, changeId: String, ) suspend fun handleNotification(notification: Notification) }
14
Kotlin
0
0
576a3128afe3b015a36480a4ea04886133d40d83
451
depl-da-prototype
Apache License 2.0
buildSrc/src/main/java/com/likethesalad/placeholder/models/VariantResPaths.kt
mannodermaus
259,418,461
true
{"Kotlin": 180595}
package com.likethesalad.placeholder.models import java.io.File data class VariantResPaths( val variantName: String, val paths: Set<File> )
0
null
0
0
5c85545ba6117ca1a3d1baea1d6c29b03d54aa75
149
android-string-reference
MIT License
app/src/main/java/de/jepfa/yapm/usecase/vault/CreateVaultUseCase.kt
jenspfahl
378,141,282
false
{"Kotlin": 891218, "HTML": 36434}
package de.jepfa.yapm.usecase.vault import android.util.Log import de.jepfa.yapm.model.encrypted.CipherAlgorithm import de.jepfa.yapm.model.session.LoginData import de.jepfa.yapm.service.PreferenceService import de.jepfa.yapm.service.secret.MasterKeyService import de.jepfa.yapm.service.secret.PbkdfIterationService import de.jepfa.yapm.service.secret.SaltService import de.jepfa.yapm.ui.BaseActivity import de.jepfa.yapm.usecase.InputUseCase import de.jepfa.yapm.usecase.session.LoginUseCase import de.jepfa.yapm.util.Constants object CreateVaultUseCase: InputUseCase<CreateVaultUseCase.Input, BaseActivity>() { data class Input(val loginData: LoginData, val pbkdfIterations: Int, val cipherAlgorithm: CipherAlgorithm) override suspend fun doExecute(input: Input, activity: BaseActivity): Boolean { PbkdfIterationService.storePbkdfIterations(input.pbkdfIterations) // before mk encryption! Log.d("ITERATIONS", "store iterations=${input.pbkdfIterations}") val salt = SaltService.getSalt(activity) val masterKey = MasterKeyService.generateMasterKey(activity) MasterKeyService.encryptAndStoreMasterKey( masterKey, input.loginData.pin, input.loginData.masterPassword, salt, input.pbkdfIterations, input.cipherAlgorithm, activity ) masterKey.clear() PreferenceService.putCurrentDate(PreferenceService.DATA_VAULT_CREATED_AT, activity) PreferenceService.putString( PreferenceService.DATA_VAULT_VERSION, Constants.CURRENT_VERSION.toString(), activity ) PreferenceService.putString( PreferenceService.DATA_CIPHER_ALGORITHM, input.cipherAlgorithm.name, activity ) return LoginUseCase.execute(input.loginData, activity).success } }
6
Kotlin
4
53
3c9078e1ad086cc94a4b4a6c4db7adf3a7f2da88
1,945
ANOTHERpass
MIT License
solar/src/main/java/com/chiksmedina/solar/lineduotone/astronomy/StarFall2.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.lineduotone.astronomy import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.lineduotone.AstronomyGroup val AstronomyGroup.StarFall2: ImageVector get() { if (_starFall2 != null) { return _starFall2!! } _starFall2 = Builder( name = "StarFall2", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(11.5803f, 4.776f) curveTo(12.275f, 3.0052f, 12.6224f, 2.1197f, 13.3488f, 2.0106f) curveTo(14.0753f, 1.9014f, 14.6997f, 2.6408f, 15.9486f, 4.1197f) lineTo(16.2716f, 4.5023f) curveTo(16.6265f, 4.9225f, 16.804f, 5.1326f, 17.0452f, 5.2526f) curveTo(17.2865f, 5.3726f, 17.5643f, 5.3888f, 18.1198f, 5.4214f) lineTo(18.6256f, 5.451f) curveTo(20.5806f, 5.5654f, 21.5581f, 5.6226f, 21.8973f, 6.2617f) curveTo(22.2365f, 6.9008f, 21.7128f, 7.6985f, 20.6654f, 9.294f) lineTo(20.3944f, 9.7068f) curveTo(20.0967f, 10.1602f, 19.9479f, 10.3869f, 19.9077f, 10.6457f) curveTo(19.8675f, 10.9045f, 19.9405f, 11.1662f, 20.0864f, 11.6895f) lineTo(20.2193f, 12.166f) curveTo(20.7328f, 14.0076f, 20.9895f, 14.9284f, 20.4727f, 15.4325f) curveTo(19.9559f, 15.9367f, 19.0078f, 15.6903f, 17.1116f, 15.1975f) lineTo(16.621f, 15.07f) curveTo(16.0822f, 14.93f, 15.8128f, 14.86f, 15.5467f, 14.8999f) curveTo(15.2805f, 14.9399f, 15.0479f, 15.0854f, 14.5825f, 15.3763f) lineTo(14.1588f, 15.6412f) curveTo(12.5212f, 16.6649f, 11.7024f, 17.1768f, 11.0438f, 16.8493f) curveTo(10.3852f, 16.5217f, 10.3229f, 15.5717f, 10.1984f, 13.6717f) lineTo(10.1662f, 13.1801f) curveTo(10.1309f, 12.6402f, 10.1132f, 12.3702f, 9.9889f, 12.1361f) curveTo(9.8646f, 11.902f, 9.6479f, 11.7302f, 9.2143f, 11.3867f) lineTo(8.8196f, 11.0739f) curveTo(7.294f, 9.8651f, 6.5312f, 9.2606f, 6.641f, 8.5541f) curveTo(6.7508f, 7.8475f, 7.6604f, 7.5067f, 9.4796f, 6.8252f) lineTo(9.9503f, 6.6489f) curveTo(10.4673f, 6.4552f, 10.7258f, 6.3584f, 10.9151f, 6.1737f) curveTo(11.1044f, 5.989f, 11.2031f, 5.7374f, 11.4005f, 5.2342f) lineTo(11.5803f, 4.776f) close() } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(6.5953f, 8.5508f) curveTo(3.4819f, 10.6857f, 1.0983f, 14.7691f, 2.3312f, 21.9998f) curveTo(3.4227f, 18.9857f, 6.7126f, 16.5716f, 10.3877f, 15.4097f) } } .build() return _starFall2!! } private var _starFall2: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
4,040
SolarIconSetAndroid
MIT License
androidApp/src/commonMain/kotlin/com/example/rocketnews/presentation/ui/screens/rockets/RocketsScreen.kt
KarelHudera
701,516,774
false
{"Kotlin": 172850, "Swift": 578}
package com.example.rocketnews.presentation.ui.screens.rockets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.core.screen.ScreenKey import cafe.adriel.voyager.core.screen.uniqueScreenKey import cafe.adriel.voyager.koin.getScreenModel import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import com.example.rocketnews.presentation.ui.common.topBars.RocketsActionAppBar import com.example.rocketnews.presentation.ui.common.RocketsList import com.example.rocketnews.presentation.ui.common.state.ManagementResourceUiState import com.example.rocketnews.presentation.ui.screens.rocketDetail.RocketDetailScreen import com.example.rocketnews.presentation.ui.screens.rocketsFavourite.RocketsFavoritesScreen import com.example.rocketnews.presentation.ui.screens.rocketsSearch.RocketsSearchScreen import kotlinx.coroutines.flow.collectLatest class RocketsScreen : Screen { override val key: ScreenKey = uniqueScreenKey @Composable override fun Content() { val rocketsViewModel = getScreenModel<RocketsViewModel>() val state by rocketsViewModel.uiState.collectAsState() val navigator = LocalNavigator.currentOrThrow LaunchedEffect(key1 = Unit) { rocketsViewModel.effect.collectLatest { effect -> when (effect) { is RocketsContract.Effect.NavigateToDetailRocket -> navigator.push(RocketDetailScreen(effect.idRocket)) is RocketsContract.Effect.NavigateToFavorites -> navigator.push(RocketsFavoritesScreen()) is RocketsContract.Effect.NavigateToSearch -> navigator.push(RocketsSearchScreen()) } } } Scaffold( topBar = { RocketsActionAppBar( title = "SpaceX Rockets", onClickFavorite = { rocketsViewModel.setEvent(RocketsContract.Event.OnFavoritesClick) }, onClickSearch = { rocketsViewModel.setEvent(RocketsContract.Event.OnSearchClick) }, isShadowEnabled = true ) }, ) { padding -> ManagementResourceUiState( modifier = Modifier .padding(padding) .fillMaxSize(), resourceUiState = state.rockets, successView = { rockets -> RocketsList( rockets = rockets, onRocketClick = { idRocket -> rocketsViewModel.setEvent( RocketsContract.Event.OnRocketClick( idRocket ) ) } ) }, onTryAgain = { rocketsViewModel.setEvent(RocketsContract.Event.OnTryCheckAgainClick) }, onCheckAgain = { rocketsViewModel.setEvent(RocketsContract.Event.OnTryCheckAgainClick) }, ) } } }
0
Kotlin
0
2
87578a2f429d2113b83388955d66ae53ff2469ae
3,519
Rocket_News_KMM
Apache License 2.0
app/src/main/java/android/hardik/attendancemanager/activities/timetable/viewmodels/PeriodDetailViewModelFactory.kt
hardik0899
258,773,751
false
null
package android.hardik.attendancemanager.activities.timetable.viewmodels import android.app.Application import android.hardik.attendancemanager.data.source.repositories.PeriodRepository import androidx.lifecycle.ViewModelProvider class PeriodDetailViewModelFactory( val periodId: Long, val periodRepository: PeriodRepository, val application: Application ) : ViewModelProvider.NewInstanceFactory() { // @Suppress("UNCHECKED_CAST") // override fun <T : ViewModel?> create(modelClass: Class<T>): T { // return PeriodDetailViewModel(PeriodRepository(application), periodId) as T // } init { val period = periodRepository.getPeriod(periodId) } }
10
Kotlin
0
2
bcfd03b94475e195135b959891ff55ec4a0e4cff
700
AttendanceManager
MIT License
core/src/com/lyeeedar/Util/AssetManager.kt
Lyeeedar
160,553,983
false
null
package com.lyeeedar.Util import com.badlogic.gdx.Gdx import com.badlogic.gdx.audio.Sound import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.Texture.TextureFilter import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter import com.badlogic.gdx.utils.Array import com.badlogic.gdx.utils.ObjectMap import com.lyeeedar.Renderables.Animation.AbstractAnimation import com.lyeeedar.Renderables.Light import com.lyeeedar.Renderables.LightAnimation import com.lyeeedar.Renderables.Particle.ParticleEffect import com.lyeeedar.Renderables.Renderable import com.lyeeedar.Renderables.Sprite.DirectionalSprite import com.lyeeedar.Renderables.Sprite.Sprite import com.lyeeedar.Renderables.Sprite.TilingSprite import java.util.* class AssetManager { companion object { private val loadedFonts = HashMap<String, BitmapFont>() @JvmOverloads fun loadFont(name: String, size: Int, colour: Color = Color.WHITE, borderWidth: Int = 1, borderColour: Color = Color.BLACK, shadow: Boolean = false): BitmapFont? { val key = name + size + colour.toString() + borderWidth + borderColour.toString() if (loadedFonts.containsKey(key)) { return loadedFonts[key] } val fgenerator = FreeTypeFontGenerator(Gdx.files.internal(name)) val parameter = FreeTypeFontParameter() parameter.size = size parameter.borderWidth = borderWidth.toFloat() parameter.kerning = true parameter.borderColor = borderColour parameter.borderStraight = true parameter.color = colour if (shadow) { parameter.shadowOffsetX = -1 parameter.shadowOffsetY = 1 } val font = fgenerator.generateFont(parameter) font.data.markupEnabled = true fgenerator.dispose() // don't forget to dispose to avoid memory leaks! loadedFonts.put(key, font) return font } private val loadedSounds = HashMap<String, Sound?>() fun loadSound(path: String): Sound? { if (loadedSounds.containsKey(path)) { return loadedSounds[path] } var file = Gdx.files.internal("Sounds/$path.mp3") if (!file.exists()) { file = Gdx.files.internal("Sounds/$path.ogg") if (!file.exists()) { loadedSounds.put(path, null) return null } } val sound = Gdx.audio.newSound(file) loadedSounds.put(path, sound) return sound } private val prepackedAtlas = TextureAtlas(Gdx.files.internal("CompressedData/SpriteAtlas.atlas")) private val loadedTextureRegions = HashMap<String, TextureRegion?>() @JvmStatic fun loadTextureRegion(path: String): TextureRegion? { if (loadedTextureRegions.containsKey(path)) { return loadedTextureRegions[path] } var atlasName = path if (atlasName.startsWith("Sprites/")) atlasName = atlasName.replaceFirst("Sprites/".toRegex(), "") atlasName = atlasName.replace(".png", "") val region = prepackedAtlas.findRegion(atlasName) if (region != null) { val textureRegion = TextureRegion(region) loadedTextureRegions.put(path, textureRegion) return textureRegion } else { loadedTextureRegions.put(path, null) return null } } private val loadedTextures = HashMap<String, Texture?>() fun loadTexture(path: String, filter: TextureFilter = TextureFilter.Linear, wrapping: Texture.TextureWrap = Texture.TextureWrap.ClampToEdge): Texture? { var rawpath = path if (!rawpath.endsWith(".png")) rawpath += ".png" val path = "CompressedData/" + rawpath.hashCode() + ".ktx" if (loadedTextures.containsKey(path)) { return loadedTextures[path] } val file = Gdx.files.internal(path) if (!file.exists()) { loadedTextures.put(path, null) return null } val region = Texture(path) region.setFilter(filter, filter) region.setWrap(wrapping, wrapping) loadedTextures.put(path, region) return region } fun loadParticleEffect(name: String): ParticleEffect { val effect = ParticleEffect.load(name) return effect } fun loadParticleEffect(xml:XmlData): ParticleEffect { val effect = ParticleEffect.load(xml.get("Name")) val colourElement = xml.getChildByName("Colour") var colour = Colour(1f, 1f, 1f, 1f) if (colourElement != null) { colour = loadColour(colourElement) } effect.colour.set(colour) effect.flipX = xml.getBoolean("FlipX", false) effect.flipY = xml.getBoolean("FlipY", false) effect.scale = xml.getFloat("Scale", 1f) effect.useFacing = xml.getBoolean("UseFacing", true) effect.timeMultiplier = xml.getFloat("TimeMultiplier", 1f) effect.killOnAnimComplete = xml.getBoolean("KillOnAnimComplete", false) return effect } fun loadSprite(name: String, drawActualSize: Boolean): Sprite { return loadSprite(name, 0.5f, Colour(1f, 1f, 1f, 1f), drawActualSize) } fun loadSprite(name: String, updateTime: Float, reverse: Boolean): Sprite { return loadSprite(name, updateTime, Colour(1f, 1f, 1f, 1f), false, reverse) } @JvmOverloads fun loadSprite(name: String, updateTime: Float = 0.5f, colour: Colour = Colour(1f, 1f, 1f, 1f), drawActualSize: Boolean = false, reverse: Boolean = false, light: Light? = null): Sprite { var updateTime = updateTime val textures = Array<TextureRegion>(false, 1, TextureRegion::class.java) // Try 0 indexed sprite var i = 0 while (true) { val tex = loadTextureRegion("Sprites/" + name + "_" + i + ".png") if (tex == null) { break } else { textures.add(tex) } i++ } // Try 1 indexed sprite if (textures.size == 0) { i = 1 while (true) { val tex = loadTextureRegion("Sprites/" + name + "_" + i + ".png") if (tex == null) { break } else { textures.add(tex) } i++ } } // Try sprite without indexes if (textures.size == 0) { val tex = loadTextureRegion("Sprites/$name.png") if (tex != null) { textures.add(tex) } } if (textures.size == 0) { throw RuntimeException("Cant find any textures for $name!") } if (reverse) { textures.reverse() } if (updateTime <= 0) { updateTime = 0.5f } val sprite = Sprite(name, updateTime, textures, colour, drawActualSize) sprite.light = light return sprite } fun tryLoadSpriteWithResources(xml:XmlData, resources: ObjectMap<String,XmlData>): Sprite { if (xml.childCount == 0) return loadSprite(resources[xml.text]) else return loadSprite(xml) } fun tryLoadSprite(xml:XmlData?): Sprite? { if (xml == null) return null else if (xml.childCount == 0) return null else return loadSprite(xml) } fun loadSprite(xml:XmlData): Sprite { val colourElement = xml.getChildByName("Colour") var colour = Colour(1f, 1f, 1f, 1f) if (colourElement != null) { colour = loadColour(colourElement) } val sprite = loadSprite( xml.get("Name"), xml.getFloat("UpdateRate", 0f), colour, xml.getBoolean("DrawActualSize", false)) sprite.repeatDelay = xml.getFloat("RepeatDelay", 0f) sprite.frameBlend = xml.getBoolean("Blend", false) sprite.disableHDR = xml.getBoolean("DisableHDR", false) if (xml.getBoolean("RandomStart", false)) { sprite.texIndex = Random.random(sprite.textures.size) sprite.animationAccumulator = Random.random(sprite.animationDelay) } val animationElement = xml.getChildByName("Animation") if (animationElement != null) { sprite.animation = AbstractAnimation.load(animationElement.getChild(0)) } val lightEl = xml.getChildByName("Light") if (lightEl != null) { sprite.light = loadLight(lightEl) } return sprite } fun loadSprite(xml:XmlData, texture: TextureRegion): Sprite { val colourElement = xml.getChildByName("Colour") var colour = Colour(1f, 1f, 1f, 1f) if (colourElement != null) { colour = loadColour(colourElement) } val textures = Array<TextureRegion>(false, 1, TextureRegion::class.java) textures.add(texture) var updateTime = xml.getFloat("UpdateRate", 0f) if (updateTime <= 0) { updateTime = 0.5f } val sprite = Sprite(xml.get("Name", "")!!, updateTime, textures, colour, xml.getBoolean("DrawActualSize", false)) sprite.repeatDelay = xml.getFloat("RepeatDelay", 0f) sprite.disableHDR = xml.getBoolean("DisableHDR", false) val animationElement = xml.getChildByName("Animation") if (animationElement != null) { sprite.animation = AbstractAnimation.load(animationElement.getChild(0)) } val lightEl = xml.getChildByName("Light") if (lightEl != null) { sprite.light = loadLight(lightEl) } return sprite } fun loadLight(xml: XmlData): Light { val light = Light() light.colour.set(loadColour(xml.getChildByName("Colour")!!)) light.baseColour.set(light.colour) val brightness = xml.getFloat("Brightness") light.baseBrightness = brightness light.colour.mul(brightness, brightness, brightness, 1.0f) light.range = xml.getFloat("Range") light.baseRange = light.range light.hasShadows = xml.getBoolean("HasShadows", false) val animEl = xml.getChildByName("Animation") if (animEl != null) { light.anim = LightAnimation.load(animEl) } return light } fun loadColour(stringCol: String, colour: Colour = Colour()): Colour { val cols = stringCol.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() colour.r = java.lang.Float.parseFloat(cols[0]) / 255.0f colour.g = java.lang.Float.parseFloat(cols[1]) / 255.0f colour.b = java.lang.Float.parseFloat(cols[2]) / 255.0f colour.a = if (cols.size > 3) cols[3].toFloat() / 255.0f else 1f return colour } fun loadColour(xml:XmlData): Colour { return loadColour(xml.text) } fun loadTilingSprite(xml:XmlData): TilingSprite { return TilingSprite.load(xml) } fun loadLayeredSprite(xml: XmlData): Sprite { val paths = Array<String>() var drawActualSize = false val layers = xml.getChildByName("Layers")!! for (layer in layers.children) { val name = layer.get("Name") drawActualSize = drawActualSize || layer.getBoolean("DrawActualSize", false) paths.add(name) } val mergedName = paths.joinToString("+") val tex = loadTextureRegion("Sprites/$mergedName.png") ?: throw RuntimeException("Cant find any textures for layered sprite $mergedName!") val sprite = Sprite(tex) sprite.drawActualSize = drawActualSize val lightEl = xml.getChildByName("Light") if (lightEl != null) { sprite.light = loadLight(lightEl) } return sprite } fun loadDirectionalSprite(xml:XmlData, size: Int = 1): DirectionalSprite { val directionalSprite = DirectionalSprite() val anims = xml.getChildByName("Animations")!! for (i in 0.. anims.childCount-1) { val el = anims.getChild(i) val name = el.get("Name").toLowerCase() val up = AssetManager.loadSprite(el.getChildByName("Up")!!) val down = AssetManager.loadSprite(el.getChildByName("Down")!!) val left = AssetManager.loadSprite(el.getChildByName("Left")!!) val right = AssetManager.loadSprite(el.getChildByName("Right")!!) up.size[0] = size up.size[1] = size down.size[0] = size down.size[1] = size directionalSprite.addAnim(name, up, down, left, right) } return directionalSprite } fun loadRenderable(xml:XmlData): Renderable { val type = xml.getAttribute("meta:RefKey", null)?.toUpperCase() ?: xml.name.toUpperCase() return when(type) { "SPRITE" -> AssetManager.loadSprite(xml) "PARTICLEEFFECT", "PARTICLE" -> AssetManager.loadParticleEffect(xml) "TILINGSPRITE" -> AssetManager.loadTilingSprite(xml) else -> throw Exception("Unknown renderable type '$type'!") }; } } }
0
Kotlin
0
0
03e3d99a94916ab2e465d55e671a8459e24a1d1d
12,081
TowerDefense
Apache License 2.0
app/src/main/java/com/carousell/monoadapter/app/MainActivity.kt
carousell
320,152,534
false
null
package com.carousell.monoadapter.app import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.carousell.monoadapter.MonoAdapter import com.carousell.monoadapter.app.databinding.ActivityMainBinding import com.carousell.monoadapter.app.databinding.AdapterSampleBinding class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val adapter = createViewBindingAdapter() binding.recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) binding.recyclerView.adapter = adapter adapter.submitList(getData()) } private fun getData() = MutableList(100) { index -> "#$index" } private fun createViewBindingAdapter() = MonoAdapter.create<AdapterSampleBinding, String>(AdapterSampleBinding::inflate) { text.text = it } private fun createNormalAdapter() = MonoAdapter.create<String>(R.layout.adapter_sample) { view, string -> view.findViewById<TextView>(R.id.text).text = string } }
0
Kotlin
1
19
8d9a402ce5e939653a5224d44ec3ead05ac2afec
1,329
MonoAdapter
Apache License 2.0
api-core/src/commonMain/kotlin/su/pank/yamusic/account/model/Subscription.kt
pank-su
717,339,473
false
{"Kotlin": 82681}
package su.pank.yamusic.account.model import kotlinx.datetime.Instant import kotlinx.serialization.Serializable import su.pank.yamusic.account.model.AutoRenewable @Serializable data class Subscription( val familyAutoRenewable: List<AutoRenewable>? = null, val hadAnySubscription: Boolean? = null, val canStartTrial: Boolean? = null, val mcdonalds: Boolean? = null, val end: Instant? = null )
4
Kotlin
0
4
3c80dad225f8bbfee32b1279feb52aaa70224ec4
410
yandex-music-api
MIT License
data/src/main/java/com/trian/data/utils/SafeApiCall.kt
triandamai
510,087,041
false
null
package com.trian.data.utils import com.google.gson.Gson import com.trian.data.utils.network.DataState import logcat.LogPriority import logcat.logcat import retrofit2.HttpException import retrofit2.Response import java.io.IOException import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException /** * Persistence Class * Author PT Cexup Telemedicine * Created by <NAME> * 01/09/2021 */ suspend fun <T> safeApiCall(call: suspend () -> Response<T>): DataState<T> { try { val response = call.invoke() //mark response as success with code between 200 until 299 if(response.isSuccessful){ return DataState.onData((response.body()) as T) }else if(response.code() in 400..403){ val gson = Gson() val json = response.errorBody()?.string() if(json.isNullOrBlank()){ return DataState.onFailure("Failed to authenticate") } val error = gson.fromJson(json,ErrorBody::class.java) return DataState.onFailure(error.message) } return DataState.onFailure(response.message()) } catch (e: Exception) { e.printStackTrace() return when (e) { is IOException ->{ DataState.onFailure(e.message ?: "") } is ConnectException -> { DataState.onFailure(com.trian.data.utils.network.CONNECT_EXCEPTION) } is UnknownHostException -> { DataState.onFailure(com.trian.data.utils.network.UNKNOWN_HOST_EXCEPTION) } is SocketTimeoutException -> { DataState.onFailure(com.trian.data.utils.network.SOCKET_TIME_OUT_EXCEPTION) } is HttpException -> { DataState.onFailure(com.trian.data.utils.network.UNKNOWN_NETWORK_EXCEPTION) } else -> { DataState.onFailure(e.message ?:"") } } } } data class ErrorBody( var message:String )
0
Kotlin
0
0
66b41b294ca7347cc41b42b99f8203991964afed
2,074
starter-pack
Apache License 2.0
lib_modbus/src/main/kotlin/com/crow/modbus/serialport/SerialPortState.kt
crowforkotlin
696,702,450
false
{"Kotlin": 129340, "C": 13860, "Makefile": 1695, "CMake": 208}
package com.crow.modbus.serialport enum class SerialPortState(val message: String) { NO_READ_WRITE_PERMISSION("没有读写权限!") }
0
Kotlin
0
2
7221b518d0518277ac2b022908c25738ddd391e7
128
KModbus
Apache License 2.0
domain/src/main/java/tachiyomi/domain/track/manga/repository/MangaTrackRepository.kt
jmir1
718,862,527
false
{"Kotlin": 4265900}
package tachiyomi.domain.track.manga.repository import kotlinx.coroutines.flow.Flow import tachiyomi.domain.track.manga.model.MangaTrack interface MangaTrackRepository { suspend fun getTrackByMangaId(id: Long): MangaTrack? suspend fun getTracksByMangaId(mangaId: Long): List<MangaTrack> fun getMangaTracksAsFlow(): Flow<List<MangaTrack>> fun getTracksByMangaIdAsFlow(mangaId: Long): Flow<List<MangaTrack>> suspend fun deleteManga(mangaId: Long, syncId: Long) suspend fun insertManga(track: MangaTrack) suspend fun insertAllManga(tracks: List<MangaTrack>) }
1
Kotlin
0
2
2584e3892d2571eac4b86702a4fe13fa76e46332
594
aniyomi-omegalul
Apache License 2.0
app/src/main/java/com/oajstudios/pocketshop/models/StoreCategory.kt
AYOMITIDE-OAJ
617,064,177
false
null
package com.oajstudios.pocketshop.models data class Category( val _links: CategoryLinks, val count: Int, val description: String, val display: String, val id: Int, val image: CategoryImage?= null, val menu_order: Int, val name: String, val parent: Int, val slug: String ) data class CategoryLinks( val collection: List<CategoryCollection>, val self: List<CategorySelf> ) data class CategoryCollection( val href: String ) data class CategorySelf( val href: String ) data class CategoryImage( val alt: String, val date_created: String, val date_created_gmt: String, val date_modified: String, val date_modified_gmt: String, val id: Int, val name: String, val src: String )
1
Kotlin
0
10
48cf66963987da31392350a9afec1125b9cfa4fa
763
pocketshop
Apache License 2.0
app/src/main/java/com/example/resumeskillapp/core/App.kt
ChorpitaSergiy
518,162,219
false
null
/* * MIT License * * Copyright (C) 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.example.resumeskillapp.core import android.app.Application import com.example.resumeskillapp.core.di.appModule import com.example.resumeskillapp.core.di.networkModule import com.example.resumeskillapp.core.di.storageModule import com.example.resumeskillapp.core.di.viewModelModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level class App : Application() { override fun onCreate() { super.onCreate() instance = this startKoin { androidLogger(Level.ERROR) androidContext(this@App) modules(listOf(appModule, networkModule, viewModelModule, storageModule)) } } companion object { lateinit var instance: App } }
0
Kotlin
0
0
18d26bbd130419bc85e2c24b62d429ec44cfc7e3
1,970
ResumeSkillApp
MIT License
spring-boot/src/main/java/com/saltedge/provider/demo/config/JacksonConfig.kt
saltedge
528,879,580
false
{"Kotlin": 79478, "Ruby": 41797, "HTML": 24867, "FreeMarker": 21940, "Java": 6270, "Dockerfile": 381, "CSS": 223}
/* * @author <NAME> (<EMAIL>) * Copyright (c) 2022 Salt Edge. */ package com.saltedge.provider.demo.config import com.fasterxml.jackson.databind.ObjectMapper import com.saltedge.provider.demo.tools.JsonTools import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary /** * Configuration of Jackson */ @Configuration open class JacksonConfig { @Bean @Primary open fun objectMapper(): ObjectMapper? = JsonTools.defaultMapper }
0
Kotlin
1
0
756d392bc6c5683cd90769a06de3ce035b6a9c02
549
saltedge-sca-demo-provider
MIT License
src/main/kotlin/engine_helpers/RedshiftController.kt
olracnai
758,262,334
false
{"Kotlin": 31476}
package engine_helpers import java.io.IOException object RedshiftController { fun redshiftCommand(runThis: String) { try { val process = ProcessBuilder("bash", "-c", "redshift -x ; $runThis").start() // Redirect error stream to standard output to capture errors process.errorStream.reader().use { reader -> reader.forEachLine { line -> println(line) } } // Read process output process.inputStream.bufferedReader().use { reader -> reader.forEachLine { line -> println(line) } } // Wait for process to finish val exitVal = process.waitFor() if (exitVal == 0) { println("Success!") } else { println("Command failure: $exitVal") } // Extra error handling } catch (e: IOException) { println("Command failure: ${e.message}") } catch (e: InterruptedException) { println("Command failure: ${e.message}") } } }
0
Kotlin
0
1
1b3573a7ea6449453723621d1194ff7dd0821447
1,042
redshift-jetpack
MIT License
store/src/commonMain/kotlin/org/mobilenativefoundation/store/store5/Read.kt
MobileNativeFoundation
226,169,258
false
{"Kotlin": 361534}
package org.mobilenativefoundation.store.store5 import kotlinx.coroutines.flow.Flow interface Read { interface Stream<Key : Any, Output : Any> { /** * Return a flow for the given key * @param request - see [StoreReadRequest] for configurations */ fun stream(request: StoreReadRequest<Key>): Flow<StoreReadResponse<Output>> } interface StreamWithConflictResolution<Key : Any, Output : Any> { fun <Response : Any> stream(request: StoreReadRequest<Key>): Flow<StoreReadResponse<Output>> } }
57
Kotlin
202
3,174
f9072fc59cc8bfe95cfe008cc8a9ce999301b242
558
Store
Apache License 2.0
azure-communication-ui/chat/src/main/java/com/azure/android/communication/ui/chat/redux/state/AppReduxState.kt
Azure
429,521,705
false
{"Kotlin": 2713288, "Java": 192826, "Shell": 3964, "HTML": 1856}
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.android.communication.ui.chat.redux.state import com.azure.android.communication.ui.chat.models.ChatInfoModel import com.azure.android.communication.ui.chat.models.EMPTY_MESSAGE_INFO_MODEL import com.azure.android.communication.ui.chat.models.LocalParticipantInfoModel import com.azure.android.communication.ui.chat.models.MessageContextMenuModel import org.threeten.bp.OffsetDateTime internal class AppReduxState( threadID: String, localParticipantIdentifier: String, localParticipantDisplayName: String?, ) : ReduxState { override var chatState: ChatState = ChatState( chatStatus = ChatStatus.NONE, chatInfoModel = ChatInfoModel( threadId = threadID, topic = null, allMessagesFetched = false, isThreadDeleted = false ), lastReadMessageId = "", messageContextMenu = MessageContextMenuModel(EMPTY_MESSAGE_INFO_MODEL, emptyList()) ) override var participantState: ParticipantsState = ParticipantsState( localParticipantInfoModel = LocalParticipantInfoModel( userIdentifier = localParticipantIdentifier, displayName = localParticipantDisplayName ), participants = mapOf(), participantTyping = mapOf(), participantsReadReceiptMap = mapOf(), latestReadMessageTimestamp = OffsetDateTime.MIN, hiddenParticipant = setOf() ) override var lifecycleState: LifecycleState = LifecycleState(LifecycleStatus.FOREGROUND) override var errorState: ErrorState = ErrorState(fatalError = null, chatCompositeErrorEvent = null) override var navigationState: NavigationState = NavigationState(NavigationStatus.NONE) override var repositoryState: RepositoryState = RepositoryState(lastUpdatedTimestamp = System.currentTimeMillis()) override var networkState: NetworkState = NetworkState(networkStatus = NetworkStatus.CONNECTED, disconnectOffsetDateTime = null) }
7
Kotlin
28
24
d7e46c6063e8e9d3ed548acff2465b5d0f57b1b2
2,094
communication-ui-library-android
MIT License
app/src/main/java/com/example/dropy/ui/components/shops/backside/dashboard/product/productslist/ProductsList.kt
dropyProd
705,360,878
false
{"Kotlin": 3916897, "Java": 20617}
package com.example.dropy.ui.components.shops.backside.dashboard.product.productslist import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.dropy.network.models.AllProductsResItem import com.example.dropy.network.models.shopdetails.Product import com.example.dropy.ui.components.commons.EmptyBlock import com.example.dropy.ui.components.shops.frontside.singleshop.shophome.BaseUrL import com.example.dropy.ui.theme.LightContainerBackground @Composable fun ProductsList( productList:List<AllProductsResItem>, onProductSelected:(product: AllProductsResItem)->Unit ){ Column( modifier = Modifier .padding(8.dp) .fillMaxWidth() .verticalScroll(rememberScrollState()) ) { if (productList.isNotEmpty()){ for (item in productList){ val index = productList.indexOf(item) item.product_name?.let { item.number_in_stack?.let { it1 -> item.product_price?.let { it2 -> item.product_cover_photo?.let { it3 -> /* val cutname = remember { mutableStateOf("") } it.forEachIndexed { index, item -> if (index in 0..5){ cutname.value += item } if (index in 6..8){ cutname.value += "." } }*/ ProductListItem( productImageUrl = "${BaseUrL}$it3", productName = it, numberOfUnits = it1, price = it2, alwaysAvailable = false, backgroundColor = if (index % 2 == 0){ LightContainerBackground }else{ Color.White }, onClick = { onProductSelected(item) } ) } } } } } }else{ EmptyBlock() } } } @Preview(showBackground = true) @Composable fun ProductsListPreview() { Column( modifier = Modifier .fillMaxHeight() .fillMaxWidth() ) { val productsList = mutableListOf( ProductsListItemDataClass( productId = 1, productImageUrl = "", productName = "Some other very long product name", numberOfUnits = 2, price = 4321, alwaysAvailable = true ), ProductsListItemDataClass( productId = 1, productImageUrl = "", productName = "Some other very long product name", numberOfUnits = 2, price = 4321, alwaysAvailable = true ), ProductsListItemDataClass( productId = 1, productImageUrl = "", productName = "Some other very long product name", numberOfUnits = 2, price = 4321, alwaysAvailable = true ) ) ProductsList( onProductSelected = {}, productList = listOf() ) } }
0
Kotlin
0
0
6d994c9c61207bac28c49717b6c250656fe4ae6b
4,295
DropyLateNights
Apache License 2.0
app/src/main/java/com/codepath/bestsellerlistapp/BestSellerBook.kt
mateamilloshi
702,118,454
false
{"Kotlin": 8597}
package com.codepath.bestsellerlistapp import com.google.gson.annotations.SerializedName import com.codepath.bestsellerlistapp.Person /** * The Model for storing a single book from the NY Times API *data class Movie( * val name: String, * val title: String, * val description: String, * val posterUrl: String * ) * * SerializedName tags MUST match the JSON response for the * object to correctly parse with the gson library. */ class Person { @SerializedName("name")//rank var name: String? = null @JvmField @SerializedName("title")//title var title: String? = null @JvmField @SerializedName("description")//author var description: String? = null //TODO ImageUrl @JvmField @SerializedName("posterUrl")//author var posterUrl: String? = null @JvmField @SerializedName("id")//author var id: String? = null @JvmField @SerializedName("profile_path")//author var profilePath: String? = null //TODO description //TODO-STRETCH-GOALS amazonUrl }
0
Kotlin
0
0
8c0b21e8f74bef1a95d99a2238ea8931da35f081
1,054
FlexterApp2
Apache License 2.0
bucketeer/src/main/kotlin/io/bucketeer/sdk/android/internal/model/response/RegisterEventsResponse.kt
bucketeer-io
517,624,444
false
null
package io.bucketeer.sdk.android.internal.model.response import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class RegisterEventsResponse( val data: RegisterEventsDataResponse, )
8
Kotlin
2
4
5544bbfb5dd127a8d2058f5112734543270b2156
207
android-client-sdk
Apache License 2.0
app/src/main/java/com/yusuf/drinkvibes/data/retrofit/entity/Moods.kt
Yusuf-Solmaz
735,562,277
false
{"Kotlin": 34107}
package com.yusuf.drinkvibes.data.retrofit.entity import com.google.gson.annotations.SerializedName import java.io.Serializable data class Moods( @SerializedName("id") val id: Int, @SerializedName("moodName") val moodName: String ) : Serializable
0
Kotlin
0
1
a96285212d262e0125b7e0658ff4caef33603476
266
DrinkVibes
Apache License 2.0
app/src/main/java/com/drs/dseller/feature_home/domain/usecases/GetHomeOffers.kt
raaja-sn
704,140,729
false
{"Kotlin": 307720}
package com.drs.dseller.feature_home.domain.usecases import com.drs.dseller.feature_home.domain.model.HomeOffer import com.drs.dseller.feature_home.domain.repository.OffersRepository import com.drs.dseller.feature_home.response.HomeResponse import javax.inject.Inject /** * Get Home Offers * * @param repo Repository object to get home screen offers */ class GetHomeOffers @Inject constructor( private val repo:OffersRepository<HomeResponse<List<HomeOffer>>> ) { suspend operator fun invoke() = repo.getHomeOffers() }
0
Kotlin
0
0
2cab9113d3e0e92b0a3c97459b1b3fd4a6e84278
541
DSeller-Android
MIT License
app/src/main/java/com/maxela/android/adapter/BindingUtils.kt
doilio
338,557,126
false
null
package com.maxela.android.adapter import android.widget.ImageView import android.widget.TextView import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide import com.maxela.android.model.WeatherResult import java.text.SimpleDateFormat import java.util.* @BindingAdapter("weatherIcon") fun ImageView.setWeatherIcon(imageUrl: String?) { imageUrl?.let { Glide.with(this).load(it).into(this) } } @BindingAdapter("cityAndCountry") fun TextView.setCityAndCountry(weatherResult: WeatherResult?) { weatherResult?.let { text = String.format("${it.name},${it.sys.country}") } } @BindingAdapter("temperature") fun TextView.setTemperature(temperature: Double?) { temperature?.let { text = String.format("${temperature.toInt()}°") } } @BindingAdapter("dateTime") fun TextView.setDateTime(dateTime: Int?) { dateTime?.let { val longDate = dateTime.toLong() * 1000 val date = Date(longDate) val format = SimpleDateFormat("EEE, dd MMMM yyyy HH:mm",Locale.getDefault()) text = format.format(date) } } @BindingAdapter("weekday") fun TextView.setWeekday(dateTime: Int?) { dateTime?.let { val longDate = dateTime.toLong() * 1000 val date = Date(longDate) val format = SimpleDateFormat("EEEE",Locale.getDefault()) text = format.format(date) } } @BindingAdapter("date") fun TextView.setDate(date: Int?) { date?.let { val longDate = date.toLong() * 1000 val data = Date(longDate) val format = SimpleDateFormat("dd MMMM yyyy HH:mm",Locale.getDefault()) text = format.format(data) } } @BindingAdapter("time") fun TextView.setTime(time: Int?) { time?.let { val longDate = time.toLong() * 1000 val date = Date(longDate) val format = SimpleDateFormat("HH:mm", Locale.getDefault()) text = format.format(date) } } @BindingAdapter("humidity") fun TextView.setHumidity(humidity: Int?) { humidity?.let { text = "$it%" } } @BindingAdapter("pressure") fun TextView.setPressure(pressure: Int?) { pressure?.let { text = String.format("$it hPa") } } @BindingAdapter("speed") fun TextView.setWindSpeed(speed: Double?) { speed?.let { text = String.format("$it km/h") } }
0
Kotlin
2
1
1a2c867e09ed95ea53d0b06834f881d18e85691f
2,323
Maxela
Apache License 2.0
server/src/main/kotlin/com/configset/server/AppConfiguration.kt
raymank26
296,910,120
false
null
package com.configset.server class AppConfiguration { private val env = System.getenv() fun validate() { if (getDaoType() == DaoType.POSTGRES) { getJdbcUrl() } } fun getDaoType(): DaoType { return when (readFromEnv("db_type", "memory")) { "postgres" -> DaoType.POSTGRES else -> DaoType.IN_MEMORY } } fun getJdbcUrl(): String { return readFromEnv("jdbc_url") } fun getUpdateDelayMs(): Long { return readFromEnv("update_delay_ms", "4000").toLong() } fun grpcPort(): Int { return 8080 } private fun readFromEnv(key: String, default: String): String { return env[key] ?: default } private fun readFromEnv(key: String): String { return env[key] ?: throw ConfigKeyRequired(key) } } class ConfigKeyRequired(val configKey: String) : RuntimeException() { } enum class DaoType { IN_MEMORY, POSTGRES ; }
0
Kotlin
0
0
3d749c4d9040ae24c5b144cdf69a3e29ba1a45d2
983
configset
Apache License 2.0
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/psi/SkinFile.kt
yyYank
78,517,828
true
{"Kotlin": 242196, "Java": 23308, "Lex": 1948, "HTML": 754}
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi import com.intellij.psi.PsiFile /* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ interface SkinFile : SkinElement, PsiFile { fun getTopLevelValue(): SkinValue? fun getAllTopLevelValues(): List<SkinValue> }
0
Kotlin
0
0
c6c49de439a88d49eefd6f7db2d74b0cc142d44f
813
LibGDXPlugin
Apache License 2.0
data/src/main/java/com/spiderbiggen/manhwa/data/usecase/chapter/GetPreviousChapters.kt
spiderbiggen
624,650,535
false
{"Kotlin": 118713}
package com.spiderbiggen.manhwa.data.usecase.chapter import com.spiderbiggen.manhwa.data.source.local.repository.ChapterRepository import com.spiderbiggen.manhwa.data.usecase.either import com.spiderbiggen.manhwa.domain.model.AppError import com.spiderbiggen.manhwa.domain.model.Chapter import com.spiderbiggen.manhwa.domain.model.Either import javax.inject.Inject class GetPreviousChapters @Inject constructor( private val chapterRepository: ChapterRepository, ) { suspend operator fun invoke(chapterId: String): Either<List<Chapter>, AppError> = chapterRepository.getPreviousChapters(chapterId).either() }
1
Kotlin
0
0
cbd3531735d456a0615f17f7fdf32b1364764c71
627
manhwa-reader
MIT License
src/main/kotlin/no/nav/syfo/dialogmelding/bestilling/database/BehandlerDialogmeldingBestillingQuery.kt
navikt
378,118,189
false
{"Kotlin": 635959, "Dockerfile": 226}
package no.nav.syfo.dialogmelding.bestilling.database import no.nav.syfo.application.database.DatabaseInterface import no.nav.syfo.application.database.toList import no.nav.syfo.dialogmelding.bestilling.domain.DialogmeldingToBehandlerBestilling import java.sql.* import java.time.Instant import java.util.UUID const val queryCreateBehandlerDialogmeldingBestilling = """ INSERT INTO BEHANDLER_DIALOGMELDING_BESTILLING ( id, uuid, behandler_id, arbeidstaker_personident, parent, conversation, type, kodeverk, kode, tekst, vedlegg, sendt, sendt_tries, created_at, updated_at ) VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id """ fun Connection.createBehandlerDialogmeldingBestilling( dialogmeldingToBehandlerBestilling: DialogmeldingToBehandlerBestilling, behandlerId: Int, ): Int { val now = Timestamp.from(Instant.now()) val idList = this.prepareStatement(queryCreateBehandlerDialogmeldingBestilling).use { it.setString(1, dialogmeldingToBehandlerBestilling.uuid.toString()) it.setInt(2, behandlerId) it.setString(3, dialogmeldingToBehandlerBestilling.arbeidstakerPersonident.value) it.setString(4, dialogmeldingToBehandlerBestilling.parentRef) it.setString(5, dialogmeldingToBehandlerBestilling.conversationUuid.toString()) it.setString(6, dialogmeldingToBehandlerBestilling.type.name) it.setString(7, dialogmeldingToBehandlerBestilling.kodeverk?.name) it.setInt(8, dialogmeldingToBehandlerBestilling.kode.value) it.setString(9, dialogmeldingToBehandlerBestilling.tekst) it.setBytes(10, dialogmeldingToBehandlerBestilling.vedlegg) it.setTimestamp(11, null) it.setInt(12, 0) it.setTimestamp(13, now) it.setTimestamp(14, now) it.executeQuery().toList { getInt("id") } } if (idList.size != 1) { throw SQLException("Creating BehandlerDialogmeldingBestilling failed, no rows affected.") } return idList.first() } const val querySetBehandlerDialogmeldingBestillingSendt = """ UPDATE BEHANDLER_DIALOGMELDING_BESTILLING SET sendt=?, sendt_tries=sendt_tries+1, updated_at=? WHERE uuid = ? """ fun DatabaseInterface.setBehandlerDialogmeldingBestillingSendt( uuid: UUID, ) { this.connection.use { connection -> val now = Timestamp.from(Instant.now()) connection.prepareStatement(querySetBehandlerDialogmeldingBestillingSendt).use { ps -> ps.setTimestamp(1, now) ps.setTimestamp(2, now) ps.setString(3, uuid.toString()) ps.execute() } connection.commit() } } const val queryIncrementBehandlerDialogmeldingBestillingSendtTries = """ UPDATE BEHANDLER_DIALOGMELDING_BESTILLING SET sendt_tries=sendt_tries+1,updated_at=? WHERE uuid = ? """ fun DatabaseInterface.incrementDialogmeldingBestillingSendtTries( uuid: UUID, ) { this.connection.use { connection -> connection.prepareStatement(queryIncrementBehandlerDialogmeldingBestillingSendtTries).use { ps -> ps.setTimestamp(1, Timestamp.from(Instant.now())) ps.setString(2, uuid.toString()) ps.execute() } connection.commit() } } const val queryGetBestillinger = """ SELECT * FROM BEHANDLER_DIALOGMELDING_BESTILLING WHERE uuid = ? """ fun Connection.getBestilling(uuid: UUID): PDialogmeldingToBehandlerBestilling? { return this.prepareStatement(queryGetBestillinger) .use { it.setString(1, uuid.toString()) it.executeQuery().toList { toPBehandlerDialogmeldingBestilling() } }.firstOrNull() } fun DatabaseInterface.getBestilling(uuid: UUID): PDialogmeldingToBehandlerBestilling? { return this.connection.use { connection -> connection.getBestilling(uuid) } } const val queryGetBestilling = """ SELECT * FROM BEHANDLER_DIALOGMELDING_BESTILLING WHERE id = ? """ fun DatabaseInterface.getBestilling(id: Int): PDialogmeldingToBehandlerBestilling? { return this.connection.use { connection -> connection.prepareStatement(queryGetBestilling).use { it -> it.setInt(1, id) it.executeQuery().toList { toPBehandlerDialogmeldingBestilling() } }.firstOrNull() } } const val queryGetBestillingerNotSent = """ SELECT * FROM BEHANDLER_DIALOGMELDING_BESTILLING WHERE sendt is NULL ORDER BY id LIMIT 50 """ fun DatabaseInterface.getDialogmeldingToBehandlerBestillingNotSendt(): List<PDialogmeldingToBehandlerBestilling> { return this.connection.use { connection -> connection.prepareStatement(queryGetBestillingerNotSent) .use { it.executeQuery().toList { toPBehandlerDialogmeldingBestilling() } } } } fun ResultSet.toPBehandlerDialogmeldingBestilling(): PDialogmeldingToBehandlerBestilling = PDialogmeldingToBehandlerBestilling( id = getInt("id"), uuid = UUID.fromString(getString("uuid")), behandlerId = getInt("behandler_id"), arbeidstakerPersonident = getString("arbeidstaker_personident"), parentRef = getString("parent"), conversationUuid = UUID.fromString(getString("conversation")), type = getString("type"), kodeverk = getString("kodeverk"), kode = getInt("kode"), tekst = getString("tekst"), vedlegg = getBytes("vedlegg"), sendt = getTimestamp("sendt"), sendtTries = getInt("sendt_tries"), )
1
Kotlin
0
0
979bf4f075a269e41d475069c9d81e09a8716bfb
5,744
isdialogmelding
MIT License
app/src/main/java/com/tc/gamegallery/domain/GetTagsCatalogUseCase.kt
JerbiJ456
804,320,356
false
{"Kotlin": 128407}
package com.tc.gamegallery.domain import com.apollographql.apollo3.api.Optional //one use case per request class GetTagsCatalogUseCase( private val gameClient: GameClient ) { suspend fun execute( pageSize: Optional<Int>, page: Optional<Int>, ): GenresTags { return gameClient .getGameTags(pageSize, page) } }
0
Kotlin
0
0
06425f3849a5ff4ec9162c8ce20dcab8e2b7a480
363
Game-Gallery
MIT License
app/src/main/java/edu/kit/dppviewer/ui/feature/importproductpage/ImportProductPageUiState.kt
boebe24
849,335,060
false
{"Kotlin": 618075}
package edu.kit.dppviewer.ui.feature.importproductpage /** * Ui State for ImportProductPage */ data class ImportProductPageUiState( val showQRScanner: Boolean = false, val showSheet: Boolean = false, val showDialog: Boolean = false, val isFlashOn: Boolean = false, val showEnterURLDialog: Boolean = false, val url: String = "", val productLoadingState: ProductLoadingState = ProductLoadingState.LOADING, )
0
Kotlin
0
3
145dc722dcff0c95f34579287fb8681160638605
436
boebe-DPP-Viewer
MIT License
app/src/main/java/br/ufrn/eaj/tads/gametetris/HomeActivity.kt
devarthurribeiro
249,906,631
false
null
package br.ufrn.eaj.tads.gametetris import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.view.View import kotlinx.android.synthetic.main.activity_home.* /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */ class HomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) supportActionBar?.setDisplayHomeAsUpEnabled(true) newGame.setOnClickListener { startActivity(Intent(this, MainActivity::class.java)) } settings.setOnClickListener { startActivity(Intent(this, SettingsActivity::class.java)) } continueGame.setOnClickListener { val i = Intent(this, MainActivity::class.java) i.putExtra("continue", false) startActivity(i) } } override fun onStart() { super.onStart() if (GameState.saved) { continueGame.visibility = View.VISIBLE } } }
0
Kotlin
2
1
ecf8b9836441efa0b0f0d4fdad3b2a980285a270
1,220
GameTetris
MIT License
src/main/kotlin/eft/weapons/builds/utils/Mapper.kt
neonailol
207,225,209
false
{"Kotlin": 55401}
package eft.weapons.builds.utils import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.MapperFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature object Mapper { private val mapper: ObjectMapper = ObjectMapper() .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) operator fun invoke(): ObjectMapper { return mapper } } fun mapper(): ObjectMapper { return Mapper() } fun stringBuilder(any: Any): String { return mapper() .writerWithDefaultPrettyPrinter() .writeValueAsString(any) } fun printJson(any: Any) { println(stringBuilder(any)) }
0
Kotlin
1
0
1254d1157a7478360480d2a4a84aad590a95e201
959
eft-codex
MIT License
src/main/kotlin/com/figure/gradle/semver/internal/command/TagList.kt
FigureTechnologies
496,001,309
false
null
/* * Copyright (C) 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.github.tcrawford.semver.internal.command import io.github.tcrawford.semver.internal.extensions.isNotPreRelease import io.github.tcrawford.semver.internal.properties.Stage import io.github.z4kn4fein.semver.Version import io.github.z4kn4fein.semver.toVersion import io.github.z4kn4fein.semver.toVersionOrNull import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.Ref class TagList( private val git: Git, ) { operator fun invoke(): List<Ref> = git.tagList().call() fun find(tagName: String): Ref? = invoke().find { it.name == tagName } val versionedTags: List<Version> get() = invoke().mapNotNull { it.name.replace(Constants.R_TAGS, "").toVersionOrNull(strict = false) } private fun latest(forMajorVersion: Int?): Version? { val stages = Stage.entries.map { stage -> stage.value.lowercase() } return versionedTags // Get only stable and staged pre-releases .filter { version -> val prereleaseLabel = version.preRelease?.substringBefore(".")?.lowercase() version.isNotPreRelease || prereleaseLabel in stages } .let { versions -> if (forMajorVersion != null) { versions.filter { version -> version.major == forMajorVersion } } else { versions } } .maxOrNull() } fun latestOrInitial(initial: String, forMajorVersion: Int?): Version = latest(forMajorVersion) ?: initial.toVersion() private val latestNonPreRelease: Version? get() = versionedTags .filter { version -> version.isNotPreRelease } .maxOrNull() fun latestNonPreReleaseOrInitial(initial: String): Version = latestNonPreRelease ?: initial.toVersion() }
3
null
2
15
321016fbc9e2bca123e4aedc7b193a565d08e264
2,479
gradle-semver-plugin
Apache License 2.0
remote/src/main/java/com/piotrek1543/android/boilerplate/remote/mapper/MainEntityMapper.kt
piotrek1543
168,876,182
false
null
package com.piotrek1543.android.boilerplate.remote.mapper import com.piotrek1543.android.boilerplate.data.model.MainEntity import com.piotrek1543.android.boilerplate.remote.model.MainModel import javax.inject.Inject /** * Map a [MainModel] to and from a [MainEntity] instance when data is moving between * this later and the Data layer */ open class MainEntityMapper @Inject constructor() : EntityMapper<MainModel, MainEntity> { /** * Map an instance of a [MainModel] to a [MainEntity] model */ override fun mapFromRemote(type: MainModel): MainEntity = MainEntity( temp = type.temp, tempMin = type.tempMin, tempMax = type.tempMax, pressure = type.pressure, seaLevel = type.seaLevel, grndLevel = type.grndLevel, humidity = type.humidity, tempKf = type.tempKf, listDt = type.listDt ) }
0
Kotlin
0
8
a5510a569d306660d03263f039ab02882c531e2c
920
sunshine_clean_architecture
MIT License
app/src/main/java/com/example/recordcounter/ui/stopwatch/StopwatchFragment.kt
EricmesquiBR
851,112,522
false
{"Kotlin": 21593}
@file:Suppress("DEPRECATION") package com.example.recordcounter.ui.stopwatch import android.app.Activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import com.example.recordcounter.NameTimeActivity import com.example.recordcounter.R import com.example.recordcounter.databinding.FragmentStopwatchBinding import com.example.recordcounter.utils.TimerService import kotlin.math.roundToInt import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.util.Log import android.widget.Toast import kotlin.math.abs @Suppress("DEPRECATION") class StopwatchFragment : Fragment() { private lateinit var binding: FragmentStopwatchBinding private lateinit var viewModel: StopwatchViewModel private var timeStarted = false private lateinit var serviceIntent: Intent private var time = 0.0 // Sensor variables private lateinit var sensorManager: SensorManager private val accelerometerListener = AccelerometerListener() private var lastAcceleration = FloatArray(3) private var lastAccelerationTime = System.currentTimeMillis() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentStopwatchBinding.inflate(inflater, container, false) viewModel = ViewModelProvider(this).get(StopwatchViewModel::class.java) sensorManager = activity?.getSystemService(Context.SENSOR_SERVICE) as SensorManager serviceIntent = Intent(activity?.applicationContext, TimerService::class.java) activity?.registerReceiver(updateTime, IntentFilter(TimerService.TIMER_UPDATED)) binding.btnStartStop.setOnClickListener { startStop() } binding.btnSaveTime.setOnClickListener { saveTime() } binding.btnReset.setOnClickListener { resetTime() } return binding.root } override fun onResume() { super.onResume() val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) sensorManager.registerListener(accelerometerListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL) } override fun onPause() { super.onPause() sensorManager.unregisterListener(accelerometerListener) } private fun getTimeStringFromDouble(time: Double): String { val resultInt = time.roundToInt() val hours = resultInt % 86400 / 3600 val minutes = resultInt % 86400 % 3600 / 60 val seconds = resultInt % 86400 % 3600 % 60 return makeTimeString(hours, minutes, seconds) } private fun makeTimeString(hour: Int, minute: Int, second: Int): String = String.format("%02d:%02d:%02d", hour, minute, second) private val updateTime: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { time = intent.getDoubleExtra(TimerService.TIMER_EXTRA, 0.0) binding.timer.text = getTimeStringFromDouble(time) } } private fun startStop() { if (!timeStarted) { startTimer() } else { stopTimer() } } private fun startTimer() { serviceIntent.putExtra(TimerService.TIMER_EXTRA, time) activity?.startService(serviceIntent) binding.btnStartStop.text = "Stop" timeStarted = true } private fun stopTimer() { activity?.stopService(serviceIntent) binding.btnStartStop.text = "Start" timeStarted = false } private fun saveTime() { val timeString = getTimeStringFromDouble(time) Toast.makeText(context, "Time to be saved: $timeString", Toast.LENGTH_SHORT).show() val intent = Intent(activity, NameTimeActivity::class.java).apply { putExtra(TimerService.TIMER_EXTRA, time) } startActivityForResult(intent, REQUEST_CODE_SAVE_TIME) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_SAVE_TIME && resultCode == Activity.RESULT_OK) { val name = data?.getStringExtra("RECORD_NAME") val timeString = data?.getStringExtra("RECORD_TIME") Toast.makeText(context, "Saved time: $timeString with name: $name", Toast.LENGTH_SHORT).show() } } private fun resetTime() { stopTimer() time = 0.0 binding.timer.text = getTimeStringFromDouble(time) } override fun onDestroy() { super.onDestroy() activity?.unregisterReceiver(updateTime) } inner class AccelerometerListener : SensorEventListener { private var lastActionTime = System.currentTimeMillis() private val COOLDOWN_PERIOD = 2000L // 2 seconds cooldown period override fun onSensorChanged(event: SensorEvent) { val x = event.values[0] val y = event.values[1] val z = event.values[2] if (lastAcceleration.isNotEmpty()) { val deltaX = abs(x - lastAcceleration[0]) val deltaY = abs(y - lastAcceleration[1]) val deltaZ = abs(z - lastAcceleration[2]) // Detect large movements if ((deltaX > LARGE_MOVEMENT_THRESHOLD || deltaY > LARGE_MOVEMENT_THRESHOLD || deltaZ > LARGE_MOVEMENT_THRESHOLD) && System.currentTimeMillis() - lastActionTime > COOLDOWN_PERIOD) { performLargeMovementAction() lastActionTime = System.currentTimeMillis() } // Detect taps if ((deltaX > TAP_THRESHOLD || deltaY > TAP_THRESHOLD || deltaZ > TAP_THRESHOLD) && System.currentTimeMillis() - lastActionTime > COOLDOWN_PERIOD) { performTapAction() lastActionTime = System.currentTimeMillis() } } lastAcceleration = event.values.clone() } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} private fun performLargeMovementAction() { Log.d("AccelerometerListener", "Large movement detected") if (!timeStarted) { startTimer() } } private fun performTapAction() { Log.d("AccelerometerListener", "Tap detected") // No action needed for tap; keeping this function for any future implementation } } companion object { private const val REQUEST_CODE_SAVE_TIME = 1 private const val LARGE_MOVEMENT_THRESHOLD = 8f private const val TAP_THRESHOLD = 2f private const val COOLDOWN_PERIOD = 2000L // 2 seconds cooldown period } }
0
Kotlin
0
0
27d1b52cb0e99ae0b2ce0feb173b0ceff066e967
7,230
record-counter
MIT License
executor/invoker/src/commonMain/kotlin/io/github/charlietap/chasm/executor/invoker/instruction/memory/load/LoadSizedNumberValueExecutor.kt
CharlieTap
743,980,037
false
{"Kotlin": 898736, "WebAssembly": 7119}
package io.github.charlietap.chasm.executor.invoker.instruction.memory.load import com.github.michaelbull.result.Result import io.github.charlietap.chasm.ast.instruction.MemArg import io.github.charlietap.chasm.executor.runtime.Stack import io.github.charlietap.chasm.executor.runtime.error.InvocationError import io.github.charlietap.chasm.executor.runtime.memory.LinearMemory import io.github.charlietap.chasm.executor.runtime.store.Store internal typealias SizedNumberValueReader<T> = LinearMemory.(Int, Int) -> Result<T, InvocationError> internal typealias LoadSizedNumberValueExecutor<T> = (Store, Stack, MemArg, Int, SizedNumberValueReader<T>, Constructor<T>) -> Result<Unit, InvocationError>
2
Kotlin
1
16
1566c1b504b4e0a31ae5008f5ada463c47de71c5
702
chasm
Apache License 2.0
kotlin-typescript/src/main/generated/typescript/raw/isMethodSignature.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("typescript") @file:JsNonModule package typescript.raw import typescript.Node internal external fun isMethodSignature(node: Node): Boolean /* node is MethodSignature */
12
null
7
983
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
232
kotlin-wrappers
Apache License 2.0
src/main/kotlin/org/consoletrader/indicators/BollingerWidthTasks.kt
tomaszbabiuk
116,781,000
false
null
package org.consoletrader.indicators import io.reactivex.Single import org.consoletrader.common.* import org.ta4j.core.TimeSeries import org.ta4j.core.indicators.EMAIndicator import org.ta4j.core.indicators.bollinger.BollingerBandsLowerIndicator import org.ta4j.core.indicators.bollinger.BollingerBandsMiddleIndicator import org.ta4j.core.indicators.bollinger.BollingerBandsUpperIndicator import org.ta4j.core.indicators.helpers.ClosePriceIndicator import org.ta4j.core.indicators.statistics.StandardDeviationIndicator abstract class BollingerWidthTask(val exchangeManager: ExchangeManager) : DataSourceTask<TimeSeries, PairAndDoubleExtendedParams>() { override fun createDataSource(params: PairAndDoubleExtendedParams): Single<TimeSeries> { return IndicatorsDataSource(exchangeManager, params.currencyPair) .create() .map { it.series } } override fun createParams(paramsRaw: String): PairAndDoubleExtendedParams { return PairAndDoubleExtendedParams(paramsRaw) } override fun verifySuccess(data: TimeSeries, params: PairAndDoubleExtendedParams): Boolean { val closePriceIndicator = ClosePriceIndicator(data) val ema20Indicator = EMAIndicator(closePriceIndicator, 20) val sd20Indicator = StandardDeviationIndicator(closePriceIndicator, 20) val middleBandIndicator = BollingerBandsMiddleIndicator(ema20Indicator) val upBandIndicator = BollingerBandsUpperIndicator(middleBandIndicator, sd20Indicator) val lowBandIndicator = BollingerBandsLowerIndicator(middleBandIndicator, sd20Indicator) val upBand = upBandIndicator.getValue(data.tickCount - 1) val lowBand = lowBandIndicator.getValue(data.tickCount - 1) val width = upBand.minus(lowBand).toDouble() return validateBollingerBandWidth(width, params) } abstract fun validateBollingerBandWidth(width: Double, params: PairAndDoubleExtendedParams): Boolean } class BollingerWidthAboveTask(exchangeManager: ExchangeManager) : BollingerWidthTask(exchangeManager) { override fun validateBollingerBandWidth(width: Double, params: PairAndDoubleExtendedParams): Boolean { val passed = width > params.value println("[${passed.toString().toUpperCase()}] Bollinger width of ${params.currencyPair}: $width > ${params.value}") return passed } override fun match(paramsRaw: String): Boolean { return paramsRaw.startsWith("bollingerwidthabove") } } class BollingerWidthBelowTask(exchangeManager: ExchangeManager) : BollingerWidthTask(exchangeManager) { override fun validateBollingerBandWidth(width: Double, params: PairAndDoubleExtendedParams): Boolean { val passed = width < params.value println("[${passed.toString().toUpperCase()}] Bollinger width of ${params.currencyPair}: $width < ${params.value}") return passed } override fun match(paramsRaw: String): Boolean { return paramsRaw.startsWith("bollingerwidthbelow") } }
1
Kotlin
2
2
9c356b4d4bef556ff6fa86ef3aeaae76689e5178
3,019
console-trader
MIT License
common/src/main/kotlin/toshio/connector/ConnectorScreen.kt
gtosh4
435,545,152
false
null
package toshio.connector import com.mojang.blaze3d.systems.RenderSystem import com.mojang.blaze3d.vertex.PoseStack import net.fabricmc.api.EnvType import net.fabricmc.api.Environment import net.minecraft.client.Minecraft import net.minecraft.client.gui.components.AbstractButton import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen import net.minecraft.core.Direction import net.minecraft.network.chat.Component import net.minecraft.network.chat.TranslatableComponent import net.minecraft.world.entity.player.Inventory import toshio.ToshIO import toshio.gui.Position import toshio.gui.Size import toshio.util.DirectionMap @Environment(EnvType.CLIENT) class ConnectorScreen(menu: ConnectorMenu?, inventory: Inventory?, component: Component?) : AbstractContainerScreen<ConnectorMenu>(menu, inventory, component) { companion object { val texture = ToshIO.id("textures/gui/container/connector.png") val buttonPos = DirectionMap( Position(46, 58), // down Position(27, 18), // up Position(61, 27), // north Position(12, 48), // south Position(8, 27), // west Position(64, 48), // east ) val buttonSize = Size(12, 14) } private val topLeft get() = Position(leftPos, topPos) override fun init() { super.init() buttonPos.forEach { (dir, pos) -> addButton(ConnectorSideButton(menu, dir, pos+topLeft, buttonSize)) } } override fun render(poseStack: PoseStack?, i: Int, j: Int, f: Float) { this.renderBackground(poseStack) super.render(poseStack, i, j, f) this.renderTooltip(poseStack, i, j) } override fun renderBg(poseStack: PoseStack?, f: Float, i: Int, j: Int) { RenderSystem.color4f(1.0f, 1.0f, 1.0f, 1.0f) minecraft!!.textureManager.bind(texture) val k = (width - imageWidth) / 2 val l = (height - imageHeight) / 2 this.blit(poseStack, k, l, 0, 0, imageWidth, imageHeight) } override fun keyPressed(key: Int, b: Int, c: Int): Boolean { if (key == 256) { minecraft?.player?.closeContainer() return true } return super.keyPressed(key, b, c) } } class ConnectorSideButton( private val menu: ConnectorMenu, private val side: Direction, pos: Position, size: Size ) : AbstractButton(pos.x, pos.y, size.w, size.h, TranslatableComponent("gui.toshio.shortdir.${side.getName()}")) { private val selected get() = side == menu.direction override fun renderButton(poseStack: PoseStack?, i: Int, j: Int, f: Float) { if (!visible) return var color = 0xe0e0e0 if (!selected) { color = -0x5f5f60 } else if (isHovered()) { color = 0xffffa0 } super.renderButton(poseStack, i, j, f) drawCenteredString( poseStack, Minecraft.getInstance().font, getText(), x + width / 2, y + (height - 8) / 2, color ) } private fun getText(): Component = TranslatableComponent("gui.toshio.shortdir.${side.getName()}") override fun onPress() { menu.direction = side } override fun renderToolTip(poseStack: PoseStack?, i: Int, j: Int) { side.getName() } }
0
Kotlin
0
0
92c052ac9b8a2f66c5312d2b649f1562785f31d3
3,374
Tosh-IO
MIT License
cccev-f2/certification-f2/cccev-certification-f2-client/src/jsMain/kotlin/cccev/f2/certification/client/certificationClient.kt
komune-io
746,816,569
false
{"Kotlin": 581952, "TypeScript": 94420, "MDX": 92741, "Gherkin": 21405, "Makefile": 5607, "JavaScript": 2459, "HTML": 1853, "Dockerfile": 1787, "CSS": 605}
package cccev.f2.certification.client import f2.client.F2Client import f2.client.ktor.F2ClientBuilder import f2.client.ktor.get import f2.dsl.fnc.F2SupplierSingle import f2.dsl.fnc.f2SupplierSingle import kotlinx.coroutines.await @JsExport actual fun certificationClient(urlBase: String): F2SupplierSingle<CertificationClient> = f2SupplierSingle { F2ClientBuilder.get(urlBase) .await() .let(::CertificationClient) } actual fun F2Client.certificationClient(): F2SupplierSingle<CertificationClient> = f2SupplierSingle { CertificationClient(this) }
0
Kotlin
0
0
8514b98e1d2b55f4611e664116526db3c8ad209f
574
connect-cccev
Apache License 2.0
src/main/kotlin/config/index/stub/ConfigOperationStubImpl.kt
penguinencounter
792,086,846
false
{"Kotlin": 671320, "Java": 128067, "Lex": 24468, "PHP": 15692, "GDScript": 6273, "HTML": 4726, "Python": 3568, "Makefile": 198}
package config.index.stub import com.intellij.psi.stubs.StubBase import com.intellij.psi.stubs.StubElement import config.psi.ConfigOperation import config.psi.impl.GdConfigOperationElementType class ConfigOperationStubImpl : StubBase<ConfigOperation>, ConfigOperationStub { private val operand: String private val leftTyped: String private val rightTyped: String constructor(parent: StubElement<*>?, operand: String, leftTyped: String, rightTyped: String) : super(parent, GdConfigOperationElementType) { this.operand = operand this.leftTyped = leftTyped this.rightTyped = rightTyped } override fun operand(): String = operand override fun leftTyped(): String = leftTyped override fun rightTyped(): String = rightTyped }
0
Kotlin
0
0
662c945adb0ee2cca4e1342a5f684ea3b8d18b75
782
gdscript
MIT License
presentation/src/main/java/org/lotka/xenonx/presentation/screen/home/HomeEvent.kt
armanqanih
840,573,405
false
{"Kotlin": 34354}
package org.lotka.xenonx.presentation.screen.home sealed class HomeEvent { object NavigateToSearchBar : HomeEvent() }
0
Kotlin
0
0
2a9ab5b0d8c94724467abbb464f72c52ba475e85
123
BEER_APP
Apache License 2.0
src/main/kotlin/org/araqnid/kotlin/setawsssocredentials/aws/Response.kt
araqnid
486,956,324
false
{"Kotlin": 78877, "Shell": 392}
package org.araqnid.kotlin.setawsssocredentials.aws external interface ResponseMetadata { /** * The status code of the last HTTP response received for this operation. */ var httpStatusCode: Number? /** * A unique identifier for the last request sent for this operation. Often * requested by AWS service teams to aid in debugging. */ var requestId: String? /** * A secondary identifier for the last request sent. Used for debugging. */ var extendedRequestId: String? /** * A tertiary identifier for the last request sent. Used for debugging. */ var cfId: String? /** * The number of times this operation was attempted. */ var attempts: Number? /** * The total amount of time (in milliseconds) that was spent waiting between * retry attempts. */ var totalRetryDelay: Number? } external interface MetadataBearer { /** * Metadata pertaining to this request. */ @JsName("\$metadata") val metadata: ResponseMetadata }
1
Kotlin
0
1
19b3fce0cd38c922880f70699cac6ee3a83130b5
1,058
set-aws-sso-credentials
Apache License 2.0
src/main/kotlin/org/araqnid/kotlin/setawsssocredentials/aws/Response.kt
araqnid
486,956,324
false
{"Kotlin": 78877, "Shell": 392}
package org.araqnid.kotlin.setawsssocredentials.aws external interface ResponseMetadata { /** * The status code of the last HTTP response received for this operation. */ var httpStatusCode: Number? /** * A unique identifier for the last request sent for this operation. Often * requested by AWS service teams to aid in debugging. */ var requestId: String? /** * A secondary identifier for the last request sent. Used for debugging. */ var extendedRequestId: String? /** * A tertiary identifier for the last request sent. Used for debugging. */ var cfId: String? /** * The number of times this operation was attempted. */ var attempts: Number? /** * The total amount of time (in milliseconds) that was spent waiting between * retry attempts. */ var totalRetryDelay: Number? } external interface MetadataBearer { /** * Metadata pertaining to this request. */ @JsName("\$metadata") val metadata: ResponseMetadata }
1
Kotlin
0
1
19b3fce0cd38c922880f70699cac6ee3a83130b5
1,058
set-aws-sso-credentials
Apache License 2.0
app/src/main/java/com/capstone/Capstone2Project/ui/screen/error/ErrorScreen.kt
JMS1208
594,071,509
false
null
package com.capstone.Capstone2Project.ui.screen.error import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.LocalTextStyle import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.airbnb.lottie.compose.* import com.capstone.Capstone2Project.utils.etc.CustomFont.nexonFont @Composable fun ErrorScreen( message: String? = null ) { val composition by rememberLottieComposition(LottieCompositionSpec.Asset("lottie/error.json")) val progress by animateLottieCompositionAsState(composition, iterations = LottieConstants.IterateForever) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { LottieAnimation( composition = composition, progress = { progress }, ) message?.let { Text( it, style = LocalTextStyle.current.copy( fontFamily = nexonFont, fontSize = 15.sp, color = Color.Gray, fontWeight = FontWeight.Normal ) ) } } }
0
Kotlin
0
0
05b10ab2563d51900fe8276568019103271f5f0e
1,583
IntervuStella
MIT License
src/main/kotlin/wiki/chess/models/AccessToken.kt
dajeo
534,636,103
false
{"Kotlin": 36272, "Dockerfile": 407}
package wiki.chess.models @kotlinx.serialization.Serializable data class AccessToken( val access_token: String, val token_type: String, val expires_in: Long, val refresh_token: String, val scope: String )
0
Kotlin
0
1
f546bc476b8d3ef43b98a970634eb75d116d89b2
226
knight
MIT License
src/main/kotlin/dev/hybridlabs/aquatic/world/biome/surface/HybridAquaticMaterialRules.kt
hybridlabs
661,391,321
false
{"Kotlin": 892890, "Java": 69899}
package dev.hybridlabs.aquatic.world.biome.surface import dev.hybridlabs.aquatic.world.biome.HybridAquaticBiomes import net.minecraft.block.Block import net.minecraft.block.Blocks import net.minecraft.world.gen.surfacebuilder.MaterialRules object HybridAquaticMaterialRules { private val SAND: MaterialRules.MaterialRule = makeStateRule(Blocks.SAND) fun makeRules(): MaterialRules.MaterialRule { val isAtOrAboveWaterLevel: MaterialRules.MaterialCondition = MaterialRules.water(-1, 0) return MaterialRules.sequence( MaterialRules.sequence( MaterialRules.condition(MaterialRules.biome(HybridAquaticBiomes.SARGASSUM_SEA), MaterialRules.condition(MaterialRules.STONE_DEPTH_FLOOR_WITH_SURFACE_DEPTH, SAND)), MaterialRules.condition(MaterialRules.biome(HybridAquaticBiomes.RED_MEADOW), MaterialRules.condition(MaterialRules.STONE_DEPTH_FLOOR_WITH_SURFACE_DEPTH, SAND)), ) ) } private fun makeStateRule(block: Block): MaterialRules.MaterialRule { return MaterialRules.block(block.defaultState) } }
6
Kotlin
0
4
82c3b26d6697d2e5666b173101ade38505a3fe4c
1,144
hybrid-aquatic
MIT License
tabulate-core/src/main/kotlin/io/github/voytech/tabulate/api/builder/exception/BuilderException.kt
voytech
262,033,710
false
null
package io.github.voytech.tabulate.api.builder.exception /** * Build-time validation exception. * @author <NAME> * @since 0.1.0 */ class BuilderException(message: String) : RuntimeException(message)
19
Kotlin
0
2
89e183487938dfa719797d8af30ee299e2db4753
203
tabulate
Apache License 2.0
src/test/kotlin/org/musyozoku/thymeleaf/dialect/ApplicationTests.kt
nosix
76,470,009
false
null
package org.musyozoku.thymeleaf.dialect import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner import org.thymeleaf.TemplateEngine import org.thymeleaf.context.Context import java.io.PrintWriter @RunWith(SpringRunner::class) @SpringBootTest class ApplicationTests { @Autowired lateinit var templateEngine: TemplateEngine @Test fun contextLoads() { Context().run { templateEngine.process("test001", this, PrintWriter(System.out)) } } }
1
Kotlin
0
0
40b2b94669481c37e4bb7dc532ca979d181fb793
659
thymeleaf-dialect
Apache License 2.0
src/main/kotlin/io/kjson/resource/ResourceLoader.kt
pwall567
406,404,133
false
{"Kotlin": 40761}
/* * @(#) ResourceLoader.kt * * resource-loader Resource loading mechanism * Copyright (c) 2023, 2024 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.kjson.resource import java.io.File import java.io.IOException import java.net.HttpURLConnection import java.net.URL import java.net.URLConnection import java.nio.file.FileSystem import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.Instant import io.kjson.util.HTTPHeader import io.kjson.util.Cache /** * The base `ResourceLoader` class. * * @author <NAME> */ abstract class ResourceLoader<T> { private val connectionFilters = mutableListOf<(HttpURLConnection) -> HttpURLConnection?>() open val defaultExtension: String? = null open val defaultMIMEType: String? = null /** * Load the resource, that is, read the external representation of the resource from the `InputStream` in the * [ResourceDescriptor] and return the internal form. */ abstract fun load(rd: ResourceDescriptor): T /** * Get a [Resource], specifying a [File]. */ fun resource(resourceFile: File): Resource<T> = Resource(resourceFile.toPath(), resourceFile.toURI().toURL(), this) /** * Get a [Resource], specifying a [Path]. */ fun resource(resourcePath: Path): Resource<T> = Resource(resourcePath, resourcePath.toUri().toURL(), this) /** * Get a [Resource], specifying a [URL]. */ fun resource(resourceURL: URL): Resource<T> = Resource(derivePath(resourceURL), resourceURL, this) /** * Load the resource identified by the specified [Resource]. This function is open for extension to allow, for * example, caching implementations to provide a returned resource bypassing the regular mechanism. */ open fun load(resource: Resource<T>): T = load(openResource(resource)) /** * Load the resource identified by the specified [URL]. */ fun load(resourceURL: URL): T = load(resource(resourceURL)) /** * Open a [Resource] for reading. This function is open for extension to allow non-standard URLs to be mapped to * actual resources. The result of this function is a [ResourceDescriptor], which contains an open `InputStream` * and all the metadata known about the resource. */ open fun openResource(resource: Resource<T>): ResourceDescriptor { try { resource.resourcePath?.let { path -> if (!Files.exists(path) || Files.isDirectory(path)) throw ResourceNotFoundException(resource.resourceURL) return ResourceDescriptor( inputStream = Files.newInputStream(path), url = resource.resourceURL, size = Files.size(path), time = Files.getLastModifiedTime(path).toInstant(), ) } val conn: URLConnection = resource.resourceURL.openConnection() if (conn is HttpURLConnection) { var httpConn: HttpURLConnection = conn for (filter in connectionFilters) httpConn = filter(httpConn) ?: throw ResourceLoaderException("Connection vetoed - ${resource.resourceURL}") // TODO think about adding support for ifModifiedSince / ETag if (httpConn.responseCode == HttpURLConnection.HTTP_NOT_FOUND) throw ResourceNotFoundException(resource.resourceURL) if (httpConn.responseCode != HttpURLConnection.HTTP_OK) throw IOException("Error status - ${httpConn.responseCode} - ${resource.resourceURL}") val contentLength = httpConn.contentLengthLong.takeIf { it >= 0 } val lastModified = httpConn.lastModified.takeIf { it != 0L }?.let { Instant.ofEpochMilli(it) } val contentTypeHeader = httpConn.contentType?.let { HTTPHeader.create(it) } val charsetName: String? = contentTypeHeader?.element()?.parameter("charset") val mimeType: String? = contentTypeHeader?.firstElementText() return ResourceDescriptor( inputStream = httpConn.inputStream, url = resource.resourceURL, charsetName = charsetName, size = contentLength, time = lastModified, mimeType = mimeType, eTag = httpConn.getHeaderField("etag"), ) } else { return ResourceDescriptor( inputStream = conn.getInputStream(), url = resource.resourceURL, ) } } catch (rle: ResourceLoaderException) { throw rle } catch (e: Exception) { throw ResourceLoaderException("Error opening resource ${resource.resourceURL}", e) } } fun addExtension(s: String): String = when { defaultExtension != null && s.indexOf('.', s.lastIndexOf(File.separatorChar) + 1) < 0 -> "$s.$defaultExtension" else -> s } fun addConnectionFilter(filter: (HttpURLConnection) -> HttpURLConnection?) { connectionFilters.add(filter) } fun addAuthorizationFilter(host: String, headerName: String, headerValue: String?) { addConnectionFilter(AuthorizationFilter(host, headerName, headerValue)) } class AuthorizationFilter( private val host: String, private val headerName: String, private val headerValue: String?, ) : (HttpURLConnection) -> HttpURLConnection? { override fun invoke(httpConn: HttpURLConnection): HttpURLConnection { if (httpConn.url.matchesHost(host)) httpConn.addRequestProperty(headerName, headerValue) return httpConn } } companion object { private val defaultFileSystem = FileSystems.getDefault() private val fileSystemCache = Cache<String, FileSystem> { FileSystems.newFileSystem(Paths.get(it), null as ClassLoader?) } fun derivePath(url: URL): Path? { val uri = url.toURI() return when (uri.scheme) { "jar" -> { val schemeSpecific = uri.schemeSpecificPart var start = schemeSpecific.indexOf(':') // probably stepped past "file:" val bang = schemeSpecific.lastIndexOf('!') if (start < 0 || bang < 0 || start > bang) return null start++ while (start + 2 < bang && schemeSpecific[start] == '/' && schemeSpecific[start + 1] == '/') start++ // implementations vary in their use of multiple slash characters val fs = fileSystemCache[schemeSpecific.substring(start, bang)] fs.getPath(schemeSpecific.substring(bang + 1)) } "file" -> defaultFileSystem.getPath(uri.path) else -> null } } fun URL.matchesHost(target: String): Boolean = if (target.startsWith("*.")) host.endsWith(target.substring(1)) || host == target.substring(2) else host == target } }
0
Kotlin
0
0
017cf351fb6934da624f41388c49d985c888a748
8,432
resource-loader
MIT License
src/main/kotlin/com/example/Game.kt
P1ben
649,408,128
false
null
package com.example import javafx.animation.AnimationTimer import javafx.application.Application import javafx.event.EventHandler import javafx.scene.Group import javafx.scene.Scene import javafx.scene.canvas.Canvas import javafx.scene.canvas.GraphicsContext import javafx.scene.control.Button import javafx.scene.control.Label import javafx.scene.control.TextField import javafx.scene.paint.Color import javafx.scene.text.Font import javafx.stage.Stage import java.io.FileInputStream import java.io.FileOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import kotlin.system.exitProcess class Game : Application() { companion object { private const val WIDTH = 410 private const val HEIGHT = 651 var game_back_interrupt = false } private var graphicsContext: GraphicsContext private lateinit var mainStg : Stage var leaderboard = Leaderboard() var lastScore = 0 lateinit var gw : GameWindow // Menu val menu_content : Group = Group() val menu = Scene(menu_content) // Menu components var menu_btn_start : Button = Button("start") var menu_btn_leaderboard : Button = Button("leaderboard") var menu_btn_back : Button = Button("back") var menu_btn_exit : Button = Button("exit") // Name input scene val name_input_content : Group = Group() val name_input = Scene(name_input_content) // Name input components var name_field : TextField = TextField("Name") var name_submit_btn = Button("submit") var name_submit_score_label = Label("Score: ") var name_submit_canvas = Canvas(WIDTH.toDouble(), HEIGHT.toDouble()) init { // Menu canvas/graphicsContext init val canvas = Canvas(WIDTH.toDouble(), HEIGHT.toDouble()) menu_content.children.add(canvas) graphicsContext = canvas.graphicsContext2D // Trying to read existing leaderboard load_leaderboard() // Menu Start Button init menu_btn_start.apply{ isVisible = true layoutX = 190.0 layoutY = 320.0 onAction = EventHandler { _ -> run { gw = GameWindow() mainStg.scene = Scene(gw) } } } // Menu Leaderboard Button init menu_btn_leaderboard.apply{ isVisible = true layoutX = 170.0 layoutY = 350.0 onAction = EventHandler { _ -> run { this.isVisible = false menu_btn_start.isVisible = false menu_btn_exit.isVisible = false menu_btn_back.isVisible = true graphicsContext.fill = Color.DARKGRAY graphicsContext.fillRect(0.0, 0.0, WIDTH.toDouble(), HEIGHT.toDouble()) load_leaderboard() leaderboard.draw(graphicsContext) } } } // Menu Back Button init menu_btn_back.apply{ isVisible = false layoutX = 190.0 layoutY = 500.0 onAction = EventHandler { _ -> run { menu_btn_start.isVisible = true menu_btn_leaderboard.isVisible = true menu_btn_exit.isVisible = true menu_btn_back.isVisible = false graphicsContext.fill = Color.DARKGRAY graphicsContext.fillRect(0.0, 0.0, WIDTH.toDouble(), HEIGHT.toDouble()) render_menu_text() } } } // Menu exit button init menu_btn_exit.apply{ isVisible = true layoutX = 193.0 layoutY = 380.0 onAction = EventHandler { _ -> run { exitProcess(0) } } } // Name Input Field init name_field.apply{ isVisible = true layoutX = 100.0 layoutY = 300.0 } // Name Input Field Submit Button init name_submit_btn.apply{ layoutX = 260.0 layoutY = 300.0 onAction = EventHandler { _ -> run { if (!name_field.text.equals("")) { leaderboard.add(name_field.text, lastScore) save_leaderboard() } mainStg.scene = menu } } } // Submit Score Label init name_submit_score_label.apply{ layoutX = 100.0 layoutY = 250.0 } // Adding objects to menu menu_content.apply{ children.add(menu_btn_start) children.add(menu_btn_back) children.add(menu_btn_leaderboard) children.add(menu_btn_exit) } // Adding objects to Name Input screen name_input_content.apply{ children.add(name_submit_canvas) children.add(name_field) children.add(name_submit_btn) children.add(name_submit_score_label) } } // Drawing "TETRIS" Title in menu fun render_menu_text(){ graphicsContext.apply{ fill = Color.GRAY font = Font.font("Comic Sans MS", 100.0) fillText("TETRIS", 12.0, 150.0) font = Font.font("Arial", 12.0) } } // JavaFX init override fun start(mainStage: Stage) { // Window init mainStage.title = "Tetris" mainStg = mainStage mainStage.scene = menu // Main loop for signal handling object : AnimationTimer() { override fun handle(currentNanoTime: Long) { tick() } }.start() // Clearing menu canvas, then rendering menu text graphicsContext.fill = Color.DARKGRAY graphicsContext.fillRect(0.0, 0.0, WIDTH.toDouble(), HEIGHT.toDouble()) render_menu_text() mainStage.show() } private fun tick() { // Waits for end signal from game if(game_back_interrupt){ game_back_interrupt = false lastScore = gw.board.score println("Score: $lastScore") // If the score is not 0, name input is required if (lastScore == 0){ mainStg.scene = menu } else { mainStg.scene = name_input name_submit_canvas.graphicsContext2D.apply{ fill = Color.WHITE fillRect(100.0, 250.0, 400.0, 50.0) fill = Color.BLACK fillText(lastScore.toString(), 150.0, 263.0) fill = Color.WHITE } } } } // Trying to save leaderboard private fun save_leaderboard() { try { val fileOut = FileOutputStream("leaderboard.ser") val out = ObjectOutputStream(fileOut) out.writeObject(leaderboard) out.close() fileOut.close() println("Score saved") } catch(e:Exception){ println("Couldn't save leaderboard") } } // Trying to load an existing leaderboard fun load_leaderboard(){ try { val fileIn = FileInputStream("leaderboard.ser") val input = ObjectInputStream(fileIn) leaderboard = input.readObject() as Leaderboard input.close() fileIn.close() println("Leaderboard loaded succesfully") } catch(e: Exception){ println("Couldn't load leaderboard") } } }
0
Kotlin
0
0
41bf7f9a62cc3cd1c1cf7070207a090b7c98cd20
7,743
Tetris-Kotlin
MIT License
src/main/kotlin/com/muedsa/snapshot/widget/ClipRect.kt
muedsa
736,941,747
false
{"Kotlin": 319488}
package com.muedsa.snapshot.widget import com.muedsa.geometry.Size import com.muedsa.snapshot.rendering.ClipBehavior import com.muedsa.snapshot.rendering.box.RenderBox import com.muedsa.snapshot.rendering.box.RenderClipRect import org.jetbrains.skia.Rect class ClipRect( val clipper: ((Size) -> Rect)? = null, val clipBehavior: ClipBehavior = ClipBehavior.HARD_EDGE, childBuilder: SingleWidgetBuilder? = null, ) : SingleChildWidget(childBuilder = childBuilder) { override fun createRenderTree(): RenderBox = RenderClipRect( clipper = clipper, clipBehavior = clipBehavior, child = child?.createRenderBox() ) }
0
Kotlin
0
0
f05f6d568a6095e61be42de8c2937e9b45fd772f
655
snapshot
MIT License
core/src/main/java/com/s_h_y_a/kotlindatastore/KotlinDataStore.kt
S-H-Y-A
454,439,254
false
null
package com.s_h_y_a.kotlindatastore import android.annotation.SuppressLint import android.content.Context @SuppressLint("StaticFieldLeak") object KotlinDataStore { private var mStaticContext: Context? = null internal var staticContext: Context get() = mStaticContext ?: throw IllegalStateException("KotlinDataStore has not been initialized.") set(value) { mStaticContext = value } val isInitialized get() = mStaticContext != null fun init(context: Context) { staticContext = context } }
0
Kotlin
0
4
575a5f5b604de0a6f86a08b0ade33bac2fd7b0b4
576
KotlinDataStore
Apache License 2.0
app/src/main/java/com/halilkrkn/finderecipe/domain/model/similar_recipe/SimilarRecipe.kt
halilkrkn
808,027,185
false
{"Kotlin": 324108}
package com.halilkrkn.finderecipe.domain.model.similar_recipe data class SimilarRecipe( val id: Int, val imageType: String, val readyInMinutes: Int, val servings: Int, val sourceUrl: String, val title: String )
0
Kotlin
0
0
2a22bbe8c63b42cd5ae614227fa0a9b6e8746913
235
FindeRecipe
MIT License
app/src/main/java/com/lpirro/tiledemo/RxBus.kt
amitkumar0000
343,741,379
false
null
package com.lpirro.tiledemo import android.util.Log import com.lpirro.tiledemo.customquicksettings.NotificationModel import com.lpirro.tiledemo.customquicksettings.QuickSettingModel import io.reactivex.Observable import io.reactivex.subjects.PublishSubject object RxBus { private val subject = PublishSubject.create<Message>() private val notificationSubject = PublishSubject.create<NotificationModel>() fun publish(model: Message) { subject.onNext(model) } fun listen(): Observable<Message> { return subject.hide() } fun publishNotification(model: NotificationModel) { notificationSubject.onNext(model) } fun listenNotification(): PublishSubject<NotificationModel> { return notificationSubject } } sealed class Message object CloseQuickSetting: Message() object ClearAllNotification: Message() data class ConfigSetting(val set: List<QuickSettingModel.TilesModel>): Message()
0
Kotlin
0
0
cc99d7b4f912807239c82c958e7e8aadc2a9637a
955
tiles
Apache License 2.0
cli/src/main/kotlin/com/gradleup/librarian/cli/CreateCommand.kt
GradleUp
808,333,288
false
{"Kotlin": 69473, "JavaScript": 1026}
package com.gradleup.librarian.cli import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.arguments.argument import com.github.kinquirer.KInquirer import com.github.kinquirer.components.promptConfirm import com.github.kinquirer.components.promptInput import com.github.kinquirer.components.promptList import com.nfeld.jsonpathkt.kotlinx.resolvePathAsStringOrNull import kotlinx.serialization.json.Json import okhttp3.OkHttpClient import okhttp3.Request import java.io.File import java.nio.file.Files import java.nio.file.attribute.PosixFilePermissions internal class CreateCommand : CliktCommand() { private val directory by argument() override fun run() { with(File(directory)) { check(!exists()) { "'$directory' already exists" } val repositoryName = KInquirer.promptInput(message = "GitHub repository name", File(directory).canonicalFile.name) val orgs = getAvailableOrganizations() val repositoryOwner = KInquirer.promptList(message = "GitHub repository owner", orgs) val developer = "$repositoryName authors" val groupId = KInquirer.promptInput("Maven group id", "io.github.$repositoryOwner.$repositoryName") val sonatypeHost = KInquirer.promptList("Sonatype host", listOf("Default", "S01")) val moduleName = KInquirer.promptInput("Module name", "module") val javaCompatibility = 8 val kotlinCompatibility = "2.0.0" val license = SupportedLicenses.MIT mkdirs() file("librarian.properties").writeText(""" java.compatibility=$javaCompatibility kotlin.compatibility=$kotlinCompatibility kdoc.olderVersions= kdoc.artifactId=kdoc sonatype.host=$sonatypeHost git.snapshots=main pom.groupId=$groupId pom.version=0.0.1-SNAPSHOT pom.description=$repositoryName pom.vcsUrl=https://github.com/$repositoryOwner/$repositoryName pom.developer=$developer pom.license=${license.fullName} pom.licenseUrl=https://raw.githubusercontent.com/$repositoryOwner/$repositoryName/main/LICENSE """.trimIndent() ) copyResource(license.name, "LICENSE") copyResource("gitignore", ".gitignore") copyResource("CHANGELOG.md") copyResource("gradle.properties") copyResource("codeStyles/codeStyleConfig.xml", ".idea/codeStyles/codeStyleConfig.xml") copyResource("codeStyles/Project.xml", ".idea/codeStyles/Project.xml") copyResource("actions/check-pull-request.yaml", ".github/workflows/check-pull-request.yaml") copyResource("actions/prepare-release.yaml", ".github/workflows/prepare-release.yaml") copyResource("actions/publish-release.yaml", ".github/workflows/publish-release.yaml") copyResource("actions/publish-snapshot.yaml", ".github/workflows/publish-snapshot.yaml") /** * copied from https://github.com/spring-io/initializr/tree/fbbbe6734e55b4f6393624985c06161b16c9fe8f/initializr-generator-spring/src/main/resources/gradle/8 * TODO: download latest version automatically */ copyResource("gradlew", "gradlew", true) copyResource("gradlew.bat", "gradlew.bat", true) copyResource("gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.jar") copyResource("gradle/wrapper/gradle-wrapper.properties", "gradle/wrapper/gradle-wrapper.properties") file("gradle").mkdirs() file("gradle/gradle-wrapper.properties").writeText(""" distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-${latestGradleRelease()}-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists """.trimIndent() ) file("gradle/libs.versions.toml").writeText("[libraries]", false) file("build.gradle.kts").writeText(""" import com.gradleup.librarian.core.librarianRoot plugins { id("org.jetbrains.kotlin.jvm").version("${latestKotlinRelease()}").apply(false) id("com.gradleup.librarian").version("${latestLibrarianRelease()}").apply(false) } librarianRoot() """.trimIndent(), overwrite = false ) file(moduleName).let { moduleDir -> moduleDir.mkdirs() moduleDir.resolve("build.gradle.kts").writeText(""" import com.gradleup.librarian.core.librarianModule plugins { id("org.jetbrains.kotlin.jvm") } librarianModule() """.trimIndent() ) moduleDir.resolve("README.md").writeText(""" # Module $moduleName """.trimIndent() ) } file("settings.gradle.kts").writeText(""" pluginManagement { listOf(repositories, dependencyResolutionManagement.repositories).forEach { it.apply { mavenCentral() google() } } } include(":$moduleName") """.trimIndent(), false ) runCommand("git", "init") runCommand("git", "add", ".") runCommand("git", "commit", "-a", "-m", "initial commit") val upload = KInquirer.promptConfirm("Upload your project to GitHub at $repositoryOwner/$repositoryName and make it public?", default = true) if (upload) { runCommand("gh", "repo", "create", "--public", "-s", ".", "--push") setupGitHub() } else { println("run 'librarian setup-github' to finish configuration") } } } } private fun getAvailableOrganizations(): List<String> { return with(File(".")) { var result = runCommandAndCaptureStdout("gh", "api", "user", "--jq", ".login") check(result.code == 0) { "Cannot run 'gh api user', make sure you have 'gh' installed. See https://cli.github.com/." } val username = result.stdout.trim() result = runCommandAndCaptureStdout("gh", "org", "list") check(result.code == 0) { "Cannot run 'gh org list', make sure you have 'gh' installed. See https://cli.github.com/." } listOf(username) + result.stdout.lines().filter { it.isNotBlank() && !it.startsWith("Showing ") } } } private fun File.writeText(text: String, overwrite: Boolean) { if (exists() && !overwrite) { return } writeText(text) } private fun latestLibrarianRelease(): String = latestTag("GradleUp", "librarian").substring(1) // drop the v private fun latestKotlinRelease(): String = latestTag("JetBrains", "kotlin").substring(1) // drop the v private fun latestGradleRelease(): String = latestTag("gradle", "gradle").toGradleRelease() private fun latestTag(owner: String, name: String): String { return Request.Builder() .get() .url("https://api.github.com/repos/$owner/$name/releases") .build() .let { OkHttpClient().newCall(it).execute() }.let { check(it.isSuccessful) { "Cannot get ${it.request.url} (${it.code}): ${it.body?.string()}" } Json.parseToJsonElement(it.body!!.string()) }.let { it.resolvePathAsStringOrNull("$[0].tag_name") ?: "Cannot locate tag_name in response: $it" } } private fun String.toGradleRelease(): String { // tag names look like v8.7.0-RC3 return Regex("v([0-9]*.[0-9]*).[0-9]*(.*)").matchEntire(this).let { check(it != null) { "Unexpected tag: '$this" } "${it.groupValues.get(1)}${it.groupValues.get(2).lowercase()}" } } private fun File.copyResource(resourceName: String) { copyResource(resourceName, resourceName) } private fun File.file(path: String): File = resolve(path) private fun File.copyResource(resourceName: String, destinationPath: String, makeExecutable: Boolean = false) { val stream = CreateCommand::class.java.classLoader.getResourceAsStream(resourceName) require(stream != null) { "Cannot open resource '$resourceName'" } stream.buffered().use { inputStream -> file(destinationPath).let { it.parentFile?.mkdirs() it.outputStream().use { outputStream -> inputStream.copyTo(outputStream) } } } if (makeExecutable) { Files.setPosixFilePermissions( file(destinationPath).toPath(), PosixFilePermissions.fromString("rwxr-xr-x") ) } } // See https://spdx.org/licenses/ enum class SupportedLicenses(val fullName: String) { MIT("MIT License") }
4
Kotlin
0
0
3ab6fe21b18da7a56acf3680926cf3057a0469ca
8,451
librarian
MIT License
app/src/main/java/com/ldf/wanandroidcompose/ui/home/ArticleItem.kt
yihu5566
646,021,523
false
null
package com.ldf.wanandroidcompose.ui.home import android.widget.TextView import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.text.TextStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.core.text.HtmlCompat import com.blankj.utilcode.util.ToastUtils import com.ldf.wanandroidcompose.base.App import com.ldf.wanandroidcompose.data.bean.Article import com.ldf.wanandroidcompose.data.bean.Tag import com.ldf.wanandroidcompose.ui.viewmodel.CollectViewModel import com.ldf.wanandroidcompose.ui.widget.CollectCompose /** * @Author : dongfang * @Created Time : 2023-06-05 15:55 * @Description: */ @Preview @Composable fun PreviewArticleItem() { ArticleItem( Article( niceDate = "2020-2-2 20:00", tags = listOf(Tag("kk", "")), fresh = true, author = "yihu", type = 1, title = "oooooo", superChapterName = "d", chapterName = "fff", collect = true ) ) } @Composable fun ArticleItem( itemBean: Article, viewModel: CollectViewModel? = null, onClick: () -> Unit = {}, ) { var collectState by remember { mutableStateOf(itemBean.collect) } Column( modifier = Modifier .fillMaxWidth() .padding(10.dp) .background(color = MaterialTheme.colors.background) .clickable(onClick = onClick) ) { Row(verticalAlignment = Alignment.CenterVertically) { if (itemBean.author.isNotEmpty()) { Text( text = itemBean.author, modifier = Modifier .padding(5.dp), ) } if (itemBean.type == 1) { Text( text = "置顶", modifier = Modifier .border(width = 1.dp, color = Color.Red, shape = RoundedCornerShape(10)) .padding(end = 3.dp, start = 3.dp), style = TextStyle(color = Color.Red) ) } Spacer(modifier = Modifier.width(width = 10.dp)) if (itemBean.fresh) { Text( text = "新", modifier = Modifier .border(width = 1.dp, color = Color.Red, shape = RoundedCornerShape(10)) .padding(end = 3.dp, start = 3.dp), style = TextStyle(color = Color.Red) ) } if (itemBean.tags.isNotEmpty()) { Text( text = itemBean.tags[0].name, modifier = Modifier .padding(5.dp), ) } Spacer(modifier = Modifier.weight(1f, true)) Text( text = itemBean.niceDate, modifier = Modifier.padding(5.dp), style = MaterialTheme.typography.h6.copy(color = Color.Gray, fontSize = 10.sp) ) } var textColor = MaterialTheme.colors.onSecondary.toArgb() AndroidView( factory = { context -> TextView(context) }, update = { it.text = HtmlCompat.fromHtml(itemBean.title, HtmlCompat.FROM_HTML_MODE_COMPACT) it.setTextColor(textColor) } ) Spacer(modifier = Modifier.height(height = 10.dp)) Row(verticalAlignment = Alignment.CenterVertically) { AndroidView( factory = { context -> TextView(context) }, update = { it.text = HtmlCompat.fromHtml( itemBean.superChapterName + '·' + itemBean.chapterName, HtmlCompat.FROM_HTML_MODE_COMPACT ) it.setTextColor(textColor) } ) Spacer(modifier = Modifier.weight(weight = 1f, true)) CollectCompose(collectState) { if (App.appViewModel.userEvent.value == null) { ToastUtils.showLong("请先登录") return@CollectCompose } if (collectState) { viewModel?.unCollectArticle(itemBean.id) } else { viewModel?.collectArticle(itemBean.id) } collectState = !collectState } } } }
0
Kotlin
0
1
a3e456565303179ae0293e75a6800239d68492e4
5,504
WanAndroidCompose
Apache License 2.0
light/src/test/kotlin/net/kotlinx/aws/module/batchStep/stepDefault/BatchStepDefaultRunnerTest.kt
mypojo
565,799,715
false
{"Kotlin": 1126686, "Java": 9531, "Jupyter Notebook": 7080}
package net.kotlinx.aws.module.batchStep.stepDefault import net.kotlinx.aws.module.batchStep.BatchStepInput import net.kotlinx.aws.module.batchStep.BatchStepListOption import net.kotlinx.aws.module.batchStep.BatchStepMode import net.kotlinx.json.gson.GsonData import net.kotlinx.json.gson.toGsonData import net.kotlinx.koin.Koins.koinLazy import net.kotlinx.kotest.KotestUtil import net.kotlinx.kotest.initTest import net.kotlinx.kotest.modules.BeSpecLight import net.kotlinx.reflect.name class BatchStepDefaultRunnerTest : BeSpecLight() { init { initTest(KotestUtil.IGNORE) Given("BatchStepDefaultRunner") { val runner by koinLazy<BatchStepDefaultRunner>() Then("StepStart 테스트") { val input = BatchStepInput(StepStart::class.name()) { jobPk = "batchStepTest" jobSk = "aaa" sfnId = "7dde7369-4d9f-4dd9-a8f2-756d3cfd28ee" listOption = BatchStepListOption { waitSeconds = 12 } mode = BatchStepMode.MAP_INLINE } val result = runner.invoke(input.toJson().toGsonData(), null)!! println(GsonData.parse(result).toPreety()) } Then("StepEnd 테스트") { val input = BatchStepInput(StepEnd::class.name()) { jobPk = "batchStepTest" jobSk = "aaa" sfnId = "7dde7369-4d9f-4dd9-a8f2-756d3cfd28ee" listOption = BatchStepListOption { waitSeconds = 12 } } val result = runner.invoke(input.toJson().toGsonData(), null)!! println(result) println(GsonData.parse(result).toPreety()) } } } }
0
Kotlin
0
1
419243ce3f60a15e78a36cb55c5c502e0c1800c8
1,879
kx_kotlin_support
MIT License
app/src/main/java/com/kenilt/skeleton/managers/listeners/EndlessRecyclerOnScrollListener.kt
kenilt
247,617,328
false
null
package com.kenilt.skeleton.managers.listeners import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView /** * Created by thangnguyen on 3/13/18. */ abstract class EndlessRecyclerOnScrollListener : RecyclerView.OnScrollListener { // The minimum amount of items to have below your current scroll position before isLoading more. var visibleThreshold = 8 var previousTotal = 0 // The total number of items in the dataset after the last load var isLoading = true // True if we are still waiting for the last set of data to load. var isEnded = false var isScrollFired = false private var currentPage = 1 private val layoutManager: RecyclerView.LayoutManager constructor(layoutManager: RecyclerView.LayoutManager) { this.layoutManager = layoutManager } constructor(layoutManager: RecyclerView.LayoutManager, startPage: Int): this(layoutManager) { this.currentPage = startPage } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) isScrollFired = true val visibleItemCount = recyclerView.childCount val totalItemCount = layoutManager.itemCount val firstVisibleItem = getFirstVisiblePosition() if (isLoading) { if (totalItemCount > previousTotal) { isLoading = false previousTotal = totalItemCount } } if (!isEnded && !isLoading && totalItemCount - visibleItemCount <= firstVisibleItem + visibleThreshold) { // End has been reached // Do something currentPage++ onLoadMore(currentPage, totalItemCount) isLoading = true } } fun getFirstVisiblePosition(): Int { if (layoutManager is LinearLayoutManager) { return layoutManager.findFirstVisibleItemPosition() } else if (layoutManager is GridLayoutManager) { return layoutManager.findFirstVisibleItemPosition() } return 0 } fun reset() { isScrollFired = false previousTotal = 0 isLoading = true isEnded = false currentPage = 1 } abstract fun onLoadMore(page: Int, totalItemCount: Int) }
0
Kotlin
0
0
9d5f445839d9741f4df5aa8cdfc46dfedada6b9b
2,378
Android-Skeleton-Project
MIT License
app/src/main/java/com/billsv/facturaelectronica/DataAPI.kt
diseno2024
768,327,103
false
{"Kotlin": 530432, "Java": 4941}
package com.billsv.facturaelectronica data class AuthRequest(val user: String, val pwd: String) data class AuthResponse( val status: String, val body: AuthBody? ) data class AuthBody( val user: String, val token: String, val rol: Rol, val roles: List<String>, val tokenType: String ) data class Rol( val nombre: String, val codigo: String, val descripcion: String?, val rolSuperior: String?, val nivel: Int?, val activo: Boolean?, val permisos: List<String>? ) data class ErrorResponse( val status: String, val error: String, val message: String )
1
Kotlin
1
0
56777f677b0f2033921517b7a829af1f2380648c
620
facturaelectronica
Apache License 2.0
dslk_anko/src/main/java/com/mozhimen/dslk/anko/core/commons/Ui.kt
mozhimen
851,115,225
false
{"Kotlin": 160097}
package com.mozhimen.dslk.anko.core.commons import android.content.Context import android.view.View import androidx.lifecycle.LifecycleOwner /** * @ClassName Ui * @Description TODO * @Author mozhimen * @Date 2024/9/2 * @Version 1.0 */ interface Ui { val ctx: Context val root: View }
0
Kotlin
0
0
a1d8038de852e0c648ce95407f6ada398c35c633
299
ADslKit
Apache License 2.0
app/src/main/java/com/github/cirorizzo/kshows/view/MainActivity.kt
cirorizzo
52,459,755
false
null
package com.github.cirorizzo.kshows.view import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.GridLayoutManager import com.github.cirorizzo.kshows.KShowsApplication import com.github.cirorizzo.kshows.R import com.github.cirorizzo.kshows.presenter.MasterPresenterImpl import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private val imagesAdapterImpl: ImagesAdapterImpl by lazy { ImagesAdapterImpl() } private val masterPresenterImpl: MasterPresenterImpl by lazy { (application as KShowsApplication).masterPresenterInject.masterPresenterImpl } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initRecyclerView() connectingToMasterPresenter() getURLs() } override fun onDestroy() { imagesAdapterImpl.unsubscribe() super.onDestroy() } private fun initRecyclerView() { containerRecyclerView.layoutManager = GridLayoutManager(this, 1) containerRecyclerView.adapter = imagesAdapterImpl } private fun connectingToMasterPresenter() { masterPresenterImpl.connect(imagesAdapterImpl) } private fun getURLs() { masterPresenterImpl.getMasterRequest() } }
0
null
4
16
6dd7a4e3ed87a667de588bd900377572cddaa21b
1,401
KShows
Apache License 2.0
carp.protocols.core/src/commonMain/kotlin/dk/cachet/carp/protocols/domain/devices/DeviceRegistration.kt
cortinico
333,548,384
true
{"Kotlin": 877308, "TypeScript": 30334}
package dk.cachet.carp.protocols.domain.devices import dk.cachet.carp.common.DateTime import dk.cachet.carp.common.Immutable import dk.cachet.carp.common.ImplementAsDataClass import dk.cachet.carp.common.serialization.NotSerializable import dk.cachet.carp.protocols.domain.StudyProtocol import kotlinx.serialization.Polymorphic import kotlinx.serialization.Serializable /** * A [DeviceRegistration] configures a [DeviceDescriptor] as part of the deployment of a [StudyProtocol]. */ @Serializable @Polymorphic @Immutable @ImplementAsDataClass abstract class DeviceRegistration { /** * An ID for the device, used to disambiguate between devices of the same type, as provided by the device itself. * It is up to specific types of devices to guarantee uniqueness across all devices of the same type. * * TODO: This might be useful for potential optimizations later (e.g., prevent pulling in data from the same source more than once), but for now is ignored. */ abstract val deviceId: String val registrationCreationDate: DateTime = DateTime.now() } /** * A helper class to configure and construct immutable [DeviceRegistration] classes. * * TODO: This and extending classes are never expected to be serialized, * but need to be [Serializable] since they are specified as generic type parameter on [DeviceDescriptor]. */ @Serializable( NotSerializable::class ) @DeviceRegistrationBuilderDsl interface DeviceRegistrationBuilder<T : DeviceRegistration> { /** * Build the immutable [DeviceRegistration] using the current configuration of this [DeviceRegistrationBuilder]. */ fun build(): T } /** * Should be applied to all builders participating in building [DeviceRegistration]s to prevent misuse of internal DSL. * For more information: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-dsl-marker/index.html */ @DslMarker annotation class DeviceRegistrationBuilderDsl
7
null
0
0
9ed082ee919066a0e4774863cf7ecc3b6d00daf1
1,944
carp.core-kotlin
MIT License
eupidcredential/src/commonTest/kotlin/at/asitplus/wallet/eupid/SerializerRegistrationTest.kt
a-sit-plus
771,032,012
false
{"Kotlin": 24103}
package at.asitplus.wallet.eupid import at.asitplus.signum.indispensable.cosef.CoseHeader import at.asitplus.signum.indispensable.cosef.CoseSigned import at.asitplus.signum.indispensable.cosef.io.ByteStringWrapper import at.asitplus.wallet.eupid.EuPidScheme.Attributes.ADMINISTRATIVE_NUMBER import at.asitplus.wallet.lib.iso.IssuerSignedItem import at.asitplus.wallet.eupid.EuPidScheme.Attributes.BIRTH_DATE import at.asitplus.wallet.eupid.EuPidScheme.Attributes.AGE_IN_YEARS import at.asitplus.wallet.eupid.EuPidScheme.Attributes.AGE_BIRTH_YEAR import at.asitplus.wallet.eupid.EuPidScheme.Attributes.AGE_OVER_18 import at.asitplus.wallet.eupid.EuPidScheme.Attributes.BIRTH_CITY import at.asitplus.wallet.eupid.EuPidScheme.Attributes.BIRTH_COUNTRY import at.asitplus.wallet.eupid.EuPidScheme.Attributes.BIRTH_PLACE import at.asitplus.wallet.eupid.EuPidScheme.Attributes.BIRTH_STATE import at.asitplus.wallet.eupid.EuPidScheme.Attributes.DOCUMENT_NUMBER import at.asitplus.wallet.eupid.EuPidScheme.Attributes.GENDER import at.asitplus.wallet.eupid.EuPidScheme.Attributes.ISSUANCE_DATE import at.asitplus.wallet.eupid.EuPidScheme.Attributes.EXPIRY_DATE import at.asitplus.wallet.eupid.EuPidScheme.Attributes.FAMILY_NAME import at.asitplus.wallet.eupid.EuPidScheme.Attributes.FAMILY_NAME_BIRTH import at.asitplus.wallet.eupid.EuPidScheme.Attributes.GIVEN_NAME import at.asitplus.wallet.eupid.EuPidScheme.Attributes.GIVEN_NAME_BIRTH import at.asitplus.wallet.eupid.EuPidScheme.Attributes.ISSUING_AUTHORITY import at.asitplus.wallet.eupid.EuPidScheme.Attributes.ISSUING_COUNTRY import at.asitplus.wallet.eupid.EuPidScheme.Attributes.ISSUING_JURISDICTION import at.asitplus.wallet.eupid.EuPidScheme.Attributes.NATIONALITY import at.asitplus.wallet.eupid.EuPidScheme.Attributes.RESIDENT_ADDRESS import at.asitplus.wallet.eupid.EuPidScheme.Attributes.RESIDENT_CITY import at.asitplus.wallet.eupid.EuPidScheme.Attributes.RESIDENT_COUNTRY import at.asitplus.wallet.eupid.EuPidScheme.Attributes.RESIDENT_HOUSE_NUMBER import at.asitplus.wallet.eupid.EuPidScheme.Attributes.RESIDENT_POSTAL_CODE import at.asitplus.wallet.eupid.EuPidScheme.Attributes.RESIDENT_STATE import at.asitplus.wallet.eupid.EuPidScheme.Attributes.RESIDENT_STREET import at.asitplus.wallet.lib.agent.SubjectCredentialStore import at.asitplus.wallet.lib.data.CredentialToJsonConverter import at.asitplus.wallet.lib.iso.IssuerSigned import io.kotest.assertions.withClue import io.kotest.core.spec.style.FreeSpec import io.kotest.datatest.withData import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import kotlinx.datetime.Instant import kotlinx.datetime.LocalDate import kotlinx.serialization.json.JsonObject import kotlin.random.Random import kotlin.random.nextUInt class SerializerRegistrationTest : FreeSpec({ "Serialization and deserialization" - { withData(nameFn = { "for ${it.key}" }, dataMap().entries) { val item = it.toIssuerSignedItem() val serialized = item.serialize(EuPidScheme.isoNamespace) val deserialized = IssuerSignedItem.deserialize(serialized, EuPidScheme.isoNamespace).getOrThrow() deserialized.elementValue shouldBe it.value } } "Serialization to JSON Element" { val claims = dataMap() val namespacedItems: Map<String, List<IssuerSignedItem>> = mapOf(EuPidScheme.isoNamespace to claims.map { it.toIssuerSignedItem() }.toList()) val issuerAuth = CoseSigned(ByteStringWrapper(CoseHeader()), null, null, byteArrayOf()) val credential = SubjectCredentialStore.StoreEntry.Iso( IssuerSigned.fromIssuerSignedItems(namespacedItems, issuerAuth), EuPidScheme ) val converted = CredentialToJsonConverter.toJsonElement(credential) .shouldBeInstanceOf<JsonObject>() .also { println(it) } val jsonMap = converted[EuPidScheme.isoNamespace] .shouldBeInstanceOf<JsonObject>() claims.forEach { withClue("Serialization for ${it.key}") { jsonMap[it.key].shouldNotBeNull() } } } }) private fun Map.Entry<String, Any>.toIssuerSignedItem() = IssuerSignedItem(Random.nextUInt(), Random.nextBytes(32), key, value) private fun dataMap(): Map<String, Any> = mapOf( FAMILY_NAME to randomString(), GIVEN_NAME to randomString(), BIRTH_DATE to randomLocalDate(), AGE_OVER_18 to Random.nextBoolean(), AGE_IN_YEARS to Random.nextUInt(1u, 99u), AGE_BIRTH_YEAR to Random.nextUInt(1900u, 2100u), FAMILY_NAME_BIRTH to randomString(), GIVEN_NAME_BIRTH to randomString(), BIRTH_PLACE to randomString(), BIRTH_COUNTRY to randomString(), BIRTH_STATE to randomString(), BIRTH_CITY to randomString(), RESIDENT_ADDRESS to randomString(), RESIDENT_COUNTRY to randomString(), RESIDENT_STATE to randomString(), RESIDENT_CITY to randomString(), RESIDENT_POSTAL_CODE to randomString(), RESIDENT_STREET to randomString(), RESIDENT_HOUSE_NUMBER to randomString(), GENDER to IsoIec5218Gender.NOT_APPLICABLE, NATIONALITY to randomString(), ISSUANCE_DATE to randomInstant(), EXPIRY_DATE to randomInstant(), ISSUING_AUTHORITY to randomString(), DOCUMENT_NUMBER to randomString(), ADMINISTRATIVE_NUMBER to randomString(), ISSUING_COUNTRY to randomString(), ISSUING_JURISDICTION to randomString(), ) private fun randomLocalDate() = LocalDate(Random.nextInt(1900, 2100), Random.nextInt(1, 12), Random.nextInt(1, 28)) private fun randomInstant() = Instant.fromEpochSeconds(Random.nextLong(1000L, 3000L))
0
Kotlin
0
1
62f11a4e4eb4690f77aa65a3166da1fd9c42cdf3
5,821
eu-pid-credential
Apache License 2.0
src/commonMain/kotlin/data/items/ReaverOfTheInfinites.kt
marisa-ashkandi
332,658,265
false
null
package `data`.items import `data`.Constants import `data`.buffs.Buffs import `data`.model.Color import `data`.model.Item import `data`.model.ItemSet import `data`.model.Socket import `data`.model.SocketBonus import `data`.socketbonus.SocketBonuses import character.Buff import character.Stats import kotlin.Array import kotlin.Boolean import kotlin.Double import kotlin.Int import kotlin.String import kotlin.collections.List import kotlin.js.JsExport @JsExport public class ReaverOfTheInfinites : Item() { public override var isAutoGenerated: Boolean = true public override var id: Int = 28222 public override var name: String = "Reaver of the Infinites" public override var itemLevel: Int = 115 public override var quality: Int = 3 public override var icon: String = "inv_axe_71.jpg" public override var inventorySlot: Int = 17 public override var itemSet: ItemSet? = null public override var itemClass: Constants.ItemClass? = Constants.ItemClass.WEAPON public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.AXE_2H public override var allowableClasses: Array<Constants.AllowableClass>? = null public override var minDmg: Double = 268.0 public override var maxDmg: Double = 403.0 public override var speed: Double = 3600.0 public override var stats: Stats = Stats( stamina = 22, resilienceRating = 27.0 ) public override var sockets: Array<Socket> = arrayOf( Socket(Color.RED), Socket(Color.YELLOW), Socket(Color.BLUE) ) public override var socketBonus: SocketBonus? = SocketBonuses.byId(2878) public override var phase: Int = 1 public override val buffs: List<Buff> by lazy { listOfNotNull( Buffs.byIdOrName(14056, "Attack Power 50", this) )} }
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
1,802
tbcsim
MIT License
src/main/kotlin/graphql/Scalars.kt
LarsKrogJensen
78,951,235
false
null
package graphql import graphql.language.BooleanValue import graphql.language.FloatValue import graphql.language.IntValue import graphql.language.StringValue import graphql.schema.Coercing import graphql.schema.GraphQLNonNull import graphql.schema.GraphQLScalarType import java.math.BigDecimal import java.math.BigInteger import java.text.SimpleDateFormat import java.util.* private val LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE) private val LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE) private val INT_MAX = BigInteger.valueOf(Int.MAX_VALUE.toLong()) private val INT_MIN = BigInteger.valueOf(Int.MIN_VALUE.toLong()) private val BYTE_MAX = BigInteger.valueOf(Byte.MAX_VALUE.toLong()) private val BYTE_MIN = BigInteger.valueOf(Byte.MIN_VALUE.toLong()) private val SHORT_MAX = BigInteger.valueOf(Short.MAX_VALUE.toLong()) private val SHORT_MIN = BigInteger.valueOf(Short.MIN_VALUE.toLong()) private fun isWholeNumber(input: Any?) = input is Long || input is Int || input is Short || input is Byte // true if its a number or string that we will attempt to convert to a number via toNumber() private fun isNumberIsh(input: Any?): Boolean = input is Number || input is String private fun toNumber(input: Any?) = when (input) { is Number -> input is String -> input.toDouble() // Use double as a intermediate Number representation else -> throw AssertException("Unexpected case - this call should be protected by a previous call to isNumberIsh()") } private fun verifyRange(input: IntValue, min: BigInteger, max: BigInteger): IntValue { val value = input.value if (value.compareTo(min) == -1 || value.compareTo(max) == 1) { throw GraphQLException("Scalar literal is too big or too small") } return input } val GraphQLInt = GraphQLScalarType("Int", "Built-in Int", object : Coercing<Int?, Int?> { override fun serialize(input: Any?): Int? = when { input is Int -> input isNumberIsh(input) -> toNumber(input).toInt() else -> null } override fun parseValue(input: Any?): Int? = serialize(input) override fun parseLiteral(input: Any?): Int? = when (input) { is IntValue -> verifyRange(input, INT_MIN, INT_MAX).value.toInt() else -> null } }) val GraphQLLong = GraphQLScalarType("Long", "Long type", object : Coercing<Long?, Long?> { override fun serialize(input: Any?): Long? = when { input is Long -> input isNumberIsh(input) -> toNumber(input).toLong() else -> null } override fun parseValue(input: Any?): Long? = serialize(input) override fun parseLiteral(input: Any?): Long? = when (input) { is StringValue -> input.value.toLong() is IntValue -> verifyRange(input, LONG_MIN, LONG_MAX).value.toLong() else -> null } }) val GraphQLShort = GraphQLScalarType("Short", "Built-in Short as Int", object : Coercing<Short?, Short?> { override fun serialize(input: Any?): Short? = when { input is Short -> input isNumberIsh(input) -> toNumber(input).toShort() else -> null } override fun parseValue(input: Any?): Short? = serialize(input) override fun parseLiteral(input: Any?): Short? = when (input) { is StringValue -> input.value.toShort() is IntValue -> verifyRange(input, SHORT_MIN, SHORT_MAX).value.toShort() else -> null } }) val GraphQLByte = GraphQLScalarType("Byte", "Built-in Byte as Int", object : Coercing<Byte?, Byte?> { override fun serialize(input: Any?): Byte? = when { input is Byte -> input isNumberIsh(input) -> toNumber(input).toByte() else -> null } override fun parseValue(input: Any?): Byte? = serialize(input) override fun parseLiteral(input: Any?): Byte? = when (input) { is StringValue -> input.value.toByte() is IntValue -> verifyRange(input, BYTE_MIN, BYTE_MAX).value.toByte() else -> null } }) val GraphQLFloat = GraphQLScalarType("Float", "Built-in Float", object : Coercing<Number?, Number?> { override fun serialize(input: Any?): Number? = when { input is Float -> input //toNumber(input.toString()).toDouble() input is Double -> input isNumberIsh(input) -> toNumber(input).toDouble() else -> null } override fun parseValue(input: Any?): Number? = serialize(input) override fun parseLiteral(input: Any?): Number? = when (input) { is FloatValue -> input.value.toDouble() is IntValue -> input.value.toDouble() else -> null } }) val GraphQLBigInteger = GraphQLScalarType("BigInteger", "Built-in java.math.BigInteger", object : Coercing<BigInteger?, BigInteger?> { override fun serialize(input: Any?): BigInteger? = when { input is BigInteger -> input input is String -> BigInteger(input) isNumberIsh(input) -> BigInteger.valueOf(toNumber(input).toLong()) else -> null } override fun parseValue(input: Any?): BigInteger? = serialize(input) override fun parseLiteral(input: Any?): BigInteger? = when (input) { is StringValue -> BigInteger(input.value) is IntValue -> input.value else -> null } }) val GraphQLBigDecimal = GraphQLScalarType("BigDecimal", "Built-in java.math.BigDecimal", object : Coercing<BigDecimal?, BigDecimal?> { override fun serialize(input: Any?): BigDecimal? = when { input is BigDecimal -> input input is String -> BigDecimal(input) isWholeNumber(input) -> BigDecimal.valueOf(toNumber(input).toLong()) input is Number -> BigDecimal.valueOf(toNumber(input).toDouble()) else -> null } override fun parseValue(input: Any?): BigDecimal? = serialize(input) override fun parseLiteral(input: Any?): BigDecimal? = when (input) { is StringValue -> BigDecimal(input.value) is IntValue -> BigDecimal(input.value) is FloatValue -> input.value else -> null } }) val GraphQLString = GraphQLScalarType("String", "Built-in String", object : Coercing<String?, String?> { override fun serialize(input: Any?): String? = input?.toString() override fun parseValue(input: Any?): String? = serialize(input) override fun parseLiteral(input: Any?): String? = when (input) { is StringValue -> input.value else -> null } }) val GraphQLStringNonNull = GraphQLNonNull(GraphQLString) val GraphQLBoolean = GraphQLScalarType("Boolean", "Built-in Boolean", object : Coercing<Boolean?, Boolean?> { override fun serialize(input: Any?): Boolean? = when (input) { is Boolean -> input is Int -> input > 0 is String -> input.toBoolean() else -> null } override fun parseValue(input: Any?): Boolean? = serialize(input) override fun parseLiteral(input: Any?): Boolean? = when (input) { is BooleanValue -> input.value else -> null } }) val GraphQLID = GraphQLScalarType("ID", "Built-in ID", object : Coercing<String?, String?> { override fun serialize(input: Any?): String? = when (input) { is String -> input is Int -> input.toString() else -> null } override fun parseValue(input: Any?): String? = serialize(input) override fun parseLiteral(input: Any?): String? = when (input) { is StringValue -> input.value is IntValue -> input.value.toString() else -> null } }) val GraphQLChar = GraphQLScalarType("Char", "Built-in Char as Character", object : Coercing<Char?, Char?> { override fun serialize(input: Any?): Char? = when (input) { is Char -> input is String -> if (input.length == 1) input[0] else null else -> null } override fun parseValue(input: Any?): Char? = serialize(input) override fun parseLiteral(input: Any?): Char? = when (input) { is StringValue -> if (input.value.length == 1) input.value[0] else null else -> null } }) val GraphQLDate = GraphQLScalarType("DateTime", "DateTime type", object : Coercing<Date?, Date?> { private val dateFormat = "yyyy-MM-dd'T'HH:mm'Z'" private val timeZone = TimeZone.getTimeZone("UTC") override fun serialize(input: Any?): Date? { when (input) { is String -> return parse(input as String?) is Date -> return input is Long -> return Date(input) is Int -> return Date(input.toLong()) else -> throw GraphQLException("Wrong timestamp value") } } override fun parseValue(input: Any?): Date? { return serialize(input) } override fun parseLiteral(input: Any?): Date? { if (input !is StringValue) return null return parse(input.value) } private fun parse(input: String?): Date { try { return simpleDateFormat.parse(input) } catch (e: Exception) { throw GraphQLException("Can not parse input date", e) } } private val simpleDateFormat: SimpleDateFormat get() { val df = SimpleDateFormat(dateFormat) df.timeZone = timeZone return df } })
0
Kotlin
1
3
aa8e3c645dedf1048e2124d43e1deff28ad16cdf
10,349
graphql-kotlin
MIT License
app/src/main/java/com/sunnyweather/permissionx/MainActivity.kt
0810yeyushengfan
405,594,819
false
null
package com.sunnyweather.permissionx import android.Manifest import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.Permission.yeyu.PermissionX class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val makeCallBtn=findViewById(R.id.makeCallBtn) as Button makeCallBtn.setOnClickListener{ PermissionX.request(this, Manifest.permission.CALL_PHONE){allGranted,deniedList-> if(allGranted){ call() }else{ Toast.makeText(this,"You denied $deniedList",Toast.LENGTH_SHORT).show() } } } val manyRequest=findViewById(R.id.manyRequest) as Button manyRequest.setOnClickListener{ PermissionX.request(this,Manifest.permission.CALL_PHONE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_CONTACTS){allGranted,deniedList-> if(allGranted){ Toast.makeText(this,"All permissions are granted",Toast.LENGTH_SHORT).show() }else{ Toast.makeText(this,"You denied $deniedList",Toast.LENGTH_SHORT).show() } } } } private fun call(){ try{ val intent= Intent(Intent.ACTION_CALL) intent.data= Uri.parse("tel:1008611") startActivity(intent) }catch (e:SecurityException){ e.printStackTrace() } } }
0
Kotlin
0
1
5e902de7cc6e35406fcdeb45727430d09151cc01
1,719
PermissionX
Apache License 2.0
TwoPage/src/main/java/com/microsoft/device/display/samples/twopage/ui/theme/Type.kt
microsoft
329,091,156
false
null
package com.microsoft.device.display.samples.twopage.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp val Typography = Typography( h5 = TextStyle( fontFamily = FontFamily.Serif, fontWeight = FontWeight.Bold, fontSize = 24.sp, letterSpacing = 0.sp ), h6 = TextStyle( fontFamily = FontFamily.Serif, fontWeight = FontWeight.Bold, fontSize = 18.sp, letterSpacing = 0.sp ), body1 = TextStyle( fontFamily = FontFamily.Serif, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp ), body2 = TextStyle( fontFamily = FontFamily.Serif, fontWeight = FontWeight.Normal, fontStyle = FontStyle.Italic, fontSize = 16.sp, lineHeight = 24.sp ), caption = TextStyle( fontFamily = FontFamily.Serif, fontWeight = FontWeight.Normal, fontSize = 14.sp, color = Color.Gray ) )
2
Kotlin
16
59
1ae8ef33490227dbd311fdc261d3cf270ccb2853
1,244
surface-duo-compose-samples
MIT License
app/src/main/java/com/nutrition/balanceme/presentation/features/add/ImageUpload.kt
DatTrannn
521,896,551
false
null
package com.nutrition.balanceme.presentation.features.add import android.net.Uri import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material.MaterialTheme.colors import androidx.compose.material.MaterialTheme.typography import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.PathEffect.Companion.dashPathEffect import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import coil.compose.rememberAsyncImagePainter import coil.compose.rememberImagePainter import coil.request.ImageRequest import coil.transform.RoundedCornersTransformation @Composable fun ImageUpload(path: Uri?, onClick: () -> Unit) { val dashColor = colors.primary val radius = CornerRadius(10f, 10f) val effect = dashPathEffect(floatArrayOf(10f, 10f), 0f) val stroke = Stroke(width = 2f, pathEffect = effect) val transformation = RoundedCornersTransformation() val painter = rememberAsyncImagePainter(ImageRequest.Builder(LocalContext.current).data(data = path) .apply(block = fun ImageRequest.Builder.() { transformations(transformation) }).build()) Box( modifier = Modifier.fillMaxWidth().height(150.dp), contentAlignment = Alignment.Center ) { Canvas(modifier = Modifier.fillMaxSize().clickable { onClick() }) { drawRoundRect(style = stroke, color = dashColor, cornerRadius = radius) } if (path != null) Image( painter = painter, contentDescription = "uploaded image", modifier = Modifier.fillMaxSize() ) Text( textAlign = TextAlign.Center, text = "Tap to upload the photo", style = typography.body1 ) } }
0
Kotlin
0
0
f51d0276b1d34e00b27b44689aedf80e1580c542
2,484
BalanceMeApp
MIT License
app/src/main/java/com/frhanklindevs/bantukuy/donor/ui/fragments/dashboard/widgets/cari/BantuCariWidget.kt
frhanklin
432,865,086
false
{"Kotlin": 168127}
package com.frhanklindevs.bantukuy.donor.ui.fragments.dashboard.widgets.cari import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.AppCompatButton import androidx.appcompat.widget.SearchView import com.frhanklindevs.bantukuy.R import com.frhanklindevs.bantukuy.databinding.FragmentBantuCariWidgetBinding import com.frhanklindevs.bantukuy.donor.ui.bottomnav.BottomNavListener import com.google.android.material.bottomnavigation.BottomNavigationView import java.util.* class BantuCariWidget : Fragment() { private var _binding : FragmentBantuCariWidgetBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentBantuCariWidgetBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setViewBehaviors() } private fun setViewBehaviors() { val bottomNavigationView = activity?.findViewById(R.id.bottom_nav_main) as BottomNavigationView bottomNavigationView.setOnItemSelectedListener(BottomNavListener.getBottomNavigationListenerFragment(this)) var text: String binding.bantuCariQuickNear.setOnClickListener{ text = "panti jakarta terdekat" val bantuSearchView = activity?.findViewById(R.id.donor_search_sv_home) as SearchView bantuSearchView.setQuery(text, true) bottomNavigationView.selectedItemId = R.id.nav_tab_search } binding.bantuCariQuickOrphanage.setOnClickListener{ text = "panti asuhan di jakarta" val bantuSearchView = activity?.findViewById(R.id.donor_search_sv_home) as SearchView bantuSearchView.setQuery(text, true) bottomNavigationView.selectedItemId = R.id.nav_tab_search } binding.bantuCariQuickNursing.setOnClickListener { text = "panti jompo di jakarta" val bantuSearchView = activity?.findViewById(R.id.donor_search_sv_home) as SearchView bantuSearchView.setQuery(text, true) bottomNavigationView.selectedItemId = R.id.nav_tab_search } binding.bantuCariSearch.setOnQueryTextListener(object: SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String): Boolean { text = query.lowercase(Locale.getDefault()) if (!text.contains("panti", true)) { text = "panti $text" } if (!text.contains("jakarta", true)) { text = "$text jakarta" } val bantuSearchView = activity?.findViewById(R.id.donor_search_sv_home) as SearchView bantuSearchView.setQuery(text, true) bottomNavigationView.selectedItemId = R.id.nav_tab_search return true } override fun onQueryTextChange(newText: String): Boolean { return false } }) binding.bantuCariButton.setOnClickListener { text = binding.bantuCariSearch.query.toString() val bantuSearchView = activity?.findViewById(R.id.donor_search_sv_home) as SearchView val bantuSearchButton = activity?.findViewById(R.id.donor_search_btn_sv_home) as AppCompatButton bantuSearchView.setQuery(text, false) bantuSearchButton.performClick() bottomNavigationView.selectedItemId = R.id.nav_tab_search } binding.bantuCariTvSubtitle.setOnClickListener { bottomNavigationView.selectedItemId = R.id.nav_tab_search } } }
0
Kotlin
0
0
304d966344317e9d09daa0d5b89f0d862e896c17
4,089
BantuKuy
Apache License 2.0
app/src/main/java/com/breezefsmsettdeycohomoeolab/features/login/model/productlistmodel/NewOdrScrOrderListModel.kt
DebashisINT
639,303,773
false
{"Kotlin": 13711722, "Java": 997141}
package com.breezefsmsettdeycohomoeolab.features.login.model.productlistmodel import com.breezefsmsettdeycohomoeolab.app.domain.NewOrderScrOrderEntity import com.breezefsmsettdeycohomoeolab.app.domain.ProductListEntity class NewOdrScrOrderListModel { var status:String? = null var message:String? = null var user_id:String? = null var order_list: ArrayList<NewOrderScrOrderEntity>? = null }
0
Kotlin
0
0
66dcb25c9f8c4f2784c4e61fe720fa4c6f83e34d
408
SettDeyCoHomoeo
Apache License 2.0
services/hanke-service/src/main/kotlin/fi/hel/haitaton/hanke/geometria/Geometriat.kt
City-of-Helsinki
300,534,352
false
{"Kotlin": 1853898, "Mustache": 92562, "Shell": 23444, "Batchfile": 5169, "PLpgSQL": 1115, "Dockerfile": 371}
package fi.hel.haitaton.hanke.geometria import com.fasterxml.jackson.annotation.JsonView import fi.hel.haitaton.hanke.ChangeLogView import fi.hel.haitaton.hanke.NotInChangeLogView import fi.hel.haitaton.hanke.domain.HasFeatures import fi.hel.haitaton.hanke.domain.HasId import io.swagger.v3.oas.annotations.media.Schema import java.time.ZonedDateTime import org.geojson.FeatureCollection @Schema(description = "Geometry data") data class Geometriat( @JsonView(ChangeLogView::class) @field:Schema(description = "Id, set by the service") override var id: Int? = null, // @JsonView(ChangeLogView::class) @field:Schema(description = "The geometry data") override var featureCollection: FeatureCollection? = null, // @field:Schema(description = "Version, set by the service") @JsonView(ChangeLogView::class) var version: Int, // @field:Schema(description = "User id of the geometry data creator, set by the service") @JsonView(NotInChangeLogView::class) var createdByUserId: String? = null, // @field:Schema(description = "Timestamp of last modification, set by the service") @JsonView(NotInChangeLogView::class) var createdAt: ZonedDateTime? = null, // @field:Schema(description = "User id of the last modifier, set by the service") @JsonView(NotInChangeLogView::class) var modifiedByUserId: String? = null, // @field:Schema(description = "Timestamp of last modification, set by the service") @JsonView(NotInChangeLogView::class) var modifiedAt: ZonedDateTime? = null ) : HasId<Int?>, HasFeatures { fun withFeatureCollection(input: FeatureCollection): Geometriat { this.featureCollection = input return this } }
9
Kotlin
5
4
f0e319fafa2706e7fb5b4a3ad406935a9e59a38d
1,742
haitaton-backend
MIT License
unleash/src/test/java/com/silvercar/unleash/integration/UnleashContextDefinition.kt
silvercar
248,339,880
false
null
package com.silvercar.unleash.integration data class UnleashContextDefinition( private val userId: String?, private val sessionId: String?, private val remoteAddress: String?, private val environment: String?, private val appName: String?, // Custom context fields used in tests private val properties: Map<String, String>? ) { fun getUserId(): String { return userId ?: "" } fun getSessionId(): String { return sessionId ?: "" } fun getRemoteAddress(): String { return remoteAddress ?: "" } fun getEnvironment(): String { return environment ?: "" } fun getAppName(): String { return appName ?: "" } fun getProperties(): Map<String, String> { return properties ?: mapOf() } }
0
null
4
12
98d12a20913bc1b91954d525c035cb638ddc1b21
745
unleash-client-kotlin
Apache License 2.0
src/main/java/io/github/orange3/unittestarchitect/worker/WorkerImpl.kt
OrangE-3
450,310,376
false
{"Kotlin": 40694}
/* * Copyright (C) 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.orange3.unittestarchitect.worker import io.github.orange3.unittestarchitect.worker.internal.helpers.FilePathHelperImpl import io.github.orange3.unittestarchitect.worker.internal.helpers.interfaces.FilePathHelper import io.github.orange3.unittestarchitect.worker.internal.makers.ClassMakerImpl import io.github.orange3.unittestarchitect.worker.internal.makers.KotlinFileMakerImpl import io.github.orange3.unittestarchitect.worker.internal.makers.interfaces.ClassMaker import io.github.orange3.unittestarchitect.worker.internal.makers.interfaces.KotlinFileMaker import io.github.orange3.unittestarchitect.worker.internal.writers.TestFileWriter import io.github.orange3.unittestarchitect.worker.internal.writers.TestFileWriterImpl import java.net.URL internal class WorkerImpl( private val urls: Array<URL>, private val sourceDirectoryList: List<String>, private val exclude: List<String>, private val filePathHelper: FilePathHelper = FilePathHelperImpl(sourceDirectoryList, exclude), private val classMaker: ClassMaker = ClassMakerImpl(urls), private val kotlinFileMaker: KotlinFileMaker = KotlinFileMakerImpl(), private val testFileWriter: TestFileWriter = TestFileWriterImpl(sourceDirectoryList) ) : Worker { override fun work() { val paths = filePathHelper.getFilePaths() for (path in paths) { val clazz = classMaker.makeClass(path) val file = clazz?.let { kotlinFileMaker.makeKotlinFile(it) } if (file != null) { testFileWriter.writeFile(file, path) } } } }
0
Kotlin
1
6
54f386b2fae3ffc19ebea84ec601d9bd4f4191ee
2,227
UnitTestArchitect
Apache License 2.0
stytch/src/main/kotlin/com/stytch/java/common/Version.kt
stytchauth
665,684,154
false
{"Kotlin": 980649}
package com.stytch.java.common internal const val VERSION = "2.0.1"
0
Kotlin
0
4
3f1b984b2f15931af4f893b913c6ed751fa6379b
69
stytch-java
MIT License
cnj/reservation-client/src/main/kotlin/com/example/reservationclient/ReservationClientApplication.kt
joshlong-attic
102,565,872
false
{"Shell": 97610, "Batchfile": 74922, "Java": 23894, "Kotlin": 22724, "Groovy": 554}
package com.example.reservationclient import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand import org.springframework.boot.ApplicationRunner import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker import org.springframework.cloud.client.discovery.DiscoveryClient import org.springframework.cloud.client.discovery.EnableDiscoveryClient import org.springframework.cloud.netflix.feign.EnableFeignClients import org.springframework.cloud.netflix.feign.FeignClient import org.springframework.cloud.netflix.zuul.EnableZuulProxy import org.springframework.cloud.stream.annotation.EnableBinding import org.springframework.cloud.stream.messaging.Source import org.springframework.context.annotation.Bean import org.springframework.messaging.support.MessageBuilder import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer import org.springframework.web.bind.annotation.* @EnableResourceServer @EnableBinding(Source::class) @EnableCircuitBreaker @EnableFeignClients @EnableDiscoveryClient @EnableZuulProxy @SpringBootApplication class ReservationClientApplication { @Bean fun init(dc: DiscoveryClient) = ApplicationRunner { dc.getInstances("reservation-service") .forEach { println("${it.serviceId}:${it.host}:${it.port}") } } /* @Bean @LoadBalanced fun rt() = RestTemplate() */ } @RestController @RequestMapping("/reservations") class ReservationApiAdapterRestController(val rc: ReservationClient, val src: Source) { val channel = src.output() fun fallback(): List<String?> = ArrayList<String?>() @HystrixCommand(fallbackMethod = "fallback") @GetMapping("/names") fun names(): List<String?> = rc.read().map { it.reservationName } @PostMapping fun write(@RequestBody r: Reservation) = this.channel.send(MessageBuilder.withPayload(r.reservationName).build()) } /* @Component class ReservationClient(@LoadBalanced val rt: RestTemplate) { fun read(): Collection<Reservation> = rt.exchange("http://reservation-service/reservations", HttpMethod.GET, null, object : ParameterizedTypeReference<Collection<Reservation>>() {}) .body } */ @FeignClient("reservation-service") interface ReservationClient { @GetMapping("/reservations") fun read(): Collection<Reservation> } class Reservation(var id: Long? = null, var reservationName: String? = null) /* @Component class CustomZuulFilter : ZuulFilter() { override fun run(): Any? = { val ctx = RequestContext.getCurrentContext() println("proxying a request to ${ctx.request.requestURI}..") null } override fun shouldFilter(): Boolean = true override fun filterType(): String = "pre" override fun filterOrder(): Int = -100 } */ fun main(args: Array<String>) { SpringApplication.run(ReservationClientApplication::class.java, *args) }
1
Shell
1
3
4a10aa077b233f695a520b0859689004a7279873
3,109
yow-hk-2017-workshop
Apache License 2.0
src/main/kotlin/com/framstag/domainbus/source/postgres/Context.kt
Framstag
233,686,175
false
null
package com.framstag.domainbus.source.postgres import com.framstag.domainbus.jdbc.ConnectionFactory import java.time.Duration /** * Immutable state part of postgres source */ data class Context(val connectionFactory : ConnectionFactory, val connectionErrorTimeout : Duration = Duration.ofSeconds(1), val selectQueryTimeout : Duration = Duration.ofSeconds(1), val deleteTimeout : Duration = Duration.ofSeconds(1), val sessionTimeout : Duration = Duration.ofSeconds(30), val emptySelectTimeout : Duration = Duration.ofMillis(100))
0
Kotlin
0
0
9b3b358e9ee6b1e5bac8dd9d72cccefe9c4c09ab
627
domainbus
Apache License 2.0
crud-framework-core/src/test/java/dev/krud/crudframework/crud/handler/krud/KrudScannerTest.kt
krud-dev
721,261,766
false
{"Gradle Kotlin DSL": 9, "Markdown": 3, "Shell": 2, "Ignore List": 6, "Batchfile": 1, "EditorConfig": 1, "Kotlin": 105, "Java": 79, "INI": 1, "YAML": 2}
package dev.krud.crudframework.crud.handler.krud import dev.krud.crudframework.crud.handler.CrudCreateHandler import dev.krud.crudframework.crud.handler.CrudDeleteHandler import dev.krud.crudframework.crud.handler.CrudReadHandler import dev.krud.crudframework.crud.handler.CrudUpdateHandler import dev.krud.crudframework.model.BaseCrudEntity import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Import import org.springframework.test.context.junit.jupiter.SpringExtension import strikt.api.expect import strikt.assertions.isEqualTo @EnableKrud private class App private class Entity : BaseCrudEntity<Int>() { override var id: Int = 1 override fun getCacheKey(): String? = "" override fun exists(): Boolean = true } @ExtendWith(SpringExtension::class) @Import(App::class) class KrudScannerTest { @MockBean private lateinit var crudCreateHandler: CrudCreateHandler @MockBean private lateinit var crudReadHandler: CrudReadHandler @MockBean private lateinit var crudUpdateHandler: CrudUpdateHandler @MockBean private lateinit var crudDeleteHandler: CrudDeleteHandler @Autowired private lateinit var applicationContext: ApplicationContext @Test fun `scanner should create beans for each entity in package`() { val beans = applicationContext.getBeansOfType(Krud::class.java) val firstBean = beans.values.first() expect { that(beans.size).isEqualTo(1) that(firstBean.entityClazz).isEqualTo(Entity::class.java) that(beans["entityKrud"]).isEqualTo(firstBean) } } }
2
Java
0
0
a3c01955a8b181c6b5cd11833f68ca1eded960b7
1,892
krud
MIT License
app/src/main/java/com/kcteam/features/viewAllOrder/interf/ColorListOnCLick.kt
DebashisINT
558,234,039
false
{"Kotlin": 11332958, "Java": 966929}
package com.kcteam.features.viewAllOrder.interf import com.kcteam.app.domain.NewOrderGenderEntity import com.kcteam.features.viewAllOrder.model.ProductOrder interface ColorListOnCLick { fun colorListOnCLick(size_qty_list: ArrayList<ProductOrder>, adpPosition:Int) }
0
Kotlin
1
1
a9aabcf48662c76db18bcece75cae9ac961da1ed
271
KidCity
Apache License 2.0
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/diagnosiskeys/storage/legacy/KeyCacheEntityTest.kt
CoraLibre
268,867,734
false
null
package de.rki.coronawarnapp.diagnosiskeys.storage.legacy import testhelpers.BaseTest class KeyCacheEntityTest : BaseTest()
6
null
499
36
8e3d915aa194cae0645ff668cca2114d9bb3d7c2
126
CoraLibre-android
Apache License 2.0
service/src/main/kotlin/io/provenance/explorer/service/AccountService.kt
provenance-io
332,035,574
false
null
package io.provenance.explorer.service import com.google.protobuf.Any import cosmos.bank.v1beta1.msgSend import cosmos.vesting.v1beta1.msgCreateVestingAccount import io.provenance.attribute.v1.Attribute import io.provenance.explorer.config.ExplorerProperties import io.provenance.explorer.config.ResourceNotFoundException import io.provenance.explorer.domain.core.logger import io.provenance.explorer.domain.entities.AccountRecord import io.provenance.explorer.domain.entities.TxAddressJoinTable import io.provenance.explorer.domain.entities.TxCacheRecord import io.provenance.explorer.domain.entities.TxCacheTable import io.provenance.explorer.domain.entities.TxMessageTable import io.provenance.explorer.domain.entities.TxMessageTypeTable import io.provenance.explorer.domain.exceptions.requireNotNullToMessage import io.provenance.explorer.domain.exceptions.requireToMessage import io.provenance.explorer.domain.exceptions.validate import io.provenance.explorer.domain.extensions.NHASH import io.provenance.explorer.domain.extensions.USD_UPPER import io.provenance.explorer.domain.extensions.diff import io.provenance.explorer.domain.extensions.fromBase64 import io.provenance.explorer.domain.extensions.getType import io.provenance.explorer.domain.extensions.isAddressAsType import io.provenance.explorer.domain.extensions.pack import io.provenance.explorer.domain.extensions.pageCountOfResults import io.provenance.explorer.domain.extensions.pageOfResults import io.provenance.explorer.domain.extensions.toAccountPubKey import io.provenance.explorer.domain.extensions.toBase64 import io.provenance.explorer.domain.extensions.toCoinStr import io.provenance.explorer.domain.extensions.toDateTime import io.provenance.explorer.domain.extensions.toDecimalString import io.provenance.explorer.domain.extensions.toObjectNode import io.provenance.explorer.domain.extensions.toOffset import io.provenance.explorer.domain.models.explorer.AccountDetail import io.provenance.explorer.domain.models.explorer.AccountRewards import io.provenance.explorer.domain.models.explorer.AttributeObj import io.provenance.explorer.domain.models.explorer.BankSendRequest import io.provenance.explorer.domain.models.explorer.CoinStr import io.provenance.explorer.domain.models.explorer.Delegation import io.provenance.explorer.domain.models.explorer.DenomBalanceBreakdown import io.provenance.explorer.domain.models.explorer.PagedResults import io.provenance.explorer.domain.models.explorer.PeriodInSeconds import io.provenance.explorer.domain.models.explorer.Reward import io.provenance.explorer.domain.models.explorer.TokenCounts import io.provenance.explorer.domain.models.explorer.UnpaginatedDelegation import io.provenance.explorer.domain.models.explorer.mapToProtoCoin import io.provenance.explorer.domain.models.explorer.toCoinStrWithPrice import io.provenance.explorer.grpc.extensions.getModuleAccName import io.provenance.explorer.grpc.extensions.isStandardAddress import io.provenance.explorer.grpc.extensions.isVesting import io.provenance.explorer.grpc.extensions.toVestingData import io.provenance.explorer.grpc.v1.AccountGrpcClient import io.provenance.explorer.grpc.v1.AttributeGrpcClient import io.provenance.explorer.grpc.v1.MetadataGrpcClient import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.andWhere import org.jetbrains.exposed.sql.innerJoin import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.transactions.transaction import org.springframework.stereotype.Service import java.math.BigDecimal @Service class AccountService( private val accountClient: AccountGrpcClient, private val props: ExplorerProperties, private val attrClient: AttributeGrpcClient, private val metadataClient: MetadataGrpcClient, private val assetService: AssetService ) { protected val logger = logger(AccountService::class) fun getAccountRaw(address: String) = transaction { AccountRecord.findByAddress(address) } ?: saveAccount(address) fun saveAccount(address: String, isContract: Boolean = false) = runBlocking { accountClient.getAccountInfo(address)?.let { AccountRecord.insertIgnore(it, isContract) } ?: if (address.isAddressAsType(props.provAccPrefix())) AccountRecord.insertUnknownAccount( address, isContract ) else throw ResourceNotFoundException("Invalid account: '$address'") } fun validateAddress(address: String) = transaction { requireNotNullToMessage(AccountRecord.findByAddress(address)) { "Address $address does not exist." } } fun getAccountDetail(address: String) = runBlocking { getAccountRaw(address).let { val attributes = async { attrClient.getAllAttributesForAddress(it.accountAddress) } val tokenCount = async { getBalances(it.accountAddress, 0, 1) } val balances = async { getBalances(it.accountAddress, 1, tokenCount.await().pagination.total.toInt()) } AccountDetail( it.type, it.accountAddress, it.accountNumber, it.baseAccount?.sequence?.toInt(), AccountRecord.findSigsByAddress(it.accountAddress).firstOrNull().toAccountPubKey(), it.data?.getModuleAccName(), attributes.await().map { attr -> attr.toResponse() }, TokenCounts( tokenCount.await().pagination.total, metadataClient.getScopesByOwner(it.accountAddress).pagination.total.toInt() ), it.isContract, assetService .getAumForList( balances.await().balancesList.associate { bal -> bal.denom to bal.amount }, "accountAUM" ) .toCoinStr(USD_UPPER), it.data?.isVesting() ?: false ) } } fun getNamesOwnedByAccount(address: String, page: Int, limit: Int) = runBlocking { attrClient.getNamesForAddress(address, page.toOffset(limit), limit).let { res -> val names = res.nameList.toList() PagedResults(res.pagination.total.pageCountOfResults(limit), names, res.pagination.total) } } suspend fun getBalances(address: String, page: Int, limit: Int) = accountClient.getAccountBalances(address, page.toOffset(limit), limit) suspend fun getBalancesAll(address: String) = accountClient.getAccountBalancesAll(address) suspend fun getSpendableBalances(address: String) = accountClient.getSpendableBalancesAll(address) @Deprecated("Use AccountService.getAccountBalancesDetailed") fun getAccountBalances(address: String, page: Int, limit: Int) = runBlocking { getBalances(address, page, limit).let { res -> val pricing = assetService.getPricingInfoIn(res.balancesList.map { it.denom }, "accountBalances") val bals = res.balancesList.map { it.toCoinStrWithPrice(pricing[it.denom]) } PagedResults(res.pagination.total.pageCountOfResults(limit), bals, res.pagination.total) } } fun getAccountBalancesDetailed(address: String, page: Int, limit: Int) = runBlocking { getBalancesAll(address).let { res -> val pricing = assetService.getPricingInfoIn(res.map { it.denom }, "accountBalances") val spendable = getSpendableBalances(address).associateBy { it.denom } val bals = res.map { DenomBalanceBreakdown( it.toCoinStrWithPrice(pricing[it.denom]), spendable[it.denom]!!.toCoinStrWithPrice(pricing[it.denom]), it.diff(spendable[it.denom]!!).toCoinStrWithPrice(pricing[it.denom], it.denom) ) }.sortedByDescending { it.total.totalBalancePrice?.amount?.toBigDecimal() ?: BigDecimal.ZERO } PagedResults( bals.count().toLong().pageCountOfResults(limit), bals.pageOfResults(page, limit), bals.count().toLong() ) } } private fun getDelegationTotal(address: String) = runBlocking { var offset = 0 val limit = 100 val results = accountClient.getDelegations(address, offset, limit) val total = results.pagination?.total ?: results.delegationResponsesCount.toLong() val delegations = results.delegationResponsesList.toMutableList() while (delegations.count() < total) { offset += limit accountClient.getDelegations(address, offset, limit).let { delegations.addAll(it.delegationResponsesList) } } delegations.sumOf { it.balance.amount.toBigDecimal() } .toCoinStr(delegations.firstOrNull()?.balance?.denom ?: NHASH) } fun getDelegations(address: String, page: Int, limit: Int) = runBlocking { accountClient.getDelegations(address, page.toOffset(limit), limit).let { res -> val list = res.delegationResponsesList.map { Delegation( it.delegation.delegatorAddress, it.delegation.validatorAddress, null, CoinStr(it.balance.amount, it.balance.denom), null, it.delegation.shares.toDecimalString(), null, null ) } val rollup = mapOf("bondedTotal" to getDelegationTotal(address)) PagedResults(res.pagination.total.pageCountOfResults(limit), list, res.pagination.total, rollup) } } fun getUnbondingDelegations(address: String) = runBlocking { accountClient.getUnbondingDelegations(address, 0, 100).let { res -> res.unbondingResponsesList.flatMap { list -> list.entriesList.map { Delegation( list.delegatorAddress, list.validatorAddress, null, CoinStr(it.balance, NHASH), CoinStr(it.initialBalance, NHASH), null, it.creationHeight.toInt(), it.completionTime.toDateTime() ) } } }.let { recs -> val total = recs.sumOf { it.amount.amount.toBigDecimal() }.toCoinStr(NHASH) UnpaginatedDelegation(recs, mapOf(Pair("unbondingTotal", total))) } } fun getRedelegations(address: String) = runBlocking { accountClient.getRedelegations(address, 0, 100).let { res -> res.redelegationResponsesList.flatMap { list -> list.entriesList.map { Delegation( list.redelegation.delegatorAddress, list.redelegation.validatorSrcAddress, list.redelegation.validatorDstAddress, CoinStr(it.balance, NHASH), CoinStr(it.redelegationEntry.initialBalance, NHASH), it.redelegationEntry.sharesDst.toDecimalString(), it.redelegationEntry.creationHeight.toInt(), it.redelegationEntry.completionTime.toDateTime() ) } } }.let { recs -> val total = recs.sumOf { it.amount.amount.toBigDecimal() }.toCoinStr(NHASH) UnpaginatedDelegation(recs, mapOf(Pair("redelegationTotal", total))) } } fun getRewards(address: String) = runBlocking { accountClient.getRewards(address).let { res -> val pricing = assetService.getPricingInfoIn( res.rewardsList.flatMap { list -> list.rewardList.map { it.denom } }, "rewards" ) AccountRewards( res.rewardsList.map { list -> Reward( list.validatorAddress, list.rewardList.map { r -> r.toCoinStrWithPrice(pricing[r.denom]) } ) }, res.totalList.map { t -> t.toCoinStrWithPrice(pricing[t.denom]) } ) } } fun createSend(request: BankSendRequest): Any { validate( validateAddress(request.from), requireToMessage(request.to.isStandardAddress(props)) { "to must be a standard address format" }, requireToMessage(request.to != request.from) { "The to address must be different that the from address" }, *request.funds.map { assetService.validateDenom(it.denom) }.toTypedArray(), requireToMessage(request.funds.none { it.amount.toLong() == 0L }) { "At least one deposit must have an amount greater than zero." } ) return msgSend { fromAddress = request.from toAddress = request.to amount.addAll(request.funds.mapToProtoCoin()) }.pack() } fun getVestingSchedule(address: String, continuousPeriod: PeriodInSeconds = PeriodInSeconds.DAY) = transaction { getAccountRaw(address).let { acc -> if (acc.data == null || acc.data?.isVesting() == false) throw ResourceNotFoundException("Invalid vesting account: '$address'") acc.data!!.toVestingData(getInitializationDate(acc), continuousPeriod) } } // Gets the origination dateTime for the account. Currently only applicable to vesting accounts private fun getInitializationDate(account: AccountRecord) = transaction { val types = listOf(msgCreateVestingAccount { }.getType()) TxAddressJoinTable .innerJoin(TxMessageTable, { TxAddressJoinTable.txHashId }, { TxMessageTable.txHashId }) .innerJoin(TxMessageTypeTable, { TxMessageTable.txMessageType }, { TxMessageTypeTable.id }) .innerJoin(TxCacheTable, { TxAddressJoinTable.txHashId }, { TxCacheTable.id }) .slice(TxCacheTable.columns) .select { TxMessageTypeTable.protoType inList types } .andWhere { TxAddressJoinTable.addressId eq account.id.value } .andWhere { TxCacheTable.errorCode.isNull() } .orderBy(Pair(TxCacheTable.txTimestamp, SortOrder.ASC)) .limit(1) .let { TxCacheRecord.wrapRows(it) } .firstOrNull() ?.txTimestamp } } fun String.getAccountType() = this.split(".").last() fun Attribute.toResponse(): AttributeObj { val data = when { this.name.contains("passport") -> this.value.toStringUtf8().fromBase64().toObjectNode().let { node -> try { // Try to parse out passport details when { node["pending"].asBoolean() -> "pending" node["expirationDate"].asText().toDateTime().isBeforeNow -> "expired" else -> "active" } } catch (e: Exception) { // If it fails, just pass back the encoded string this.value.toStringUtf8().toBase64() } } else -> this.value.toStringUtf8().toBase64() } return AttributeObj(this.name, data) }
16
Kotlin
2
3
e1bc9c0c3aff7e22ae8a33545fd628d11f7092f4
15,386
explorer-service
Apache License 2.0
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/dbms/queries/operators/logical/transform/LimitLogicalOperatorNode.kt
vitrivr
160,775,368
false
null
package org.vitrivr.cottontail.dbms.queries.operators.logical.transform import org.vitrivr.cottontail.dbms.queries.operators.logical.UnaryLogicalOperatorNode import org.vitrivr.cottontail.dbms.queries.operators.physical.transform.LimitPhysicalOperatorNode /** * A [UnaryLogicalOperatorNode] that represents the application of a LIMIT and/or SKIP clause on the final result. * * @author <NAME> * @version 2.2.0 */ class LimitLogicalOperatorNode(input: Logical? = null, val limit: Long, val skip: Long) : UnaryLogicalOperatorNode(input) { companion object { private const val NODE_NAME = "Limit" } /** The name of this [LimitLogicalOperatorNode]. */ override val name: String get() = NODE_NAME /** * Creates and returns a copy of this [LimitLogicalOperatorNode] without any children or parents. * * @return Copy of this [LimitLogicalOperatorNode]. */ override fun copy() = LimitLogicalOperatorNode(limit = this.limit, skip = this.skip) /** * Returns a [LimitPhysicalOperatorNode] representation of this [LimitLogicalOperatorNode] * * @return [LimitPhysicalOperatorNode] */ override fun implement(): Physical = LimitPhysicalOperatorNode(this.input?.implement(), this.limit, this.skip) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LimitLogicalOperatorNode) return false if (limit != other.limit) return false if (skip != other.skip) return false return true } /** Generates and returns a hash code for this [LimitLogicalOperatorNode]. */ override fun hashCode(): Int { var result = limit.hashCode() result = 27 * result + skip.hashCode() return result } /** Generates and returns a [String] representation of this [LimitLogicalOperatorNode]. */ override fun toString() = "${super.toString()}[${this.skip},${this.limit}]" }
8
Kotlin
15
15
c6e06263d9163f697e0aa5dc334a910521620215
1,959
cottontaildb
MIT License