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/recepguzel/cryptoxcleanarchitecture/data/source/locale/CoinFavoriteDao.kt
|
recepbrk
| 801,143,879
| false
|
{"Kotlin": 105580}
|
package com.recepguzel.cryptoxcleanarchitecture.data.source.locale
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.recepguzel.cryptoxcleanarchitecture.data.model.CryptoData
@Dao
interface CoinFavoriteDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addCoin(coin: CryptoData): Long
@Delete
suspend fun deleteCoin(coin: CryptoData)
@Query("SELECT*FROM favorite_table")
fun getFavoriteList(): LiveData<List<CryptoData>>
@Query("SELECT COUNT(*) FROM favorite_table WHERE name = :coinName")
suspend fun isCoinFavorite(coinName: String): Int
}
| 0
|
Kotlin
|
0
| 0
|
c03edbf4e2bfdf3b2257ff9e35644f610d6c5e5c
| 739
|
CryptoXCleanArchitecture
|
Apache License 2.0
|
app/src/main/java/com/leomurca/tompero/ui/recipes/RecipeAdapter.kt
|
leonardoamurca
| 366,860,524
| false
| null |
package com.leomurca.tompero.ui.recipes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.leomurca.tompero.R
import com.leomurca.tompero.models.Recipe
class RecipeAdapter(
private val onClick: (Recipe) -> Unit
) : RecyclerView.Adapter<RecipeAdapter.ViewHolder>() {
private var recipes: List<Recipe> = emptyList<Recipe>()
fun setRecipes(recipeList: List<Recipe>) {
recipes = recipeList
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflatedView = LayoutInflater.from(parent.context).inflate(
R.layout.item_recipe,
parent,
false
)
return ViewHolder(inflatedView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(recipes[position], onClick)
}
override fun getItemCount() = recipes.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(recipe: Recipe, onClick: (Recipe) -> Unit) {
itemView.findViewById<CardView>(R.id.recipeCard).setOnClickListener { onClick(recipe) }
itemView.findViewById<TextView>(R.id.title).text = recipe.title
itemView.findViewById<TextView>(R.id.description).text = recipe.description
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f46641beb6c3507a4e9b8243f26974c94fb27489
| 1,504
|
tompero-android
|
MIT License
|
OptiGUI/src/main/kotlin/opekope2/optigui/toast/InspectorToast.kt
|
opekope2
| 578,779,647
| false
|
{"Kotlin": 120485, "Java": 5448}
|
package opekope2.optigui.toast
import net.minecraft.client.gui.DrawContext
import net.minecraft.client.toast.Toast
import net.minecraft.client.toast.ToastManager
import net.minecraft.text.Text
import net.minecraft.util.Identifier
/**
* A toast displaying the inspector message.
*/
class InspectorToast : Toast {
override fun draw(context: DrawContext, manager: ToastManager, startTime: Long): Toast.Visibility {
val textRenderer = manager.client.textRenderer
context.drawGuiTexture(TEXTURE, 0, 0, width, height)
context.drawText(textRenderer, TITLE, 7, 7, 0xFF00FFFF.toInt(), false)
context.drawText(textRenderer, DESCRIPTION, 7, 18, 0xFFFFFFFF.toInt(), false)
return if (startTime >= 4000 * manager.notificationDisplayTimeMultiplier) Toast.Visibility.HIDE
else Toast.Visibility.SHOW
}
companion object {
private val TEXTURE = Identifier("toast/advancement")
private val TITLE = Text.translatable("optigui.toast.inspector.title")
private val DESCRIPTION = Text.translatable("optigui.toast.inspector.description")
}
}
| 13
|
Kotlin
|
7
| 23
|
eddf1b61160c4e73124675e6d36e4f53d998ed98
| 1,111
|
OptiGUI
|
MIT License
|
app/src/main/java/com/steve/githubinfosearcher/datasource/api/SearchApi.kt
|
steve0802
| 269,522,575
| false
| null |
package com.steve.githubinfosearcher.datasource.api
import com.steve.githubinfosearcher.datasource.response.SearchApiResponse
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface SearchApi {
@GET("search/users")
suspend fun getUserList(@Query("q") filter: String?,
@Query("per_page") perPage: Int?,
@Query("page") page: Int? ): Response<SearchApiResponse>
}
| 0
|
Kotlin
|
0
| 0
|
9fd44baef9908d72fe8b82251bd0d9ac8112ba0c
| 444
|
GitHubInfoSearcher
|
MIT License
|
flow-sample-multikey/src/androidTest/java/flow/sample/multikey/MultiKeySampleTest.kt
|
minyushov
| 87,313,471
| true
|
{"Kotlin": 158999, "Shell": 933}
|
/*
* Copyright 2016 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flow.sample.multikey
import android.view.View
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.isDialog
import androidx.test.espresso.matcher.RootMatchers.withDecorView
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import org.hamcrest.Matchers.`is`
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class MultiKeySampleTest {
@Rule
@JvmField
val rule = activityScenarioRule<MultiKeySampleActivity>()
lateinit var decorView: View
@Before
fun setUp() {
rule.scenario.onActivity { activity ->
decorView = activity.window.decorView;
}
}
@Test
fun walkthrough() {
// Start on ScreenOne.
onView(withText(ScreenOne().toString())).check(matches(isDisplayed()))
// Click to show DialogScreen.
onView(withText(ScreenOne().toString())).perform(click())
onView(withText(DialogScreen(ScreenTwo()).toString()))
.inRoot(isDialog())
.check(matches(isDisplayed()))
// We should still see ScreenOne behind the dialog.
onView(withText(ScreenOne().toString()))
.inRoot(withDecorView(`is`(decorView)))
// Let's rotate to make sure we keep the dialog and the view.
UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).setOrientationRight()
// Should still see DialogScreen.
onView(withText(DialogScreen(ScreenTwo()).toString()))
.inRoot(isDialog())
.check(matches(isDisplayed()))
onView(withText(ScreenOne().toString()))
.inRoot(withDecorView(`is`(decorView)))
// Click Yes on dialog to advance to ScreenTwo.
onView(withText("Yes")).inRoot(isDialog()).perform(click())
// Should be on ScreenTwo.
onView(withText(ScreenTwo().toString())).check(matches(isDisplayed()))
// Press back to go back to the dialog.
pressBack()
// Should see the Dialog over ScreenOne again.
onView(withText(DialogScreen(ScreenTwo()).toString()))
.inRoot(isDialog())
.check(matches(isDisplayed()))
onView(withText(ScreenOne().toString()))
.inRoot(withDecorView(`is`(decorView)))
// Click forward to ScreenTwo
// Click Yes on dialog to advance to ScreenTwo.
onView(withText("Yes")).inRoot(isDialog()).perform(click())
// Click screen to go back to ScreenOne, skipping the dialog.
onView(withText(ScreenTwo().toString())).perform(click())
onView(withText(ScreenOne().toString())).check(matches(isDisplayed()))
}
}
| 0
|
Kotlin
|
0
| 0
|
7b6403601decf6762e7e3f1ea10f468f22aa54ae
| 3,461
|
flow
|
Apache License 2.0
|
CheckersVisionApp/app/src/main/java/com/example/checkersvisionapp/model/checkers/CheckersPosition.kt
|
b3nny01
| 773,932,332
| false
|
{"Kotlin": 35688, "Python": 19262, "Java": 9232, "C++": 5922}
|
package com.example.checkersvisionapp.model.checkers
import android.graphics.Bitmap
class CheckersPosition(val game: CheckersGame, val n:Int, val img:Bitmap)
| 0
|
Kotlin
|
0
| 0
|
21fe76877025d4fadfe1d5de4a79ec073cbb281c
| 159
|
CheckersVision
|
MIT License
|
app/TaskManagerPlus/app/src/main/java/maif/taskmanagerplus/ui/login/LoginActivity.kt
|
maiconfang
| 867,286,298
| false
|
{"Kotlin": 53248}
|
package maif.taskmanagerplus.ui.login
import android.app.Activity
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import maif.taskmanagerplus.MainActivity
import maif.taskmanagerplus.databinding.ActivityLoginBinding
import maif.taskmanagerplus.R
class LoginActivity : AppCompatActivity() {
private lateinit var loginViewModel: LoginViewModel
private lateinit var binding: ActivityLoginBinding
private lateinit var username: EditText
private lateinit var warningMessageTextView: TextView
private var lastToastMessage: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
username = binding.username
val password = <PASSWORD>
val login = binding.login
val loading = binding.loading
warningMessageTextView = binding.warningMessage!! // Correctly cast to TextView
// Definir a mensagem aqui
warningMessageTextView.text = "The Email and Password fields accept any value, for example, <EMAIL> and 123456"
warningMessageTextView.visibility = View.VISIBLE // Torna o TextView visível
// Initialize the ViewModel
loginViewModel = ViewModelProvider(this, LoginViewModelFactory())
.get(LoginViewModel::class.java)
// Observe form state changes and update UI accordingly
loginViewModel.loginFormState.observe(this@LoginActivity, Observer {
val loginState = it ?: return@Observer
// Disable login button unless both username / password are valid
login.isEnabled = loginState.isDataValid
if (loginState.usernameError != null) {
username.error = getString(loginState.usernameError)
}
if (loginState.passwordError != null) {
password.error = getString(loginState.passwordError)
}
})
// Observe login result and navigate to the main screen upon success
loginViewModel.loginResult.observe(this@LoginActivity, Observer {
val loginResult = it ?: return@Observer
loading.visibility = View.GONE
if (loginResult.error != null) {
showLoginFailed(loginResult.error)
}
if (loginResult.success != null) {
updateUiWithUser(loginResult.success)
}
setResult(Activity.RESULT_OK)
// Complete and destroy login activity once successful
finish()
})
// Text watcher to monitor input changes for username and password
username.afterTextChanged {
loginViewModel.loginDataChanged(
username.text.toString(),
password.text.toString()
)
}
password.apply {
afterTextChanged {
loginViewModel.loginDataChanged(
username.text.toString(),
password.text.toString()
)
}
// Handle "Done" action on the keyboard
setOnEditorActionListener { _, actionId, _ ->
when (actionId) {
EditorInfo.IME_ACTION_DONE ->
loginViewModel.login(
username.text.toString(),
password.text.toString()
)
}
false
}
// Click listener for login button
login.setOnClickListener {
loading.visibility = View.VISIBLE
loginViewModel.login(username.text.toString(), password.text.toString())
}
}
// Observe the warning message from the ViewModel and display it if needed
loginViewModel.warningMessage.observe(this, Observer { message ->
if (message.isNotEmpty()) {
warningMessageTextView.text = Editable.Factory.getInstance().newEditable(message)
warningMessageTextView.visibility = View.VISIBLE
} else {
warningMessageTextView.visibility = View.GONE
}
})
}
// Update UI with the logged-in user's information
private fun updateUiWithUser(model: LoggedInUserView) {
val welcome = getString(R.string.welcome)
val displayName = model.displayName
lastToastMessage = "$welcome $displayName"
Toast.makeText(
applicationContext,
"$welcome $displayName",
Toast.LENGTH_LONG
).show()
// Navigate to MainActivity after successful login
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("USER_EMAIL", username.text.toString())
startActivity(intent)
finish() // Close the login screen
}
// Show an error message if login fails
private fun showLoginFailed(@StringRes errorString: Int) {
Toast.makeText(applicationContext, errorString, Toast.LENGTH_SHORT).show()
}
fun getLastToastMessage(): String? {
return lastToastMessage
}
}
/**
* Extension function to simplify setting an afterTextChanged action to EditText components.
*/
fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
afterTextChanged.invoke(editable.toString())
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})
}
| 0
|
Kotlin
|
0
| 0
|
08454cb98c6e9a02c378a9efbdda2cca9354c12c
| 6,142
|
taskmanagerplus-android-app
|
MIT License
|
examples/yfiles-optimizer/src/main/kotlin/com/test/example/app/App.kt
|
turansky
| 239,704,753
| false
| null |
package com.test.example.app
class App {
fun whatIsTheMeaningOfLife(): String = "42"
fun kyky(): List<String> = listOf("ky", "ky")
}
| 0
|
Kotlin
|
4
| 40
|
c2de9cae2f6f61adcf8ac3d48d7020054342a571
| 143
|
kfc-plugins
|
Apache License 2.0
|
app/src/androidTest/java/org/wikipedia/tinkoff/a/Feed.kt
|
surnin26
| 632,479,810
| false
| null |
package org.wikipedia.tinkoff.a
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.wikipedia.main.MainActivity
import org.wikipedia.tinkoff.screens.Menu
import org.wikipedia.tinkoff.screens.OnboardPage
import org.wikipedia.tinkoff.screens.Settings
import org.wikipedia.tinkoff.screens.SettingsFeed
@RunWith(AndroidJUnit4::class)
class Feed {
@get:Rule
val activityRule = ActivityScenarioRule(MainActivity::class.java)
@Test
fun feedSettingsCheck() {
OnboardPage().navigateToMainPage()
Menu().openSettings()
Settings().openFeedSettings()
SettingsFeed().verifyFeedOptions()
}
}
| 0
|
Kotlin
|
0
| 0
|
5b88b09031971d9a46d530f3baa8c9aa211039c7
| 778
|
tinkoffWikipedia
|
Apache License 2.0
|
src/main/kotlin/net/leanix/vsm/githubbroker/connector/domain/AssignmentProvider.kt
|
leanix
| 563,788,890
| false
|
{"Kotlin": 96728, "Dockerfile": 244}
|
package net.leanix.vsm.githubbroker.connector.domain
interface AssignmentProvider {
fun getAssignments(integrationName: String, configSetName: String): Result<List<Assignment>>
}
| 0
|
Kotlin
|
1
| 4
|
13f61af20a53bb7fcbd0a0b435a8839d0da573f6
| 184
|
vsm-github-broker
|
Apache License 2.0
|
hoplite-yaml/src/test/kotlin/com/sksamuel/hoplite/decoder/Base64DecoderTest.kt
|
sksamuel
| 187,727,131
| false
|
{"Kotlin": 582464}
|
package com.sksamuel.hoplite.decoder
import com.sksamuel.hoplite.ConfigException
import com.sksamuel.hoplite.ConfigLoader
import com.sksamuel.hoplite.ConfigLoaderBuilder
import com.sksamuel.hoplite.yaml.YamlPropertySource
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldContain
import java.nio.ByteBuffer
class Base64DecoderTest : StringSpec({
"base64 decoded from string" {
data class Test(val b: Base64)
val config = ConfigLoader().loadConfigOrThrow<Test>("/base64.yml")
config shouldBe Test(Base64(ByteBuffer.wrap("hello world".encodeToByteArray())))
}
"invalid base64" {
data class Test(val b: Base64)
shouldThrow<ConfigException> {
ConfigLoaderBuilder.default()
.addSource(YamlPropertySource("b: 123!"))
.build()
.loadConfigOrThrow<Test>()
}.message shouldContain "Base64 could not be decoded from a String value: 123!"
}
})
| 21
|
Kotlin
|
74
| 918
|
c21e77ea11e26d7852cb6a1859bfc26dee74974e
| 1,021
|
hoplite
|
Apache License 2.0
|
app/src/main/java/com/moji/sevenchallenge/models/Category.kt
|
mojikashani
| 305,633,671
| false
| null |
package com.moji.sevenchallenge.models
data class Category(
val index: Int,
val name: String,
val displayName: String,
var movieTitles: List<MovieTitle> = listOf()
)
| 0
|
Kotlin
|
0
| 0
|
62042e6217552ede74f4d42a6301539d5b55fc63
| 182
|
SevenPlus
|
Apache License 2.0
|
app/src/main/java/ru/nikstep/alarm/util/date/dateUtils.kt
|
nikita715
| 224,504,692
| false
| null |
package ru.nikstep.alarm.util.date
import java.util.Calendar
import java.util.GregorianCalendar
fun formatDate(hour: Int, minute: Int) =
hour.toString().padStart(2, '0') + ":" + minute.toString().padStart(2, '0')
class CurrentDateInfo private constructor(
private val calendar: Calendar = Calendar.getInstance()
) {
val year: Int
get() = calendar.get(Calendar.YEAR)
val month: Int
get() = calendar.get(Calendar.MONTH)
val day: Int
get() = calendar.get(Calendar.DAY_OF_MONTH)
val hour: Int
get() = calendar.get(Calendar.HOUR)
val minute: Int
get() = calendar.get(Calendar.MINUTE)
val second: Int
get() = calendar.get(Calendar.SECOND)
operator fun plus(type: Int) = CurrentDateInfoChange(this, type, CalendarChangeType.PLUS)
operator fun plusAssign(data: CurrentDateInfoChangeData): Unit = calendar.add(data.type, data.value)
operator fun minus(type: Int) = CurrentDateInfoChange(this, type, CalendarChangeType.MINUS)
class CurrentDateInfoChange internal constructor(
private val currentDateInfo: CurrentDateInfo,
private val type: Int,
private val calendarChangeType: CalendarChangeType
) {
infix fun of(value: Int) = currentDateInfo.also {
when (calendarChangeType) {
CalendarChangeType.PLUS -> it.calendar.add(type, value)
CalendarChangeType.MINUS -> it.calendar.roll(type, value)
}
}
}
class CurrentDateInfoChangeData constructor(
internal val value: Int,
internal val type: Int
)
internal enum class CalendarChangeType {
PLUS,
MINUS
}
companion object {
fun getCurrentDate() = CurrentDateInfo()
}
}
infix fun Int.of(type: Int): CurrentDateInfo.CurrentDateInfoChangeData =
CurrentDateInfo.CurrentDateInfoChangeData(this, type)
operator fun Calendar.plus(plusValue: Int): CalendarPlus = CalendarPlus(this, plusValue)
fun Calendar.isBeforeNow() = before(Calendar.getInstance())
class CalendarPlus(
private val calendar: Calendar,
private val plusValue: Int
) {
infix fun of(type: Int): Calendar = calendar.also { it.add(type, plusValue) }
}
fun buildNextAlarmCalendar(hour: Int, minute: Int): Calendar {
val year: Int
val month: Int
val dayOfMonth: Int
CurrentDateInfo.getCurrentDate().also { dateInfo ->
if (dateInfo.hour >= hour && dateInfo.minute >= minute) {
dateInfo += 1 of Calendar.DAY_OF_MONTH
}
dayOfMonth = dateInfo.day
year = dateInfo.year
month = dateInfo.month
}
return GregorianCalendar(year, month, dayOfMonth, hour, minute)
}
fun buildNextAlarmReminderCalendar(hour: Int, minute: Int, minutesBeforeTheAlarm: Int): Calendar =
buildNextAlarmCalendar(hour, minute).also { it.add(Calendar.MINUTE, -minutesBeforeTheAlarm) }
| 0
|
Kotlin
|
0
| 1
|
5eae531ba4a8184f4f8abfefcbab2c4486efc003
| 2,912
|
spotify-alarm-clock
|
Apache License 2.0
|
app/src/main/java/com/shivamkumarjha/supaflix/ui/detail/DetailInteractionEvents.kt
|
ShivamKumarJha
| 353,360,246
| false
| null |
package com.shivamkumarjha.supaflix.ui.detail
import com.shivamkumarjha.supaflix.model.db.History
import com.shivamkumarjha.supaflix.model.xmovies.Property
import com.shivamkumarjha.supaflix.model.xmovies.SimilarContents
sealed class DetailInteractionEvents {
object NavigateUp : DetailInteractionEvents()
data class OpenEpisode(val history: History) : DetailInteractionEvents()
data class OpenMovieDetail(val similarContents: SimilarContents) : DetailInteractionEvents()
data class SearchGenre(val property: Property) : DetailInteractionEvents()
data class SearchActor(val property: Property) : DetailInteractionEvents()
data class SearchDirector(val property: Property) : DetailInteractionEvents()
data class SearchCountry(val property: Property) : DetailInteractionEvents()
}
| 0
|
Kotlin
|
1
| 9
|
f027c8ae631b032b621ef2f33c8370b8919b7043
| 808
|
supaflix
|
MIT License
|
src/main/kotlin/de/sambalmueslie/discord/bot/staffsergeant/discord/processor/NotifyOnAssignedRoleProcessor.kt
|
Black-Forrest-Development
| 517,332,893
| false
| null |
//package de.sambalmueslie.discord.bot.staffsergeant.discord.processor
//
//
//import de.sambalmueslie.discord.bot.staffsergeant.discord.DiscordBot
//import de.sambalmueslie.discord.bot.staffsergeant.discord.db.MemberNotifiedRoleEntry
//import de.sambalmueslie.discord.bot.staffsergeant.discord.db.MemberNotifiedRoleEntryRepository
//import de.sambalmueslie.discord.bot.staffsergeant.message.MessageService
//import de.sambalmueslie.discord.bot.staffsergeant.message.api.Message
//import discord4j.core.event.domain.guild.MemberUpdateEvent
//import discord4j.core.`object`.entity.Member
//import discord4j.core.`object`.entity.Role
//import discord4j.core.`object`.entity.channel.PrivateChannel
//import kotlinx.coroutines.Dispatchers
//import kotlinx.coroutines.reactor.awaitSingle
//import kotlinx.coroutines.reactor.awaitSingleOrNull
//import kotlinx.coroutines.withContext
//import org.apache.velocity.VelocityContext
//import org.apache.velocity.app.VelocityEngine
//import org.slf4j.Logger
//import org.slf4j.LoggerFactory
//import java.io.StringWriter
//
//class NotifyOnAssignedRoleProcessor(
// private val messageService: MessageService,
// private val repository: MemberNotifiedRoleEntryRepository,
//) {
//
// companion object {
// val logger: Logger = LoggerFactory.getLogger(NotifyOnAssignedRoleProcessor::class.java)
// }
//
// private val ve = VelocityEngine()
//
// init {
// ve.init()
// }
//
// suspend fun handleMemberUpdateEvent(event: MemberUpdateEvent){
// val member = event.member.awaitSingleOrNull() ?: return DiscordBot.logger.error("Cannot get member from event")
// val channel = member.privateChannel.awaitSingle()
// val roles = member.roles.toIterable().associateBy { it.name }
// DiscordBot.logger.info("Found roles for member ${roles.keys}")
//
// val memberId = member.id.asLong()
// val entries = repository.findByMemberId(memberId).associateBy { it.role }
//
// roles.values.forEach { updateActiveRoles(it, entries, channel, member) }
// cleanupRemovedRoles(entries, roles)
// }
//
//
// private suspend fun updateActiveRoles(
// role: Role, entries: Map<String, MemberNotifiedRoleEntry>, channel: PrivateChannel, member: Member
// ) {
// val message = messageService.getMessageForRole(role.guildId.asLong(), role.name)
// val entry = entries[role.name]
// if (message == null && entry == null) return
// if (message == null && entry != null) {
// withContext(Dispatchers.IO) {
// repository.delete(entry)
// }
// }
// if (message != null && entry == null) {
// channel.createMessage(resolve(member, role, message)).awaitSingle()
// val memberId = member.id.asLong()
// withContext(Dispatchers.IO) {
// repository.save(MemberNotifiedRoleEntry("$memberId#${role.name}", memberId, role.name))
// }
// }
// }
//
// private fun resolve(member: Member, role: Role, message: Message): String {
// val context = VelocityContext(
// mapOf(
// Pair("member", member), Pair("role", role)
// )
// )
// val writer = StringWriter()
// ve.evaluate(context, writer, message.name, message.text)
// return writer.toString()
// }
//
// private suspend fun cleanupRemovedRoles(
// entries: Map<String, MemberNotifiedRoleEntry>, roles: Map<String, Role>
// ) {
// val removed = entries.filter { !roles.containsKey(it.key) }.map { it.value }
// if (removed.isNotEmpty()) withContext(Dispatchers.IO) {
// repository.deleteAll(removed)
// }
// }
//}
| 1
|
Kotlin
|
0
| 0
|
74ca1f87eb5b825ab98d8a260dd7a6c0bc91f215
| 3,748
|
staffseargant
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/batch/EcsContainerDefinitionPropsDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 70198112}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.batch
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Boolean
import kotlin.Number
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.Map
import kotlin.collections.MutableList
import software.amazon.awscdk.Size
import software.amazon.awscdk.services.batch.EcsContainerDefinitionProps
import software.amazon.awscdk.services.batch.EcsVolume
import software.amazon.awscdk.services.batch.LinuxParameters
import software.amazon.awscdk.services.batch.Secret
import software.amazon.awscdk.services.ecs.ContainerImage
import software.amazon.awscdk.services.ecs.LogDriver
import software.amazon.awscdk.services.iam.IRole
/**
* Props to configure an EcsContainerDefinition.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.*;
* import software.amazon.awscdk.services.batch.*;
* import software.amazon.awscdk.services.ecs.*;
* import software.amazon.awscdk.services.iam.*;
* ContainerImage containerImage;
* EcsVolume ecsVolume;
* LinuxParameters linuxParameters;
* LogDriver logDriver;
* Role role;
* Secret secret;
* Size size;
* EcsContainerDefinitionProps ecsContainerDefinitionProps = EcsContainerDefinitionProps.builder()
* .cpu(123)
* .image(containerImage)
* .memory(size)
* // the properties below are optional
* .command(List.of("command"))
* .environment(Map.of(
* "environmentKey", "environment"))
* .executionRole(role)
* .jobRole(role)
* .linuxParameters(linuxParameters)
* .logging(logDriver)
* .readonlyRootFilesystem(false)
* .secrets(Map.of(
* "secretsKey", secret))
* .user("user")
* .volumes(List.of(ecsVolume))
* .build();
* ```
*/
@CdkDslMarker
public class EcsContainerDefinitionPropsDsl {
private val cdkBuilder: EcsContainerDefinitionProps.Builder =
EcsContainerDefinitionProps.builder()
private val _command: MutableList<String> = mutableListOf()
private val _volumes: MutableList<EcsVolume> = mutableListOf()
/** @param command The command that's passed to the container. */
public fun command(vararg command: String) {
_command.addAll(listOf(*command))
}
/** @param command The command that's passed to the container. */
public fun command(command: Collection<String>) {
_command.addAll(command)
}
/**
* @param cpu The number of vCPUs reserved for the container. Each vCPU is equivalent to 1,024
* CPU shares. For containers running on EC2 resources, you must specify at least one vCPU.
*/
public fun cpu(cpu: Number) {
cdkBuilder.cpu(cpu)
}
/**
* @param environment The environment variables to pass to a container. Cannot start with
* `AWS_BATCH`. We don't recommend using plaintext environment variables for sensitive
* information, such as credential data.
*/
public fun environment(environment: Map<String, String>) {
cdkBuilder.environment(environment)
}
/**
* @param executionRole The role used by Amazon ECS container and AWS Fargate agents to make AWS
* API calls on your behalf.
*/
public fun executionRole(executionRole: IRole) {
cdkBuilder.executionRole(executionRole)
}
/** @param image The image that this container will run. */
public fun image(image: ContainerImage) {
cdkBuilder.image(image)
}
/** @param jobRole The role that the container can assume. */
public fun jobRole(jobRole: IRole) {
cdkBuilder.jobRole(jobRole)
}
/**
* @param linuxParameters Linux-specific modifications that are applied to the container, such
* as details for device mappings.
*/
public fun linuxParameters(linuxParameters: LinuxParameters) {
cdkBuilder.linuxParameters(linuxParameters)
}
/** @param logging The loging configuration for this Job. */
public fun logging(logging: LogDriver) {
cdkBuilder.logging(logging)
}
/**
* @param memory The memory hard limit present to the container. If your container attempts to
* exceed the memory specified, the container is terminated. You must specify at least 4 MiB
* of memory for a job.
*/
public fun memory(memory: Size) {
cdkBuilder.memory(memory)
}
/** @param readonlyRootFilesystem Gives the container readonly access to its root filesystem. */
public fun readonlyRootFilesystem(readonlyRootFilesystem: Boolean) {
cdkBuilder.readonlyRootFilesystem(readonlyRootFilesystem)
}
/**
* @param secrets A map from environment variable names to the secrets for the container. Allows
* your job definitions to reference the secret by the environment variable name defined in
* this property.
*/
public fun secrets(secrets: Map<String, Secret>) {
cdkBuilder.secrets(secrets)
}
/** @param user The user name to use inside the container. */
public fun user(user: String) {
cdkBuilder.user(user)
}
/**
* @param volumes The volumes to mount to this container. Automatically added to the job
* definition.
*/
public fun volumes(vararg volumes: EcsVolume) {
_volumes.addAll(listOf(*volumes))
}
/**
* @param volumes The volumes to mount to this container. Automatically added to the job
* definition.
*/
public fun volumes(volumes: Collection<EcsVolume>) {
_volumes.addAll(volumes)
}
public fun build(): EcsContainerDefinitionProps {
if (_command.isNotEmpty()) cdkBuilder.command(_command)
if (_volumes.isNotEmpty()) cdkBuilder.volumes(_volumes)
return cdkBuilder.build()
}
}
| 0
|
Kotlin
|
0
| 3
|
256ad92aebe2bcf9a4160089a02c76809dbbedba
| 6,026
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
asyncapi-core/src/test/kotlin/com/asyncapi/v3/schema/multiformat/asyncapi/NullSchemaFormatTest.kt
|
asyncapi
| 262,555,517
| false
|
{"Kotlin": 1663312, "Java": 768695}
|
package com.asyncapi.v3.schema.multiformat.asyncapi
import com.asyncapi.v3.schema.json.*
import com.asyncapi.v3.schema.multiformat.AsyncAPIFormatSchema
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
import java.util.stream.Stream
abstract class NullSchemaFormatTest: AsyncAPIFormatSchemaTest() {
@ArgumentsSource(Json::class)
@ParameterizedTest(name = "Read: {0}")
override fun parseJson(
asyncAPIFormatSchemaToCompareWithFilePath: String,
asyncAPIFormatSchema: AsyncAPIFormatSchema
) {
compareSchemas(asyncAPIFormatSchemaToCompareWithFilePath, asyncAPIFormatSchema)
}
@ArgumentsSource(Yaml::class)
@ParameterizedTest(name = "Read: {0}")
override fun parseYaml(
asyncAPIFormatSchemaToCompareWithFilePath: String,
asyncAPIFormatSchema: AsyncAPIFormatSchema
) {
compareSchemas(asyncAPIFormatSchemaToCompareWithFilePath, asyncAPIFormatSchema)
}
class Json: ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> {
return Stream.of(
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/arrays.schema.json",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", ArraysSchemaTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/complex-object.schema.json",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", ComplexObjectTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/conditional-validation-if-else.schema.json",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", ConditionalValidationIfElse().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/draft-07-core-schema-meta-schema.json",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", Draft07CoreSchemaMetaSchemaTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/enumerated-values.schema.json",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", EnumeratedValuesTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/person.schema.json",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", PersonTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/regex-pattern.schema.json",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", RegexPatternTest().asyncAPISchema())
)
)
}
}
class Yaml: ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> {
return Stream.of(
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/arrays.schema.yaml",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", ArraysSchemaTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/complex-object.schema.yaml",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", ComplexObjectTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/conditional-validation-if-else.schema.yaml",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", ConditionalValidationIfElse().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/draft-07-core-schema-meta-schema.yaml",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", Draft07CoreSchemaMetaSchemaTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/enumerated-values.schema.yaml",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", EnumeratedValuesTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/person.schema.yaml",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", PersonTest().asyncAPISchema())
),
Arguments.of(
"/json/v3/schema/multiformat/schemaFormat is null/regex-pattern.schema.yaml",
AsyncAPIFormatSchema("application/vnd.aai.asyncapi+json;version=3.0.0", RegexPatternTest().asyncAPISchema())
)
)
}
}
}
| 11
|
Kotlin
|
22
| 64
|
94a3d1628b17ec58659693bc9ad3b98bca53f172
| 5,494
|
jasyncapi
|
Apache License 2.0
|
benchmark/src/main/kotlin/dev/marlonlom/apps/benchmark/ExampleStartupBenchmark.kt
|
marlonlom
| 668,920,205
| false
| null |
/*
* Copyright 2023 marlonlom
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
*/
package dev.marlonlom.apps.benchmark
import androidx.benchmark.macro.StartupMode
import androidx.benchmark.macro.StartupTimingMetric
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* This is an example startup benchmark.
*
* It navigates to the device's home screen, and launches the default activity.
*
* Before running this benchmark:
* 1) switch your app's active build variant in the Studio (affects Studio runs only)
* 2) add `<profileable android:shell="true" />` to your app's manifest, within the `<application>` tag
*
* Run this benchmark from Studio to see startup measurements, and captured system traces
* for investigating your app's performance.
*/
@RunWith(AndroidJUnit4::class)
class ExampleStartupBenchmark {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
@Test
fun startup() = benchmarkRule.measureRepeated(
packageName = "dev.marlonlom.apps.efecty_nmoc",
metrics = listOf(StartupTimingMetric()),
iterations = 5,
startupMode = StartupMode.COLD
) {
pressHome()
startActivityAndWait()
}
}
| 0
|
Kotlin
|
0
| 0
|
0d7d8efadca32664a783c282b1743d7456d8c2c7
| 1,394
|
moneyio
|
MIT License
|
src/main/kotlin/me/stkai/mybatis/log/util/PrintUtils.kt
|
Stkai
| 405,568,439
| false
| null |
/*
* Copyright (c) 2021. St.kai.
*
* 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 me.stkai.mybatis.log.util
import com.intellij.execution.ui.ConsoleView
import com.intellij.execution.ui.ConsoleViewContentType
/**
* 打印工具类
*
* @author St.kai
* @version 1.0
* @since 2021-09-09 20:40
*/
class PrintUtils(message: String, consoleViewContentType: ConsoleViewContentType) {
init {
consoleView.print(message + "\n", consoleViewContentType)
}
companion object {
lateinit var consoleView: ConsoleView
fun debug(message: String) {
consoleView.print(message + "\n", ConsoleViewContentType.LOG_DEBUG_OUTPUT)
}
fun info(message: String) {
consoleView.print(message + "\n", ConsoleViewContentType.LOG_INFO_OUTPUT)
}
fun warn(message: String) {
consoleView.print(message + "\n", ConsoleViewContentType.LOG_WARNING_OUTPUT)
}
fun error(message: String) {
consoleView.print(message + "\n", ConsoleViewContentType.ERROR_OUTPUT)
}
fun normal(message: String) {
consoleView.print(message + "\n", ConsoleViewContentType.NORMAL_OUTPUT)
}
fun system(message: String) {
consoleView.print(message + "\n", ConsoleViewContentType.SYSTEM_OUTPUT)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e412131f7bcf4c1ce65c1c3721bbdac63e835237
| 1,861
|
intellij-mybatis-log-plugin
|
Apache License 2.0
|
src/main/kotlin/sishbi/vertx/kotlin/DB.kt
|
sishbi
| 764,792,610
| false
|
{"Kotlin": 14646}
|
package sishbi.vertx.kotlin
import io.vertx.core.Vertx
import io.vertx.kotlin.pgclient.pgConnectOptionsOf
import io.vertx.kotlin.sqlclient.poolOptionsOf
import io.vertx.pgclient.PgBuilder
import io.vertx.sqlclient.Pool
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import org.flywaydb.core.Flyway
private val LOG = KotlinLogging.logger {}
class DB(vertx: Vertx) {
init {
pool = PgBuilder
.pool()
.with(poolOptionsOf(maxSize = 5))
.connectingTo(
pgConnectOptionsOf(
host = configuration.dbHost,
port = configuration.dbPort,
database = configuration.dbDB,
user = configuration.dbUser,
password = <PASSWORD>
)
)
.using(vertx)
.build()
}
suspend fun initDB(): Boolean = withContext(Dispatchers.IO) {
try {
Flyway
.configure()
.dataSource(configuration.dbUrl, configuration.dbUser, configuration.dbPassword)
.load()
.migrate()
.success
} catch (e: Exception) {
LOG.error(e) { "Failed to migrate DB" }
throw e
}
}
companion object {
lateinit var pool: Pool
}
}
| 0
|
Kotlin
|
0
| 0
|
6781b7f8f9b91e29d908d8b51ed1ea83e4d63c86
| 1,399
|
kotlin-vertx-talk
|
MIT License
|
app/src/main/kotlin/server/persistence/BackupsDal.kt
|
skeid21
| 676,324,775
| false
|
{"Kotlin": 71888, "Dockerfile": 281}
|
package server.persistence
import com.google.inject.Inject
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.kotlin.datetime.timestamp
import org.jetbrains.exposed.sql.transactions.transaction
import server.models.Backup
import server.models.BackupName
import server.models.asBackupName
/** Data definition for the Backups table* */
object Backups : IntIdTable() {
val name: Column<String> = varchar("name", 2083).uniqueIndex()
val createTime: Column<Instant> = timestamp("create_time")
val displayName: Column<String> = varchar("display_name", 256)
val cronSchedule: Column<String> = varchar("cron_schedule", 256)
val schedulePaused: Column<Int> = integer("schedule_paused")
val sourceDir: Column<String> = varchar("source_dir", 4096)
val destinationDir: Column<String> = varchar("destination_dir", 4096)
val config: Column<String> = text("config")
}
/** DAO for interacting with the [Backups] table * */
class DAOBackup(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<DAOBackup>(Backups)
var name by Backups.name
var createTime by Backups.createTime
var displayName by Backups.displayName
var cronSchedule by Backups.cronSchedule
var schedulePaused by Backups.schedulePaused
var sourceDir by Backups.sourceDir
var destinationDir by Backups.destinationDir
var config by Backups.config
}
/** A data access layer for persisting [Backup] core models */
class BackupsDal @Inject constructor(private val db: Database) {
fun create(backup: Backup): Backup =
transaction(db) {
DAOBackup.new {
name = backup.name.value
createTime = Clock.System.now()
update(backup)
}
}
.toBackup()
fun get(name: BackupName): Backup? = transaction(db) { getByName(name) }?.toBackup()
fun list(): List<Backup> = transaction(db) { DAOBackup.all().map { it.toBackup() } }
fun update(backup: Backup): Backup? =
transaction(db) { getByName(backup.name)?.apply { update(backup) } }?.toBackup()
fun delete(name: BackupName) = transaction(db) { getByName(name)?.delete() }
private fun getByName(name: BackupName): DAOBackup? =
DAOBackup.find { Backups.name eq name.value }.firstOrNull()
}
/** Update the [DAOBackup] with fields from the specified [Backup] */
private fun DAOBackup.update(backup: Backup) {
displayName = backup.displayName
cronSchedule = backup.cronSchedule
schedulePaused = if (backup.schedulePaused) 1 else 0
sourceDir = backup.sourceDir
destinationDir = backup.destinationDir
config = backup.config
}
/** Converts a [DAOBackup] to a [Backup]* */
private fun DAOBackup.toBackup(): Backup =
Backup(
name = name.asBackupName(),
createTime = createTime,
displayName = displayName,
cronSchedule = cronSchedule,
schedulePaused = schedulePaused == 1,
sourceDir = sourceDir,
destinationDir = destinationDir,
config = config)
| 0
|
Kotlin
|
0
| 0
|
3f6b76706687b3119b8be0780f04e3e4c9826e5a
| 3,279
|
unraid_rclone_backup
|
MIT License
|
tools/sql_extraction/src/main/kotlin/output/Location.kt
|
arcdesign
| 275,235,867
| true
|
{"HTML": 705589, "TSQL": 53723, "Kotlin": 24145, "Python": 23450, "Shell": 6071, "Java": 1507, "PLpgSQL": 1174, "PLSQL": 1102}
|
package com.google.cloud.sqlecosystem.sqlextraction.output
import java.lang.Integer.max
import java.lang.Integer.min
/**
* All values inclusive
*/
data class Location(
val startLine: Int,
val startColumn: Int,
val endLine: Int,
val endColumn: Int
) {
companion object {
/** Returns the union of [a] and [b] */
fun combine(a: Location, b: Location): Location {
return Location(
startLine = min(a.startLine, b.startLine),
startColumn = when {
a.startLine < b.startLine -> a.startColumn
a.startLine > b.startLine -> b.startColumn
else -> min(a.startColumn, b.startColumn)
},
endLine = max(a.endLine, b.endLine),
endColumn = when {
a.endLine > b.endLine -> a.endColumn
a.endLine < b.endLine -> b.endColumn
else -> max(a.endColumn, b.endColumn)
}
)
}
/** Reduces [locations] into the union using [combine] */
fun combine(locations: Iterable<Location>): Location {
return locations.reduce { a, b -> combine(a, b) }
}
}
}
| 0
| null |
0
| 0
|
ff2125daec1d2e8d22ed2568268baa868888a700
| 1,243
|
bigquery-utils
|
Apache License 2.0
|
data/src/androidTest/java/com/robertomiranda/data/room/UsersDaoTest.kt
|
RoberMiranda92
| 259,187,177
| false
| null |
package com.robertomiranda.data.room
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.robertomiranda.data.BaseDataBaseTest
import com.robertomiranda.data.room.dao.UsersDao
import com.robertomiranda.data.room.models.UserRoom
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class UsersDaoTest : BaseDataBaseTest() {
private lateinit var usersDao: UsersDao
override fun setUpChild() {
super.setUpChild()
usersDao = database.usersDao()
}
@Test
fun insertAndGetAllUsers() {
val usersList = mutableListOf<UserRoom>(
User1,
User2
)
usersDao.addAll(usersList).test().await()
val testObserver = usersDao.getAllUsers().test()
testObserver.awaitCount(1)
testObserver.assertResult(usersList)
testObserver.dispose()
}
@Test
fun insertAndGetPostByID() {
val usersList = mutableListOf<UserRoom>(
User1,
User2
)
usersDao.addAll(usersList).test().await()
val testObserver = usersDao.getUserById(1).test()
testObserver.awaitCount(1)
testObserver.assertResult(User1)
testObserver.dispose()
}
companion object {
val User1 = UserRoom(
1, "hildegard.org", 1, "1-770-736-8031 x56442",
"Romaguera-Crona",
1, "<EMAIL>", "Bret"
)
val User2 = UserRoom(
2, "anastasia.net", 2, "010-692-6593 x09125",
"<NAME>",
2, "<EMAIL>", "Antonette"
)
}
}
| 0
|
Kotlin
|
0
| 0
|
b37b413cf2f26596294040938a089998cfd6d93f
| 1,604
|
Post-List
|
Apache License 2.0
|
theme-vitamin/features/src/main/java/org/gdglille/devfest/android/theme/vitamin/features/PartnersVM.kt
|
GerardPaligot
| 444,230,272
| false
| null |
package org.gdglille.devfest.android.theme.vitamin.features
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import org.gdglille.devfest.android.data.viewmodels.PartnersUiState
import org.gdglille.devfest.android.data.viewmodels.PartnersViewModel
import org.gdglille.devfest.android.theme.vitamin.ui.screens.partners.Partners
import org.gdglille.devfest.android.ui.resources.R
import org.gdglille.devfest.repositories.AgendaRepository
@Composable
fun PartnersVM(
agendaRepository: AgendaRepository,
onPartnerClick: (siteUrl: String?) -> Unit,
modifier: Modifier = Modifier,
viewModel: PartnersViewModel = viewModel(
factory = PartnersViewModel.Factory.create(agendaRepository)
)
) {
val uiState = viewModel.uiState.collectAsState()
when (uiState.value) {
is PartnersUiState.Loading -> Partners(
partners = (uiState.value as PartnersUiState.Loading).partners,
modifier = modifier,
isLoading = true,
onPartnerClick = {}
)
is PartnersUiState.Failure -> Text(text = stringResource(id = R.string.text_error))
is PartnersUiState.Success -> Partners(
partners = (uiState.value as PartnersUiState.Success).partners,
modifier = modifier,
onPartnerClick = onPartnerClick
)
}
}
| 11
| null |
6
| 126
|
6823162e323d6975403611ad787df99e6541d251
| 1,548
|
conferences4hall
|
Apache License 2.0
|
picker-file/src/main/java/chooongg/box/picker/file/breadcrumbs/BreadcrumbsLayoutManager.kt
|
Chooongg
| 298,511,826
| false
| null |
package chooongg.box.picker.file.breadcrumbs
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.LinearLayoutManager
class BreadcrumbsLayoutManager : LinearLayoutManager {
constructor(context: Context) : super(context)
constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(
context, orientation, reverseLayout
)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(
context, attrs, defStyleAttr, defStyleRes
)
// override fun supportsPredictiveItemAnimations(): Boolean {
// return false
// }
}
| 0
|
Kotlin
|
1
| 2
|
f2b4adac448036ef2e48ec2a3ac030c7f8d0fe2e
| 664
|
ChooonggBox
|
Apache License 2.0
|
lib/src/androidMain/kotlin/io/vithor/domehttp/DefaultDispatcher.kt
|
Hazer
| 190,490,922
| false
| null |
package io.vithor.domehttp
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
actual val DefaultDispatcher: CoroutineDispatcher
get() = Dispatchers.IO
| 1
|
Kotlin
|
0
| 4
|
8e41652ce0981a5ed6389e5ddde04aeadd9c5b0c
| 189
|
DomeHTTP
|
MIT License
|
src/main/kotlin/com/vk/admstorm/configuration/runanything/RunAnythingConfigurationRunner.kt
|
VKCOM
| 454,408,302
| false
| null |
package com.vk.admstorm.configuration.runanything
import com.vk.admstorm.configuration.WithSshConfigurationRunner
class RunAnythingConfigurationRunner : WithSshConfigurationRunner(
withDebug = false,
inEDT = false,
RunAnythingConfiguration::class
) {
override fun getRunnerId() = "RunAnything"
}
| 32
|
Kotlin
|
3
| 9
|
a0f16edbaab1b37ae08b7244df9d0585b7949042
| 314
|
admstorm
|
MIT License
|
src/main/java/com/jagrosh/jmusicbot/commands/SkipCmd.kt
|
JellyBrick
| 144,745,076
| true
|
{"Kotlin": 160880}
|
/*
* Copyright 2016 <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.jagrosh.jmusicbot.commands
import com.jagrosh.jdautilities.command.CommandEvent
import com.jagrosh.jmusicbot.Bot
import com.jagrosh.jmusicbot.audio.AudioHandler
/**
*
* @author <NAME> <<EMAIL>a.grosh></<EMAIL>>
*/
class SkipCmd(bot: Bot) : MusicCommand(bot) {
init {
this.name = "skip"
this.help = "votes to skip the current song"
this.aliases = arrayOf("voteskip")
this.beListening = true
this.bePlaying = true
}
public override fun doCommand(event: CommandEvent) {
val handler = event.guild.audioManager.sendingHandler as AudioHandler
if (event.author.idLong == handler.requester) {
event.reply(event.client.success + " Skipped **" + handler.player.playingTrack.info.title + "**")
handler.player.stopTrack()
} else {
val listeners = event.selfMember.voiceState.channel.members.stream()
.filter { m -> !m.user.isBot && !m.voiceState.isDeafened }.count().toInt()
var msg: String
if (handler.votes.contains(event.author.id))
msg = event.client.warning + " You already voted to skip this song `["
else {
msg = event.client.success + " You voted to skip the song `["
handler.votes.add(event.author.id)
}
val skippers = event.selfMember.voiceState.channel.members.stream()
.filter { m -> handler.votes.contains(m.user.id) }.count().toInt()
val required = Math.ceil(listeners * .55).toInt()
msg += skippers.toString() + " votes, " + required + "/" + listeners + " needed]`"
if (skippers >= required) {
val u = event.jda.getUserById(handler.requester)
msg += ("\n" + event.client.success + " Skipped **" + handler.player.playingTrack.info.title
+ "**" + if (handler.requester == 0L) "" else " (requested by " + (if (u == null) "someone" else "**" + u.name + "**") + ")")
handler.player.stopTrack()
}
event.reply(msg)
}
}
}
| 0
|
Kotlin
|
0
| 6
|
746b756aaa84f7fd27174d6cad3239dee402af1f
| 2,743
|
MusicBot-Kotlin
|
Apache License 2.0
|
src/main/kotlin/com/skywalker/active/repository/ActiveRepository.kt
|
duxingxia081
| 133,362,521
| false
| null |
package com.skywalker.active.repository
import com.skywalker.active.dto.ActiveDTO
import com.skywalker.base.bo.MhoSkywalkerActive
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.util.*
@Repository
interface ActiveRepository : JpaRepository<MhoSkywalkerActive, Long>, JpaSpecificationExecutor<MhoSkywalkerActive> {
@Query("select new com.skywalker.active.dto.ActiveDTO(f.activeId,f.activeTitle,f.postUserId,f.typeId,f.startAddressName,f.startAddressCoordinate,f.endAddressName,f.endAddressCoordinate,f.goTime,f.days,f.charge,f.content,f.coverImage,u.userName,u.nickname,u.headImage,t.typeName,f.timeCreate) from MhoSkywalkerActive f,MhoSkywalkerUser u,MhoSkywalkerActiveType t where f.postUserId=u.userId and f.typeId=t.typeId and f.typeId=?1 and f.timeCreate<?2 order by f.timeCreate desc")
fun listAllByTypeId(typeId: Long, time: Date, pageable: Pageable): Page<ActiveDTO>?
@Query("select new com.skywalker.active.dto.ActiveDTO(f.activeId,f.activeTitle,f.postUserId,f.typeId,f.startAddressName,f.startAddressCoordinate,f.endAddressName,f.endAddressCoordinate,f.goTime,f.days,f.charge,f.content,f.coverImage,u.userName,u.nickname,u.headImage,t.typeName,f.timeCreate) from MhoSkywalkerActive f,MhoSkywalkerUser u,MhoSkywalkerActiveType t where f.postUserId=u.userId and f.typeId=t.typeId and f.activeId=?1 order by f.timeCreate desc")
fun listAllByActiveId(activeId: Long): ActiveDTO
@Query("from MhoSkywalkerActive f where f.postUserId=?1 and f.timeCreate>?2 order by f.timeCreate desc")
fun listActiveByUserId(userId: Long, timeCreate: Date): List<MhoSkywalkerActive>?
@Query("select new com.skywalker.active.dto.ActiveDTO(f.activeId,f.activeTitle,f.postUserId,f.typeId,f.startAddressName,f.startAddressCoordinate,f.endAddressName,f.endAddressCoordinate,f.goTime,f.days,f.charge,f.content,f.coverImage,u.userName,u.nickname,u.headImage,t.typeName,f.timeCreate) from MhoSkywalkerActive f,MhoSkywalkerUser u,MhoSkywalkerActiveType t where f.postUserId=u.userId and f.typeId=t.typeId and f.typeId=?1 and f.timeCreate>?2 order by f.timeCreate desc")
fun findByTimeCreateAfter(typeId: Long, time: Date): List<ActiveDTO>?
}
| 0
|
Kotlin
|
0
| 0
|
4551912543cf95b2372a0aa0d9142f2faa2fcbf5
| 2,448
|
skywalker
|
Apache License 2.0
|
src/main/kotlin/Day4.kt
|
ivan-gusiev
| 726,608,707
| false
|
{"Kotlin": 34715, "Python": 2022, "Makefile": 50}
|
import util.AocDay
import util.AocInput
typealias Day4InputType = List<Day4.ScratchCard>;
class Day4 : Runner {
val TEST_INPUT: String = """
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
""".trimIndent()
override fun run() {
val day = AocDay("2023".toInt(), "4".toInt())
val lines = AocInput.lines(day)
//val lines = TEST_INPUT.split("\n")
val cards = lines.map(ScratchCard::parse)
part1(cards)
part2(cards)
}
private fun part1(input: Day4InputType) {
val scores = input.map(ScratchCard::part1Score)
println(scores.sum())
}
private fun part2(input: Day4InputType) {
val calculator = ScoreCalculator(input)
val totalScore = input
.map { x -> calculator.scoreByIndex(x.id) }
.reduce(CardDistribution::plus)
.ids
.reduce(Int::plus)
println(totalScore)
}
class ScoreCalculator(private val cards: List<ScratchCard>) {
private val distributionByIndexCache = mutableMapOf<Int, CardDistribution>()
private fun getByIndex(i: Int): ScratchCard {
return cards[i - 1]
}
private fun calculateDistribution(i: Int): CardDistribution {
val nums = IntArray(cards.size)
val card = getByIndex(i)
val winnerIds = card.winnerIds()
nums[i - 1] = 1
var distro = CardDistribution(nums)
winnerIds.forEach { distro += scoreByIndex(it) }
return distro
}
fun scoreByIndex(i: Int): CardDistribution {
return distributionByIndexCache.getOrPut(i) {
calculateDistribution(i)
}
}
}
data class CardDistribution(val ids: IntArray) {
operator fun plus(other: CardDistribution): CardDistribution {
return CardDistribution(ids.zip(other.ids) { a, b -> a + b }.toIntArray())
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CardDistribution
return ids.contentEquals(other.ids)
}
override fun hashCode(): Int {
return ids.contentHashCode()
}
override fun toString(): String {
return ids.joinToString(",")
}
}
data class ScratchCard(val id: Int, val winningNumbers: List<Int>, val scratchNumbers: List<Int>) {
companion object {
// parses text like a line of from TEST_INPUT and returns a ScratchCard
fun parse(input: String): ScratchCard {
val parts = input.replace("Card ", "").split(":")
val id = parts[0].trim().toInt()
val numbers = parts[1].split("|").map { it.trim() }
val winningNumbers = numbers[0].split(Regex("\\s+")).map(String::toInt)
val scratchNumbers = numbers[1].split(Regex("\\s+")).map(String::toInt)
return ScratchCard(id, winningNumbers, scratchNumbers)
}
}
private fun winningCount(): Int {
return scratchNumbers.count { it in winningNumbers }
}
// return 0 if winningCount() == 0, and 2^i, where i is the number of winning numbers
fun part1Score(): Int {
val count = winningCount()
if (count == 0) return 0
return 1 shl (count - 1)
}
fun winnerIds(): List<Int> {
return (id + 1..id + winningCount()).toList()
}
// returns the representation of ScratchCard as a String, like TEST_INPUT
override fun toString(): String {
return "Card $id: ${winningNumbers.joinToString(" ")} | ${scratchNumbers.joinToString(" ")}"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5585816b435b42b4e7c77ce9c8cabc544b2ada18
| 4,137
|
advent-of-code-2023
|
MIT License
|
webauthn/src/main/java/com/lycorp/webauthn/model/Fido2PromptInfo.kt
|
line
| 855,639,495
| false
|
{"Kotlin": 187679}
|
/*
* Copyright 2024 LY Corporation
*
* LY Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.lycorp.webauthn.model
data class Fido2PromptInfo(
val title: CharSequence? = "Biometric Authentication",
val subtitle: CharSequence? = "Enter biometric credentials to proceed",
val description: CharSequence? = "Input your Fingerprint or FaceID to ensure it's you!",
val negativeButtonText: CharSequence? = "Cancel",
)
| 0
|
Kotlin
|
0
| 3
|
f0dca2ed5b66c7aeebc1574c84d1d4c9086b615b
| 978
|
webauthn-kotlin
|
Apache License 2.0
|
app/src/main/java/com/handy/projetfinalenativelependu/AddActivity.kt
|
Handy-up
| 872,648,123
| false
|
{"Kotlin": 55032}
|
package com.handy.projetfinalenativelependu
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
class AddActivity : AppCompatActivity() {
lateinit var editmotFrancais: EditText
lateinit var editmotAnglais: EditText
lateinit var radioGroup: RadioGroup
lateinit var btn_ajouter: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_add)
editmotFrancais = findViewById(R.id.editMotFrancais)
editmotAnglais = findViewById(R.id.editMotAnglais)
radioGroup = findViewById(R.id.radioGroupSettingsLangue)
btn_ajouter = findViewById(R.id.btn_ajouter)
btn_ajouter.setOnClickListener {
val DB = DatabaseHelper(this@AddActivity)
val motFrancais = editmotFrancais.text.toString().trim()
val motAnglais = editmotAnglais.text.toString().trim()
val radioButtonId = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(radioButtonId)
if (motFrancais.isNotEmpty() && motAnglais.isNotEmpty() && radioButton != null) {
val difficulte = when (radioButton.id) {
R.id.radioFacile -> "Facile"
R.id.radioMoyen -> "Moyen"
R.id.radioDifficile -> "Difficile"
else -> "Facile"
}
DB.ajouterMot(this@AddActivity, motFrancais, motAnglais, difficulte)
Toast.makeText(this, "Ajouté avec succès!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(
this,
"Veuillez remplir tous les champs et sélectionner la difficulté.",
Toast.LENGTH_SHORT
).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a1a9fa1d7cee33516a670466dbff06fd8778bf27
| 2,093
|
Jeu-Mobile-Pendu
|
MIT License
|
feature.main/src/main/java/lac/feature/main/app/mobile/bookmarks/BookmarksSubModule.kt
|
bandysik
| 143,031,693
| false
| null |
package lac.feature.main.app.mobile.bookmarks
import lac.feature.main.app.mobile.bookmarks.Params.VIEW
import org.koin.dsl.module.applicationContext
val bookmarksSubModule = applicationContext {
factory { params ->
BookmarksPresenter(params[VIEW], get(), get()) as BookmarksContract.Presenter
}
}
object Params {
const val VIEW = "VIEW"
}
| 0
|
Kotlin
|
0
| 1
|
c2e0478c93eb5eaf7ec1632d2257427a9174443e
| 361
|
LAC
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Roulette.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.Roulette: ImageVector
get() {
if (_roulette != null) {
return _roulette!!
}
_roulette = Builder(name = "Roulette", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(17.999f, 14.508f)
curveToRelative(-0.33f, 0.788f, -0.806f, 1.496f, -1.416f, 2.103f)
lineToRelative(1.759f, 1.768f)
curveToRelative(-0.83f, 0.825f, -1.82f, 1.487f, -2.918f, 1.941f)
lineToRelative(-0.951f, -2.306f)
curveToRelative(-0.783f, 0.322f, -1.615f, 0.486f, -2.473f, 0.486f)
horizontalLineToRelative(-0.015f)
lineToRelative(0.013f, 2.5f)
curveToRelative(-1.223f, 0.0f, -2.389f, -0.248f, -3.453f, -0.692f)
lineToRelative(0.961f, -2.303f)
curveToRelative(-0.791f, -0.329f, -1.499f, -0.805f, -2.106f, -1.412f)
lineToRelative(-1.766f, 1.762f)
curveToRelative(-0.827f, -0.829f, -1.492f, -1.818f, -1.947f, -2.916f)
lineToRelative(2.305f, -0.953f)
curveToRelative(-0.326f, -0.789f, -0.492f, -1.625f, -0.492f, -2.486f)
verticalLineToRelative(-0.062f)
lineToRelative(-2.499f, 0.052f)
curveToRelative(0.001f, -1.238f, 0.254f, -2.419f, 0.71f, -3.493f)
lineToRelative(2.3f, 0.973f)
curveToRelative(0.333f, -0.787f, 0.812f, -1.492f, 1.424f, -2.096f)
lineToRelative(-1.751f, -1.775f)
curveToRelative(0.833f, -0.822f, 1.826f, -1.481f, 2.926f, -1.93f)
lineToRelative(0.94f, 2.309f)
curveToRelative(0.778f, -0.316f, 1.603f, -0.477f, 2.485f, -0.478f)
lineToRelative(0.004f, -0.5f)
lineToRelative(-0.031f, -2.0f)
curveToRelative(1.233f, 0.001f, 2.409f, 0.252f, 3.48f, 0.704f)
lineToRelative(-0.969f, 2.301f)
curveToRelative(0.789f, 0.332f, 1.495f, 0.81f, 2.099f, 1.42f)
lineToRelative(1.772f, -1.754f)
curveToRelative(0.823f, 0.831f, 1.484f, 1.822f, 1.935f, 2.921f)
lineToRelative(-2.307f, 0.947f)
curveToRelative(0.32f, 0.78f, 0.482f, 1.608f, 0.482f, 2.461f)
verticalLineToRelative(0.031f)
lineToRelative(2.5f, -0.026f)
curveToRelative(0.0f, 1.228f, -0.25f, 2.399f, -0.698f, 3.466f)
lineToRelative(-2.303f, -0.964f)
close()
moveTo(16.061f, 10.061f)
lineToRelative(-1.939f, 1.939f)
lineToRelative(1.939f, 1.939f)
lineToRelative(-2.121f, 2.121f)
lineToRelative(-1.939f, -1.939f)
lineToRelative(-1.939f, 1.939f)
lineToRelative(-2.121f, -2.121f)
lineToRelative(1.939f, -1.939f)
lineToRelative(-1.939f, -1.939f)
lineToRelative(2.121f, -2.121f)
lineToRelative(1.939f, 1.939f)
lineToRelative(1.939f, -1.939f)
lineToRelative(2.121f, 2.121f)
close()
}
}
.build()
return _roulette!!
}
private var _roulette: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,502
|
icons
|
MIT License
|
app/src/main/java/com/example/tier/base/InternetException.kt
|
cenkcavga
| 480,894,535
| false
| null |
package com.example.tier.base
import java.io.IOException
class InternetException() : IOException() {
override val message: String
get() = "Please check your internet connection"
}
| 0
|
Kotlin
|
0
| 0
|
67ad17c45014103e9e1b4feb7b4f2c7294d7532a
| 206
|
Tier
|
Apache License 2.0
|
core/core_domain/src/main/java/com/serj113/pokedex/core/domain/usecase/impl/GetSpeciesUseCaseImpl.kt
|
serj113
| 668,290,121
| false
|
{"Kotlin": 111698}
|
package com.serj113.pokedex.core.domain.usecase.impl
import com.serj113.pokedex.core.domain.repository.PokemonRepository
import com.serj113.pokedex.core.domain.usecase.GetSpeciesUseCase
import com.serj113.pokedex.core.model.ApiResult
import com.serj113.pokedex.core.model.PokemonSpeciesResponse
import javax.inject.Inject
class GetSpeciesUseCaseImpl @Inject constructor(
private val repository: PokemonRepository,
) : GetSpeciesUseCase {
override suspend fun invoke(id: Int): ApiResult<PokemonSpeciesResponse> {
return repository.fetchPokemonSpecies(id)
}
}
| 0
|
Kotlin
|
0
| 0
|
ef4dffd562e4114aae5b805909c65d12643fc275
| 569
|
pokedex
|
Apache License 2.0
|
feature/edit-note/core/src/main/kotlin/ru/maksonic/beresta/feature/edit_note/core/ui/widget/EditNoteTopBar.kt
|
maksonic
| 580,058,579
| false
| null |
package ru.maksonic.beresta.feature.edit_note.core.ui.widget
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import ru.maksonic.beresta.ui.theme.Theme
import ru.maksonic.beresta.ui.theme.component.dp4
import ru.maksonic.beresta.ui.theme.icons.AppIcon
import ru.maksonic.beresta.ui.theme.icons.ArrowBack
import ru.maksonic.beresta.ui.theme.icons.MoreVertical
import ru.maksonic.beresta.ui.widget.button.IconActionCircleOverflow
/**
* @Author maksonic on 27.04.2023
*/
@Composable
fun EditNoteTopBar(backAction: () -> Unit, menuAction: () -> Unit, modifier: Modifier = Modifier) {
Row(
modifier
.fillMaxWidth()
.height(Theme.widgetSize.topBarNormalHeight)
.padding(start = dp4, end = dp4),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
IconActionCircleOverflow(icon = AppIcon.ArrowBack, onBtnClicked = backAction)
IconActionCircleOverflow(icon = AppIcon.MoreVertical, onBtnClicked = menuAction)
}
}
| 0
|
Kotlin
|
0
| 0
|
b1c3480b9e715f7f02302b955af64cf032e4224a
| 1,365
|
Beresta
|
MIT License
|
features/onboarding/src/main/java/io/dotanuki/norris/onboarding/OnboardingActivity.kt
|
bentleypark
| 350,624,647
| true
|
{"Kotlin": 142785, "Shell": 1445}
|
package io.dotanuki.norris.onboarding
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import io.dotanuki.logger.Logger
import io.dotanuki.norris.features.utilties.selfBind
import io.dotanuki.norris.features.utilties.viewBinding
import io.dotanuki.norris.navigator.Navigator
import io.dotanuki.norris.navigator.Screen
import io.dotanuki.norris.onboarding.OnboardingScreenState.Failed
import io.dotanuki.norris.onboarding.OnboardingScreenState.Idle
import io.dotanuki.norris.onboarding.OnboardingScreenState.Success
import io.dotanuki.norris.onboarding.databinding.ActivityOnboardingBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.kodein.di.DIAware
import org.kodein.di.instance
import android.R.anim.fade_in as FadeIn
import android.R.anim.fade_out as FadeOut
class OnboardingActivity : AppCompatActivity(), DIAware {
override val di by selfBind()
private val viewBindings by viewBinding(ActivityOnboardingBinding::inflate)
private val logger by instance<Logger>()
private val navigator by instance<Navigator>()
private val viewModel by instance<OnboardingViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBindings.root)
lifecycleScope.launch {
delay(1000)
viewModel.bind().collect { render(it) }
}
}
private fun render(state: OnboardingScreenState) {
when (state) {
Idle -> launch()
Success -> {
logger.i("Success -> Categories fetched, proceding to facts")
proceedToFacts()
}
Failed -> {
logger.e("Error -> $state")
proceedToFacts()
}
}
}
private fun launch() {
viewModel.handleApplicationLaunch()
}
private fun proceedToFacts() {
navigator.navigateTo(Screen.FactsList)
overridePendingTransition(FadeIn, FadeOut)
finish()
}
}
| 0
| null |
0
| 0
|
4c01aea710a7cefa246da2d6b875e123cbcf724b
| 2,127
|
norris
|
MIT License
|
google-apple-payments/src/commonMain/kotlin/com/khalid/multiplatform/googleapple/payments/Platform.kt
|
khalid64927
| 783,337,790
| false
|
{"Kotlin": 32412}
|
@file:Suppress("MatchingDeclarationName")
package com.khalid.multiplatform.googleapple.payments
expect interface PaymentInterface {
suspend fun canMakePayments(): Boolean
suspend fun makePayments(amount: String, callback: (result: Result<String>) -> Unit)
}
| 1
|
Kotlin
|
0
| 2
|
f2c9f16c9a5ff28ee6ca6e069cb422b17bf18285
| 270
|
google-apple-pay
|
Apache License 2.0
|
src/main/kotlin/br/com/zup/detail/DetailPixKeyResponse.kt
|
brenohof
| 383,853,953
| true
|
{"Kotlin": 34428, "Smarty": 2032, "Dockerfile": 175}
|
package br.com.zup.detail
import br.com.zup.create.AccountType
import br.com.zup.create.KeyType
import java.time.LocalDateTime
data class DetailPixKeyResponse(
val pixId: String,
val clientId: String,
val keyType: KeyType?,
val keyValue: String,
val owner: OwnerResponse,
val account: AccountResponse,
val createdAt: LocalDateTime
)
data class OwnerResponse(val name: String, val cpf: String)
data class AccountResponse(
val institutionName: String,
val branch: String,
val accountNumber: String,
val accountType: AccountType?
)
| 0
|
Kotlin
|
0
| 0
|
0ef178056d08741c9d0c1d42c8c6c2751863f884
| 576
|
pix-keymanager-rest
|
Apache License 2.0
|
src/test/kotlin/com/github/mpe85/grampa/grammar/ChoiceRuleTests.kt
|
mpe85
| 138,511,038
| false
|
{"Kotlin": 267705, "Java": 1073}
|
package com.github.mpe85.grampa.grammar
import com.github.mpe85.grampa.legalCodePoints
import com.github.mpe85.grampa.parser.Parser
import com.github.mpe85.grampa.rule.Rule
import com.github.mpe85.grampa.rule.StringRule
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.arbitrary.set
import io.kotest.property.arbitrary.string
import io.kotest.property.checkAll
class ChoiceRuleTests : StringSpec({
fun grammars(rules: List<Rule<Unit>>) = listOf(
object : AbstractGrammar<Unit>() {
override fun start() = choice(*rules.toTypedArray())
},
object : AbstractGrammar<Unit>() {
override fun start() = choice(rules)
},
object : AbstractGrammar<Unit>() {
override fun start() = rules.reduce { acc, rule -> acc or rule }
},
)
"Choice rule matches first matching rule" {
checkAll(Arb.set(Arb.string(1..10, legalCodePoints()), 2..10)) { strings ->
grammars(strings.map { StringRule(it) }).forEach { grammar ->
val random = strings.random()
Parser(grammar).run(random).apply {
matched shouldBe true
matchedEntireInput shouldBe (strings.first { random.startsWith(it) } == random)
matchedInput shouldBe strings.first { random.startsWith(it) }
restOfInput shouldBe random.removePrefix(strings.first { random.startsWith(it) })
}
}
}
}
"Empty Choice rule matches any input" {
checkAll(Arb.string(0..10, legalCodePoints())) { str ->
Parser(object : AbstractGrammar<Unit>() {
override fun start() = choice()
}).run(str).apply {
matched shouldBe true
matchedEntireInput shouldBe str.isEmpty()
matchedInput shouldBe ""
restOfInput shouldBe str
}
}
}
})
| 1
|
Kotlin
|
1
| 13
|
b035245f817762fe475fe479d82d6c2aa61eea39
| 2,028
|
grampa
|
MIT License
|
app/src/main/java/com/douglasqueiroz/thewallet/ui/navigation/TheWalletNavHost.kt
|
douglas-queiroz
| 643,561,645
| false
| null |
package com.douglasqueiroz.thewallet.ui.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.douglasqueiroz.thewallet.di.UtilModule
import com.douglasqueiroz.thewallet.feature.assets.assetsScreen
import com.douglasqueiroz.thewallet.feature.currencylist.currencyListScreen
import com.douglasqueiroz.thewallet.feature.home.homeScreen
import com.douglasqueiroz.thewallet.feature.settings.settingsScreen
@Composable
fun TheWalletNavHost() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "home"
) {
UtilModule.getNavController = {
navController
}
homeScreen()
assetsScreen()
settingsScreen()
currencyListScreen()
}
}
| 0
|
Kotlin
|
0
| 0
|
b32bc30c705696b7c5cbe8d1d8b2f348b3d5ff06
| 884
|
TheWallet
|
Apache License 2.0
|
frontend/kobweb-compose/src/jsMain/kotlin/com/varabyte/kobweb/compose/ui/modifiers/TransitionModifiers.kt
|
varabyte
| 389,223,226
| false
|
{"Kotlin": 1183340}
|
package com.varabyte.kobweb.compose.ui.modifiers
import com.varabyte.kobweb.compose.attributes.onTransitionCancel
import com.varabyte.kobweb.compose.attributes.onTransitionEnd
import com.varabyte.kobweb.compose.attributes.onTransitionRun
import com.varabyte.kobweb.compose.attributes.onTransitionStart
import com.varabyte.kobweb.compose.css.*
import com.varabyte.kobweb.compose.events.SyntheticTransitionEvent
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.attrsModifier
import com.varabyte.kobweb.compose.ui.styleModifier
import org.jetbrains.compose.web.css.*
fun Modifier.transition(vararg transitions: CSSTransition) = styleModifier {
transition(*transitions)
}
// Convenience method for accepting the output of CSSTransition.group(...)
fun Modifier.transition(transitions: Array<CSSTransition>) = styleModifier {
transition(*transitions)
}
fun Modifier.onTransitionCancel(listener: (SyntheticTransitionEvent) -> Unit): Modifier = attrsModifier {
onTransitionCancel(listener)
}
fun Modifier.onTransitionEnd(listener: (SyntheticTransitionEvent) -> Unit): Modifier = attrsModifier {
onTransitionEnd(listener)
}
fun Modifier.onTransitionRun(listener: (SyntheticTransitionEvent) -> Unit): Modifier = attrsModifier {
onTransitionRun(listener)
}
fun Modifier.onTransitionStart(listener: (SyntheticTransitionEvent) -> Unit): Modifier = attrsModifier {
onTransitionStart(listener)
}
| 113
|
Kotlin
|
48
| 992
|
a6061d7a3b53383e055a94ef4aa430af6647f8b4
| 1,448
|
kobweb
|
Apache License 2.0
|
app/src/main/java/com/flowfoundation/wallet/page/staking/providers/presenter/ProviderTitlePresenter.kt
|
Outblock
| 692,942,645
| false
|
{"Kotlin": 2036345, "Java": 104150}
|
package com.flowfoundation.wallet.page.staking.providers.presenter
import android.view.View
import android.widget.TextView
import com.flowfoundation.wallet.base.presenter.BasePresenter
import com.flowfoundation.wallet.base.recyclerview.BaseViewHolder
import com.flowfoundation.wallet.page.staking.providers.model.ProviderTitleModel
class ProviderTitlePresenter(
private val view: View,
) : BaseViewHolder(view), BasePresenter<ProviderTitleModel> {
override fun bind(model: ProviderTitleModel) {
(view as? TextView)?.text = model.title
}
}
| 60
|
Kotlin
|
4
| 0
|
73cf4c0812bd963047289f876a19e7484ab958c3
| 561
|
FRW-Android
|
Apache License 2.0
|
app/src/main/java/com/mapmyindia/sdk/demo/kotlin/activity/AddCustomInfoWindowActivity.kt
|
MapmyIndia
| 458,154,500
| true
|
{"INI": 1, "Gradle": 4, "Shell": 1, "Markdown": 97, "Batchfile": 1, "Ignore List": 2, "YAML": 1, "Java Properties": 1, "Proguard": 1, "XML": 102, "JSON": 1, "Java": 114, "Kotlin": 108}
|
package com.mapmyindia.sdk.demo.kotlin.activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.mapmyindia.sdk.demo.R
import com.mapmyindia.sdk.demo.databinding.BaseLayoutBinding
import com.mapmyindia.sdk.maps.MapmyIndiaMap
import com.mapmyindia.sdk.maps.OnMapReadyCallback
import com.mapmyindia.sdk.maps.annotations.MarkerOptions
import com.mapmyindia.sdk.maps.camera.CameraUpdateFactory
import com.mapmyindia.sdk.maps.geometry.LatLng
import com.mapmyindia.sdk.maps.geometry.LatLngBounds
/**
* Created by Saksham on 2/12/19.
*/
class AddCustomInfoWindowActivity : AppCompatActivity(), OnMapReadyCallback {
private val latLngList: MutableList<LatLng> = ArrayList()
private lateinit var mBinding: BaseLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = DataBindingUtil.setContentView(this, R.layout.base_layout)
mBinding.mapView.onCreate(savedInstanceState)
mBinding.mapView.getMapAsync(this)
latLngList.add(LatLng(25.321684, 82.987289))
latLngList.add(LatLng(25.331684, 82.997289))
latLngList.add(LatLng(25.321684, 82.887289))
latLngList.add(LatLng(25.311684, 82.987289))
}
override fun onMapError(p0: Int, p1: String?) {
}
override fun onMapReady(mapmyIndiaMap: MapmyIndiaMap) {
latLngList.forEach {
mapmyIndiaMap.addMarker(MarkerOptions().position(it).setTitle("XYZ"))
}
mapmyIndiaMap.setInfoWindowAdapter {
val view: View? = LayoutInflater.from(this@AddCustomInfoWindowActivity).inflate(R.layout.custom_info_window_layout, null)
val textView: TextView = view?.findViewById(R.id.text)!!
textView.text = it.title
return@setInfoWindowAdapter view
}
mapmyIndiaMap.setOnMarkerClickListener {
Toast.makeText(this, it.position.toString(), Toast.LENGTH_SHORT).show()
return@setOnMarkerClickListener false
}
val latLngBounds: LatLngBounds = LatLngBounds.Builder()
.includes(latLngList)
.build()
mapmyIndiaMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 100, 10, 100, 10))
}
override fun onStart() {
super.onStart()
mBinding.mapView.onStart()
}
override fun onResume() {
super.onResume()
mBinding.mapView.onResume()
}
override fun onPause() {
super.onPause()
mBinding.mapView.onPause()
}
override fun onStop() {
super.onStop()
mBinding.mapView.onStop()
}
override fun onDestroy() {
super.onDestroy()
mBinding.mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mBinding.mapView.onLowMemory()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mBinding.mapView.onSaveInstanceState(outState)
}
}
| 0
|
Java
|
3
| 3
|
0c995ebcedb84b250733fc43d61bfb3d89479dd6
| 3,194
|
mapmyindia-maps-vectorSDK-android
|
BSD 1-Clause License
|
src/main/java/net/ccbluex/liquidbounce/features/command/commands/HClipCommand.kt
|
2946257770
| 693,652,489
| false
|
{"Java": 1812636, "Kotlin": 1801560, "GLSL": 13689, "JavaScript": 9199, "HTML": 850}
|
/*
* LiquidBounce+ Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
* https://github.com/WYSI-Foundation/LiquidBouncePlus/
*/
package net.ccbluex.liquidbounce.features.command.commands
import net.ccbluex.liquidbounce.features.command.Command
import net.ccbluex.liquidbounce.utils.MovementUtils
class HClipCommand : Command("hclip", emptyArray()) {
/**
* Execute commands with provided [args]
*/
override fun execute(args: Array<String>) {
if (args.size > 1) {
try {
MovementUtils.forward(args[1].toDouble())
chat("You were teleported.")
} catch (exception: NumberFormatException) {
chatSyntaxError()
}
return
}
chatSyntax("hclip <value>")
}
}
| 1
| null |
1
| 1
|
4e111df6cd3ca03da3b285eb8572ef79a9ff8695
| 850
|
VulgarSense
|
Apache License 2.0
|
health-platform-v1/HealthPlatformSample/app/src/main/java/com/example/healthplatformsample/presentation/components/SessionDetailsSeries.kt
|
android
| 368,660,859
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.healthplatformsample.presentation.components
import androidx.annotation.StringRes
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.ui.res.stringResource
import com.example.healthplatformsample.R
import com.google.android.libraries.healthdata.data.SeriesValue
import java.time.LocalDateTime
import java.time.ZoneId
fun LazyListScope.sessionDetailsSeries(
@StringRes labelId: Int,
series: List<SeriesValue>
) {
item {
Text(text = stringResource(id = labelId), style = MaterialTheme.typography.h5)
}
items(series) {
val time = LocalDateTime.ofInstant(it.time, ZoneId.systemDefault())
Text(
text = stringResource(
R.string.time_and_value,
time.toString(),
it.longValue.toString()
)
)
}
}
| 5
|
Kotlin
|
38
| 58
|
58c3f3fe86ecea1107f66b836faead8dea4d0142
| 1,610
|
health-samples
|
Apache License 2.0
|
survey/src/main/java/com.quickbirdstudios.surveykit/backend/views/question_parts/MultipleChoicePart.kt
|
sanjay-shyamal
| 211,853,040
| true
|
{"Kotlin": 119217, "Shell": 8542}
|
package com.quickbirdstudios.surveykit.backend.views.question_parts
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.LinearLayout
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import com.quickbirdstudios.survey.R
import com.quickbirdstudios.surveykit.SurveyTheme
import com.quickbirdstudios.surveykit.TextChoice
import com.quickbirdstudios.surveykit.backend.helpers.extensions.px
import com.quickbirdstudios.surveykit.backend.views.main_parts.StyleablePart
import com.quickbirdstudios.surveykit.backend.views.question_parts.helper.BackgroundDrawable
import com.quickbirdstudios.surveykit.backend.views.question_parts.helper.createSelectableThemedBackground
internal class MultipleChoicePart @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : LinearLayout(context, attrs), StyleablePart {
//region Public API
@ColorInt
var themeColor: Int = ContextCompat.getColor(context, R.color.cyan_normal)
set(color) {
update(options)
field = color
}
@ColorInt
var checkBoxTextColor: Int = ContextCompat.getColor(context, R.color.cyan_text)
set(color) {
update(options)
field = color
}
@ColorInt
var defaultColor: Int = Color.BLACK
var options: List<TextChoice> = emptyList()
set(value) {
update(value)
field = value
}
var selected: List<TextChoice>
get() = selectedChoices()
set(list) {
list.forEach { selected ->
this.findViewWithTag<CheckBox>(options.indexOf(selected))?.isChecked = true
}
}
fun isOneSelected(): Boolean = this.selectedChoices().isNotEmpty()
var onCheckedChangeListener: (View, Boolean) -> Unit = { _, _ -> }
//endregion
//region Overrides
override fun style(surveyTheme: SurveyTheme) {
themeColor = surveyTheme.themeColor
checkBoxTextColor = surveyTheme.textColor
}
//endregion
//region Private API
private val fields: List<CheckBox>
get() = (0 until this.childCount).mapNotNull { this.findViewWithTag(it) as? CheckBox }
private fun update(list: List<TextChoice>) {
val selectedChoices = selected
this.removeAllViews()
list.forEachIndexed { index, textChoice ->
val item = if (index == list.size - 1) createLastCheckBox(textChoice.text, index)
else createCheckBox(textChoice.text, index)
if (selectedChoices.contains(textChoice)) {
item.isChecked = true
item.setTextColor(checkBoxTextColor)
}
this.addView(item)
}
}
private fun selectedChoices(): List<TextChoice> {
return fields
.filter { it.isChecked }
.map { options[it.tag as Int] }
}
private fun selectedCheckBoxes(): List<CheckBox> = fields.filter { it.isChecked }
//endregion
//region Internal listeners
private val internalCheckedChangeListener: (View, Boolean) -> Unit = { checkBox, checked ->
fields.forEach { it.setTextColor(defaultColor) }
selectedCheckBoxes().forEach { it.setTextColor(checkBoxTextColor) }
onCheckedChangeListener(checkBox, checked)
}
//endregion
//region Checkbox Creation Helpers
private fun createCheckBox(@StringRes label: Int, tag: Int): CheckBox {
val verticalPaddingEditText = context.px(
context.resources.getDimension(R.dimen.text_field_vertical_padding)
).toInt()
val horizontalPaddingEditTextLeft = context.px(
context.resources.getDimension(R.dimen.text_field_horizontal_padding_left)
).toInt()
val horizontalPaddingEditTextRight = context.px(
context.resources.getDimension(R.dimen.text_field_horizontal_padding_right)
).toInt()
val checkBox = CheckBox(context).apply {
id = View.generateViewId()
setText(label)
this.tag = tag
isFocusable = true
isClickable = true
buttonDrawable = null
textSize = 20f
setOnClickListener { internalCheckedChangeListener(this, this.isChecked) }
setPadding(
horizontalPaddingEditTextLeft,
verticalPaddingEditText,
horizontalPaddingEditTextRight,
verticalPaddingEditText
)
val layoutParams = LayoutParams(
LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
this.layoutParams = layoutParams
}
Handler().post {
checkBox.background = checkBox.createSelectableThemedBackground(
context, BackgroundDrawable.Border.Top, themeColor
)
}
return checkBox
}
private fun createLastCheckBox(@StringRes label: Int, tag: Int): CheckBox {
val createCheckBox = createCheckBox(label, tag)
Handler().post {
createCheckBox.background = createCheckBox.createSelectableThemedBackground(
context, BackgroundDrawable.Border.Both, themeColor
)
}
return createCheckBox
}
//endregion
init {
this.let {
gravity = Gravity.CENTER
layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
orientation = VERTICAL
}
}
}
| 0
| null |
0
| 0
|
0216399a2bca01a958c16f9e0c5ff77ffdca44ca
| 5,774
|
SurveyKit
|
MIT License
|
src/test/kotlin/nl/knaw/huc/di/rd/tag/creole/PatternAssert.kt
|
HuygensING
| 222,932,987
| false
| null |
package nl.knaw.huc.di.rd.tag.creole
/*-
* #%L
* creole
* =======
* Copyright (C) 2016 - 2019 HuC DI (KNAW)
* =======
* 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.
* #L%
*/
import org.assertj.core.api.AbstractObjectAssert
class PatternAssert(actual: Pattern) : AbstractObjectAssert<PatternAssert, Pattern>(actual, PatternAssert::class.java) {
val isNullable: PatternAssert
get() {
isNotNull
val actualNullable = actual.isNullable
if (!actualNullable) {
val assertjErrorMessage = "\nExpecting isNullable of:\n <%s>\nto be:\n <%s>\nbut was:\n <%s>"
failWithMessage(assertjErrorMessage, actual, true, false)
}
return myself
}
val isNotNullable: PatternAssert
get() {
isNotNull
val actualNotNullable = !actual.isNullable
if (!actualNotNullable) {
val assertjErrorMessage = "\nExpecting isNullable of:\n <%s>\nto be:\n <%s>\nbut was:\n <%s>"
failWithMessage(assertjErrorMessage, actual, false, true)
}
return myself
}
fun allowsText(): PatternAssert {
isNotNull
val allowsText = actual.allowsText()
if (!allowsText) {
val assertjErrorMessage = "\nExpecting allowsText of:\n <%s>\nto be:\n <%s>\nbut was:\n <%s>"
failWithMessage(assertjErrorMessage, actual, true, false)
}
return myself
}
fun doesNotAllowText(): PatternAssert {
isNotNull
val doesNotAllowText = !actual.allowsText()
if (!doesNotAllowText) {
val assertjErrorMessage = "\nExpecting allowsText of:\n <%s>\nto be:\n <%s>\nbut was:\n <%s>"
failWithMessage(assertjErrorMessage, actual, false, true)
}
return myself
}
}
| 0
|
Kotlin
|
0
| 0
|
85c63513e6ea39c15db541c47428f4ddb7d43b40
| 2,390
|
creole
|
Apache License 2.0
|
app/src/main/java/com/macroz/wordler/adapters/WordListElementAdapter.kt
|
MaciejRozpedek
| 462,682,311
| false
|
{"Kotlin": 62017}
|
package com.macroz.wordler.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.macroz.wordler.R
import com.macroz.wordler.adapters.WordListElementAdapter.WordViewHolder
import com.macroz.wordler.data.StudyObject
class WordListElementAdapter :
ListAdapter<StudyObject, WordViewHolder>(WORDS_COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder {
return WordViewHolder.create(parent)
}
override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
val current = getItem(position)
holder.bind(
current.mainWord, current.mainWordDescription, current.answerWord, current.answerWordDescription
)
}
class WordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val mainWordTextView: TextView = itemView.findViewById(R.id.mainWord)
private val subsWordTextView: TextView = itemView.findViewById(R.id.subsidiaryWord)
fun bind(
mainWord: String, mainWordDescription: String, answerWord: String, answerWordDescription: String
) {
if (mainWordDescription == null || mainWordDescription == "") {
mainWordTextView.text = mainWord
} else {
mainWordTextView.text = "${mainWord} (${mainWordDescription})"
}
if (answerWordDescription == null || answerWordDescription == "") {
subsWordTextView.text = answerWord
} else {
subsWordTextView.text = "${answerWord} (${answerWordDescription})"
}
}
companion object {
fun create(parent: ViewGroup): WordViewHolder {
val view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.word_list_element, parent, false)
return WordViewHolder(view)
}
}
}
companion object {
private val WORDS_COMPARATOR = object : DiffUtil.ItemCallback<StudyObject>() {
override fun areItemsTheSame(oldItem: StudyObject, newItem: StudyObject): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(oldItem: StudyObject, newItem: StudyObject): Boolean {
return if (oldItem.mainWord == newItem.mainWord) {
oldItem.answerWord == newItem.answerWord
} else {
oldItem.mainWord == newItem.mainWord
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
57598c92f0ae01b1896f3cef8447297721b55f1e
| 2,765
|
Wordler
|
Apache License 2.0
|
src/main/kotlin/org/ewlameijer/knowviz/data/Relationship.kt
|
EWLameijer
| 455,957,747
| false
|
{"Kotlin": 11262}
|
package org.ewlameijer.knowviz.data
enum class RelationshipArity { OneToOne, OneToMany }
enum class RelationshipType(val text: String, val arity: RelationshipArity) {
IsA(
"is a(n)",
RelationshipArity.OneToOne
),
CanHave(
"can have",
RelationshipArity.OneToMany
),
HasA(
"has a(n)",
RelationshipArity.OneToMany
)
}
sealed class Relationship(val origin: Concept, val relationshipType: RelationshipType) {
companion object {
fun fromString(s: String?) = RelationshipType.values().firstOrNull { it.text == s }
fun ofWithIsValid(source: Concept?, s: String?, destinations: Set<Concept>): Boolean =
if (source == null) false
else {
when (fromString(s)?.arity) {
null -> false
RelationshipArity.OneToOne -> destinations.size == 1
RelationshipArity.OneToMany -> destinations.isNotEmpty()
}
}
fun of(source: Concept?, s: String?, destinations: Set<Concept>): Relationship {
require(ofWithIsValid(source, s, destinations))
val relationshipType = fromString(s)!!
return if (relationshipType.arity == RelationshipArity.OneToOne) OneToOneRelationship(
source!!,
relationshipType,
destinations.toList().first()
) else OneToManyRelationship(
source!!,
relationshipType,
destinations.toMutableSet() // make defensive copy against clearing original set
)
}
}
abstract fun hasDestination(concept: Concept) : Boolean
abstract fun canAddDestination(concept: Concept) : Boolean
abstract fun addDestination(concept: Concept)
}
class OneToOneRelationship(origin: Concept, relationshipType: RelationshipType, val destination: Concept) :
Relationship(origin, relationshipType) {
override fun hasDestination(concept: Concept): Boolean = destination == concept
override fun canAddDestination(concept: Concept) = false
override fun addDestination(concept: Concept) =
throw IllegalStateException("OneToOneRelationship: Can't add a destination to an existing OneToOneRelationship.")
override fun toString() = "$origin $relationshipType $destination"
}
class OneToManyRelationship(origin: Concept, relationshipType: RelationshipType, val destinations: MutableSet<Concept>) :
Relationship(origin, relationshipType) {
override fun hasDestination(concept: Concept): Boolean = concept in destinations
override fun canAddDestination(concept: Concept) = concept !in destinations
override fun addDestination(concept: Concept) {
require(canAddDestination(concept)) { "OneToManyRelationship.addDestination: Cannot add duplicate destination concept."}
destinations.add(concept)
}
override fun toString() = destinations.joinToString("\n") { "$origin $relationshipType $it" }
}
| 0
|
Kotlin
|
0
| 0
|
d5c5a6069c5de4e2804d49705471f029699f0ef0
| 3,024
|
knowledge-visualizer
|
MIT License
|
android/src/main/kotlin/org/ar/rtc_engine/ArRtcStreamKitPlugin.kt
|
anyRTC
| 308,827,129
| false
| null |
package org.ar.rtc_engine
import android.os.Handler
import android.os.Looper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import org.ar.rtc.RtcEngine
import org.ar.rtc.base.StreamingKitManager
import java.lang.Exception
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.javaMethod
class ArRtcStreamKitPlugin(private val rtcEnginePlugin: ArRtcEnginePlugin) : FlutterPlugin, MethodChannel.MethodCallHandler {
private lateinit var methodChannel: MethodChannel
private val manager = StreamingKitManager()
fun initPlugin(binaryMessenger: BinaryMessenger) {
methodChannel = MethodChannel(binaryMessenger, "ar_rtc_stream_kit")
methodChannel.setMethodCallHandler(this)
}
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
initPlugin(binding.binaryMessenger)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
}
private fun engine(): RtcEngine? {
return rtcEnginePlugin.engine()
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
manager::class.declaredMemberFunctions.find { it.name == call.method }?.let { function ->
function.javaMethod?.let { method ->
try {
val parameters = mutableListOf<Any?>()
call.arguments<Map<*, *>>()?.toMutableMap()?.let {
if (call.method == "createInstance") {
it["engine"] = engine()
}
parameters.add(it)
}
method.invoke(manager, *parameters.toTypedArray(), ResultCallback(result))
return@onMethodCall
} catch (e: Exception) {
e.printStackTrace()
}
}
}
result.notImplemented()
}
}
| 0
|
Dart
|
7
| 19
|
b81282f06e344eea33830a52aa3049053a189412
| 2,216
|
Flutter-SDK
|
MIT License
|
src/commonMain/kotlin/com/ditchoom/mqtt5/controlpacket/properties/ServerKeepAlive.kt
|
DitchOoM
| 422,091,819
| false
| null |
package com.ditchoom.mqtt5.controlpacket.properties
import com.ditchoom.buffer.WriteBuffer
data class ServerKeepAlive(val seconds: Int) : Property(0x13, Type.TWO_BYTE_INTEGER) {
override fun size(): Int = 3
override fun write(buffer: WriteBuffer): Int = write(buffer, seconds.toUShort())
}
| 0
|
Kotlin
|
0
| 0
|
eb45a9961e1873dd4bd3abb7446d25f96e14f7cf
| 300
|
mqtt-5-models
|
Apache License 2.0
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/KuwaharaFilter.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: KuwaharaFilter
*
* Full name: System`KuwaharaFilter
*
* Usage: KuwaharaFilter[data, r] computes for each element p in data the variance of the values in the four (r + 1) × (r + 1) squares that have p as a corner, and replaces p with the mean of the values of the square with least variance.
*
* Options: None
*
* Attributes: Protected
*
* local: paclet:ref/KuwaharaFilter
* Documentation: web: http://reference.wolfram.com/language/ref/KuwaharaFilter.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun kuwaharaFilter(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("KuwaharaFilter", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,134
|
mathemagika
|
Apache License 2.0
|
src/main/kotlin/com/adi3000/cloud/nextcloud/NextcloudHandler.kt
|
Adi3000
| 548,244,043
| false
|
{"Kotlin": 12458}
|
package com.adi3000.cloud.nextcloud
import jakarta.inject.Inject
import jakarta.inject.Singleton
import org.aarboard.nextcloud.api.NextcloudConnector
import java.io.File
//TODO implement endpoint to register a password
// cf. https://docs.nextcloud.com/server/latest/developer_manual/client_apis/LoginFlow/index.html#converting-to-app-passwords
@Singleton
class NextcloudHandler (@Inject val nextcloudConfig: NextcloudConfiguration){
fun uploadFile(file: File, directory:String, filename: String, userId: String ){
val user = nextcloudConfig.properties.users.first{ it.user == userId }
val connector = NextcloudConnector(nextcloudConfig.properties.server, user.login, user.password)
if ( ! connector.folderExists(nextcloudConfig.properties.folder)) {
connector.createFolder(nextcloudConfig.properties.folder)
}
if (! connector.folderExists("${nextcloudConfig.properties.folder}/$directory")){
connector.createFolder("${nextcloudConfig.properties.folder}/$directory")
}
connector.uploadFile(file, "${nextcloudConfig.properties.folder}/$directory/$filename")
}
}
| 1
|
Kotlin
|
1
| 0
|
661232cd3eba26668e6a41df72b15a6b91a52d63
| 1,151
|
cloud-bridge
|
MIT License
|
src/main/kotlin/top/idwangmo/lingling/util/LinglingRequestStaticsSingleton.kt
|
moyu-x
| 146,326,167
| false
|
{"Kotlin": 11384}
|
package top.idwangmo.lingling.util
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import top.idwangmo.lingling.config.LinglingURLConfig
class LinglingRequestStaticsSingleton private constructor() {
companion object {
fun getInstance() = Holder.INSTANCE!!
}
private object Holder {
val INSTANCE = Retrofit.Builder().baseUrl(LinglingURLConfig.URL).addConverterFactory(ScalarsConverterFactory.create()).build();
}
}
| 0
|
Kotlin
|
0
| 0
|
127ce882925827d9ab00f1ee9220c12d307f23ca
| 487
|
lingling
|
MIT License
|
app/src/main/kotlin/jp/co/yumemi/android/code_check/common/view/WebView.kt
|
MarcoDzuong
| 406,395,463
| false
| null |
package jp.co.yumemi.android.code_check.common.view
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.webkit.*
import androidx.activity.compose.BackHandler
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.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import kotlinx.coroutines.launch
@Composable
fun WebViewProgress(modifier: Modifier = Modifier, url:String, onBack: (webView: WebView?) -> Unit, initSettings: (webSettings: WebSettings?) -> Unit = {}){
var rememberWebViewProgress: Int by remember { mutableStateOf(-1) }
Box {
CustomWebView(
modifier = modifier,
url = url,
onProgressChange = { progress ->
rememberWebViewProgress = progress
},
initSettings = initSettings, onBack = onBack, onReceivedError = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
}
}
)
LinearProgressIndicator(
progress = rememberWebViewProgress * 1.0F / 100F,
modifier = Modifier
.fillMaxWidth()
.height(if (rememberWebViewProgress == 100) 0.dp else 5.dp),
color = Color.Red
)
}
}
@Composable
fun CustomWebView(modifier: Modifier = Modifier,
url:String,
onBack: (webView: WebView?) -> Unit,
onProgressChange: (progress:Int)->Unit = {},
initSettings: (webSettings: WebSettings?) -> Unit = {},
onReceivedError: (error: WebResourceError?) -> Unit = {}){
val webViewChromeClient = object: WebChromeClient(){
override fun onProgressChanged(view: WebView?, newProgress: Int) {
onProgressChange(newProgress)
super.onProgressChanged(view, newProgress)
}
}
val webViewClient = object: WebViewClient(){
override fun onPageStarted(view: WebView?, url: String?,
favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
onProgressChange(-1)
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
onProgressChange(100)
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
if(null == request?.url) return false
val showOverrideUrl = request.url.toString()
try {
if (!showOverrideUrl.startsWith("http://")
&& !showOverrideUrl.startsWith("https://")) {
Intent(Intent.ACTION_VIEW, Uri.parse(showOverrideUrl)).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
view?.context?.applicationContext?.startActivity(this)
}
return true
}
}catch (e:Exception){
return true
}
return super.shouldOverrideUrlLoading(view, request)
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
super.onReceivedError(view, request, error)
onReceivedError(error)
}
}
var webView:WebView? = null
val coroutineScope = rememberCoroutineScope()
AndroidView(modifier = modifier,factory = { ctx ->
WebView(ctx).apply {
this.webViewClient = webViewClient
this.webChromeClient = webViewChromeClient
initSettings(this.settings)
webView = this
loadUrl(url)
}
})
BackHandler {
coroutineScope.launch {
onBack(webView)
}
}
}
| 0
|
Kotlin
|
0
| 2
|
703e158b758aa7ddc05ab75a670b183d7c8d092f
| 4,473
|
yumemi-android-engineer-codecheck
|
Apache License 2.0
|
ui-kit/src/main/kotlin/org/p2p/uikit/components/left_side/LeftSideCellModel.kt
|
p2p-org
| 306,035,988
| false
| null |
package org.p2p.uikit.components.left_side
import android.text.TextUtils
import org.p2p.uikit.components.icon_wrapper.IconWrapperCellModel
import org.p2p.uikit.utils.text.TextViewCellModel
sealed interface LeftSideCellModel {
data class IconWithText(
val icon: IconWrapperCellModel? = null,
val firstLineText: TextViewCellModel? = null,
val secondLineText: TextViewCellModel? = null,
val thirdLineText: TextViewCellModel? = null,
// styling
val firstLineTextEllipsize: TextUtils.TruncateAt? = TextUtils.TruncateAt.MIDDLE,
) : LeftSideCellModel
}
| 8
|
Kotlin
|
16
| 28
|
71b282491cdafd26be1ffc412a971daaa9c06c61
| 605
|
key-app-android
|
MIT License
|
src/jvmMain/kotlin/com/github/jershell/kbase64/extensions.kt
|
jershell
| 199,182,415
| false
| null |
package com.github.jershell.kbase64
actual fun String.decodeBase64(): String = String(this.toByteArray().decodeBase64())
actual fun String.decodeBase64ToByteArray(): ByteArray = this.toByteArray().decodeBase64()
actual fun ByteArray.decodeBase64ToString(): String = String(this.decodeBase64())
actual fun String.encodeToBase64(): String = String(this.toByteArray().encodeBase64())
actual fun ByteArray.encodeToBase64(): String = String(this.encodeBase64())
| 0
|
Kotlin
|
1
| 8
|
bc15b0f2295b967a9a53f7578efd170ae1263213
| 457
|
kbase64
|
MIT License
|
app/src/main/java/com/mertyazi/moviesappxml/core/domain/model/FavoriteMovie.kt
|
MertYazi
| 866,983,599
| false
|
{"Kotlin": 58054}
|
package com.mertyazi.moviesappxml.core.domain.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Created by Mert Yazi
*/
@Entity
class FavoriteMovie(
@PrimaryKey val id: String,
@ColumnInfo(name = "movie_title") val movieTitle : String,
@ColumnInfo(name = "movie_poster") val moviePoster : String,
@ColumnInfo(name = "movie_poster_with_title") val moviePosterWithTitle : String
)
| 0
|
Kotlin
|
0
| 0
|
6bccf2f6878e8d3beff17dbe7c0a2a9ea07b11f3
| 454
|
MoviesAppXML
|
Apache License 2.0
|
app/src/main/java/info/free/scp/bean/CommentModel.kt
|
zhufree
| 145,660,707
| false
|
{"Kotlin": 369198, "CSS": 82454}
|
package info.free.scp.bean
data class CommentModel(var comment: String = "",
var title: String = "",
var username: String = "",
var time: String = "",
var reply: List<CommentModel>)
| 0
|
Kotlin
|
4
| 20
|
bf686e8969530dde5afd8442c9486b30378ae40f
| 278
|
SCP-Android
|
MIT License
|
app/src/main/java/com/thejawnpaul/gptinvestor/ui/theme/Color.kt
|
jawnpaul
| 777,897,163
| false
|
{"Kotlin": 157930}
|
package com.thejawnpaul.gptinvestor.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val md_theme_light_primary = Color(0xFF005FAF)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFD4E3FF)
val md_theme_light_onPrimaryContainer = Color(0xFF001C3A)
val md_theme_light_secondary = Color(0xFFB90C55)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFFFD9DF)
val md_theme_light_onSecondaryContainer = Color(0xFF3F0018)
val md_theme_light_tertiary = Color(0xFF875200)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFDDBA)
val md_theme_light_onTertiaryContainer = Color(0xFF2B1700)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFF8FDFF)
val md_theme_light_onBackground = Color(0xFF001F25)
val md_theme_light_surface = Color(0xFFF8FDFF)
val md_theme_light_onSurface = Color(0xFF001F25)
val md_theme_light_surfaceVariant = Color(0xFFE0E2EC)
val md_theme_light_onSurfaceVariant = Color(0xFF43474E)
val md_theme_light_outline = Color(0xFF74777F)
val md_theme_light_inverseOnSurface = Color(0xFFD6F6FF)
val md_theme_light_inverseSurface = Color(0xFF00363F)
val md_theme_light_inversePrimary = Color(0xFFA5C8FF)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF005FAF)
val md_theme_light_outlineVariant = Color(0xFFC3C6CF)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFA5C8FF)
val md_theme_dark_onPrimary = Color(0xFF00315F)
val md_theme_dark_primaryContainer = Color(0xFF004786)
val md_theme_dark_onPrimaryContainer = Color(0xFFD4E3FF)
val md_theme_dark_secondary = Color(0xFFFFB1C2)
val md_theme_dark_onSecondary = Color(0xFF66002B)
val md_theme_dark_secondaryContainer = Color(0xFF8F003F)
val md_theme_dark_onSecondaryContainer = Color(0xFFFFD9DF)
val md_theme_dark_tertiary = Color(0xFFFFB865)
val md_theme_dark_onTertiary = Color(0xFF482A00)
val md_theme_dark_tertiaryContainer = Color(0xFF663D00)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDDBA)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF001F25)
val md_theme_dark_onBackground = Color(0xFFA6EEFF)
val md_theme_dark_surface = Color(0xFF001F25)
val md_theme_dark_onSurface = Color(0xFFA6EEFF)
val md_theme_dark_surfaceVariant = Color(0xFF43474E)
val md_theme_dark_onSurfaceVariant = Color(0xFFC3C6CF)
val md_theme_dark_outline = Color(0xFF8D9199)
val md_theme_dark_inverseOnSurface = Color(0xFF001F25)
val md_theme_dark_inverseSurface = Color(0xFFA6EEFF)
val md_theme_dark_inversePrimary = Color(0xFF005FAF)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFFA5C8FF)
val md_theme_dark_outlineVariant = Color(0xFF43474E)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF1976D2)
| 0
|
Kotlin
|
2
| 9
|
b3e8959714fa70dd4afb89c08e8a468355e1f9a0
| 3,412
|
gpt-investor-android
|
MIT License
|
src/generated/kotlin/net/highteq/cylab/awssdk/dynamodb/kotlin/dsl/model/GlobalSecondaryIndexDescriptionDSL.kt
|
cylab
| 258,882,001
| false
| null |
/*
This file was generated from https://github.com/aws/aws-sdk-java-v2 by https://github.com/cylab/aws-kotlin-dsl-builder
Like the original code, this file and project is licensed under
Apache License Version 2.0
See LICENSE.txt for more info
*/
@file:Suppress("DEPRECATION", "NOTHING_TO_INLINE")
package net.highteq.cylab.awssdk.dynamodb.kotlin.dsl.model
import kotlin.DeprecationLevel.HIDDEN
import kotlin.DeprecationLevel.WARNING
import net.highteq.cylab.awssdk.dynamodb.kotlin.dsl.DynamodbDSL
import net.highteq.cylab.awssdk.dynamodb.kotlin.dsl.DynamodbDSLMarker
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndexDescription
import software.amazon.awssdk.services.dynamodb.model.IndexStatus
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement
import software.amazon.awssdk.services.dynamodb.model.Projection
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription
/**
* Builds instances of type GlobalSecondaryIndexDescription:
* Represents the properties of a global secondary index.
*/
@DynamodbDSLMarker
inline class GlobalSecondaryIndexDescriptionDSL(
@Deprecated("Usage of the builder field is not recommended. It might vanish in any new release!", level = WARNING)
val builder: GlobalSecondaryIndexDescription.Builder
){
@PublishedApi
internal fun build(): GlobalSecondaryIndexDescription = builder.build()
/**
*
*/
inline var backfilling: Boolean?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.backfilling(value)
}
/**
*
*/
inline var indexArn: String?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.indexArn(value)
}
/**
*
*/
inline var indexName: String?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.indexName(value)
}
/**
*
*/
inline var indexSizeBytes: Long?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.indexSizeBytes(value)
}
/**
*
*/
inline var indexStatus: IndexStatus?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.indexStatus(value)
}
/**
*
*/
inline var itemCount: Long?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.itemCount(value)
}
/**
*
*/
inline var keySchema: Collection<KeySchemaElement>?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.keySchema(value)
}
/**
*
*/
inline var projection: Projection?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.projection(value)
}
/**
*
*/
inline var provisionedThroughput: ProvisionedThroughputDescription?
@Deprecated("", level = HIDDEN) // Hide from Kotlin callers
get() = throw UnsupportedOperationException()
set(value) {
builder.provisionedThroughput(value)
}
/**
*
*/
inline fun indexStatus(value: String?) {
builder.indexStatus(value)
}
/**
*
*/
inline fun keySchema(dslBlock: KeySchemaElementCollectionDSL.() -> Unit) {
builder.keySchema(DynamodbDSL.Companion.keySchemaElementCollection(dslBlock))
}
/**
*
*/
inline fun projection(dslBlock: ProjectionDSL.() -> Unit) {
builder.projection(DynamodbDSL.Companion.projection(dslBlock))
}
/**
*
*/
inline fun provisionedThroughput(dslBlock: ProvisionedThroughputDescriptionDSL.() -> Unit) {
builder.provisionedThroughput(DynamodbDSL.Companion.provisionedThroughputDescription(dslBlock))
}
}
/**
* Builds instances of type GlobalSecondaryIndexDescription:
* Represents the properties of a global secondary index.
*/
inline fun globalSecondaryIndexDescription(dslBlock: GlobalSecondaryIndexDescriptionDSL.() -> Unit) =
GlobalSecondaryIndexDescriptionDSL(GlobalSecondaryIndexDescription.builder()).apply(dslBlock).build()
/**
* Builds instances of type GlobalSecondaryIndexDescription:
* Represents the properties of a global secondary index.
*/
inline fun DynamodbDSL.Companion.globalSecondaryIndexDescription(dslBlock: GlobalSecondaryIndexDescriptionDSL.() -> Unit) =
GlobalSecondaryIndexDescriptionDSL(GlobalSecondaryIndexDescription.builder()).apply(dslBlock).build()
| 0
|
Kotlin
|
0
| 4
|
b3f40e013e78f363794f7671a43de88983280bb9
| 4,855
|
awssdk-dynamodb-kotlin-dsl
|
Apache License 2.0
|
platform/backend/bridge/src/integrationTest/kotlin/io/hamal/bridge/http/controller/exec/BaseExecControllerTest.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 3316689, "C": 1401511, "TypeScript": 450023, "Lua": 193995, "C++": 40651, "Makefile": 11728, "Java": 7564, "JavaScript": 5832, "SCSS": 5191, "CMake": 2838, "CSS": 1626, "HTML": 1245, "Shell": 993}
|
package io.hamal.bridge.http.controller.exec
import io.hamal.bridge.http.controller.BaseControllerTest
internal sealed class BaseExecControllerTest : BaseControllerTest()
| 44
|
Kotlin
|
0
| 0
|
1c9b1ad3368823ad9c339b6a56532a602cef7c63
| 172
|
hamal
|
Creative Commons Zero v1.0 Universal
|
TeamCode/src/main/java/asiankoala/ftc2022/sunmi/opmodes/tests/TuneServos.kt
|
ftc-noteam
| 539,184,063
| false
| null |
package asiankoala.ftc2022.sunmi.opmodes.tests
import asiankoala.ftc2022.sunmi.commands.subsystem.ArmCmd
import asiankoala.ftc2022.sunmi.commands.subsystem.PivotCmd
import asiankoala.ftc2022.sunmi.subsystems.Arm
import asiankoala.ftc2022.sunmi.subsystems.Claw
import asiankoala.ftc2022.sunmi.subsystems.Pivot
import asiankoala.ftc2022.sunmi.subsystems.constants.ArmConstants
import asiankoala.ftc2022.sunmi.subsystems.constants.ClawConstants
import asiankoala.ftc2022.sunmi.subsystems.constants.PivotConstants
import com.asiankoala.koawalib.command.KOpMode
import com.asiankoala.koawalib.command.commands.InstantCmd
import com.asiankoala.koawalib.logger.Logger
import com.asiankoala.koawalib.logger.LoggerConfig
import com.qualcomm.robotcore.eventloop.opmode.TeleOp
class TuneServos : KOpMode(true, 8) {
override fun mInit() {
Logger.config = LoggerConfig.DASHBOARD_CONFIG
val claw = Claw()
val pivot = Pivot()
val arm = Arm()
driver.rightTrigger.onPress(InstantCmd({ arm.setTarget(ArmConstants.intake )}))
driver.rightBumper.onPress(InstantCmd({ arm.setTarget(ArmConstants.home )}))
driver.leftTrigger.onPress(InstantCmd({ claw.setTarget(ClawConstants.open )}))
driver.leftBumper.onPress(InstantCmd({ claw.setTarget(ClawConstants.close )}))
driver.dpadDown.onPress(ArmCmd(arm, ArmConstants.deposit))
driver.dpadUp.onPress(PivotCmd(pivot, PivotConstants.home))
driver.dpadLeft.onPress(PivotCmd(pivot, PivotConstants.deposit))
driver.dpadRight.onPress(PivotCmd(pivot, PivotConstants.ground))
}
}
| 0
|
Kotlin
|
0
| 7
|
68d489dd69a2d0e8859f1a8ef2a65fcf8eb86952
| 1,600
|
PowerPlay
|
BSD 3-Clause Clear License
|
src/main/kotlin/cc/tweaked_programs/partnership/main/block/cannon/MarineCannonBlock.kt
|
tweaked-programs
| 733,540,479
| false
|
{"Kotlin": 160511, "Java": 10462}
|
package cc.tweaked_programs.partnership.main.block.cannon
import cc.tweaked_programs.partnership.main.registries.BlockEntityRegistries
import cc.tweaked_programs.partnership.main.registries.ItemRegistries
import com.mojang.serialization.MapCodec
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.sounds.SoundEvents
import net.minecraft.sounds.SoundSource
import net.minecraft.world.InteractionHand
import net.minecraft.world.InteractionResult
import net.minecraft.world.MenuProvider
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.Items
import net.minecraft.world.item.context.BlockPlaceContext
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.*
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.entity.BlockEntityTicker
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.level.block.state.properties.BlockStateProperties
import net.minecraft.world.phys.BlockHitResult
import net.minecraft.world.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.Shapes
import net.minecraft.world.phys.shapes.VoxelShape
class MarineCannonBlock(properties: Properties) : BaseEntityBlock(properties), EntityBlock {
override fun codec(): MapCodec<out BaseEntityBlock> = throw NotImplementedError("Normally not required in 1.20.4")
init {
registerDefaultState(stateDefinition.any()
.setValue(BlockStateProperties.HORIZONTAL_FACING, Direction.NORTH)
)
}
override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): BlockEntity = MarineCannonBlockEntity(blockPos, blockState)
override fun <T : BlockEntity> getTicker(level: Level, blockState: BlockState, blockEntityType: BlockEntityType<T>): BlockEntityTicker<T>?
= if (level.isClientSide || blockEntityType != BlockEntityRegistries.MARINE_CANNON) null else BlockEntityTicker { requiredLevel, blockPos, requiredBlockState, be: T ->
MarineCannonBlockEntity.tick(requiredLevel, blockPos, requiredBlockState, be as MarineCannonBlockEntity)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun use(blockState: BlockState, level: Level, blockPos: BlockPos, player: Player,
interactionHand: InteractionHand, blockHitResult: BlockHitResult): InteractionResult {
if (level.isClientSide) return InteractionResult.SUCCESS
val mainHandItem = player.mainHandItem
if (mainHandItem.isEmpty) {
val menuProvider = blockState.getMenuProvider(level, blockPos)
menuProvider?.let { player.openMenu(it) }
return InteractionResult.SUCCESS
}
val blockEntity = level.getBlockEntity(blockPos)
if (blockEntity !is MarineCannonBlockEntity)
return InteractionResult.SUCCESS
when (mainHandItem.item) {
Items.GUNPOWDER -> {
if (blockEntity.getPower() >= MarineCannonBlockEntity.MAX_POWER)
return InteractionResult.SUCCESS
if (!player.isCreative)
mainHandItem.count -= 1
blockEntity.loadOneGunpowder()
level.playSound(
null,
blockPos,
SoundEvents.NOTE_BLOCK_SNARE.value(),
SoundSource.BLOCKS,
1f,
1F/3F * blockEntity.getPower()
)
}
ItemRegistries.CANNONBALL -> {
if (blockEntity.isLoaded())
return InteractionResult.SUCCESS
if (!player.isCreative)
mainHandItem.count -= 1
blockEntity.fill()
level.playSound(
null,
blockPos,
SoundEvents.DECORATED_POT_PLACE,
SoundSource.BLOCKS,
1f,
0.3F
)
}
}
return InteractionResult.SUCCESS
}
@Suppress("OVERRIDE_DEPRECATION")
override fun neighborChanged(blockState: BlockState, level: Level, blockPos: BlockPos, block: Block, blockPos2: BlockPos, bl: Boolean) {
if (level.hasNeighborSignal(blockPos) || level.hasNeighborSignal(blockPos.below())) {
val blockEntity = level.getBlockEntity(blockPos)
if (blockEntity !is MarineCannonBlockEntity)
return
if (blockEntity.getPower() > 0 && blockEntity.isLoaded()) {
blockEntity.prepareShoot()
}
}
}
@Suppress("OVERRIDE_DEPRECATION")
override fun isSignalSource(state: BlockState): Boolean = true
@Suppress("OVERRIDE_DEPRECATION")
override fun getMenuProvider(blockState: BlockState, level: Level, blockPos: BlockPos): MenuProvider? {
val blockEntity = level.getBlockEntity(blockPos)
return if (blockEntity is MarineCannonBlockEntity) blockEntity else null
}
override fun createBlockStateDefinition(builder: StateDefinition.Builder<Block, BlockState>) { builder
.add(BlockStateProperties.HORIZONTAL_FACING)
}
override fun getStateForPlacement(ctx: BlockPlaceContext): BlockState? = defaultBlockState()
.setValue(BlockStateProperties.HORIZONTAL_FACING, if (ctx.player?.isCrouching == true) ctx.horizontalDirection.opposite else ctx.horizontalDirection)
@Suppress("OVERRIDE_DEPRECATION")
override fun triggerEvent(blockState: BlockState, level: Level, blockPos: BlockPos, i: Int, j: Int): Boolean {
super.triggerEvent(blockState, level, blockPos, i, j)
val blockEntity = level.getBlockEntity(blockPos) ?: return false
return blockEntity.triggerEvent(i, j)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun rotate(blockState: BlockState, rotation: Rotation): BlockState {
return blockState.setValue(HorizontalDirectionalBlock.FACING, rotation.rotate(blockState.getValue(HorizontalDirectionalBlock.FACING) as Direction)) as BlockState
}
@Suppress("OVERRIDE_DEPRECATION")
override fun mirror(blockState: BlockState, mirror: Mirror): BlockState {
return blockState.rotate(mirror.getRotation(blockState.getValue(HorizontalDirectionalBlock.FACING) as Direction))
}
@Suppress("OVERRIDE_DEPRECATION")
override fun getRenderShape(blockState: BlockState): RenderShape = RenderShape.INVISIBLE
@Suppress("OVERRIDE_DEPRECATION")
override fun getShape(blockState: BlockState, blockGetter: BlockGetter, blockPos: BlockPos,
collisionContext: CollisionContext
): VoxelShape = shape
companion object {
private val shape: VoxelShape = Shapes.empty()
.let { Shapes.or(it, Shapes.create(0.31875, 0.31875, 0.31875, 0.68125, 0.68125, 0.68125)) }
}
}
| 1
|
Kotlin
|
2
| 0
|
6a601a4376b1f32ee3270f72b7f0a844ec83d2e4
| 7,069
|
Partnership
|
MIT License
|
src/main/kotlin/com/github/frozencure/helix/http/ResourceService.kt
|
frozencure
| 253,615,832
| false
| null |
package com.github.frozencure.helix.http
import com.github.frozencure.helix.auth.basic.default
import com.github.frozencure.helix.auth.model.AuthCredentials
import com.github.frozencure.helix.auth.model.OAuthCredentials
import com.github.frozencure.helix.auth.oauth.oauth
import io.ktor.client.*
import io.ktor.client.engine.apache.*
import io.ktor.client.features.auth.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
/**
* An abstract service class where the configuration of the HTTP client happens.
* @constructor Creates a new resource service given an HTTP client.
* @param httpClient The HTTP client used to perform HTTP requests.
*/
abstract class ResourceService(
protected val httpClient: HttpClient
) {
/**
* Creates a new resource service object given some [AuthCredentials].
* Uses an [Apache] engine and a [KotlinxSerializer] for the JSON de-/serialization.
* @param credentials The credentials necessary for authenticating the requests made by the HTTP client.
*/
constructor(
credentials: AuthCredentials
)
: this(HttpClient(Apache) {
install(JsonFeature) {
serializer = KotlinxSerializer()
}
install(Auth) {
if (credentials is OAuthCredentials) {
oauth {
clientId = credentials.clientId
clientKey = credentials.clientKey
token = credentials.token
}
} else {
default {
clientId = credentials.clientId
clientKey = credentials.clientKey
}
}
}
})
companion object {
const val BASE_URL = "https://api.twitch.tv/helix"
}
}
| 3
|
Kotlin
|
3
| 17
|
285d49ad2ddf19f8ba2d0973ca17a40168fac914
| 1,801
|
twitch-client
|
MIT License
|
xposed/src/main/java/moe/fuqiuluo/dobby/Dobby.kt
|
fuqiuluo
| 870,496,630
| false
|
{"Kotlin": 314857, "AIDL": 21153, "C++": 16173, "Java": 3777, "C": 2930, "CMake": 476}
|
package moe.fuqiuluo.dobby
object Dobby {
external fun setStatus(status: Boolean)
}
| 0
|
Kotlin
|
3
| 10
|
f05b29c0bbe25130c92edda842730466ed49ef3b
| 90
|
Portal
|
Apache License 2.0
|
compiler/src/main/kotlin/se/ansman/kotshi/model/AdapterKey.kt
|
ansman
| 95,685,398
| false
| null |
package se.ansman.kotshi.model
import com.squareup.kotlinpoet.ANY
import com.squareup.kotlinpoet.ARRAY
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.DelicateKotlinPoetApi
import com.squareup.kotlinpoet.Dynamic
import com.squareup.kotlinpoet.LambdaTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.STAR
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.WildcardTypeName
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.tag
import com.squareup.kotlinpoet.tags.TypeAliasTag
import com.squareup.moshi.Types
import se.ansman.kotshi.notNull
import java.util.Locale
data class AdapterKey(
val type: TypeName,
val jsonQualifiers: Set<AnnotationModel>
)
fun AdapterKey.asRuntimeType(typeVariableAccessor: (TypeVariableName) -> CodeBlock): CodeBlock =
(type.tag<TypeAliasTag>()?.abbreviatedType ?: type).asRuntimeType(typeVariableAccessor)
val AdapterKey.suggestedAdapterName: String
get() = buildString {
jsonQualifiers.joinTo(this, "") { it.annotationName.simpleName }
append(type.baseAdapterName)
append("Adapter")
replace(0, 1, this[0].lowercase(Locale.ROOT))
}
private val TypeName.baseAdapterName: String
get() = when (this) {
is ClassName -> simpleNames.joinToString("")
Dynamic -> "dynamic"
is LambdaTypeName -> buildString {
append(receiver?.baseAdapterName ?: "")
for (parameter in parameters) {
append(parameter.type.baseAdapterName)
}
append(returnType.baseAdapterName)
append("Lambda")
}
is ParameterizedTypeName -> typeArguments.joinToString("") { it.baseAdapterName } + rawType.baseAdapterName
is TypeVariableName -> name
is WildcardTypeName -> when {
inTypes.size == 1 -> inTypes[0].baseAdapterName
outTypes == STAR.outTypes -> "Star"
else -> outTypes[0].baseAdapterName
}
}
private fun TypeName.asRuntimeType(typeVariableAccessor: (TypeVariableName) -> CodeBlock): CodeBlock =
when (this) {
is ParameterizedTypeName ->
CodeBlock.builder()
.add(
"%T.newParameterizedType(%T::class.javaObjectType", moshiTypes, if (rawType == ARRAY) {
// Arrays are special, you cannot just do Array::class.java
this
} else {
rawType.notNull()
}
)
.apply {
for (typeArgument in typeArguments) {
add(", ")
add(typeArgument.asRuntimeType(typeVariableAccessor))
}
}
.add(")")
.build()
is WildcardTypeName -> when {
inTypes.size == 1 -> inTypes[0].asRuntimeType(typeVariableAccessor)
outTypes[0] == ANY -> ANY.asRuntimeType(typeVariableAccessor)
else -> outTypes[0].asRuntimeType(typeVariableAccessor)
}
is LambdaTypeName -> asParameterizedTypeName().asRuntimeType(typeVariableAccessor)
is TypeVariableName -> typeVariableAccessor(this)
else -> CodeBlock.of("%T::class.javaObjectType", notNull())
}
@OptIn(DelicateKotlinPoetApi::class)
val moshiTypes = Types::class.java.asClassName()
private fun LambdaTypeName.asParameterizedTypeName(): ParameterizedTypeName {
val parameters = mutableListOf<TypeName>()
receiver?.let(parameters::add)
parameters.addAll(parameters)
parameters.add(returnType)
return ClassName("kotlin", "Function${parameters.size + (if (receiver == null) 0 else 1)}")
.parameterizedBy(parameters)
}
| 2
|
Kotlin
|
40
| 697
|
a82b4e8105d169b948c97dd59d9867a8b9de91cd
| 3,975
|
kotshi
|
Apache License 2.0
|
app/src/main/java/com/koleff/kare_android/ui/view_model/ExerciseDetailsConfiguratorViewModel.kt
|
MartinKoleff
| 741,013,199
| false
|
{"Kotlin": 655085}
|
package com.koleff.kare_android.ui.view_model
import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.koleff.kare_android.common.di.IoDispatcher
import com.koleff.kare_android.common.navigation.Destination
import com.koleff.kare_android.common.navigation.NavigationController
import com.koleff.kare_android.common.navigation.NavigationEvent
import com.koleff.kare_android.data.model.dto.ExerciseDto
import com.koleff.kare_android.data.model.dto.MuscleGroup
import com.koleff.kare_android.data.model.dto.WorkoutDetailsDto
import com.koleff.kare_android.ui.state.ExerciseState
import com.koleff.kare_android.domain.usecases.ExerciseUseCases
import com.koleff.kare_android.domain.usecases.WorkoutUseCases
import com.koleff.kare_android.ui.event.OnExerciseUpdateEvent
import com.koleff.kare_android.ui.state.WorkoutState
import com.koleff.kare_android.ui.state.WorkoutDetailsState
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectIndexed
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Qualifier
@HiltViewModel
class ExerciseDetailsConfiguratorViewModel @Inject constructor(
private val exerciseUseCases: ExerciseUseCases,
private val workoutUseCases: WorkoutUseCases,
private val navigationController: NavigationController,
private val savedStateHandle: SavedStateHandle,
@IoDispatcher private val dispatcher: CoroutineDispatcher
) : BaseViewModel(navigationController) {
private val exerciseId: Int = savedStateHandle.get<String>("exercise_id")?.toIntOrNull() ?: -1
private val workoutId: Int = savedStateHandle.get<String>("workout_id")?.toIntOrNull() ?: -1
private val initialMuscleGroupId =
savedStateHandle.get<String>("muscle_group_id")?.toIntOrNull() ?: -1
val initialMuscleGroup = MuscleGroup.fromId(initialMuscleGroupId)
private var _exerciseState: MutableStateFlow<ExerciseState> = MutableStateFlow(ExerciseState())
val exerciseState: StateFlow<ExerciseState>
get() = _exerciseState
private var _selectedWorkoutState: MutableStateFlow<WorkoutDetailsState> =
MutableStateFlow(WorkoutDetailsState())
val selectedWorkoutState: StateFlow<WorkoutDetailsState>
get() = _selectedWorkoutState
private var _updateWorkoutState: MutableStateFlow<WorkoutDetailsState> =
MutableStateFlow(WorkoutDetailsState())
val updateWorkoutState: StateFlow<WorkoutDetailsState>
get() = _updateWorkoutState
init {
getExercise(exerciseId)
getWorkoutDetails(workoutId)
}
private fun getExercise(exerciseId: Int) {
viewModelScope.launch(dispatcher) {
exerciseUseCases.getExerciseUseCase(exerciseId).collect { exerciseState ->
_exerciseState.value = exerciseState
}
}
}
private fun getWorkoutDetails(workoutId: Int) {
viewModelScope.launch(dispatcher) {
workoutUseCases.getWorkoutDetailsUseCase(workoutId).collect { workoutDetailsState ->
_selectedWorkoutState.value = workoutDetailsState
}
}
}
fun onExerciseUpdateEvent(event: OnExerciseUpdateEvent) {
val selectedWorkout: WorkoutDetailsDto
when (event) {
is OnExerciseUpdateEvent.OnExerciseDelete -> {
selectedWorkout = selectedWorkoutState.value.workoutDetails
val exercise = event.exercise
viewModelScope.launch(dispatcher) {
workoutUseCases.deleteExerciseUseCase(
workoutId = selectedWorkout.workoutId,
exerciseId = exercise.exerciseId
).collect { updateWorkoutState ->
_updateWorkoutState.value = updateWorkoutState
}
}
}
is OnExerciseUpdateEvent.OnExerciseSubmit -> {
selectedWorkout = selectedWorkoutState.value.workoutDetails
val exercise = event.exercise
viewModelScope.launch(dispatcher) {
workoutUseCases.addExerciseUseCase(
workoutId = selectedWorkout.workoutId,
exercise = exercise
).collect { updateWorkoutState ->
_updateWorkoutState.value = updateWorkoutState
}
}
}
}
}
private fun resetUpdateWorkoutState() {
_updateWorkoutState.value = WorkoutDetailsState()
}
//Navigation
fun navigateToWorkoutDetails(workoutId: Int) {
super.onNavigationEvent(
NavigationEvent.PopUpToAndNavigateTo(
destinationRoute = Destination.WorkoutDetails(
workoutId
).route,
popUpToRoute = Destination.Workouts.route,
inclusive = false
)
)
//Raise a flag to update Workouts screen...
savedStateHandle["hasUpdated"] = true
Log.d("ExerciseDetailsConfiguratorViewModel", "hasUpdated set to true.")
//Reset state
resetUpdateWorkoutState()
}
override fun clearError() {
if(exerciseState.value.isError){
_exerciseState.value = ExerciseState()
}
if(updateWorkoutState.value.isError){
_updateWorkoutState.value = WorkoutDetailsState()
}
if(selectedWorkoutState.value.isError){
_selectedWorkoutState.value = WorkoutDetailsState()
}
}
}
| 15
|
Kotlin
|
0
| 4
|
e31db6fb293ae0b00fd9c4526b1f8d5c2be64b67
| 5,941
|
KareFitnessApp
|
MIT License
|
data/src/main/kotlin/com/r2b/apps/xuser/data/storage/UserDAO.kt
|
r2bapps
| 497,688,954
| false
|
{"Kotlin": 139683}
|
package com.r2b.apps.xuser.data.storage
import androidx.room.*
import com.r2b.apps.xuser.data.storage.entity.UserDB
@Dao
interface UserDAO: BaseDAO<UserDB> {
/*
REMEMBER:
SQLite have no boolean data type
Room maps boolean data to an INTEGER column
Room mapping true to 1 and false to 0
*/
@Query("SELECT * FROM User WHERE deleted = 0 ORDER BY id ASC LIMIT :items OFFSET :page")
suspend fun page(page: Int, items: Int): List<UserDB>
@Query("SELECT * FROM User WHERE id IN (:id) AND deleted = 0")
suspend fun read(id: Int): List<UserDB>
@Query("SELECT COUNT(id) FROM User")
suspend fun count(): Int
}
| 0
|
Kotlin
|
2
| 0
|
c4b47a564e0d07a787b6d237eb18f23fd0d6d0f6
| 669
|
assessment
|
MIT License
|
testerum-steps-api/src/main/kotlin/com/testerum_api/testerum_steps_api/test_context/test_vars/TestVariables.kt
|
testerum
| 301,253,207
| false
| null |
package com.testerum_api.testerum_steps_api.test_context.test_vars
import com.testerum_api.testerum_steps_api.services.TesterumService
interface TestVariables : TesterumService {
fun contains(name: String): Boolean
/**
* @throws VariableNotFoundException is [name] is not defined
*/
operator fun get(name: String): Any?
fun getOrDefault(name: String, defaultValue: Any?): Any?
fun getOrDefault(name: String, defaultValueSupplier: () -> Any?): Any?
/**
* @return the previous value, or null if [name] was previously not defined
*/
operator fun set(name: String, value: Any?): Any?
fun resolveIn(text: String): String
fun getVariablesDetailsForDebugging(): String
}
| 0
|
Kotlin
|
0
| 0
|
5d111508b6cb36ccf7f07daac6bdeffa023f00ac
| 729
|
testerum-api
|
Apache License 2.0
|
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/ViewCompactAltSharp.kt
|
karakum-team
| 387,062,541
| false
|
{"Kotlin": 3037818, "TypeScript": 2249, "HTML": 724, "CSS": 86}
|
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ViewCompactAltSharp")
package mui.icons.material
@JsName("default")
external val ViewCompactAltSharp: SvgIconComponent
| 1
|
Kotlin
|
5
| 35
|
7c4376ba64ea84a5c40255d83c8c046978c3843d
| 202
|
mui-kotlin
|
Apache License 2.0
|
core/src/jsMain/kotlin/com/lehaine/littlekt/graphics/gl/UniformLocation.kt
|
littlektframework
| 442,309,478
| false
|
{"Kotlin": 2285392}
|
package com.lehaine.littlekt.graphics.gl
import org.khronos.webgl.WebGLUniformLocation
/**
* @author Colton Daily
* @date 9/28/2021
*/
actual class UniformLocation(val delegate: WebGLUniformLocation)
| 14
|
Kotlin
|
9
| 291
|
89f372fd18e47998d9b1d3add93ba92e4dcaca6e
| 204
|
littlekt
|
Apache License 2.0
|
dependency/src/main/kotlin/dev/skzr/lib/dependency/repository/MavenRepository.kt
|
SkyezerFox
| 377,899,980
| false
| null |
package dev.skzr.lib.dependency.repository
import dev.skzr.lib.dependency.Dependency
import dev.skzr.lib.dependency.artifact.ArtifactPom
import dev.skzr.lib.dependency.artifact.ArtifactPomDependency
import dev.skzr.lib.dependency.artifact.asArray
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.BufferedSource
import org.w3c.dom.Element
import org.xml.sax.InputSource
import java.io.StringReader
import javax.xml.parsers.DocumentBuilderFactory
/**
* Convert this dependency into a Maven URI.
*/
fun Dependency.toMavenURI(endpoint: HttpUrl, suffix: String?): HttpUrl {
val builder = endpoint.newBuilder()
// split group id and add
this.groupId.split(".").forEach {
builder.addPathSegment(it)
}
// add path segments
return builder
.addPathSegment(this.artifactId)
.addPathSegment(this.version)
.addPathSegment(this.qualifier + (suffix ?: ""))
.build()
}
/**
* A Maven repository found at the target endpoint.
*/
internal class MavenRepository(val endpoint: HttpUrl) : Repository() {
private val factory = DocumentBuilderFactory.newDefaultInstance()
override val name = this.endpoint.toString()
/**
* Construct a new Maven repository using a string URL.
*/
constructor(endpoint: String) : this(endpoint.toHttpUrl())
override fun fetchDependencyPom(dependency: Dependency): ArtifactPom? {
return try {
// build request
val request = Request.Builder()
.method("GET", null)
.url(dependency.toMavenURI(this.endpoint, ".pom"))
.build()
// make request
val response = OkHttpClient().newCall(request).execute()
// create pom
val pom = factory.newDocumentBuilder().parse(InputSource(StringReader(response.body!!.string()))).firstChild as Element
// get base info
val groupId = pom.getElementsByTagName("groupId").item(0).textContent
val artifactId = pom.getElementsByTagName("artifactId").item(0).textContent
val version = pom.getElementsByTagName("version").item(0).textContent
// fetch dependencies
val dependencies = pom.getElementsByTagName("dependencies")
.item(0)
.childNodes.asArray()
.filter {
it.hasChildNodes()
}.map {
ArtifactPomDependency.fromElement(it as Element)
}
// return
ArtifactPom(groupId, artifactId, version, dependencies)
} catch (e: Exception) {
e.printStackTrace()
null
}
}
override fun fetchDependencyChecksum(dependency: Dependency): String? {
return try {
val request = Request.Builder()
.method("GET", null)
.url(dependency.toMavenURI(this.endpoint, ".jar.md5"))
.build()
// make request
OkHttpClient().newCall(request).execute().body?.string()
} catch(e: Exception) {
e.printStackTrace()
null
}
}
override fun fetchDependencyJar(dependency: Dependency): BufferedSource? {
return try {
val request = Request.Builder()
.method("GET", null)
.url(dependency.toMavenURI(this.endpoint, ".jar"))
.build()
OkHttpClient().newCall(request).execute().body?.source()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8172aa60ffdc06e6818d67334f3938b02502f2f2
| 3,112
|
skzr-lib
|
MIT License
|
src/main/kotlin/tv/dotstart/badge/service/connector/github/model/License.kt
|
dotStart
| 136,342,051
| false
|
{"Kotlin": 144091, "HTML": 4749, "JavaScript": 2747, "Dockerfile": 278}
|
/*
* Copyright 2020 <NAME> <<EMAIL>>
* and other copyright owners as documented in the project's IP log.
*
* 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 tv.dotstart.badge.service.connector.github.model
import com.fasterxml.jackson.annotation.JsonProperty
/**
* @author [<NAME>](mailto:<EMAIL>)
* @date 08/05/2020
*/
data class License(
val key: String,
val name: String,
@JsonProperty("spdx_id")
val spdxId: String?,
@JsonProperty("node_id")
val nodeId: String)
| 0
|
Kotlin
|
1
| 0
|
f2d471ae6b9687f437dddc7dbb6287102727b97a
| 1,015
|
Badges
|
Apache License 2.0
|
app/src/main/java/com/aowen/monolith/data/BuildListItem.kt
|
heatcreep
| 677,508,642
| false
|
{"Kotlin": 1082631}
|
package com.aowen.monolith.data
import com.aowen.monolith.data.database.model.FavoriteBuildListEntity
import java.sql.Timestamp
import java.util.UUID
data class BuildListItem(
val id: Int = 0,
val userId: String? = null,
val title: String = "",
val author: String = "",
val role: String = "unknown",
val description: String? = "",
val heroId: Int = 999,
val crest: Int = 0,
val buildItems: List<Int> = emptyList(),
val skillOrder: List<Int>? = null,
val upvotes: Int = 0,
val downvotes: Int = 0,
val modules: List<ItemModule> = emptyList(),
val createdAt: String? = "",
val updatedAt: String? = "",
val version: String? = ""
)
data class ItemModule(
val title: String = "",
val items: List<Int> = emptyList(),
)
fun BuildDto.create(): BuildListItem {
return BuildListItem(
id = id,
title = title,
author = author,
role = role,
description = description,
heroId = heroId,
crest = crestId,
buildItems = listOfNotNull(item1Id, item2Id, item3Id, item4Id, item5Id, item6Id),
skillOrder = skillOrder,
upvotes = upvotesCount,
downvotes = downvotesCount,
createdAt = createdAt,
updatedAt = updatedAt,
modules = modules.map { it.create() },
version = gameVersion.name
)
}
fun ModuleDto.create(): ItemModule {
return ItemModule(
title = title,
items = listOfNotNull(item1Id, item2Id, item3Id, item4Id, item5Id, item6Id),
)
}
fun BuildListItem.asFavoriteBuildListEntity(): FavoriteBuildListEntity {
return FavoriteBuildListEntity(
buildId = id,
heroId = heroId,
role = role,
title = title,
description = description,
author = author,
crestId = crest,
itemIds = buildItems,
upvotesCount = upvotes,
downvotesCount = downvotes,
createdAt = createdAt,
gameVersion = version ?: ""
)
}
fun BuildListItem.asFavoriteBuildDto(userId: UUID): FavoriteBuildDto {
return FavoriteBuildDto(
id = UUID.randomUUID(),
createdAt = Timestamp(System.currentTimeMillis()).toString(),
userId = userId,
buildId = id,
heroId = heroId,
role = role,
title = title,
description = description,
author = author,
crestId = crest,
itemIds = buildItems,
upvotesCount = upvotes,
downvotesCount = downvotes,
gameVersion = version ?: ""
)
}
| 11
|
Kotlin
|
0
| 2
|
fba188346b2b110b4a9c837cca7225ee1ba0bb65
| 2,550
|
predecessor-monolith
|
MIT License
|
corda/services/src/main/kotlin/nl/tno/federated/corda/services/graphdb/GraphDBService.kt
|
federatedplatforms
| 781,315,852
| false
|
{"Kotlin": 233863, "Java": 126363, "TypeScript": 10886, "HTML": 10475, "Svelte": 7001, "JavaScript": 5457, "Dockerfile": 1547, "CSS": 1017, "Python": 1014, "Makefile": 291}
|
package nl.tno.federated.corda.services.graphdb
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import nl.tno.federated.services.PrefixHandlerQueries
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.HttpClient
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClientBuilder
import org.slf4j.LoggerFactory
import java.io.InputStream
import java.net.URI
import java.net.URLEncoder
import java.nio.charset.StandardCharsets.UTF_8
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
/**
* Exception thrown when anything happens in the GraphDBService
*/
open class GraphDBException(message: String) : Exception(message)
/**
* Exception that might occur when the GraphDB server returns an exception (500..599)
*/
class GraphDBClientException(message: String) : GraphDBException(message)
/**
* Exception that might occur when an invalid request is made to the GraphDB server (400..499)
*/
class GraphDBServerException(message: String) : GraphDBException(message)
class GraphDBService : IGraphDBService {
private val log = LoggerFactory.getLogger(GraphDBService::class.java)
private val properties: Properties by lazy {
getInputStreamFromClassPathResource("database.properties").use {
if (it == null) log.warn("database.properties could not be found!")
val properties = Properties()
properties.load(it)
with(System.getProperties()) {
getProperty("triplestore.protocol")?.run {
log.info("Overriding database.properties with System properties: triplestore.protocol: {}", this)
properties.setProperty("triplestore.protocol", this)
}
getProperty("triplestore.host")?.run {
log.info("Overriding database.properties with System properties: triplestore.host: {}", this)
properties.setProperty("triplestore.host", this)
}
getProperty("triplestore.port")?.let {
log.info("Overriding database.properties with System properties: triplestore.port: {}", this)
properties.setProperty("triplestore.port", it)
}
}
log.info("Loaded database.properties: triplestore.protocol: {}, triplestore.host: {}, triplestore.port: {}", properties.get("triplestore.protocol"), properties.get("triplestore.host"), properties.get("triplestore.port"))
properties
}
}
private var externalHttpClient: HttpClient? = null
/**
* See: https://www.baeldung.com/httpclient-timeout
* And: https://www.baeldung.com/httpclient-connection-management
*/
private val client: HttpClient by lazy {
if (externalHttpClient != null) externalHttpClient!!
else {
HttpClientBuilder.create()
.setMaxConnPerRoute(properties.getProperty("triplestore.maxConnectionsPerRoute").toIntOrNull() ?: 50)
.setMaxConnTotal(properties.getProperty("triplestore.maxConnectionsTotal").toIntOrNull() ?: 100)
.setDefaultRequestConfig(
RequestConfig.custom()
.setConnectTimeout(properties.getProperty("triplestore.connectTimeoutMillis").toIntOrNull() ?: 5000)
.setConnectionRequestTimeout(properties.getProperty("triplestore.connectTimeoutMillis").toIntOrNull() ?: 5000)
.setSocketTimeout(properties.getProperty("triplestore.socketTimeoutMillis").toIntOrNull() ?: 5000)
.build()
)
.build()
}
}
override fun queryEventIds(): String {
val sparql = """
${PrefixHandlerQueries.getPrefixesEvent()}
select ?s where {
?s a Event:Event
}
""".trimIndent()
return performSparql(sparql) ?: ""
}
override fun generalSPARQLquery(query: String, privateRepo: Boolean): String {
return performSparql(query.trimIndent(), privateRepo) ?: ""
}
override fun queryEventById(id: String): String {
assertSPARQLInput(id)
assertSPARQLInput(id)
val sparql = """
${PrefixHandlerQueries.getPrefixesEvent()}
select ?s where {
?s a Event:Event .
FILTER regex (STR(?s), "$id")
}
""".trimIndent()
return performSparql(sparql) ?: ""
}
override fun queryAllEventPropertiesById(id: String): String {
val sparql = """
${PrefixHandlerQueries.getPrefixesEvent()}
${PrefixHandlerQueries.getPrefixesDigitalTwin()}
SELECT DISTINCT ?subject ?object ?object1 ?object2
WHERE {
?subject a Event:Event .
?subject Event:involvesBusinessTransaction ?object .
?subject Event:involvesDigitalTwin ?object1, ?object2 .
?object1 a dt:Equipment .
?object2 a dt:TransportMeans .
FILTER regex (STR(?subject), "$id")
}
""".trimIndent()
return performSparql(sparql) ?: ""
}
override fun queryEventComponent(id: String): String {
val sparql = """
${PrefixHandlerQueries.getPrefixesSemanticElements()}
SELECT ?subject
WHERE {
?subject a owl:NamedIndividual
FILTER regex (STR(?subject), "$id")
}
""".trimIndent()
return performSparql(sparql) ?: ""
}
override fun isQueryResultEmpty(queryResult: String): Boolean {
val mapper = jacksonObjectMapper().readTree(queryResult)
val queryBindings = mapper["results"]["bindings"].elements()
return !queryBindings.hasNext()
}
// order of the arguments in queryResult: object = business transaction, object1 = equipment, object2 = transport means
override fun areEventComponentsAccurate(queryResult: String, businessTransaction: String, transportMeans: String, equipmentUsed: String): Boolean {
val mapper = jacksonObjectMapper().readTree(queryResult)
val bindings = mapper["results"]["bindings"]
val businessTransactionFromQueryURI = bindings[0]["object"]["value"].asText()
val businessTransactionFromQuery = businessTransactionFromQueryURI.split("#")[1]
if (businessTransaction !in businessTransactionFromQuery) return false
val equipmentFromQueryURI = bindings[0]["object1"]["value"].asText()
val equipmentFromQuery = equipmentFromQueryURI.split("#")[1]
if (equipmentUsed !in equipmentFromQuery) return false
val transportMeansFromQueryURI = bindings[0]["object2"]["value"].asText()
val transportMeansFromQuery = transportMeansFromQueryURI.split("#")[1]
if (transportMeans !in transportMeansFromQuery) return false
return true
}
override fun queryCityName(locationName: String): String {
val queryCity = """
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX Event: <https://ontology.tno.nl/logistics/federated/Event#>
PREFIX pi: <https://ontology.tno.nl/logistics/federated/PhysicalInfrastructure#>
select ?oCity where {
?s a Event:Event .
?s Event:involvesPhysicalInfrastructure ?o .
?o pi:cityName ?oCity .
FILTER regex(str(?o), "$locationName")
}""".trimIndent()
return performSparql(queryCity) ?: ""
}
override fun queryCountryName(locationName: String): String {
val queryCountry = """
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX Event: <https://ontology.tno.nl/logistics/federated/Event#>
PREFIX pi: <https://ontology.tno.nl/logistics/federated/PhysicalInfrastructure#>
select ?oCountry where {
?s a Event:Event .
?s Event:involvesPhysicalInfrastructure ?o .
?o pi:countryName ?oCountry .
FILTER regex(str(?o), "$locationName")
}""".trimIndent()
return performSparql(queryCountry) ?: ""
}
override fun queryCountryGivenEventId(eventId: String): String {
val queryCountryByEventId = """
PREFIX Event: <https://ontology.tno.nl/logistics/federated/Event#>
PREFIX pi: <https://ontology.tno.nl/logistics/federated/PhysicalInfrastructure#>
select ?oCountry where {
?s a Event:Event .
?s Event:involvesPhysicalInfrastructure ?o .
?o pi:countryName ?oCountry .
FILTER regex(str(?s), "$eventId")
}""".trimIndent()
return performSparql(queryCountryByEventId) ?: ""
}
override fun unpackCountriesFromSPARQLresult(sparqlResult: String): List<String> {
val mapper = jacksonObjectMapper().readTree(sparqlResult)
val bindings = mapper["results"]["bindings"]
val extractedCountries = mutableListOf<String>()
for (country in bindings.elements()) {
extractedCountries.add(country["oCountry"]["value"].asText())
}
return extractedCountries
}
override fun insertEvent(ttl: String, privateRepo: Boolean): Boolean {
val uri = getRepositoryURI(privateRepo)
val result = client.post(URI("$uri/statements"), ttl)
log.info("Insert into GraphDB, statusCode: {}, responseBody: {}", result.statusLine.statusCode, result.bodyAsString)
return result.bodyAsString.isNullOrEmpty()
}
private fun performSparql(sparql: String, privateRepo: Boolean = false): String? {
val uri = getRepositoryURI(privateRepo)
return client.get(URI("$uri?query=${URLEncoder.encode(sparql, UTF_8.toString())}"))?.bodyAsString
}
private fun getRepositoryURI(privateRepo: Boolean): String {
return with(properties) {
val protocol = getProperty("triplestore.protocol")
val host = getProperty("triplestore.host")
val port = getProperty("triplestore.port")
val repository = if (privateRepo) getProperty("triplestore.private-repository") else getProperty("triplestore.repository")
"$protocol://$host:$port/repositories/$repository"
}
}
private fun getInputStreamFromClassPathResource(filename: String): InputStream? {
val file = Paths.get(filename)
if (Files.exists(file)) {
log.info("Using file: {}", file.toAbsolutePath())
return Files.newInputStream(file)
}
log.info("Using classpath resource: {}", filename)
return Thread.currentThread().contextClassLoader.getResourceAsStream(filename)
}
/**
* Check for possible to S(PAR)QL injection.
*/
private fun assertSPARQLInput(str: String) {
val suspiciousChars = listOf('?', '{', '}', ':')
if (str.any { it in suspiciousChars }) {
throw GraphDBException("Suspicious character detected in SPARQL input.")
}
}
}
private val HttpEntity.contentAsString: String
get() = String(content.readBytes(), UTF_8)
private fun HttpClient.get(uri: URI): HttpResponse? {
val request = HttpGet(uri).apply {
setHeader("Accept", "application/json")
}
return execute(request)
}
private fun HttpClient.post(uri: URI, body: String): HttpResponse {
return post(
uri, StringEntity(body), mapOf(
"Accept" to "application/json",
"Content-Type" to "text/turtle"
)
)
}
private fun HttpClient.post(uri: URI, entity: HttpEntity, headers: Map<String, String>): HttpResponse {
val request = HttpPost(uri).apply {
this.entity = entity
headers.forEach { (key, value) ->
setHeader(key, value)
}
}
return execute(request)
}
private val HttpResponse.bodyAsString: String?
get() {
return when (statusLine.statusCode) {
in 400..499 -> throw GraphDBClientException(entity?.contentAsString ?: "Bad request when accessing GraphDB")
in 500..599 -> throw GraphDBServerException(entity?.contentAsString ?: "Internal server error when accessing GraphDB")
else -> entity?.contentAsString
}
}
| 0
|
Kotlin
|
0
| 0
|
55aa6b8f3e5faa32c378e3dc0e21b8c7fd57fa04
| 12,375
|
FEDeRATED-BDI
|
Apache License 2.0
|
virtualjoystick/src/main/java/com/yoimerdr/android/virtualjoystick/geometry/Position.kt
|
yoimerdr
| 752,392,779
| false
|
{"Kotlin": 112504, "CSS": 2645}
|
package com.yoimerdr.android.virtualjoystick.geometry
class Position(
override var x: Float,
override var y: Float
) : FixedPosition(), MutablePosition {
constructor() : this(0.0f, 0.0f)
constructor(x: Int, y: Int) : this(x.toFloat(), y.toFloat())
constructor(x: Double, y: Double) : this(x.toFloat(), y.toFloat())
constructor(position: ImmutablePosition) : this(position.x, position.y)
override fun set(x: Float, y: Float) {
this.x = x
this.y = y
}
override fun set(position: ImmutablePosition) = set(position.x, position.y)
override fun negate() {
x = -x
y = -y
}
override fun xOffset(dx: Float) {
this.x += dx
}
override fun yOffset(dy: Float) {
this.y += dy
}
override fun offset(dx: Float, dy: Float) {
xOffset(dx)
yOffset(dy)
}
override fun offset(position: ImmutablePosition) = offset(position.x, position.y)
override fun toImmutable(): ImmutablePosition = FixedPosition(this)
override fun toString(): String = "Position(x=%.2f,y=%.2f)".format(x, y)
}
| 0
|
Kotlin
|
0
| 0
|
1ede27026dae3058a37b52ce6fc91272441fb601
| 1,113
|
AndroidVirtualJoystick
|
Apache License 2.0
|
hurl-core/src/main/kotlin/com/orange/ccmd/hurl/core/query/jsonpath/JsonPath.kt
|
isabella232
| 379,204,586
| true
|
{"Kotlin": 512534, "Python": 22137, "Shell": 3425, "HTML": 1830, "Mustache": 1098}
|
/*
* Copyright (C) 2020 Orange
*
* Hurl JVM (JVM Runner for https://hurl.dev)
*
* 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.orange.ccmd.hurl.core.query.jsonpath
import com.jayway.jsonpath.Configuration
import com.jayway.jsonpath.JsonPath
import com.jayway.jsonpath.Option
import com.jayway.jsonpath.PathNotFoundException
import com.orange.ccmd.hurl.core.query.InvalidQueryException
class JsonPath {
companion object {
fun evaluate(expr: String, json: String): JsonPathResult {
val ret: List<Any> = try {
val conf = Configuration.defaultConfiguration().addOptions(Option.ALWAYS_RETURN_LIST)
JsonPath.using(conf).parse(json).read(expr)
} catch (e: PathNotFoundException) {
return JsonPathNotFound
} catch (e: Exception) {
throw InvalidQueryException("$e")
}
// If the jsonpath expression return only one element, we try coerce this result
// into a string, number of boolean if it possible.
return if (ret.size == 1) {
JsonPathOk(result = JsonType.toJson(ret[0]))
} else {
JsonPathOk(result = JsonType.toJson(ret))
}
}
}
}
| 0
| null |
0
| 0
|
787bb3f83ff6629a5d3a391518675b60e2a28e9b
| 1,792
|
hurl-jvm
|
Apache License 2.0
|
hoplite-core/src/main/kotlin/com/sksamuel/hoplite/preprocessor/PropsPreprocessor.kt
|
fagossa
| 199,613,556
| true
|
{"Kotlin": 151981, "Shell": 126}
|
package com.sksamuel.hoplite.preprocessor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
/**
* Loads properties from a file and replaces strings of the form ${key} with the
* value of that key in the properties file.
*
* When creating this class, you can specify the location of the properties file
* either as a [Path] or as a resource on the classpath.
*/
class PropsPreprocessor(private val path: Path) : Preprocessor {
private val regex = "\\$\\{(.*?)}".toRegex()
private val props = Properties().apply {
this.load(Files.newInputStream(path))
}
override fun process(value: String): String = regex.replace(value) {
val key = it.groupValues[1]
props[key]?.toString() ?: it.value
}
companion object {
operator fun invoke(resource: String) = PropsPreprocessor(Paths.get(javaClass.getResource(resource).path))
}
}
| 0
|
Kotlin
|
0
| 0
|
3d584243f8718f573d414d2b209adeaad1679b29
| 907
|
hoplite
|
Apache License 2.0
|
src/main/kotlin/no/nav/hm/grunndata/db/iso/IsoCategory.kt
|
navikt
| 555,213,385
| false
|
{"Kotlin": 192632, "Dockerfile": 107, "Shell": 53}
|
package no.nav.hm.grunndata.db.iso
import io.micronaut.data.annotation.Id
import io.micronaut.data.annotation.MappedEntity
import io.micronaut.data.annotation.TypeDef
import io.micronaut.data.model.DataType
import java.time.LocalDateTime
import java.util.*
@MappedEntity("isocategory_v1")
data class IsoCategory(
@field: Id
val id: UUID = UUID.randomUUID(),
val isoCode: String,
val isoTitle: String,
val isoTitleShort: String?,
val isoText: String,
val isoTextShort: String?,
@field:TypeDef(type = DataType.JSON)
val isoTranslations: IsoTranslations = IsoTranslations(),
val isoLevel: Int,
val isActive: Boolean = true,
val showTech: Boolean = true,
val allowMulti: Boolean = true,
val created: LocalDateTime = LocalDateTime.now(),
val updated: LocalDateTime = LocalDateTime.now(),
@field:TypeDef(type = DataType.JSON)
val searchWords: List<String> = emptyList()
)
data class IsoTranslations(
val titleEn: String?=null,
val textEn: String?=null,
)
fun IsoCategory.toDTO(): IsoCategoryDTO = IsoCategoryDTO(
id = id,
isoCode = isoCode,
isoTitle = isoTitle,
isoTitleShort = isoTitleShort,
isoText = isoText,
isoTextShort = isoTextShort,
isoTranslations = IsoTranslationsDTO(titleEn = isoTranslations.titleEn, textEn = isoTranslations.textEn),
isoLevel = isoLevel,
isActive = isActive,
showTech = showTech,
allowMulti = allowMulti,
searchWords = searchWords
)
data class IsoCategoryDTO(
val id: UUID,
val isoCode: String,
val isoTitle: String,
val isoTitleShort: String?=null,
val isoText: String,
val isoTextShort: String?=null,
val isoTranslations: IsoTranslationsDTO?=null,
val isoLevel: Int,
val isActive: Boolean = true,
val showTech: Boolean = true,
val allowMulti: Boolean = true,
val created: LocalDateTime = LocalDateTime.now(),
val updated: LocalDateTime = LocalDateTime.now(),
val searchWords: List<String> = emptyList()
)
data class IsoTranslationsDTO(
val titleEn: String?=null,
val textEn: String?=null,
)
| 0
|
Kotlin
|
0
| 1
|
29709fb0ef96137c478e07123a106445b9c3eadd
| 2,111
|
hm-grunndata-db
|
MIT License
|
src/test/kotlin/org/geepawhill/rules/StupidUiTest.kt
|
GeePawHill
| 192,393,731
| false
| null |
package org.geepawhill.rules
import javafx.scene.Node
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import javafx.scene.layout.VBox
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.testfx.api.FxRobot
import org.testfx.api.FxToolkit
import tornadofx.*
abstract class StupidUiTest {
private var endOfBeforeEach = false
lateinit var robot: FxRobot
lateinit var container: Parent
lateinit var scene: Scene
abstract fun beforeUi(): Parent
@BeforeEach
fun beforeEach() {
FxToolkit.registerPrimaryStage()
robot = FxRobot()
container = beforeUi()
scene = Scene(container)
FxToolkit.setupScene { scene }
FxToolkit.showStage()
endOfBeforeEach = true
}
inline fun <reified T : Node> FxRobot.byTypeAndId(id: String): T {
return lookup<Node> { it.id == id }.query() as T
}
inline fun <reified T : Node> byId(id: String): T {
afterBeforeEachRequired()
return robot.lookup<Node> { it.id == id }.query() as T
}
inline fun <reified T : Node> byPredicate(noinline pred: (node: Node) -> Boolean): T {
afterBeforeEachRequired()
return robot.lookup<Node> { pred(it) }.query() as T
}
fun afterBeforeEachRequired() {
if (!endOfBeforeEach) throw RuntimeException("You can only use byXxxx methods in the @Test text itself.")
}
}
@Disabled("Testing UI's this way sucks.")
class AnotherTest : StupidUiTest() {
lateinit var button: Button
lateinit var editor: TextField
lateinit var label: Label
override fun beforeUi() = VBox().apply {
button = button("ClickMe!") {
action {
text = "Clicked!"
}
}
editor = textfield("Start")
label("Label") {
id = "TheLabel"
}
}
@Test
fun `find by id`() {
label = byId("TheLabel")
}
@Test
fun `find by predicate`() {
label = byPredicate { it is Label }
}
@Test
fun `clicking button changes its text`() {
robot.clickOn(button)
assertThat(button.text).isEqualTo("Clicked!")
}
@Test
fun `changing text changes it`() {
robot.clickOn(editor)
robot.type(KeyCode.X, 5)
assertThat(editor.text).isEqualTo("Startxxxxx")
}
}
| 0
|
Kotlin
|
0
| 0
|
55fbadc1e504bf134d542f3cd99b5c4ad5c7ccf9
| 2,591
|
rules
|
MIT License
|
idea/testData/checker/Bounds2.fir.kt
|
justknow23
| 353,953,137
| true
| null |
fun test() {
foo<Int?>()
foo<Int>()
bar<Int?>()
bar<Int>()
bar<Double?>()
bar<Double>()
1.<error descr="[INAPPLICABLE_CANDIDATE] Inapplicable candidate(s): /buzz">buzz</error><Double>()
}
fun <T : Any> foo() {}
fun <T : Int?> bar() {}
fun <T : Int> Int.buzz() : Unit {}
| 0
| null |
0
| 0
|
eefb6e94a90c3e3ca84216f608e592bf1f478272
| 299
|
kotlin
|
Apache License 2.0
|
client/slack-spring-api-client/src/test/kotlin/io/olaph/slack/client/spring/group/chat/DefaultUpdateMethodTest.kt
|
nmchau
| 183,535,942
| true
|
{"Kotlin": 505011}
|
package io.olaph.slack.client.spring.group.chat
import io.olaph.slack.client.spring.MockServerHelper
import io.olaph.slack.client.spring.Verifier
import io.olaph.slack.client.spring.group.RestTemplateFactory
import io.olaph.slack.dto.jackson.group.chat.ErrorChatUpdateResponse
import io.olaph.slack.dto.jackson.group.chat.SlackChatUpdateRequest
import io.olaph.slack.dto.jackson.group.chat.SuccessfulChatUpdateResponse
import io.olaph.slack.dto.jackson.group.chat.sample
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.web.client.RestTemplate
class DefaultUpdateMethodTest {
private lateinit var mockTemplate: RestTemplate
@BeforeEach
fun setup() {
mockTemplate = RestTemplateFactory.slackTemplate()
}
@Test
@DisplayName("chat.update Failure")
fun chatUpdateFailure() {
val response = ErrorChatUpdateResponse.sample()
val mockServer = MockServerHelper.buildMockRestServer(mockTemplate, response, "chat.update")
val verifier = Verifier(response)
DefaultUpdateMethod("", mockTemplate)
.with(SlackChatUpdateRequest.sample())
.onFailure { verifier.set(it) }
.onSuccess { }
.invoke()
mockServer.verify()
verifier.verify()
}
@Test
@DisplayName("chat.update Success")
fun chatUpdateSuccess() {
val response = SuccessfulChatUpdateResponse.sample()
val mockServer = MockServerHelper.buildMockRestServer(mockTemplate, response, "chat.update")
val verifier = Verifier(response)
DefaultUpdateMethod("", mockTemplate)
.with(SlackChatUpdateRequest.sample())
.onSuccess { verifier.set(it) }
.invoke()
mockServer.verify()
verifier.verify()
}
}
| 0
|
Kotlin
|
0
| 0
|
227983e8f31bf9bc9b0056782328679f4a3409f1
| 1,894
|
slack-spring-boot-starter
|
MIT License
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_COPY.kt
|
msrd0
| 363,665,023
| false
| null |
/* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
import de.msrd0.fontawesome.Style.REGULAR
/** Copy */
object FA_COPY: Icon {
override val name get() = "Copy"
override val unicode get() = "f0c5"
override val styles get() = setOf(SOLID, REGULAR)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M384 96L384 0h-112c-26.51 0-48 21.49-48 48v288c0 26.51 21.49 48 48 48H464c26.51 0 48-21.49 48-48V128h-95.1C398.4 128 384 113.6 384 96zM416 0v96h96L416 0zM192 352V128h-144c-26.51 0-48 21.49-48 48v288c0 26.51 21.49 48 48 48h192c26.51 0 48-21.49 48-48L288 416h-32C220.7 416 192 387.3 192 352z"/></svg>"""
REGULAR -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"/></svg>"""
else -> null
}
}
| 0
|
Kotlin
|
0
| 0
|
1358935395f9254cab27852457e2aa6c58902e16
| 2,185
|
fontawesome-kt
|
Apache License 2.0
|
app/src/main/java/com/suihan74/nedge/models/NotchSetting.kt
|
suihan74
| 314,771,954
| false
|
{"Kotlin": 295747}
|
package com.suihan74.nedge.models
import android.graphics.Rect
import com.suihan74.utilities.serialization.RectSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* 通知表示のノッチ部分の描画設定
*/
@Serializable
sealed class NotchSetting(
/** ノッチの種類 */
@SerialName("notch_type")
val type: NotchType
) {
@Serializable(RectSerializer::class)
abstract val rect: Rect
companion object {
/**
* ノッチ種類に対応した設定の実体を生成
*/
fun createInstance(type: NotchType, rect: Rect? = null) = when(type) {
NotchType.NONE -> EmptyNotchSetting()
NotchType.RECTANGLE -> RectangleNotchSetting(rect!!)
NotchType.WATER_DROP -> WaterDropNotchSetting(rect!!)
NotchType.PUNCH_HOLE -> PunchHoleNotchSetting(rect!!)
NotchType.CORNER -> CornerNotchSetting(rect!!)
}
}
}
/**
* ノッチ設定なし
*/
@Serializable
class EmptyNotchSetting : NotchSetting(type = NotchType.NONE) {
@Serializable(RectSerializer::class)
override val rect: Rect = Rect()
}
// ------ //
/**
* 矩形ノッチ用の描画設定
*/
@Serializable
data class RectangleNotchSetting(
@Serializable(RectSerializer::class)
override val rect: Rect,
/** 上部の角丸半径 */
val majorRadius: Float = 0f,
/** 下部の角丸半径 */
val minorRadius: Float = 0f,
/** 上部幅の伸縮調整 */
val majorWidthAdjustment: Float = 0f,
/** 下部幅の伸縮調整 */
val minorWidthAdjustment: Float = .7f,
/** 高さの伸縮調整 */
val heightAdjustment: Float = 0f
) : NotchSetting(NotchType.RECTANGLE)
// ------ //
/**
* 水滴ノッチ用の描画設定
*/
@Serializable
data class WaterDropNotchSetting(
@Serializable(RectSerializer::class)
override val rect: Rect,
/** 上部の角丸半径 */
val majorRadius: Float = 10f,
/** 幅の伸縮調整 */
val widthAdjustment: Float = 0f,
/** 高さの伸縮調整 */
val heightAdjustment: Float = 10f
) : NotchSetting(NotchType.WATER_DROP)
// ------ //
/**
* パンチホールノッチ用の描画設定
*/
@Serializable
data class PunchHoleNotchSetting(
@Serializable(RectSerializer::class)
override val rect: Rect,
/** 中心位置X */
val cx: Float = 0f,
/** 中心位置Y */
val cy: Float = 0f,
/** 半径 */
val radius: Float = 16f,
/** 上下辺 */
val horizontalEdgeSize: Float = 0f,
/** 左右辺 */
val verticalEdgeSize: Float = 0f
) : NotchSetting(NotchType.PUNCH_HOLE)
// ------ //
/**
* 角部ノッチ用の描画設定
*/
@Serializable
data class CornerNotchSetting(
@Serializable(RectSerializer::class)
override val rect: Rect,
/** 横方向の辺からノッチへの角丸 */
val majorRadius: Float = 0f,
/** 画面内側の角丸 */
val middleRadius: Float = 0f,
/** ノッチから縦方向の辺への角丸 */
val minorRadius: Float = 0f,
/** 上部幅の伸縮調整 */
val majorWidthAdjustment: Float = 0f,
/** 下部幅の伸縮調整 */
val minorWidthAdjustment: Float = .7f,
/** 高さの伸縮調整 */
val heightAdjustment: Float = 0f
) : NotchSetting(NotchType.CORNER)
| 2
|
Kotlin
|
0
| 0
|
cb85fa289cdd4cae55f3dd2d1f1c7b1e02a59fcb
| 2,915
|
nEdge
|
MIT License
|
app/src/main/java/com/example/movies/OnListFragmentInteractionListener.kt
|
hopeDeJesusCodes
| 699,382,123
| false
|
{"Kotlin": 8944}
|
package com.example.movies
/**
* This interface is used by the [MovieInfo] to ensure
* it has an appropriate Listener.
*
* In this app, it's implemented by [MoviesFragment]
*/
interface OnListFragmentInteractionListener {
fun onItemClick(item: InTheatersMovie)
}
| 0
|
Kotlin
|
0
| 0
|
d0d498c03b9261e86d990e4f5e047a24c40b11e7
| 275
|
Movies
|
Apache License 2.0
|
app/src/main/java/com/example/moviesapp/viewmodels/MainViewModel.kt
|
vjadhao04
| 620,771,961
| false
|
{"Kotlin": 56524}
|
package com.example.moviesapp.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.example.moviesapp.models.MoviesList
import com.example.moviesapp.repository.MoviesRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainViewModel(private val moviesRepository: MoviesRepository):ViewModel() {
init {
viewModelScope.launch(Dispatchers.IO) {
moviesRepository.getMovie(1)
}
}
val movies=moviesRepository.getMovie().cachedIn(viewModelScope)
}
| 0
|
Kotlin
|
0
| 2
|
4cdf05c493645d418b1bbbb634175250219203ff
| 633
|
Find-your-movies-and-shows
|
MIT License
|
app/src/main/java/com/dreamsoftware/fitflextv/domain/usecase/SignOffUseCase.kt
|
sergio11
| 534,529,261
| false
|
{"Kotlin": 614049}
|
package com.dreamsoftware.fitflextv.domain.usecase
import com.dreamsoftware.fitflextv.domain.repository.IUserRepository
import com.dreamsoftware.fudge.core.FudgeTvUseCase
class SignOffUseCase(
private val userRepository: IUserRepository,
): FudgeTvUseCase<Unit>() {
override suspend fun onExecuted() {
userRepository.signOff()
}
}
| 0
|
Kotlin
|
4
| 40
|
98f42de1194e7cbaa6e5507a7cd5feaa6452849e
| 352
|
fitflextv_android
|
MIT License
|
core/domain/src/test/java/com/jocode/domain/GetSearchItemUseCaseTest.kt
|
jocode
| 675,887,183
| false
| null |
package com.jocode.domain
import com.example.items_search.SearchRepository
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
class GetSearchItemUseCaseTest {
private lateinit var searchRepository: SearchRepository
private lateinit var useCase: GetSearchItemUseCase
@Before
fun setUp() {
searchRepository = mockk()
useCase = GetSearchItemUseCase(searchRepository)
}
@Test
fun `when invoke useCase check the repository call`() = runBlocking {
// Given
val query = "query"
coEvery { searchRepository.getSearchPagingSource(query) } returns mockk()
// When
val result = useCase(query)
// Then
println(result)
coVerify { searchRepository.getSearchPagingSource(query) }
}
@Test
fun `when not invoke useCase check the repository call`() = runBlocking {
// Given
val query = "query"
coEvery { searchRepository.getSearchPagingSource(query) } returns mockk()
// Repository is not called
coVerify(exactly = 0) { searchRepository.getSearchPagingSource(query) }
}
}
| 0
|
Kotlin
|
0
| 0
|
44aceed4b47c8d4576bbf43958db3e137a5aab2a
| 1,233
|
Meli-MobileTest
|
MIT License
|
AndroidApp/app/src/main/java/com/example/weatherapp/client/StationClient.kt
|
SandorBalazsHU
| 550,199,906
| false
|
{"Kotlin": 80979, "PHP": 50845, "C++": 19149, "Vue": 12199, "TypeScript": 7300, "CSS": 2514, "JavaScript": 440, "HTML": 425}
|
package com.example.weatherapp.client
import android.os.SystemClock
import android.util.Log
import com.example.weatherapi.data.api.MeasurementsApi
import com.example.weatherapi.data.api.PicturesApi
import com.example.weatherapi.data.api.StationsApi
import com.example.weatherapi.data.entities.ApiResponseEntity
import com.example.weatherapi.data.entities.MeasurementEntity
import com.example.weatherapp.data.hardware.HardwareEntity
import com.example.weatherapp.data.hardware.HwMeasurementsEntity
import com.example.weatherapp.data.hardware.MeasurementsRepository
import kotlinx.coroutines.*
import okhttp3.MediaType.Companion.get
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.internal.toImmutableList
import org.openapitools.client.infrastructure.ApiClient
import retrofit2.Response
class StationClient(
private val measurementsRepository: MeasurementsRepository = MeasurementsRepository(),
private val apiClient: ApiClient = ApiClient(authNames = arrayOf("apiKeyAuth"))
) {
private val measurementService = apiClient.createService(MeasurementsApi::class.java)
private val picturesService = apiClient.createService(PicturesApi::class.java)
private val statusService = apiClient.createService(StationsApi::class.java)
fun setApiKey(key: String) {
try {
apiClient.setApiKey(key)
} catch (ex: Exception){
Log.e("WeatherStationClient", "Could not set api key", ex)
}
}
/*
* Poll the hardware units, send the result to the api server.
* Returns false if one of the hardware units did not respond correctly.
* */
suspend fun addMeasurements(addresses: Map<String, HardwareEntity>): Pair<Boolean, Int?> = withContext(Dispatchers.IO) {
val results: MutableList<MeasurementEntity> = mutableListOf()
var wasSuccess = true
for ((name, ent) in addresses) {
when(val res = getMeasurement(ent.ipAddress)) {
is ClientResult.Success -> {
if (res.res != null){
results.add(res.res)
}
}
else -> {
wasSuccess = false
Log.e("WeatherStationClient",
"Misc. error for hardware named $name")
}
}
}
if(results.isNotEmpty()){
runClientCatching {
measurementService.addMeasurements(results.toImmutableList())
}.let { wasSuccess to getCode(it) }
} else {
wasSuccess to 200
}
}
suspend fun addPicture(file: java.io.File): Int? = withContext(Dispatchers.IO) {
runClientCatching {
Log.d("WeatherStationClient", "RUN CLIENT")
val bytes = file.readBytes()
val body =
bytes.toRequestBody("application/octet-stream".toMediaTypeOrNull(), 0, bytes.size)
val res = picturesService.addPicture("application/octet-stream", body)
Log.d("WeatherStationClient", "add picture code: ${res.code()}")
res
}.let { getCode(it) }
}
suspend fun addStatus(status: Int): Int? = withContext(Dispatchers.IO) {
runClientCatching {
statusService.updateStationStatus(status)
}.let { getCode(it) }
}
private suspend fun getMeasurement(address: String) : ClientResult<MeasurementEntity?> =
runClientCatching {
val hwEnt = measurementsRepository.measurements(address)
hwEnt?.let { translateMeasurement(it) }
}
private fun translateMeasurement(hwEnt: HwMeasurementsEntity) : MeasurementEntity =
MeasurementEntity(
temperature = hwEnt.temp,
pressure = hwEnt.pressure,
humidity = hwEnt.humidity,
timestamp = SystemClock.elapsedRealtime(),
battery = hwEnt.battery
)
}
sealed class ClientResult<out T> {
data class Success<T>(val res: T): ClientResult<T>()
data class Error(val err: Exception): ClientResult<Nothing>()
}
fun getCode(res: ClientResult<Response<ApiResponseEntity>>): Int? =
when(res) {
is ClientResult.Success ->
res.res.code()
else ->
null
}
suspend inline fun <R> runClientCatching(noinline block: suspend CoroutineScope.() -> R): ClientResult<R> =
try {
val res = withTimeout( 10*1000L, block)
ClientResult.Success(res)
} catch (cancellationException: CancellationException) {
//avoid interference with coroutines
throw cancellationException
} catch (e: Exception){
Log.e("WeatherStationClient", "request error", e)
ClientResult.Error(e)
}
| 3
|
Kotlin
|
0
| 1
|
1fd8cef6bd1a63417fb0c649126ace6588fa6d24
| 4,800
|
elte-ik-msc-weather-cam
|
MIT License
|
core/src/commonMain/kotlin/maryk/core/query/requests/Requests.kt
|
marykdb
| 290,454,412
| false
|
{"Kotlin": 3039332, "JavaScript": 1004}
|
package maryk.core.query.requests
import maryk.core.definitions.Operation.Request
import maryk.core.inject.InjectWithReference
import maryk.core.models.serializers.SingleValueDataModelSerializer
import maryk.core.properties.IsPropertyContext
import maryk.core.models.SingleValueDataModel
import maryk.core.properties.definitions.EmbeddedObjectDefinition
import maryk.core.properties.definitions.InternalMultiTypeDefinition
import maryk.core.properties.definitions.ListDefinition
import maryk.core.properties.definitions.contextual.ContextInjectCollectionOnWriteDefinition
import maryk.core.properties.definitions.list
import maryk.core.properties.definitions.wrapper.IsDefinitionWrapper
import maryk.core.properties.definitions.wrapper.contextual
import maryk.core.properties.types.TypedValue
import maryk.core.protobuf.WriteCacheReader
import maryk.core.protobuf.WriteCacheWriter
import maryk.core.query.RequestContext
import maryk.core.values.IsValueItems
import maryk.core.values.ObjectValues
/** Object to contain multiple [requests] */
data class Requests internal constructor(
val requests: List<IsTransportableRequest<*>>,
internal var injectables: List<InjectWithReference>?
): IsOperation {
override val operationType = Request
constructor(vararg request: IsTransportableRequest<*>) : this(request.toList())
constructor(requests: List<IsTransportableRequest<*>>) : this(requests, null)
/**
* From the context of JSON/YAML this object only contains a single property.
* This is however not true for Protobuf. There this object contains a list of injectables.
*/
companion object : SingleValueDataModel<TypedValue<RequestType, Any>, TypedValue<RequestType, Any>, Requests, Companion, RequestContext>(
singlePropertyDefinitionGetter = {
@Suppress("UNCHECKED_CAST")
Companion.requests as IsDefinitionWrapper<TypedValue<RequestType, Any>, TypedValue<RequestType, Any>, RequestContext, Requests>
}
) {
val requests by list(
index = 1u,
getter = Requests::requests,
valueDefinition = InternalMultiTypeDefinition(
typeEnum = RequestType,
definitionMap = mapOfRequestTypeEmbeddedObjectDefinitions,
keepAsValues = true
),
fromSerializable = { it.value },
toSerializable = {
@Suppress("UNCHECKED_CAST")
when (it) {
is TypedValue<*, *> -> it as TypedValue<RequestType, Any>
is IsTransportableRequest<*> -> TypedValue(it.requestType, it)
else -> throw Exception("Unknown type for MultiType")
}
}
)
internal val injectables by contextual(
index = 2u,
getter = Requests::injectables,
definition = ContextInjectCollectionOnWriteDefinition(
definition = ListDefinition(
valueDefinition = EmbeddedObjectDefinition(
dataModel = { InjectWithReference }
)
),
valueInjector = { context: RequestContext? ->
context?.collectedInjects as List<InjectWithReference>? ?: listOf()
}
)
)
override fun invoke(values: ObjectValues<Requests, Companion>)= Requests(
requests = values(1u),
injectables = values(2u)
)
override val Serializer = object: SingleValueDataModelSerializer<TypedValue<RequestType, Any>, TypedValue<RequestType, Any>, Requests, Companion, RequestContext>(
model = this,
singlePropertyDefinitionGetter = singlePropertyDefinitionGetter
) {
/** Inject injectables if it is found on context */
private fun injectValues(
definition: IsDefinitionWrapper<Any, Any, IsPropertyContext, Requests>,
context: RequestContext?,
value: Any?
) = if (definition == injectables && context != null) {
context.collectedInjects
} else value
override fun protoBufLengthToAddForField(
value: Any?,
definition: IsDefinitionWrapper<Any, Any, IsPropertyContext, Requests>,
cacher: WriteCacheWriter,
context: RequestContext?
): Int {
val valueToPass = injectValues(definition, context, value)
return super.protoBufLengthToAddForField(valueToPass, definition, cacher, context)
}
override fun writeProtoBufField(
value: Any?,
definition: IsDefinitionWrapper<Any, Any, IsPropertyContext, Requests>,
cacheGetter: WriteCacheReader,
writer: (byte: Byte) -> Unit,
context: RequestContext?
) {
val valueToPass = injectValues(definition, context, value)
super.writeProtoBufField(valueToPass, definition, cacheGetter, writer, context)
}
override fun createValues(
context: RequestContext?,
items: IsValueItems
): ObjectValues<Requests, Companion> {
val map = super.createValues(context, items)
@Suppress("UNCHECKED_CAST")
val injectables = map.remove(injectables.index) as? List<InjectWithReference>?
injectables?.forEach {
it.injectInValues(map)
}
return map
}
}
}
}
| 1
|
Kotlin
|
1
| 8
|
530e0b7f41cc16920b69b7c8adf7b5718733ce2f
| 5,667
|
maryk
|
Apache License 2.0
|
app/src/main/java/com/commit451/gitlab/activity/BuildActivity.kt
|
Commit451
| 39,787,724
| false
| null |
package com.commit451.gitlab.activity
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.commit451.addendum.design.snackbar
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.adapter.BuildPagerAdapter
import com.commit451.gitlab.event.BuildChangedEvent
import com.commit451.gitlab.extension.getDownloadBuildUrl
import com.commit451.gitlab.extension.with
import com.commit451.gitlab.model.api.Build
import com.commit451.gitlab.model.api.Project
import com.commit451.gitlab.util.DownloadUtil
import kotlinx.android.synthetic.main.activity_build.*
import kotlinx.android.synthetic.main.progress_fullscreen.*
import timber.log.Timber
/**
* Shows the details of a build
*/
class BuildActivity : BaseActivity() {
companion object {
private const val REQUEST_PERMISSION_WRITE_STORAGE = 1337
private const val KEY_PROJECT = "key_project"
private const val KEY_BUILD = "key_merge_request"
fun newIntent(context: Context, project: Project, build: Build): Intent {
val intent = Intent(context, BuildActivity::class.java)
intent.putExtra(KEY_PROJECT, project)
intent.putExtra(KEY_BUILD, build)
return intent
}
}
private lateinit var menuItemDownload: MenuItem
private lateinit var project: Project
private lateinit var build: Build
private val onMenuItemClickListener = Toolbar.OnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_retry -> {
fullscreenProgress.visibility = View.VISIBLE
App.get().gitLab.retryBuild(project.id, build.id)
.with(this)
.subscribe({
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.build_started)
App.bus().post(BuildChangedEvent(build))
}, {
Timber.e(it)
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.unable_to_retry_build)
})
return@OnMenuItemClickListener true
}
R.id.action_erase -> {
fullscreenProgress.visibility = View.VISIBLE
App.get().gitLab.eraseBuild(project.id, build.id)
.with(this)
.subscribe({
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.build_erased)
App.bus().post(BuildChangedEvent(it))
}, {
Timber.e(it)
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.unable_to_erase_build)
})
return@OnMenuItemClickListener true
}
R.id.action_cancel -> {
fullscreenProgress.visibility = View.VISIBLE
App.get().gitLab.cancelBuild(project.id, build.id)
.with(this)
.subscribe({
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.build_canceled)
App.bus().post(BuildChangedEvent(it))
}, {
Timber.e(it)
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.unable_to_cancel_build)
})
return@OnMenuItemClickListener true
}
R.id.action_download -> {
checkDownloadBuild()
return@OnMenuItemClickListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_build)
project = intent.getParcelableExtra(KEY_PROJECT)!!
build = intent.getParcelableExtra(KEY_BUILD)!!
toolbar.title = String.format(getString(R.string.build_number), build.id)
toolbar.setNavigationIcon(R.drawable.ic_back_24dp)
toolbar.setNavigationOnClickListener { onBackPressed() }
toolbar.subtitle = project.nameWithNamespace
toolbar.inflateMenu(R.menu.retry)
toolbar.inflateMenu(R.menu.erase)
toolbar.inflateMenu(R.menu.cancel)
toolbar.inflateMenu(R.menu.download)
toolbar.setOnMenuItemClickListener(onMenuItemClickListener)
menuItemDownload = toolbar.menu.findItem(R.id.action_download)
menuItemDownload.isVisible = build.artifactsFile != null
setupTabs()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSION_WRITE_STORAGE -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
downloadBuild()
}
}
}
}
private fun setupTabs() {
val sectionsPagerAdapter = BuildPagerAdapter(
this,
supportFragmentManager,
project,
build)
viewPager.adapter = sectionsPagerAdapter
tabLayout.setupWithViewPager(viewPager)
}
@SuppressLint("NewApi")
private fun checkDownloadBuild() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
downloadBuild()
} else {
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PERMISSION_WRITE_STORAGE)
}
}
private fun downloadBuild() {
val account = App.get().getAccount()
val downloadUrl = build.getDownloadBuildUrl(App.get().getAccount().serverUrl!!, project)
Timber.d("Downloading build: $downloadUrl")
val artifactsFileName = build.artifactsFile?.fileName
if (artifactsFileName != null) {
DownloadUtil.download(this, account, downloadUrl, artifactsFileName)
}
}
}
| 6
|
Kotlin
|
27
| 248
|
504b5311c00ac2b87ba728d74925c6f46e6c5781
| 6,583
|
LabCoat
|
Apache License 2.0
|
shared/src/commonMain/kotlin/ru/vitaliy/belyaev/wishapp/shared/domain/LinksAdapter.kt
|
VitaliyBelyaev
| 398,851,175
| false
|
{"Kotlin": 386804, "Swift": 91562, "Ruby": 2345}
|
package ru.vitaliy.belyaev.wishapp.shared.domain
object LinksAdapter {
private const val LINKS_SEPARATOR = "|"
fun addLinkAndGetAccumulatedString(link: String, currentLinks: List<String>): String {
val newList = currentLinks.toMutableList().apply {
add(link)
}
return newList.joinToString(separator = LINKS_SEPARATOR)
}
fun removeLinkAndGetAccumulatedString(link: String, currentLinks: List<String>): String {
val newList = currentLinks.filter { it != link }
return newList.joinToString(separator = LINKS_SEPARATOR)
}
fun getLinksListFromString(linksString: String): List<String> {
return if (linksString.isBlank()) {
emptyList()
} else {
linksString.split(LINKS_SEPARATOR)
}
}
}
| 1
|
Kotlin
|
1
| 23
|
f034eebfd9adaea16f723b3aeb0825b946beea96
| 812
|
WishApp
|
Apache License 2.0
|
app/src/main/java/org/p2p/wallet/feerelayer/model/SwapData.kt
|
p2p-org
| 306,035,988
| false
|
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
|
package org.p2p.wallet.feerelayer.model
import org.p2p.solanaj.core.PublicKey
import java.math.BigInteger
sealed class SwapData {
data class Direct(
val programId: String,
val accountPubkey: String,
val authorityPubkey: String,
val transferAuthorityPubkey: String,
val sourcePubkey: String,
val destinationPubkey: String,
val poolTokenMintPubkey: String,
val poolFeeAccountPubkey: String,
val amountIn: BigInteger,
val minimumAmountOut: BigInteger
) : SwapData()
data class SplTransitive(
val from: Direct,
val to: Direct,
val transitTokenMintPubkey: String,
val transitTokenAccountAddress: PublicKey,
val needsCreateTransitTokenAccount: Boolean
) : SwapData()
}
| 8
|
Kotlin
|
18
| 34
|
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
| 803
|
key-app-android
|
MIT License
|
compiler/testData/diagnostics/tests/typealias/flexibleTypeExpansion.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// FIR_IDENTICAL
// FILE: J.java
public class J {
public static <T> T id(T t) { return null; }
public static String bar() { return null; }
}
// FILE: main.kt
typealias S = String?
fun foo(x1: S, y1: String?) {
val x2 = J.id(x1) ?: return
val y2 = J.id(y1) ?: return
val t = J.bar() ?: return // StackOverflowError happeded when analysing this piece of code
x2.length
y2.length
t.length
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 424
|
kotlin
|
Apache License 2.0
|
buildSrc/src/main/kotlin/dependencies/MyDependencies.kt
|
barakkadev
| 715,421,993
| false
|
{"Kotlin": 50365}
|
package dependencies
/** Created by github.com/im-o on 12/13/2022. */
object MyDependencies {
// DEFAULT DEPENDENCIES
const val core_ktx = "androidx.core:core-ktx:${Versions.core_ktx_version}"
const val lifecycle_ktx = "androidx.lifecycle:lifecycle-runtime-ktx:${Versions.lifecycle_ktx_version}"
const val activity_compose = "androidx.activity:activity-compose:${Versions.activity_compose_version}"
const val compose_bom = "androidx.compose:compose-bom:${Versions.compose_bom_version}"
const val ui_compose = "androidx.compose.ui:ui"
const val ui_graphics = "androidx.compose.ui:ui-graphics"
const val ui_tooling_preview = "androidx.compose.ui:ui-tooling-preview"
const val material3_compose = "androidx.compose.material3:material3"
const val material_icons_extended = "androidx.compose.material:material-icons-extended"
const val material_compose = "androidx.compose.material:material:${Versions.material_compose_version}"
const val constraintlayout_compose = "androidx.constraintlayout:constraintlayout-compose:${Versions.constraintlayout_compose_version}"
const val junit = "junit:junit:${Versions.junit_version}"
const val test_ext_junit = "androidx.test.ext:junit:${Versions.test_ext_junit_version}"
const val navigation_compose = "androidx.navigation:navigation-compose:${Versions.navigation_compose}"
// REMOTE
const val retrofit = "com.squareup.retrofit2:retrofit:${Versions.retrofit_version}"
const val retrofit2_converter_gson = "com.squareup.retrofit2:converter-gson:${Versions.retrofit_version}"
const val retrofit2_adapter_rxjava2 = "com.squareup.retrofit2:adapter-rxjava2:${Versions.retrofit_version}"
const val okhttp3 = "com.squareup.okhttp3:logging-interceptor:${Versions.okHttp3_version}"
// HILT
const val hilt_android = "com.google.dagger:hilt-android:${Versions.hilt_android}"
const val hilt_android_compiler = "com.google.dagger:hilt-android-compiler:${Versions.hilt_android}"
const val hilt_compose = "androidx.hilt:hilt-navigation-compose:${Versions.hilt_compose}"
const val hilt_compose_compiler = "androidx.hilt:hilt-compiler:${Versions.hilt_compose}"
// MAPS
const val maps_compose = "com.google.maps.android:maps-compose:${Versions.maps_compose_version}"
const val maps_compose_utils = "com.google.maps.android:maps-compose-utils:${Versions.maps_compose_version}"
const val maps_compose_widgets = "com.google.maps.android:maps-compose-widgets:${Versions.maps_compose_version}"
const val play_service_maps = "com.google.android.gms:play-services-maps:${Versions.play_service_maps_version}"
}
| 0
|
Kotlin
|
0
| 0
|
f611a4948ad62a9abeedf5c9db1adb8008ec5cca
| 2,645
|
gomap-picker-android-compose
|
MIT License
|
comant-site/src/main/kotlin/com/psenchanka/comant/controller/ClassController.kt
|
kodek16
| 58,888,130
| false
|
{"Kotlin": 40851, "JavaScript": 17887, "HTML": 10517, "CSS": 1697}
|
package com.psenchanka.comant.controller
import com.psenchanka.comant.dto.DetailedClassDto
import com.psenchanka.comant.dto.InstructorClassDto
import com.psenchanka.comant.service.ClassService
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.*
import springfox.documentation.annotations.ApiIgnore
@RestController
@RequestMapping("/api/classes")
open class ClassController @Autowired constructor(val classService: ClassService) {
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No class with given id")
class ClassNotFoundException : RuntimeException()
@RequestMapping("/{id}", method = arrayOf(RequestMethod.GET))
@ApiOperation("Get class data",
notes = "Returns detailed data for for target class." +
" For course instructors also includes additional protected data")
@ApiResponses(
ApiResponse(code = 200, message = "OK"),
ApiResponse(code = 404, message = "No class with given id")
)
@Transactional
open fun getClass(
@ApiIgnore @ModelAttribute("myUsername") myUsername: String?,
@ApiParam("Id of target class") @PathVariable id: String
): DetailedClassDto {
val class_ = try {
classService.findById(id.toInt())
} catch (e: NumberFormatException) {
throw ClassNotFoundException()
}
if (class_ != null) {
return if (class_.course.instructors.any { it.username == myUsername }) {
InstructorClassDto.from(class_)
} else {
DetailedClassDto.from(class_)
}
} else {
throw ClassNotFoundException()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
e16af1a6a466b389e3201e4f366661377578412d
| 2,031
|
comant
|
MIT License
|
bracer/src/main/java/zlc/season/bracer/BundleParams.kt
|
ssseasonnn
| 232,527,137
| false
| null |
package zlc.season.bracer
import android.os.Bundle
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import kotlin.reflect.KType
class BundleParamsDelegate<T>(
private val bundle: Bundle,
private val customKey: String = "",
private val defaultValue: T? = null,
private val type: KType
) : ReadOnlyProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
val key = customKey.ifEmpty { property.name }
return Optional(bundle = bundle).get(key, type, defaultValue)
}
}
class BundleMutableParamsDelegate<T>(
private val bundle: Bundle,
private val customKey: String = "",
private val defaultValue: T? = null,
private val type: KType
) : ReadWriteProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
val key = customKey.ifEmpty { property.name }
return Optional(bundle = bundle).get(key, type, defaultValue)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
val key = customKey.ifEmpty { property.name }
Optional(bundle = bundle).put(key, type, value)
}
}
| 1
|
Kotlin
|
3
| 64
|
4527dfa56b2e9d7479cc58d39ad604f4f3ea262b
| 1,212
|
Bracer
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.