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/pandacorp/noteui/domain/usecase/note/UpdateNoteUseCase.kt
|
MrRuslanYT
| 547,794,682 | false | null |
package com.pandacorp.noteui.domain.usecase.note
import com.pandacorp.noteui.domain.model.NoteItem
import com.pandacorp.noteui.domain.repository.NoteRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class UpdateNoteUseCase(private val repository: NoteRepository) {
suspend operator fun invoke(noteItem: NoteItem) = withContext(Dispatchers.IO) {
repository.update(noteItem)
}
}
| 0 |
Kotlin
|
0
| 0 |
a6f87ce049770420e6a04bfc08cacfa32c8d4b8d
| 431 |
NoteUI
|
Apache License 2.0
|
app/src/main/java/com/erkindilekci/borutobook/presentation/util/EmptyScreen.kt
|
erkindilekci
| 649,616,697 | false | null |
package com.erkindilekci.borutobook.presentation.util
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import com.erkindilekci.borutobook.R
import com.erkindilekci.borutobook.domain.model.Hero
import com.erkindilekci.borutobook.presentation.ui.theme.iconColor
import java.net.ConnectException
import java.net.SocketTimeoutException
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun EmptyScreen(
error: LoadState.Error? = null,
heroes: LazyPagingItems<Hero>? = null
) {
var message by rememberSaveable { mutableStateOf("Find your Favorite Hero!") }
var icon by rememberSaveable { mutableStateOf(R.drawable.search) }
if (error != null) {
message = parseErrorMessage(error)
icon = R.drawable.network_error
}
var startAnimation by rememberSaveable { mutableStateOf(false) }
val alphaAnim by animateFloatAsState(
targetValue = if (startAnimation) 0.7f else 0f,
animationSpec = tween(1000)
)
LaunchedEffect(key1 = true) {
startAnimation = true
}
var isRefreshing by remember { mutableStateOf(false) }
val refreshState = rememberPullRefreshState(
refreshing = isRefreshing,
onRefresh = {
isRefreshing = true
heroes?.refresh()
isRefreshing = false
}
)
Column(
modifier = Modifier
.fillMaxSize()
.pullRefresh(state = refreshState, enabled = error != null),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
PullRefreshIndicator(
state = refreshState,
refreshing = isRefreshing
)
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
modifier = Modifier
.alpha(alphaAnim)
.size(120.dp),
painter = painterResource(id = icon),
contentDescription = stringResource(R.string.error_icon),
tint = MaterialTheme.iconColor
)
Spacer(modifier = Modifier.height(12.dp))
Text(
modifier = Modifier.alpha(alphaAnim),
text = message,
color = MaterialTheme.iconColor,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium,
fontSize = MaterialTheme.typography.subtitle1.fontSize
)
}
}
}
fun parseErrorMessage(error: LoadState.Error): String {
return when (error.error) {
is SocketTimeoutException -> {
"Server Unavailable."
}
is ConnectException -> {
"Internet Unavailable."
}
else -> {
"Unknown Error."
}
}
}
| 0 |
Kotlin
|
0
| 0 |
e1ed8921f65747449cf23fc02aeaddef0706c838
| 4,550 |
BorutoBook
|
Apache License 2.0
|
src/main/java/com/sbg/arena/core/Camera.kt
|
SoulBeaver
| 17,563,154 | false | null |
package com.sbg.arena.core
import com.sbg.arena.configuration.Configuration
import com.sbg.arena.core.geom.Point
import org.newdawn.slick.Graphics
import org.apache.logging.log4j.LogManager
class Camera(val configuration: Configuration) {
private val logger = LogManager.getLogger(javaClass<Camera>())!!
private var cameraCenter = Point(0, 0)
private val viewportWidth: Int
private val viewportHeight: Int
private val worldWidth: Int
private val worldHeight: Int
private val maximumOffset: Dimension
private val minimumOffset: Dimension;
{
viewportWidth = configuration.viewportWidth
viewportHeight = configuration.viewportHeight
worldWidth = configuration.columns * configuration.tileWidth
worldHeight = configuration.rows * configuration.tileHeight
maximumOffset = Dimension(worldWidth - viewportWidth,
worldHeight - viewportHeight)
minimumOffset = Dimension(0, 0)
}
/**
* Update and center the camera on the current point, or against the edges of the screen if not
* enough space remains.
*
* @param centerOn The focus of the camera
*/
fun update(centerOn: Point) {
var cameraX = (centerOn.x * configuration.tileWidth) - viewportWidth / 2
var cameraY = (centerOn.y * configuration.tileHeight) - viewportHeight / 2
if (cameraX > maximumOffset.width)
cameraX = maximumOffset.width
else if (cameraX < minimumOffset.width)
cameraX = minimumOffset.width
if (cameraY > maximumOffset.height)
cameraY = maximumOffset.height
else if (cameraY < minimumOffset.height)
cameraY = minimumOffset.height
cameraCenter = Point(cameraX, cameraY)
}
/**
* Renders the scene at the current camera position.
*
* @param graphics The graphics device to render the screen
* @param use Function block in which the currently rendered scene is to be filled
*/
fun renderGameplay(graphics: Graphics, use: () -> Unit) {
graphics.translate(-cameraCenter.x.toFloat(), -cameraCenter.y.toFloat())
use()
graphics.translate(cameraCenter.x.toFloat(), cameraCenter.y.toFloat())
}
}
| 0 |
Kotlin
|
0
| 0 |
6c9f35ab564ce1f5eab10b01ce932254fa76b068
| 2,296 |
Arena--7DRL-
|
Apache License 2.0
|
HAdManager/src/main/java/com/hashim/hadmanager/adsmodule/fallbackstrategies/FbFallbackStrategy.kt
|
hashimTahir
| 437,785,236 | false | null |
package com.hashim.hadmanager.adsmodule.fallbackstrategies
import com.hashim.hadmanager.adsmodule.types.AdPriorityType
import com.hashim.hadmanager.adsmodule.types.AdsType
object AdMobFallbackStrategy : Strategy {
override fun hBannerStrategy(
hGlobalPriority: AdPriorityType,
hAdsType: AdsType
): AdPriorityType {
return when (hGlobalPriority) {
AdPriorityType.H_AD_MOB -> {
when (hAdsType) {
AdsType.H_FACEBOOK -> AdPriorityType.H_NONE
AdsType.H_MOPUP -> AdPriorityType.H_FACE_BOOK
AdsType.H_ADMOB -> AdPriorityType.H_MOP_UP
}
}
else -> AdPriorityType.H_NONE
}
}
override fun hNativeBannerStrategy(
hGlobalPriority: AdPriorityType,
hAdsType: AdsType
): AdPriorityType {
return when (hGlobalPriority) {
AdPriorityType.H_AD_MOB -> {
when (hAdsType) {
AdsType.H_FACEBOOK -> AdPriorityType.H_NONE
AdsType.H_MOPUP -> AdPriorityType.H_FACE_BOOK
AdsType.H_ADMOB -> AdPriorityType.H_MOP_UP
}
}
else -> AdPriorityType.H_NONE
}
}
override fun hNativeAdvancedtrategy(
hGlobalPriority: AdPriorityType,
hAdsType: AdsType
): AdPriorityType {
return when (hGlobalPriority) {
AdPriorityType.H_AD_MOB -> {
when (hAdsType) {
AdsType.H_FACEBOOK -> AdPriorityType.H_NONE
AdsType.H_MOPUP -> AdPriorityType.H_FACE_BOOK
AdsType.H_ADMOB -> AdPriorityType.H_MOP_UP
}
}
else -> AdPriorityType.H_NONE
}
}
override fun hInterstetialStrategy(
hGlobalPriority: AdPriorityType,
hAdsType: AdsType
): AdPriorityType {
return when (hGlobalPriority) {
AdPriorityType.H_AD_MOB -> {
when (hAdsType) {
AdsType.H_FACEBOOK -> AdPriorityType.H_NONE
AdsType.H_MOPUP -> AdPriorityType.H_FACE_BOOK
AdsType.H_ADMOB -> AdPriorityType.H_MOP_UP
}
}
else -> AdPriorityType.H_NONE
}
}
}
| 0 |
Kotlin
|
0
| 9 |
1775e5335f017bfc0762213d9b6fe1272d704134
| 2,339 |
AndroidAdManager
|
Apache License 2.0
|
android/app/src/main/java/com/algorand/android/ui/common/transactiontips/TransactionTipsViewModel.kt
|
AllanMangeni
| 412,352,101 | true |
{"Kotlin": 1709104}
|
/*
* Copyright 2019 Algorand, 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 com.algorand.android.ui.common.transactiontips
import android.content.SharedPreferences
import androidx.hilt.lifecycle.ViewModelInject
import com.algorand.android.core.BaseViewModel
import com.algorand.android.utils.preference.getFirstTransactionWarningPreference
import com.algorand.android.utils.preference.setFirstTransactionWarningPreference
class TransactionTipsViewModel @ViewModelInject constructor(
private val sharedPref: SharedPreferences
) : BaseViewModel() {
fun getFirstTransactionPreference(): Boolean {
return sharedPref.getFirstTransactionWarningPreference()
}
fun setFirstTransactionPreference() {
sharedPref.setFirstTransactionWarningPreference()
}
}
| 1 |
Kotlin
|
0
| 1 |
d47f08026fa797ea6474622ce5d1990666a241e9
| 1,299 |
algorand-wallet
|
Apache License 2.0
|
api/src/main/kotlin/no/nav/kafkamanager/utils/KafkaPropertiesFactory.kt
|
navikt
| 368,531,873 | false |
{"Kotlin": 27153, "TypeScript": 24396, "JavaScript": 8133, "CSS": 2206, "HTML": 551, "Dockerfile": 178}
|
package no.nav.kafkamanager.utils
import io.confluent.kafka.serializers.KafkaAvroDeserializer
import io.confluent.kafka.serializers.KafkaAvroSerializerConfig
import no.nav.common.kafka.util.KafkaEnvironmentVariables.*
import no.nav.common.kafka.util.KafkaPropertiesBuilder
import no.nav.common.utils.Credentials
import no.nav.common.utils.EnvironmentUtils.getRequiredProperty
import no.nav.kafkamanager.controller.KafkaAdminController
import no.nav.kafkamanager.domain.DeserializerType
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.apache.kafka.clients.consumer.ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG
import org.apache.kafka.clients.consumer.ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG
import org.apache.kafka.common.serialization.*
import java.util.*
object KafkaPropertiesFactory {
fun createOnPremConsumerProperties(
kafkaBrokerUrl: String,
credentials: Credentials,
schemaRegistryUrl: String?,
keyDeserializerType: DeserializerType,
valueDeserializerType: DeserializerType
): Properties {
val builder = KafkaPropertiesBuilder.consumerBuilder()
.withBaseProperties()
.withProp(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, KafkaAdminController.MAX_KAFKA_RECORDS)
.withBrokerUrl(kafkaBrokerUrl)
.withOnPremAuth(credentials.username, credentials.password)
.withProp(KEY_DESERIALIZER_CLASS_CONFIG, findDeserializer(keyDeserializerType).name)
.withProp(VALUE_DESERIALIZER_CLASS_CONFIG, findDeserializer(valueDeserializerType).name)
if (schemaRegistryUrl != null) {
if (schemaRegistryUrl.isNotBlank()) {
builder.withProp(KafkaAvroSerializerConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl)
}
}
return builder.build()
}
fun createAivenConsumerProperties(
keyDeserializerType: DeserializerType,
valueDeserializerType: DeserializerType
): Properties {
val schemaRegistryUrl = getRequiredProperty(KAFKA_SCHEMA_REGISTRY)
val schemaRegistryUsername = getRequiredProperty(KAFKA_SCHEMA_REGISTRY_USER)
val schemaRegistryPassword = getRequiredProperty(KAFKA_SCHEMA_REGISTRY_PASSWORD)
return KafkaPropertiesBuilder.consumerBuilder()
.withBaseProperties()
.withProp(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, KafkaAdminController.MAX_KAFKA_RECORDS)
.withAivenBrokerUrl()
.withAivenAuth()
.withProp(KEY_DESERIALIZER_CLASS_CONFIG, findDeserializer(keyDeserializerType).name)
.withProp(VALUE_DESERIALIZER_CLASS_CONFIG, findDeserializer(valueDeserializerType).name)
.withProp(KafkaAvroSerializerConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl)
.withProp(KafkaAvroSerializerConfig.BASIC_AUTH_CREDENTIALS_SOURCE, "USER_INFO")
.withProp(KafkaAvroSerializerConfig.USER_INFO_CONFIG, "$schemaRegistryUsername:$schemaRegistryPassword")
.build()
}
private fun findDeserializer(deserializerType: DeserializerType): Class<*> {
return when (deserializerType) {
DeserializerType.STRING -> StringDeserializer::class.java
DeserializerType.DOUBLE -> DoubleDeserializer::class.java
DeserializerType.FLOAT -> FloatDeserializer::class.java
DeserializerType.INTEGER -> IntegerDeserializer::class.java
DeserializerType.LONG -> LongDeserializer::class.java
DeserializerType.SHORT -> ShortDeserializer::class.java
DeserializerType.UUID -> UUIDDeserializer::class.java
DeserializerType.AVRO -> KafkaAvroDeserializer::class.java
}
}
}
| 2 |
Kotlin
|
1
| 3 |
fa8b15d8d8681811426498104a93f243ef0ee223
| 3,727 |
kafka-manager
|
MIT License
|
app/src/main/java/com/cs6018/canvasexample/DrawingApplication.kt
|
YuanRuQian
| 682,634,145 | false |
{"Kotlin": 105914}
|
package com.cs6018.canvasexample
import android.app.Application
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
class DrawingApplication : Application() {
private val scope = CoroutineScope(SupervisorJob())
private val db by lazy { DrawingInfoDatabase.getDatabase(applicationContext) }
val drawingInfoRepository by lazy { DrawingInfoRepository(scope, db.drawingInfoDao()) }
}
| 1 |
Kotlin
|
0
| 0 |
1256df2b5f31e0de7f4c4ff68c278632d1259931
| 423 |
CS6018-Group-Project
|
MIT License
|
app/src/main/java/com/lmqr/ha9_comp_service/A9AccessibilityService.kt
|
damianmqr
| 770,035,080 | false | null |
package com.lmqr.ha9_comp_service
import android.accessibilityservice.AccessibilityService
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.database.ContentObserver
import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.Point
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.widget.Button
import androidx.preference.PreferenceManager
import com.lmqr.ha9_comp_service.command_runners.CommandRunner
import com.lmqr.ha9_comp_service.command_runners.RootCommandRunner
import com.lmqr.ha9_comp_service.databinding.FloatingMenuLayoutBinding
import kotlin.math.max
import kotlin.math.min
class A9AccessibilityService : AccessibilityService(), SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var commandRunner: CommandRunner
private lateinit var temperatureModeManager: TemperatureModeManager
private lateinit var refreshModeManager: RefreshModeManager
private lateinit var sharedPreferences: SharedPreferences
private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when(intent.action){
Intent.ACTION_SCREEN_OFF -> {
temperatureModeManager.onScreenChange(false)
menuBinding.close()
}
Intent.ACTION_SCREEN_ON -> {
temperatureModeManager.onScreenChange(true)
}
Intent.ACTION_USER_PRESENT -> {
commandRunner.runCommands(arrayOf("setup"))
}
}
}
}
private val handler = Handler(Looper.getMainLooper())
fun getBrightnessFromSetting() = min(
max(
Settings.System.getInt(
contentResolver, Settings.System.SCREEN_BRIGHTNESS, 0
) - 1, 0
), 255
) / 255f
override fun onCreate() {
super.onCreate()
commandRunner = RootCommandRunner()// FIFOCommandRunner(filesDir.absolutePath)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
refreshModeManager = RefreshModeManager(
sharedPreferences,
commandRunner
)
temperatureModeManager = TemperatureModeManager(
if (sharedPreferences.getBoolean("night_mode", false))
TemperatureMode.Night
else
TemperatureMode.White,
getBrightnessFromSetting(),
commandRunner,
)
val filter = IntentFilter()
filter.addAction(Intent.ACTION_SCREEN_ON)
filter.addAction(Intent.ACTION_SCREEN_OFF)
filter.addAction(Intent.ACTION_USER_PRESENT)
registerReceiver(receiver, filter)
contentObserver = object : ContentObserver(handler) {
override fun onChange(selfChange: Boolean) {
temperatureModeManager.brightness = getBrightnessFromSetting()
}
}
contentResolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS),
true, contentObserver as ContentObserver
)
}
override fun onInterrupt() {
}
private var lastClickTime: Long = 0
private val singlePressRunnable = Runnable {
if(sharedPreferences.getBoolean("swap_clear_button", false))
openFloatingMenu()
else
commandRunner.runCommands(arrayOf("r"))
}
override fun onKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN) {
when (event.scanCode) {
766 -> {
if (!Settings.canDrawOverlays(baseContext))
requestOverlayPermission()
else {
val clickTime: Long = System.currentTimeMillis()
if (clickTime - lastClickTime < 350) {
handler.removeCallbacks(singlePressRunnable)
if(sharedPreferences.getBoolean("swap_clear_button", false))
commandRunner.runCommands(arrayOf("r"))
else
openFloatingMenu()
}else{
handler.postDelayed(singlePressRunnable, 350)
}
lastClickTime = clickTime
}
return true
}
}
}
return super.onKeyEvent(event)
}
private fun requestOverlayPermission() {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:$packageName")
)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Log.e("OverlayPermission", "Activity not found exception", e)
}
}
private fun getAppUsableScreenSize(context: Context): Point {
val windowManager = context.getSystemService(WINDOW_SERVICE) as WindowManager
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size)
return size
}
private fun getRealScreenSize(context: Context): Point {
val windowManager = context.getSystemService(WINDOW_SERVICE) as WindowManager
val display = windowManager.defaultDisplay
val size = Point()
display.getRealSize(size)
return size
}
private fun getNavBarHeight(): Int {
val appUsableSize: Point = getAppUsableScreenSize(this)
val realScreenSize: Point = getRealScreenSize(this)
if (appUsableSize.y < realScreenSize.y)
return (realScreenSize.y - appUsableSize.y)
return 0
}
private var menuBinding: FloatingMenuLayoutBinding? = null
@SuppressLint("ClickableViewAccessibility", "InflateParams")
private fun openFloatingMenu() {
try {
menuBinding?.run{
if (root.visibility == View.VISIBLE) {
root.visibility = View.GONE
}else{
root.visibility = View.VISIBLE
nightSwitch.visibility =
if(sharedPreferences.getBoolean("disable_nightmode", false))
View.GONE
else View.VISIBLE
updateButtons(refreshModeManager.currentMode)
}
}?:run{
val wm = getSystemService(WINDOW_SERVICE) as WindowManager
val inflater = LayoutInflater.from(this)
val view = inflater.inflate(R.layout.floating_menu_layout, null, false)
val layoutParams = WindowManager.LayoutParams().apply {
type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
format = PixelFormat.TRANSLUCENT
flags = flags or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
width = WindowManager.LayoutParams.MATCH_PARENT
height = WindowManager.LayoutParams.WRAP_CONTENT
gravity = Gravity.BOTTOM
y = getNavBarHeight()
}
menuBinding = FloatingMenuLayoutBinding.bind(view).apply {
root.setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_OUTSIDE)
close()
false
}
button1.setOnClickListener {
refreshModeManager.changeMode(RefreshMode.CLEAR)
updateButtons(refreshModeManager.currentMode)
}
button2.setOnClickListener {
refreshModeManager.changeMode(RefreshMode.BALANCED)
updateButtons(refreshModeManager.currentMode)
}
button3.setOnClickListener {
refreshModeManager.changeMode(RefreshMode.SMOOTH)
updateButtons(refreshModeManager.currentMode)
}
button4.setOnClickListener {
refreshModeManager.changeMode(RefreshMode.SPEED)
updateButtons(refreshModeManager.currentMode)
}
settingsIcon.setOnClickListener {
val settingsIntent = Intent(
this@A9AccessibilityService,
SettingsActivity::class.java
)
settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
close()
startActivity(settingsIntent)
}
nightSwitch.setOnCheckedChangeListener { _, checked ->
val currentMode = sharedPreferences.getBoolean("night_mode", false)
if(currentMode != checked) {
sharedPreferences.edit().putBoolean("night_mode", checked).apply()
}
}
nightSwitch.isChecked = sharedPreferences.getBoolean("night_mode", false)
nightSwitch.visibility =
if(sharedPreferences.getBoolean("disable_nightmode", false))
View.GONE
else View.VISIBLE
updateButtons(refreshModeManager.currentMode)
wm.addView(root, layoutParams)
}
}
}catch (ex: Exception){
ex.printStackTrace()
}
}
override fun onDestroy() {
contentObserver?.let { contentResolver.unregisterContentObserver(it) }
commandRunner.onDestroy()
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
unregisterReceiver(receiver)
super.onDestroy()
}
private var contentObserver: ContentObserver? = null
override fun onServiceConnected() {
}
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
event.letPackageNameClassName{ pkgName, clsName ->
val componentName = ComponentName(
pkgName,
clsName
)
try {
packageManager.getActivityInfo(componentName, 0)
refreshModeManager.onAppChange(pkgName)
menuBinding.updateButtons(refreshModeManager.currentMode)
} catch (_: PackageManager.NameNotFoundException) {}
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
when(key){
"disable_nightmode" -> {
temperatureModeManager.isDisabled =
(sharedPreferences?.getBoolean("disable_nightmode", false) == true)
if (!temperatureModeManager.isDisabled) {
if (sharedPreferences?.getBoolean("night_mode", false) == true)
temperatureModeManager.setMode(TemperatureMode.Night)
else
temperatureModeManager.setMode(TemperatureMode.White)
}
}
"night_mode" -> {
if(sharedPreferences?.getBoolean("night_mode", false) == true){
menuBinding?.nightSwitch?.isChecked = true
temperatureModeManager.setMode(TemperatureMode.Night)
}else{
menuBinding?.nightSwitch?.isChecked = false
temperatureModeManager.setMode(TemperatureMode.White)
}
}
}
}
}
fun AccessibilityEvent?.letPackageNameClassName(block: (String, String)->Unit) {
this?.run {
if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED)
this.className?.let { clsName ->
this.packageName?.let { pkgName -> block(pkgName.toString(), clsName.toString()) }
}
}
}
fun FloatingMenuLayoutBinding?.close() = this?.run{
root.visibility = View.GONE
}
fun FloatingMenuLayoutBinding?.updateButtons(mode: RefreshMode) = this?.run{
listOf(button1, button2, button3, button4).forEach(Button::deselect)
when (mode) {
RefreshMode.CLEAR -> button1
RefreshMode.BALANCED -> button2
RefreshMode.SMOOTH -> button3
RefreshMode.SPEED -> button4
else -> null
}?.select()
}
fun Button.deselect(){
setBackgroundResource(R.drawable.drawable_border_normal)
setTextColor(Color.BLACK)
}
fun Button.select(){
setBackgroundResource(R.drawable.drawable_border_pressed)
setTextColor(Color.WHITE)
}
| 0 | null |
0
| 3 |
039e6e37dfde93253a2d864c0f8bece0590f5a32
| 13,655 |
a9_accessibility_service
|
MIT License
|
wavesplatform/src/main/java/com/wavesplatform/sdk/model/response/node/transaction/MassTransferTransactionResponse.kt
|
wavesplatform
| 176,732,507 | false | null |
package com.wavesplatform.sdk.model.response.node.transaction
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import com.wavesplatform.sdk.model.request.node.BaseTransaction
import com.wavesplatform.sdk.model.request.node.MassTransferTransaction.Transfer
import kotlinx.android.parcel.Parcelize
/**
* See [com.wavesplatform.sdk.model.request.node.MassTransferTransaction]
*/
@Parcelize
class MassTransferTransactionResponse(
@SerializedName("assetId")
var assetId: String?,
@SerializedName("attachment")
var attachment: String,
@SerializedName("transferCount")
var transferCount: Int,
@SerializedName("totalAmount")
var totalAmount: Long,
@SerializedName("transfers")
var transfers: Array<Transfer>
) :
BaseTransactionResponse(type = BaseTransaction.MASS_TRANSFER), Parcelable
| 3 |
Kotlin
|
8
| 16 |
07df259e47dfba2b99ad06f012a97062e7036356
| 856 |
WavesSDK-android
|
MIT License
|
kotlin-native/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmStaticCFuntion.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
/*
// TODO: generate automatically during build.
// The code below is generated with
fun main() {
println("""
package kotlinx.cinterop
@OptIn(ExperimentalStdlibApi::class)
@PublishedApi
internal inline fun <reified T> t() = kotlin.reflect.typeOf<T>()
""".trimIndent())
repeat(23) { count ->
val typeParameterNames = (1 .. count).map { "P$it" }
val typeParameters = (typeParameterNames + "R").joinToString { "reified $it" }
val functionType = buildString {
append('(')
typeParameterNames.joinTo(this)
append(") -> R")
}
println("""
inline fun <$typeParameters> staticCFunction(noinline function: $functionType): CPointer<CFunction<$functionType>> =
staticCFunctionImpl(
function,
${(listOf("R") + typeParameterNames).joinToString { "t<$it>()" }}
)
""".trimIndent())
}
}
*/
package kotlinx.cinterop
@OptIn(ExperimentalStdlibApi::class)
@PublishedApi
internal inline fun <reified T> t() = kotlin.reflect.typeOf<T>()
inline fun <reified R> staticCFunction(noinline function: () -> R): CPointer<CFunction<() -> R>> =
staticCFunctionImpl(
function,
t<R>()
)
inline fun <reified P1, reified R> staticCFunction(noinline function: (P1) -> R): CPointer<CFunction<(P1) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>()
)
inline fun <reified P1, reified P2, reified R> staticCFunction(noinline function: (P1, P2) -> R): CPointer<CFunction<(P1, P2) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>()
)
inline fun <reified P1, reified P2, reified P3, reified R> staticCFunction(noinline function: (P1, P2, P3) -> R): CPointer<CFunction<(P1, P2, P3) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified R> staticCFunction(noinline function: (P1, P2, P3, P4) -> R): CPointer<CFunction<(P1, P2, P3, P4) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified P15, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>(), t<P15>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified P15, reified P16, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>(), t<P15>(), t<P16>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified P15, reified P16, reified P17, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>(), t<P15>(), t<P16>(), t<P17>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified P15, reified P16, reified P17, reified P18, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>(), t<P15>(), t<P16>(), t<P17>(), t<P18>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified P15, reified P16, reified P17, reified P18, reified P19, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>(), t<P15>(), t<P16>(), t<P17>(), t<P18>(), t<P19>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified P15, reified P16, reified P17, reified P18, reified P19, reified P20, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>(), t<P15>(), t<P16>(), t<P17>(), t<P18>(), t<P19>(), t<P20>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified P15, reified P16, reified P17, reified P18, reified P19, reified P20, reified P21, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>(), t<P15>(), t<P16>(), t<P17>(), t<P18>(), t<P19>(), t<P20>(), t<P21>()
)
inline fun <reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7, reified P8, reified P9, reified P10, reified P11, reified P12, reified P13, reified P14, reified P15, reified P16, reified P17, reified P18, reified P19, reified P20, reified P21, reified P22, reified R> staticCFunction(noinline function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R>> =
staticCFunctionImpl(
function,
t<R>(), t<P1>(), t<P2>(), t<P3>(), t<P4>(), t<P5>(), t<P6>(), t<P7>(), t<P8>(), t<P9>(), t<P10>(), t<P11>(), t<P12>(), t<P13>(), t<P14>(), t<P15>(), t<P16>(), t<P17>(), t<P18>(), t<P19>(), t<P20>(), t<P21>(), t<P22>()
)
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 13,308 |
kotlin
|
Apache License 2.0
|
boquila-testing/src/main/java/com/levibostian/boquilatesting/MockRemoteConfigAdapter.kt
|
levibostian
| 275,052,178 | false |
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "YAML": 1, "Markdown": 5, "INI": 4, "Proguard": 5, "Kotlin": 19, "XML": 15, "Java": 1}
|
package com.levibostian.boquilatesting
import com.levibostian.boquila.BaseRemoteConfigAdapter
import com.levibostian.boquila.RemoteConfigAdapter
import com.levibostian.boquila.plugins.RemoteConfigAdapterPlugin
open class MockRemoteConfigAdapter(plugins: List<RemoteConfigAdapterPlugin> = listOf()): BaseRemoteConfigAdapter(plugins) {
/**
Stores the values you want to override in the mock.
*/
open var valueOverrides: Map<String, String> = mapOf()
/**
Attempts to transform the value you pass into something else usable
*/
open fun setValue(id: String, value: String) {
val oldValueOverrides = this.valueOverrides.toMutableMap()
oldValueOverrides[id] = value
this.valueOverrides = oldValueOverrides
}
open fun <T: Any> setValue(id: String, value: T) {
var transformedValue: String? = null
this.plugins.forEach { plugin ->
if (transformedValue == null) {
transformedValue = plugin.transformToStringValue(value)
}
}
val stringValue = transformedValue ?: throw CannotTransformStringValueError("No plugins you provided were able to set the value. Provide different plugins.")
this.setValue(id, stringValue)
}
open override fun getStringValue(id: String): String? = valueOverrides[id]
/**
* By default, does not do anything. Override this method in your own subclass to do something.
*/
open override fun activate() {
}
/**
* By default, does not do anything. Override this method in your own subclass to do something.
*/
open override fun refresh(onComplete: (Result<Unit>) -> Unit) {
onComplete(Result.success(Unit))
}
class CannotTransformStringValueError(message: String): Throwable(message)
}
| 1 | null |
1
| 1 |
de936b47cb8eb08e73078b593116d7193e76d48a
| 1,817 |
Boquila-Android
|
MIT License
|
mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt
|
square
| 5,152,285 | false | null |
/*
* Copyright (C) 2011 Google 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 mockwebserver3
import java.io.IOException
import java.net.Inet6Address
import java.net.Socket
import javax.net.ssl.SSLSocket
import okhttp3.ExperimentalOkHttpApi
import okhttp3.Handshake
import okhttp3.Handshake.Companion.handshake
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.internal.platform.Platform
import okio.Buffer
/** An HTTP request that came into the mock web server. */
@ExperimentalOkHttpApi
class RecordedRequest(
val requestLine: String,
/** All headers. */
val headers: Headers,
/**
* The sizes of the chunks of this request's body, or an empty list if the request's body
* was empty or unchunked.
*/
val chunkSizes: List<Int>,
/** The total size of the body of this POST request (before truncation).*/
val bodySize: Long,
/** The body of this POST request. This may be truncated. */
val body: Buffer,
/**
* The index of this request on its HTTP connection. Since a single HTTP connection may serve
* multiple requests, each request is assigned its own sequence number.
*/
val sequenceNumber: Int,
socket: Socket,
/**
* The failure MockWebServer recorded when attempting to decode this request. If, for example,
* the inbound request was truncated, this exception will be non-null.
*/
val failure: IOException? = null,
) {
val method: String?
val path: String?
/**
* The TLS handshake of the connection that carried this request, or null if the request was
* received without TLS.
*/
val handshake: Handshake?
val requestUrl: HttpUrl?
/**
* Returns the name of the server the client requested via the SNI (Server Name Indication)
* attribute in the TLS handshake. Unlike the rest of the HTTP exchange, this name is sent in
* cleartext and may be monitored or blocked by a proxy or other middlebox.
*/
val handshakeServerNames: List<String>
init {
if (socket is SSLSocket) {
try {
this.handshake = socket.session.handshake()
this.handshakeServerNames = Platform.get().getHandshakeServerNames(socket)
} catch (e: IOException) {
throw IllegalArgumentException(e)
}
} else {
this.handshake = null
this.handshakeServerNames = listOf()
}
if (requestLine.isNotEmpty()) {
val methodEnd = requestLine.indexOf(' ')
val pathEnd = requestLine.indexOf(' ', methodEnd + 1)
this.method = requestLine.substring(0, methodEnd)
var path = requestLine.substring(methodEnd + 1, pathEnd)
if (!path.startsWith("/")) {
path = "/"
}
this.path = path
val scheme = if (socket is SSLSocket) "https" else "http"
val localPort = socket.localPort
val hostAndPort =
headers[":authority"]
?: headers["Host"]
?: when (val inetAddress = socket.localAddress) {
is Inet6Address -> "[${inetAddress.hostAddress}]:$localPort"
else -> "${inetAddress.hostAddress}:$localPort"
}
// Allow null in failure case to allow for testing bad requests
this.requestUrl = "$scheme://$hostAndPort$path".toHttpUrlOrNull()
} else {
this.requestUrl = null
this.method = null
this.path = null
}
}
override fun toString(): String = requestLine
}
| 2 | null |
9282
| 45,832 |
dbedfd000c8e84bc914c619714b8c9bf7f3e06d4
| 3,919 |
okhttp
|
Apache License 2.0
|
data_component/src/main/java/com/xyoye/data_component/data/MagnetSubgroupData.kt
|
xyoye
| 138,993,190 | false |
{"Kotlin": 1580261, "Java": 495885, "Shell": 17996}
|
package com.xyoye.data_component.data
import com.squareup.moshi.JsonClass
/**
* Created by xyoye on 2020/10/26.
*/
@JsonClass(generateAdapter = true)
data class MagnetSubgroupData(
val Subgroups: MutableList<MagnetScreenData> = mutableListOf()
)
| 28 |
Kotlin
|
93
| 946 |
b60bd028ce160ff37aba3eaf70fd0b2cbfa5eab0
| 254 |
DanDanPlayForAndroid
|
Apache License 2.0
|
app/src/main/java/com/github/amazingweather/presentation/component/viewholder/MainViewHolder.kt
|
Edydaoud
| 264,558,030 | false | null |
package com.github.amazingweather.presentation.component.viewholder
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.view.View
import com.github.amazingweather.R
import com.github.amazingweather.data.Keys
import com.github.amazingweather.data.Keys.getImageUrl
import com.github.amazingweather.data.Keys.getWindSpeedUnit
import com.github.amazingweather.presentation.base.BaseViewHolder
import com.github.amazingweather.presentation.component.view.CityWeatherUiView
import com.github.amazingweather.presentation.component.view.CityWeatherUiView.Companion.CONDITION_CHANGED
import com.github.amazingweather.presentation.component.view.CityWeatherUiView.Companion.HUMIDITY_CHANGED
import com.github.amazingweather.presentation.component.view.CityWeatherUiView.Companion.ICON_CHANGED
import com.github.amazingweather.presentation.component.view.CityWeatherUiView.Companion.NAME_CHANGED
import com.github.amazingweather.presentation.component.view.CityWeatherUiView.Companion.TEMP_CHANGED
import com.github.amazingweather.presentation.component.view.CityWeatherUiView.Companion.TEMP_MAX_CHANGED
import com.github.amazingweather.presentation.component.view.CityWeatherUiView.Companion.TEMP_MIN_CHANGED
import com.github.amazingweather.presentation.component.view.CityWeatherUiView.Companion.WIND_SPEED_CHANGED
import kotlinx.android.synthetic.main.city_weather_item_layout.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.URL
class MainViewHolder(itemView: View) : BaseViewHolder<CityWeatherUiView>(itemView) {
override fun bindView(position: Int, item: CityWeatherUiView) {
bindCityName(item.name)
bindWeatherTempAndCondition(item.temp, item.condition)
bindTempLowHigh(item.tempMin, item.tempMax)
bindIcon(item)
bindWind(item.windSpeed)
bindHumidity(item.humidity)
}
private fun bindHumidity(humidity: Int) {
itemView.humidityTextView.text =
itemView.resources.getString(R.string.humidity).format(humidity)
}
private fun bindWind(windSpeed: Int) {
itemView.windTextView.text =
itemView.resources.getString(getWindSpeedUnit()).format(windSpeed)
}
private fun bindIcon(item: CityWeatherUiView) {
item.doAction {
val url = URL(getImageUrl(item.icon))
val bmp: Bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream())
withContext(Dispatchers.Main) {
itemView.cityWeatherIconIV.post { itemView.cityWeatherIconIV.setImageBitmap(bmp) }
}
}
}
private fun bindTempLowHigh(tempMin: Int, tempMax: Int) {
itemView.cityTempHighLowTextView.text =
itemView.resources.getString(R.string.min_max).format(tempMax, tempMin)
}
private fun bindWeatherTempAndCondition(temp: Int, condition: String) {
itemView.cityTempAndCondTextView.text =
itemView.resources.getString(R.string.weather_condition).format(
itemView.resources.getString(
Keys.getTempUnit()
).format(temp), condition
)
}
private fun bindCityName(name: String) {
itemView.cityNameTV.text = name
}
override fun bindViewPayloads(position: Int, item: CityWeatherUiView, diffSet: Set<String>) {
diffSet.forEach {
when (it) {
ICON_CHANGED -> bindIcon(item)
CONDITION_CHANGED, TEMP_CHANGED -> bindWeatherTempAndCondition(
item.temp,
item.condition
)
NAME_CHANGED -> bindCityName(item.name)
HUMIDITY_CHANGED -> bindHumidity(item.humidity)
TEMP_MAX_CHANGED, TEMP_MIN_CHANGED -> bindTempLowHigh(item.tempMin, item.tempMax)
WIND_SPEED_CHANGED -> bindWind(item.windSpeed)
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
5f974711242a596d8cf46ff4f16a4104f4e341ba
| 3,956 |
AmazingWeather
|
Apache License 2.0
|
tmp/arrays/youTrackTests/7383.kt
|
DaniilStepanov
| 228,623,440 | false | null |
// Original bug: KT-27514
sealed class Either<A, B> {
class Left<A, B>(val value: A) : Either<A, B>()
class Right<A, B>(val value: B) : Either<A, B>()
}
fun f(): Either<String, Boolean> =
Either.Left("abc")
fun g(e: Either<String, Boolean>): Int = when (e) {
is Either.Left -> e.value.length
is Either.Right -> if (e.value) 1 else 0
}
fun main(args: Array<String>) {
println(g(f()))
}
| 1 | null |
11
| 1 |
602285ec60b01eee473dcb0b08ce497b1c254983
| 413 |
bbfgradle
|
Apache License 2.0
|
src/main/java/kotlinx/reflect/lite/descriptors/impl/ClassBasedDeclarationContainerDescriptorImpl.kt
|
Kotlin
| 41,860,868 | false |
{"Kotlin": 516851, "Java": 75}
|
/*
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
// Most logic copied from: https://github.com/JetBrains/kotlin/blob/master/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt
package kotlinx.reflect.lite.descriptors.impl
import kotlinx.reflect.lite.builtins.*
import kotlinx.reflect.lite.descriptors.*
import kotlinx.reflect.lite.impl.*
import kotlinx.reflect.lite.impl.KotlinReflectionInternalError
import kotlinx.reflect.lite.misc.*
import java.lang.reflect.*
internal abstract class ClassBasedDeclarationContainerDescriptorImpl(
override val jClass: Class<*>
) : ClassBasedDeclarationContainerDescriptor {
protected open val methodOwner: Class<*> by lazy {
jClass.wrapperByPrimitive ?: jClass
}
override val module by lazy {
ModuleDescriptorImpl(jClass.safeClassLoader)
}
abstract val memberScope: MemberScope
abstract val staticScope: MemberScope
private val declaredNonStaticMembers: Collection<KCallableImpl<*>> by lazy {
getMembers(memberScope, MemberBelonginess.DECLARED)
}
private val declaredStaticMembers: Collection<KCallableImpl<*>> by lazy {
getMembers(staticScope, MemberBelonginess.DECLARED)
}
private val inheritedNonStaticMembers: Collection<KCallableImpl<*>> by lazy {
getMembers(memberScope, MemberBelonginess.INHERITED)
}
private val inheritedStaticMembers: Collection<KCallableImpl<*>> by lazy {
getMembers(staticScope, MemberBelonginess.INHERITED)
}
private val allNonStaticMembers: Collection<KCallableImpl<*>> by lazy {
declaredNonStaticMembers + inheritedNonStaticMembers
}
private val allStaticMembers: Collection<KCallableImpl<*>> by lazy {
declaredStaticMembers + inheritedStaticMembers
}
override val declaredMembers: Collection<KCallableImpl<*>> by lazy {
declaredNonStaticMembers + declaredStaticMembers
}
override val allMembers: Collection<KCallableImpl<*>> by lazy {
allNonStaticMembers + allStaticMembers
}
private fun getMembers(scope: MemberScope, belonginess: MemberBelonginess): Collection<KCallableImpl<*>> =
(scope.functions + scope.properties).mapNotNull { descriptor ->
if (belonginess.accept(descriptor)) createKCallable(descriptor) else null
}.toList()
protected enum class MemberBelonginess {
DECLARED,
INHERITED;
fun accept(member: CallableDescriptor): Boolean =
member.isReal == (this == DECLARED)
}
private fun Class<*>.lookupMethod(
name: String, parameterTypes: Array<Class<*>>, returnType: Class<*>, isStaticDefault: Boolean
): Method? {
// Static "$default" method in any class takes an instance of that class as the first parameter.
if (isStaticDefault) {
parameterTypes[0] = this
}
tryGetMethod(name, parameterTypes, returnType)?.let { return it }
superclass?.lookupMethod(name, parameterTypes, returnType, isStaticDefault)?.let { return it }
// TODO: avoid exponential complexity here
for (superInterface in interfaces) {
superInterface.lookupMethod(name, parameterTypes, returnType, isStaticDefault)?.let { return it }
// Static "$default" methods should be looked up in each DefaultImpls class, see KT-33430
if (isStaticDefault) {
val defaultImpls = superInterface.safeClassLoader.tryLoadClass(superInterface.name + JvmAbi.DEFAULT_IMPLS_SUFFIX)
if (defaultImpls != null) {
parameterTypes[0] = superInterface
defaultImpls.tryGetMethod(name, parameterTypes, returnType)?.let { return it }
}
}
}
return null
}
private fun Class<*>.tryGetMethod(name: String, parameterTypes: Array<Class<*>>, returnType: Class<*>): Method? =
try {
val result = getDeclaredMethod(name, *parameterTypes)
if (result.returnType == returnType) result
else {
// If we've found a method with an unexpected return type, it's likely that there are several methods in this class
// with the given parameter types and Java reflection API has returned not the one we're looking for.
// Falling back to enumerating all methods in the class in this (rather rare) case.
// Example: class A(val x: Int) { fun getX(): String = ... }
declaredMethods.firstOrNull { method ->
method.name == name && method.returnType == returnType && method.parameterTypes.contentEquals(parameterTypes)
}
}
} catch (e: NoSuchMethodException) {
null
}
private fun Class<*>.tryGetConstructor(parameterTypes: List<Class<*>>): Constructor<*>? =
try {
getDeclaredConstructor(*parameterTypes.toTypedArray())
} catch (e: NoSuchMethodException) {
null
}
override fun findMethodBySignature(name: String, desc: String): Method? {
if (name == "<init>") return null
val parameterTypes = loadParameterTypes(desc).toTypedArray()
val returnType = loadReturnType(desc)
methodOwner.lookupMethod(name, parameterTypes, returnType, false)?.let { return it }
// Methods from java.lang.Object (equals, hashCode, toString) cannot be found in the interface via
// Class.getMethod/getDeclaredMethod, so for interfaces, we also look in java.lang.Object.
if (methodOwner.isInterface) {
Any::class.java.lookupMethod(name, parameterTypes, returnType, false)?.let { return it }
}
return null
}
override fun findDefaultMethod(name: String, desc: String, isMember: Boolean): Method? {
if (name == "<init>") return null
val parameterTypes = arrayListOf<Class<*>>()
if (isMember) {
// Note that this value is replaced inside the lookupMethod call below, for each class/interface in the hierarchy.
parameterTypes.add(jClass)
}
addParametersAndMasks(parameterTypes, desc, false)
return methodOwner.lookupMethod(
name + JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX, parameterTypes.toTypedArray(), loadReturnType(desc), isStaticDefault = isMember
)
}
override fun findConstructorBySignature(desc: String): Constructor<*>? =
jClass.tryGetConstructor(loadParameterTypes(desc))
override fun findDefaultConstructor(desc: String): Constructor<*>? =
jClass.tryGetConstructor(arrayListOf<Class<*>>().also { parameterTypes ->
addParametersAndMasks(parameterTypes, desc, true)
})
private fun addParametersAndMasks(result: MutableList<Class<*>>, desc: String, isConstructor: Boolean) {
val valueParameters = loadParameterTypes(desc)
result.addAll(valueParameters)
repeat((valueParameters.size + Integer.SIZE - 1) / Integer.SIZE) {
result.add(Integer.TYPE)
}
result.add(if (isConstructor) DEFAULT_CONSTRUCTOR_MARKER else Any::class.java)
}
private fun loadParameterTypes(desc: String): List<Class<*>> {
val result = arrayListOf<Class<*>>()
var begin = 1
while (desc[begin] != ')') {
var end = begin
while (desc[end] == '[') end++
@Suppress("SpellCheckingInspection")
when (desc[end]) {
in "VZCBSIFJD" -> end++
'L' -> end = desc.indexOf(';', begin) + 1
else -> throw KotlinReflectionInternalError("Unknown type prefix in the method signature: $desc")
}
result.add(parseType(desc, begin, end))
begin = end
}
return result
}
private fun parseType(desc: String, begin: Int, end: Int): Class<*> =
when (desc[begin]) {
'L' -> jClass.safeClassLoader.loadClass(desc.substring(begin + 1, end - 1).replace('/', '.'))
'[' -> parseType(desc, begin + 1, end).createArrayType()
'V' -> Void.TYPE
'Z' -> Boolean::class.java
'C' -> Char::class.java
'B' -> Byte::class.java
'S' -> Short::class.java
'I' -> Int::class.java
'F' -> Float::class.java
'J' -> Long::class.java
'D' -> Double::class.java
else -> throw KotlinReflectionInternalError("Unknown type prefix in the method signature: $desc")
}
private fun loadReturnType(desc: String): Class<*> =
parseType(desc, desc.indexOf(')') + 1, desc.length)
companion object {
private val DEFAULT_CONSTRUCTOR_MARKER = Class.forName("kotlin.jvm.internal.DefaultConstructorMarker")
}
override fun equals(other: Any?): Boolean {
return other is ClassBasedDeclarationContainerDescriptor && jClass == other.jClass
}
override fun hashCode(): Int = jClass.hashCode()
}
| 3 |
Kotlin
|
13
| 156 |
32ffe53981eb559939b6c2f15661138661b31bc6
| 9,096 |
kotlinx.reflect.lite
|
Apache License 2.0
|
core/src/main/java/space/narrate/waylan/core/data/prefs/UserPreferences.kt
|
narrate-co
| 171,908,990 | false | null |
package space.narrate.waylan.core.data.prefs
/**
* Preferences which should be specific to a valid, logged in user.
*/
object UserPreferences {
// Onboarding prefs
const val HAS_SEEN_RECENTS_BANNER = "has_seen_recents_banner"
const val HAS_SEEN_TRENDING_BANNER = "has_seen_trending_banner"
const val HAS_SEEN_FAVORITES_BANNER = "has_seen_favorites_banner"
const val HAS_SEEN_DRAG_DISMISS_OVERLAY = "has_seen_drag_dismiss_overlay"
// Filter prefs
const val RECENTS_LIST_FILTER = "recents_list_filter"
const val TRENDING_LIST_FILTER = "trending_list_filter"
const val FAVORITES_LIST_FILTER = "favorites_list_filter"
// Orientation prefs
const val PORTRAIT_TO_LANDSCAPE_ORIENTATION_CHANGE_COUNT = "portrait_to_landscape_rotation_count"
const val LANDSCAPE_TO_PORTRAIT_ORIENTATION_CHANGE_COUNT = "landscape_to_portrait_rotation_count"
const val IS_ABLE_TO_SUGGEST_ORIENTATION_UNLOCK = "is_able_to_suggest_orientation_unlock"
// Developer prefs
const val USE_TEST_SKUS = "use_test_skus"
}
| 25 | null |
1
| 14 |
c5640fb3bab994fd2c78cabd83fa962fbff75911
| 1,051 |
waylan_android
|
Apache License 2.0
|
kex-core/src/main/kotlin/org/vorpal/research/kex/util/PathClassLoader.kt
|
vorpal-research
| 204,454,367 | false | null |
package org.vorpal.research.kex.util
import java.nio.file.Path
import java.util.jar.JarFile
import kotlin.io.path.exists
import kotlin.io.path.isDirectory
import kotlin.io.path.readBytes
class PathClassLoader(
val paths: List<Path>,
parent: ClassLoader = PathClassLoader::class.java.classLoader
) : ClassLoader(parent) {
private val cache = hashMapOf<String, Class<*>>()
private fun readClassFromJar(name: String, path: Path): ByteArray? {
val fileName = name.asmString + ".class"
val jarFile = JarFile(path.toFile())
val entry = jarFile.getJarEntry(fileName) ?: return null
return jarFile.getInputStream(entry).readBytes()
}
private fun readClassFromDirectory(name: String, path: Path): ByteArray? {
val fileName = name.asmString + ".class"
val resolved = path.resolve(fileName)
return when {
resolved.exists() -> resolved.readBytes()
else -> null
}
}
private fun defineClass(name: String, bytes: ByteArray): Class<*> {
val klass = defineClass(name, bytes, 0, bytes.size)
cache[name] = klass
return klass
}
override fun loadClass(name: String): Class<*> = synchronized(this.getClassLoadingLock(name)) {
if (name in cache) return cache[name]!!
for (path in paths) {
val bytes = when {
path.isDirectory() -> readClassFromDirectory(name, path)
path.fileName.toString().endsWith(".jar") -> readClassFromJar(name, path)
else -> null
}
if (bytes != null) {
return defineClass(name, bytes)
}
}
return parent?.loadClass(name) ?: throw ClassNotFoundException()
}
}
| 9 | null |
20
| 28 |
459dd8cb1c5b1512b5a920260cd0ebe503861b3e
| 1,763 |
kex
|
Apache License 2.0
|
app/src/main/java/com/test/shoppingapp/di/ShoppingComponent.kt
|
NayaneshGupte
| 196,730,583 | false | null |
package com.test.shoppingapp.di
import com.test.shoppingapp.ShoppingApplication
import com.test.shoppingapp.network.NetworkSDKModule
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
@Singleton
@Component(
modules = [AndroidSupportInjectionModule::class,
AppModule::class,
ActivityBuilderModule::class,
NetworkSDKModule::class]
)
interface ShoppingComponent : AndroidInjector<ShoppingApplication> {
override fun inject(shoppingApplication: ShoppingApplication)
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: ShoppingApplication): Builder
fun build(): ShoppingComponent
}
}
| 1 | null |
1
| 1 |
077764040c04650245e221ec434539239dccf53c
| 812 |
MVVM-Demo
|
Apache License 2.0
|
lib/DevBase/src/main/java/dev/base/expand/mvp/DevBaseMVPActivity.kt
|
afkT
| 147,776,221 | false | null |
package dev.base.expand.mvp
import android.os.Bundle
import dev.base.activity.DevBaseActivity
/**
* detail: MVP Activity 基类
* @author Ttt
* 需要自己实现 Contract ( 契约类 ) 用来管理 View 与 Presenter 的交互
*/
abstract class DevBaseMVPActivity<P : MVP.Presenter<out MVP.IView, out MVP.IModel>> :
DevBaseActivity() {
// MVP Presenter
lateinit var presenter: P
override fun onCreate(savedInstanceState: Bundle?) {
// 创建 MVP 模式的 Presenter
presenter = createPresenter()
// lifecycle
presenter?.let { lifecycle.addObserver(it) }
// 初始化操作
super.onCreate(savedInstanceState)
}
/**
* 初始化创建 Presenter
* @return [MVP.Presenter]
*/
abstract fun createPresenter(): P
}
| 1 | null |
221
| 882 |
2fd4c7582a97968d73d67124b6b2e57eda18e90f
| 739 |
DevUtils
|
Apache License 2.0
|
app/core/src/main/java/com/fsck/k9/controller/KoinModule.kt
|
stefan01
| 222,450,885 | true |
{"INI": 3, "YAML": 2, "Gradle": 23, "Shell": 5, "Markdown": 9, "Git Attributes": 1, "Batchfile": 1, "Text": 5, "Ignore List": 4, "Git Config": 1, "XML": 431, "AIDL": 2, "Java": 622, "SVG": 67, "PostScript": 1, "Kotlin": 312, "HTML": 1, "E-mail": 8, "Proguard": 1}
|
package com.fsck.k9.controller
import org.koin.dsl.module.applicationContext
val controllerModule = applicationContext {
bean { MessagingController(get(), get(), get(), get(), get(), get(), get(), get(), get("controllerExtensions")) }
bean { DefaultUnreadMessageCountProvider(get(), get(), get(), get()) as UnreadMessageCountProvider }
}
| 0 | null |
0
| 0 |
b6819eabf11479c0057bcb999662722518df37c0
| 348 |
k-9
|
Apache License 2.0
|
bbfgradle/src/com/stepanov/bbf/bugfinder/mutator/transformations/tce/UsagesSamplesGenerator.kt
|
DaniilStepanov
| 346,008,310 | false |
{"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1}
|
package com.stepanov.bbf.bugfinder.mutator.transformations.tce
import com.stepanov.bbf.bugfinder.mutator.transformations.Factory
import com.stepanov.bbf.bugfinder.util.findFunByName
import com.stepanov.bbf.bugfinder.util.getAllPSIChildrenOfType
import com.stepanov.bbf.bugfinder.util.replaceThis
import com.stepanov.bbf.reduktor.parser.PSICreator
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter
import org.jetbrains.kotlin.psi.psiUtil.isProtected
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.types.KotlinType
import kotlin.random.Random
object UsagesSamplesGenerator {
fun generate(file: KtFile): List<Triple<KtExpression, String, KotlinType?>> {
//val ctx = PSICreator.analyze(file)!!
val instanceGenerator = RandomInstancesGenerator(file)
val res = mutableListOf<KtExpression>()
generateForKlasses(file, res, instanceGenerator)
val withTypes = generateTypes(file, res.joinToString("\n") { it.text })
generateForFuncs(file, res, instanceGenerator, withTypes)
val resToStr = res.joinToString("\n") { it.text }
return generateTypes(file, resToStr)
}
private fun generateForFuncs(
file: KtFile,
res: MutableList<KtExpression>,
generator: RandomInstancesGenerator,
klassInstances: List<Triple<KtExpression, String, KotlinType?>>
) {
for (func in file.getAllPSIChildrenOfType<KtNamedFunction>().filter { it.isTopLevel }) {
if (func.name?.startsWith("box") == true) continue
val (instance, valueParams) = generator.generateTopLevelFunctionCall(func) ?: continue
val valueArgs =
if (instance is KtCallExpression) instance.valueArguments
else null
for ((valueArg, param) in valueArgs?.zip(valueParams) ?: listOf()) {
if (param.typeReference == null) continue
val anotherExpr = klassInstances.getValueOfType(param.typeReference!!.text)
if (anotherExpr != null && Random.nextBoolean()) {
valueArg.replaceThis(anotherExpr.copy())
}
}
res.add(instance)
}
}
private fun generateForKlasses(
file: KtFile,
res: MutableList<KtExpression>,
generator: RandomInstancesGenerator,
funInstances: List<Triple<KtExpression, String, KotlinType?>> = listOf()
) {
val classes = file.getAllPSIChildrenOfType<KtClassOrObject>()
for (klass in classes) {
val openFuncsAndProps = mutableListOf<String>()
klass.primaryConstructor?.valueParameters
?.filter { it.isPropertyParameter() && !it.isPrivate() && it.name != null }
?.forEach { openFuncsAndProps.add(it.name!!) }
filterOpenFuncsAndPropsFromDecl(klass.declarations).forEach { openFuncsAndProps.add(it) }
val instanceOfKlass = generator.generateRandomInstanceOfClass(klass)
openFuncsAndProps
.mapNotNull {
if (it.startsWith("CoBj"))
Factory.psiFactory.createExpressionIfPossible("${klass.name}.${it.substringAfter("CoBj")}")
else
Factory.psiFactory.createExpressionIfPossible("${instanceOfKlass?.text}.$it")
}
.forEach { res.add(it) }
}
}
private fun filterOpenFuncsAndPropsFromDecl(declarations: List<KtDeclaration>): List<String> {
val openFuncsAndProps = mutableListOf<String>()
for (decl in declarations) {
if (decl.isPrivate() || decl.isProtected() || (decl.name == null && decl !is KtObjectDeclaration)) continue
when (decl) {
is KtProperty -> openFuncsAndProps.add(decl.name!!)
is KtNamedFunction -> openFuncsAndProps.add("${decl.name!!}()")
is KtObjectDeclaration ->
filterOpenFuncsAndPropsFromDecl(decl.declarations).forEach {
openFuncsAndProps.add("CoBj$it")
}
}
}
return openFuncsAndProps
}
private fun generateTypes(file: KtFile, resToStr: String): List<Triple<KtExpression, String, KotlinType?>> {
val func = Factory.psiFactory.createFunction("fun usageExamples(){\n$resToStr\n}")
val newFile = Factory.psiFactory.createFile(file.text + "\n\n" + func.text)
val ctx = PSICreator.analyze(newFile)!!
val myFunc = newFile.findFunByName("usageExamples")!!
return myFunc.getAllPSIChildrenOfType<KtExpression>()
.filter { it.parent == myFunc.bodyBlockExpression }
.map { Triple(it, it.text, it.getType(ctx)) }
.filter { it.third != null }
}
fun List<Triple<KtExpression, String, KotlinType?>>.getValueOfType(type: String): KtExpression? =
this.filter { it.third?.let { it.toString() == type || it.toString() == type.substringBefore('?') } ?: false }
.randomOrNull()?.first
}
| 1 | null |
1
| 1 |
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
| 5,161 |
kotlinWithFuzzer
|
Apache License 2.0
|
annotation/src/main/java/com/arch/jonnyhsia/compass/facade/CompassPage.kt
|
jonnyhsia
| 179,116,275 | false |
{"Gradle": 11, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "Gradle Kotlin DSL": 1, "Kotlin": 37, "Proguard": 2, "XML": 15, "Java": 5}
|
package com.arch.jonnyhsia.compass.facade
import com.arch.jonnyhsia.compass.facade.enums.TargetType
abstract class CompassMeta {
abstract val name: String
abstract val target: Class<*>
abstract val type: Int
abstract val extras: Int
abstract val group: String
}
class CompassEcho(
override val name: String,
override val target: Class<*>,
override val type: Int = TargetType.UNKNOWN,
override val extras: Int,
override val group: String = ""
) : CompassMeta()
class CompassPage @JvmOverloads constructor(
override val name: String,
override val target: Class<*>,
override val type: Int = TargetType.UNKNOWN,
override val extras: Int,
override val group: String = "",
) : CompassMeta()
| 0 |
Kotlin
|
0
| 3 |
c75369da07ac8a1170610d1f28c9bc4812acc9ee
| 749 |
compass
|
MIT License
|
idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideImplementMembersHandler.kt
|
Spring-Xu
| 43,350,123 | false | null |
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.core.overrideImplement
import com.intellij.codeInsight.hint.HintManager
import com.intellij.ide.util.MemberChooser
import com.intellij.lang.LanguageCodeInsightActionHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptor
import org.jetbrains.kotlin.idea.quickfix.moveCaretIntoGeneratedElement
import org.jetbrains.kotlin.idea.util.ShortenReferences
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import java.util.*
public abstract class OverrideImplementMembersHandler : LanguageCodeInsightActionHandler {
public fun collectMembersToGenerate(classOrObject: JetClassOrObject): Collection<OverrideMemberChooserObject> {
val descriptor = classOrObject.resolveToDescriptor() as? ClassDescriptor ?: return emptySet()
return collectMembersToGenerate(descriptor, classOrObject.project)
}
protected abstract fun collectMembersToGenerate(descriptor: ClassDescriptor, project: Project): Collection<OverrideMemberChooserObject>
private fun showOverrideImplementChooser(project: Project, members: Array<OverrideMemberChooserObject>): MemberChooser<OverrideMemberChooserObject>? {
val chooser = MemberChooser(members, true, true, project)
chooser.title = getChooserTitle()
chooser.show()
if (chooser.exitCode != DialogWrapper.OK_EXIT_CODE) return null
return chooser
}
protected abstract fun getChooserTitle(): String
override fun isValidFor(editor: Editor, file: PsiFile): Boolean {
if (file !is JetFile) return false
val elementAtCaret = file.findElementAt(editor.caretModel.offset)
val classOrObject = elementAtCaret?.getNonStrictParentOfType<JetClassOrObject>()
return classOrObject != null
}
protected abstract fun getNoMembersFoundHint(): String
public fun invoke(project: Project, editor: Editor, file: PsiFile, implementAll: Boolean) {
val elementAtCaret = file.findElementAt(editor.caretModel.offset)
val classOrObject = elementAtCaret?.getNonStrictParentOfType<JetClassOrObject>()!!
val members = collectMembersToGenerate(classOrObject)
if (members.isEmpty() && !implementAll) {
HintManager.getInstance().showErrorHint(editor, getNoMembersFoundHint())
return
}
val selectedElements = if (implementAll) {
members
}
else {
val chooser = showOverrideImplementChooser(project, members.toTypedArray()) ?: return
chooser.selectedElements ?: return
}
if (selectedElements.isEmpty()) return
PsiDocumentManager.getInstance(project).commitAllDocuments()
generateMembers(editor, classOrObject, selectedElements)
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) = invoke(project, editor, file, false)
override fun startInWriteAction(): Boolean = false
companion object {
public fun generateMembers(editor: Editor, classOrObject: JetClassOrObject, selectedElements: Collection<OverrideMemberChooserObject>) {
runWriteAction {
if (selectedElements.isEmpty()) return@runWriteAction
val body = classOrObject.getOrCreateBody()
var afterAnchor = findInsertAfterAnchor(editor, body) ?: return@runWriteAction
var firstGenerated: PsiElement? = null
val project = classOrObject.project
val insertedMembers = ArrayList<JetCallableDeclaration>()
for (memberObject in selectedElements) {
val member = memberObject.generateMember(project)
val added = body.addAfter(member, afterAnchor) as JetCallableDeclaration
if (firstGenerated == null) {
firstGenerated = added
}
afterAnchor = added
insertedMembers.add(added)
}
ShortenReferences.DEFAULT.process(insertedMembers)
moveCaretIntoGeneratedElement(editor, firstGenerated!!)
}
}
private fun findInsertAfterAnchor(editor: Editor, body: JetClassBody): PsiElement? {
val afterAnchor = body.lBrace ?: return null
val offset = editor.caretModel.offset
val offsetCursorElement = PsiTreeUtil.findFirstParent(body.containingFile.findElementAt(offset)) {
it.parent == body
}
if (offsetCursorElement is PsiWhiteSpace) {
return removeAfterOffset(offset, offsetCursorElement)
}
if (offsetCursorElement != null && offsetCursorElement != body.rBrace) {
return offsetCursorElement
}
return afterAnchor
}
private fun removeAfterOffset(offset: Int, whiteSpace: PsiWhiteSpace): PsiElement {
val spaceNode = whiteSpace.node
if (spaceNode.textRange.contains(offset)) {
var beforeWhiteSpaceText = spaceNode.text.substring(0, offset - spaceNode.startOffset)
if (!StringUtil.containsLineBreak(beforeWhiteSpaceText)) {
// Prevent insertion on same line
beforeWhiteSpaceText += "\n"
}
val factory = JetPsiFactory(whiteSpace.project)
val insertAfter = whiteSpace.prevSibling
whiteSpace.delete()
val beforeSpace = factory.createWhiteSpace(beforeWhiteSpaceText)
insertAfter.parent.addAfter(beforeSpace, insertAfter)
return insertAfter.nextSibling
}
return whiteSpace
}
}
}
| 0 | null |
0
| 1 |
a55f9feacbf3e85ea064cc2aee6ecfd5e699918d
| 6,887 |
kotlin
|
Apache License 2.0
|
wanandroid/src/main/java/com/lyl/wanandroid/ui/fragment/wechatpublic/WeChatContentItemDataSouce.kt
|
laiyuling424
| 145,495,250 | false | null |
package com.lyl.wanandroid.ui.fragment.wechatpublic
import androidx.paging.ItemKeyedDataSource
import com.lyl.wanandroid.http.ApiServer
import com.lyl.wanandroid.ui.base.ExecuteOnceObserver
import com.lyl.wanandroid.util.MyLog
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Create By: lyl
* Date: 2019-07-08 18:46
*/
class WeChatContentItemDataSouce(val id: Int) : ItemKeyedDataSource<Int, WeChatContentBean>() {
private val apiGenerate by lazy {
ApiServer.getApiServer()
}
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<WeChatContentBean>) {
MyLog.Logd("loadInitial idd====>" + WeChatPublicFragment.idd!!.value)
MyLog.Logd("loadInitial id====>" + id)
apiGenerate.getWeChatPublicHistoryData(WeChatPublicFragment.idd!!.value!!, 1)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.subscribe(ExecuteOnceObserver(onExecuteOnceNext = {
// Log.d("lyll","next")
// Log.d("lyll","data="+ it.data!!.datas!![0].link)
MyLog.Logd("loadInitial====>" + it.data!!.datas!![0].author)
callback.onResult(it.data!!.datas!!)
}, onExecuteOnceError = {
// Log.d("lyll","error")
}, onExecuteOnceComplete = {
// Log.d("lyll","complete")
}))
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<WeChatContentBean>) {
MyLog.Logd("loadAfter idd====>" + WeChatPublicFragment.idd!!.value)
MyLog.Logd("loadAfter id====>" + id)
apiGenerate.getWeChatPublicHistoryData(WeChatPublicFragment.idd!!.value!!, 1)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.subscribe(ExecuteOnceObserver(onExecuteOnceNext = {
MyLog.Logd("loadAfter====>" + it.data!!.datas!![0].author)
callback.onResult(it.data!!.datas!!)
}, onExecuteOnceError = {
// Log.d("lyll","error")
}, onExecuteOnceComplete = {
// Log.d("lyll","complete")
}))
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<WeChatContentBean>) {
MyLog.Logd("loadBefore idd====>" + WeChatPublicFragment.idd!!.value)
MyLog.Logd("loadBefore id====>" + id)
apiGenerate.getWeChatPublicHistoryData(WeChatPublicFragment.idd!!.value!!, 1)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.subscribe(ExecuteOnceObserver(onExecuteOnceNext = {
MyLog.Logd("loadBefore====>" + it.data!!.datas!![0].author)
callback.onResult(it.data!!.datas!!)
}, onExecuteOnceError = {
// Log.d("lyll","error")
}, onExecuteOnceComplete = {
// Log.d("lyll","complete")
}))
}
override fun getKey(item: WeChatContentBean): Int {
return item.id!!
}
}
| 1 |
C++
|
2
| 5 |
8c8d10aa48546f0a66f0a466990e3b2f886b011c
| 3,415 |
lylproject
|
MIT License
|
src/main/kotlin/io/github/luke_biel/navigation/IonStructureViewModel.kt
|
luke-biel
| 232,924,280 | false |
{"Gradle": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 30, "XML": 1, "JFlex": 1, "Kotlin": 18, "YAML": 2}
|
package io.github.luke_biel.navigation
import com.intellij.ide.structureView.StructureViewModel.ElementInfoProvider
import com.intellij.ide.structureView.StructureViewModelBase
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.util.treeView.smartTree.Sorter
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiFile
import io.github.luke_biel.psi.IonFile
import io.github.luke_biel.psi.impl.IonHeaderItemImpl
class IonStructureViewModel(psiFile: PsiFile, editor: Editor?) :
StructureViewModelBase(psiFile, editor,
IonStructureViewElement(psiFile as IonFile)
), ElementInfoProvider {
override fun getSorters(): Array<Sorter> {
return arrayOf(Sorter.ALPHA_SORTER)
}
override fun isAlwaysShowsPlus(element: StructureViewTreeElement): Boolean {
return false
}
override fun isAlwaysLeaf(element: StructureViewTreeElement): Boolean {
return false
}
init {
withSuitableClasses(IonHeaderItemImpl::class.java)
}
}
| 2 |
Kotlin
|
0
| 2 |
84d84967c5e235b8fc0318d1b5f8ae2c8b4ea057
| 1,043 |
IonType
|
MIT License
|
room/room-compiler-processing-testing/src/main/java/androidx/room/compiler/processing/util/Source.kt
|
JetBrains
| 351,708,598 | true | null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.util
import com.google.testing.compile.JavaFileObjects
import org.intellij.lang.annotations.Language
import java.io.File
import javax.tools.JavaFileObject
/**
* Common abstraction for test sources in kotlin and java
*/
sealed class Source {
abstract val relativePath: String
abstract val contents: String
abstract fun toJFO(): JavaFileObject
override fun toString(): String {
return "SourceFile[$relativePath]"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Source) return false
if (relativePath != other.relativePath) return false
if (contents != other.contents) return false
return true
}
override fun hashCode(): Int {
var result = relativePath.hashCode()
result = 31 * result + contents.hashCode()
return result
}
class JavaSource(
val qName: String,
override val contents: String
) : Source() {
override fun toJFO(): JavaFileObject {
return JavaFileObjects.forSourceString(
qName,
contents
)
}
override val relativePath
get() = qName.replace(".", File.separator) + ".java"
}
class KotlinSource(
override val relativePath: String,
override val contents: String
) : Source() {
override fun toJFO(): JavaFileObject {
throw IllegalStateException("cannot include kotlin code in javac compilation")
}
}
companion object {
fun java(
qName: String,
@Language("java")
code: String
): Source {
return JavaSource(
qName,
code
)
}
fun kotlin(
filePath: String,
@Language("kotlin")
code: String
): Source {
return KotlinSource(
filePath,
code
)
}
/**
* Convenience method to convert JFO's to the Source objects in XProcessing so that we can
* convert room tests to the common API w/o major code refactor
*/
fun fromJavaFileObject(javaFileObject: JavaFileObject): Source {
val uri = javaFileObject.toUri()
// parse name from uri
val contents = javaFileObject.openReader(true).use {
it.readText()
}
val qName = if (uri.scheme == "mem") {
// in java compile testing, path includes SOURCE_OUTPUT, drop it
uri.path.substringAfter("SOURCE_OUTPUT/").replace('/', '.')
} else {
uri.path.replace('/', '.')
}
val javaExt = ".java"
check(qName.endsWith(javaExt)) {
"expected a java source file, $qName does not seem like one"
}
return java(qName.dropLast(javaExt.length), contents)
}
fun loadKotlinSource(
file: File,
relativePath: String
): Source {
check(file.exists() && file.name.endsWith(".kt"))
return kotlin(relativePath, file.readText())
}
fun loadJavaSource(
file: File,
qName: String
): Source {
check(file.exists() && file.name.endsWith(".java"))
return java(qName, file.readText())
}
fun load(
file: File,
qName: String,
relativePath: String
): Source {
check(file.exists()) {
"file does not exist: ${file.canonicalPath}"
}
return when {
file.name.endsWith(".kt") -> loadKotlinSource(file, relativePath)
file.name.endsWith(".java") -> loadJavaSource(file, qName)
else -> error("invalid file extension ${file.name}")
}
}
}
}
| 29 |
Java
|
937
| 59 |
3fbd775007164912b34a1d59a923ad3387028b97
| 4,643 |
androidx
|
Apache License 2.0
|
platform/build-scripts/icons/tests/org/jetbrains/intellij/build/images/sync/dotnet/DotnetIconsTransformationTest.kt
|
ingokegel
| 72,937,917 | true | null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.images.sync.dotnet
import org.jetbrains.intellij.build.images.sync.dotnet.DotnetIconsTransformation.dotnetDarkSuffices
import org.jetbrains.intellij.build.images.sync.dotnet.DotnetIconsTransformation.dotnetExpUiDaySuffix
import org.jetbrains.intellij.build.images.sync.dotnet.DotnetIconsTransformation.dotnetExpUiNightSuffix
import org.jetbrains.intellij.build.images.sync.dotnet.DotnetIconsTransformation.dotnetLightSuffices
import org.jetbrains.intellij.build.images.sync.dotnet.DotnetIconsTransformation.ideaDarkSuffix
import org.jetbrains.intellij.build.images.sync.isAncestorOf
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.File
@RunWith(Parameterized::class)
internal class DotnetIconsTransformationTest(private val braces: DotnetIcon.Braces) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun braces(): Collection<Array<Any>> = DotnetIcon.BRACES.map {
@Suppress("RemoveExplicitTypeArguments")
arrayOf<Any>(it)
}
}
@Rule
@JvmField
val iconsRepo = TemporaryFolder()
private fun String.brace() : String = if (isNotEmpty()) "${braces.start}$this${braces.end}" else this
private data class Suffix(val after: String, val before: String, val isExpUi: Boolean = false)
private fun `icons test`(suffices: List<String>, expected: List<Suffix>) {
val name = "icon"
val ext = "svg"
suffices.forEach {
val suffix = it.brace()
iconsRepo.newFile("$name$suffix.$ext").writeText(suffix)
}
DotnetIconsTransformation.transformToIdeaFormat(iconsRepo.root.toPath())
iconsRepo.root.walkTopDown().filter { it.isFile }.toList().also {
assert(it.count() == expected.count()) {
"Expected: $expected, actual $it"
}
}.forEach { result ->
val suffix = expected.singleOrNull {
result.name == "$name${it.after}.$ext" && it.isExpUi == result.isInExpUi()
}
assert(suffix != null) {
"$result doesn't have expected suffix: $expected"
}
val content = result.readText()
assert(content == suffix?.before) {
"$result check failed, expected content: ${suffix?.before}, actual: $content"
}
}
}
private fun File.isInExpUi() = iconsRepo.root.resolve("expui").toPath().isAncestorOf(this.toPath())
@Test
fun `light icons test`() = `icons test`(
dotnetLightSuffices + "unknown",
listOf(Suffix("", dotnetLightSuffices.first().brace()))
)
@Test
fun `dark icons test`() = `icons test`(
dotnetDarkSuffices + "unknown",
// expect anything because we don't have basic light icons
listOf()
)
@Test
fun `expui day icons test`() = `icons test`(
dotnetLightSuffices + dotnetExpUiDaySuffix,
listOf(
Suffix("", dotnetLightSuffices.first().brace()),
Suffix("", dotnetExpUiDaySuffix.brace(), true),
)
)
@Test
fun `expui night icons test`() = `icons test`(
dotnetLightSuffices + dotnetExpUiNightSuffix,
listOf(
Suffix("", dotnetLightSuffices.first().brace()),
Suffix(ideaDarkSuffix, dotnetExpUiNightSuffix.brace(), true),
)
)
@Test
fun `mixed expui icons test`() = `icons test`(
dotnetDarkSuffices + dotnetLightSuffices + dotnetExpUiNightSuffix + dotnetExpUiDaySuffix + "unknown",
listOf(
Suffix("", dotnetLightSuffices.first().brace()),
Suffix(ideaDarkSuffix, dotnetDarkSuffices.first().brace()),
Suffix(ideaDarkSuffix, dotnetExpUiNightSuffix.brace(), true),
Suffix("", dotnetExpUiDaySuffix.brace(), true),
)
)
@Test
fun `mixed icons test`() = `icons test`(
dotnetDarkSuffices + dotnetLightSuffices + "unknown",
listOf(
Suffix("", dotnetLightSuffices.first().brace()),
Suffix(ideaDarkSuffix, dotnetDarkSuffices.first().brace())
)
)
}
| 1 | null |
1
| 2 |
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 4,047 |
intellij-community
|
Apache License 2.0
|
partiql-cli/src/main/kotlin/org/partiql/cli/format/ExplainFormatter.kt
|
partiql
| 186,474,394 | false | null |
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at:
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.partiql.cli.format
import org.partiql.lang.eval.PartiQLResult
internal object ExplainFormatter {
internal fun format(result: PartiQLResult.Explain.Domain): String {
val format = result.format?.toUpperCase() ?: ExplainFormats.ION_SEXP.name
val formatOption = ExplainFormats.valueOf(format)
return formatOption.formatter.format(result.value)
}
private enum class ExplainFormats(val formatter: NodeFormatter) {
ION_SEXP(SexpFormatter),
TREE(TreeFormatter),
DOT(DotFormatter),
DOT_URL(DotUrlFormatter)
}
}
| 306 | null |
60
| 539 |
306ec7c1dc143660d6d861cc9626cbc3ac444ec6
| 1,175 |
partiql-lang-kotlin
|
Apache License 2.0
|
compiler/testData/diagnostics/testsWithJvmBackend/duplicateJvmSignature/erasure/superTraitAndDelegationToTraitImpl_old.kt
|
JetBrains
| 3,432,266 | false | null |
// !DIAGNOSTICS: -UNUSED_PARAMETER
// TARGET_BACKEND: JVM_OLD
interface A<T> {
fun foo(l: List<T>)
}
interface B {
fun foo(l: List<Int>) {}
}
class <!CONFLICTING_INHERITED_JVM_DECLARATIONS, CONFLICTING_JVM_DECLARATIONS!>C(f: A<String>)<!>: A<String> by f, B
<!DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE!>class D<!>(f: A<Int>): A<Int> by f, B
| 154 | null |
5566
| 45,025 |
8a69904d02dd3e40fae5f2a1be4093d44a227788
| 352 |
kotlin
|
Apache License 2.0
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangesViewPanel.kt
|
JetBrains
| 2,489,216 | false | null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces.CHANGES_VIEW_TOOLBAR
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.toolbarLayout.ToolbarLayoutStrategy
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.ui.*
import com.intellij.ui.IdeBorderFactory.createBorder
import com.intellij.ui.ScrollPaneFactory.createScrollPane
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import javax.swing.JComponent
import javax.swing.SwingConstants
import kotlin.properties.Delegates.observable
class ChangesViewPanel(val changesView: ChangesListView) : BorderLayoutPanel() {
val toolbarActionGroup = DefaultActionGroup()
var isToolbarHorizontal: Boolean by observable(false) { _, oldValue, newValue ->
if (oldValue != newValue) {
addToolbar(newValue) // this also removes toolbar from previous parent
}
}
val toolbar: ActionToolbar =
ActionManager.getInstance().createActionToolbar(CHANGES_VIEW_TOOLBAR, toolbarActionGroup, isToolbarHorizontal).apply {
setTargetComponent(changesView)
}
var statusComponent by observable<JComponent?>(null) { _, oldValue, newValue ->
if (oldValue == newValue) return@observable
if (oldValue != null) centerPanel.remove(oldValue)
if (newValue != null) centerPanel.addToBottom(newValue)
}
private val changesScrollPane = createScrollPane(changesView)
private val centerPanel = simplePanel(changesScrollPane).andTransparent()
init {
addToCenter(centerPanel)
addToolbar(isToolbarHorizontal)
}
override fun updateUI() {
super.updateUI()
background = UIUtil.getTreeBackground()
}
private fun addToolbar(isHorizontal: Boolean) {
toolbar.layoutStrategy = ToolbarLayoutStrategy.AUTOLAYOUT_STRATEGY
if (isHorizontal) {
toolbar.setOrientation(SwingConstants.HORIZONTAL)
ScrollableContentBorder.setup(changesScrollPane, Side.TOP, centerPanel)
addToTop(toolbar.component)
}
else {
toolbar.setOrientation(SwingConstants.VERTICAL)
ScrollableContentBorder.setup(changesScrollPane, Side.LEFT, centerPanel)
addToLeft(toolbar.component)
}
}
}
| 284 | null |
5162
| 16,707 |
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
| 2,566 |
intellij-community
|
Apache License 2.0
|
analysis/symbol-light-classes/testData/lightElements/propertyAccessor.kt
|
JetBrains
| 3,432,266 | false | null |
// EXPECTED: org.jetbrains.kotlin.light.classes.symbol.methods.SymbolLightAccessorMethod
val p: Int = 42
g<caret>et
| 181 | null |
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 119 |
kotlin
|
Apache License 2.0
|
front-end/right-rainAS/app/src/main/java/com/example/rightrain/Map.kt
|
Isaquehg
| 607,414,269 | false |
{"Java": 54074, "Python": 11396, "C++": 9139, "Kotlin": 3154, "Dockerfile": 910}
|
package com.example.rightrain
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import com.mapbox.geojson.Point
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.MapView
import com.mapbox.maps.Style
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager
class Map : AppCompatActivity() {
fun addAnnotationToMap(context: Context, mapView: MapView, coordinates: List<Pair<Double, Double>>) {
mapView!!.getMapboxMap().setCamera(
CameraOptions.Builder()
.center(Point.fromLngLat(-45.7037, -22.2522))
.zoom(11.0)
.build()
)
// Create an instance of the Annotation API and get the PointAnnotationManager.
bitmapFromDrawableRes(
context,
R.drawable.red_marker
)?.let {
val annotationApi = mapView?.annotations
val pointAnnotationManager = annotationApi?.createPointAnnotationManager(mapView!!)
coordinates.forEach { coordinate ->
// Set options for the resulting symbol layer.
val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions()
// Define a geographic coordinate.
.withPoint(Point.fromLngLat(coordinate.second, coordinate.first))
// Specify the bitmap you assigned to the point annotation
// The bitmap will be added to map style automatically.
.withIconImage(it)
// Add the resulting pointAnnotation to the map.
pointAnnotationManager?.create(pointAnnotationOptions)
}
}
}
fun bitmapFromDrawableRes(context: Context, @DrawableRes resourceId: Int) =
convertDrawableToBitmap(AppCompatResources.getDrawable(context, resourceId))
fun convertDrawableToBitmap(sourceDrawable: Drawable?): Bitmap? {
if (sourceDrawable == null) {
return null
}
return if (sourceDrawable is BitmapDrawable) {
sourceDrawable.bitmap
} else {
// copying drawable object to not manipulate on the same reference
val constantState = sourceDrawable.constantState ?: return null
val drawable = constantState.newDrawable().mutate()
val bitmap: Bitmap = Bitmap.createBitmap(
drawable.intrinsicWidth, drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
bitmap
}
}
}
| 1 | null |
1
| 1 |
ac28ef2427ca44f0ecb35a2be77c7d37bee8fd15
| 3,154 |
right-rain
|
MIT License
|
yebi-core/src/nativeMain/kotlin/platforms.native.kt
|
elouyi
| 450,418,416 | false |
{"Kotlin": 32757}
|
package com.elouyi.yebi
import io.ktor.client.*
import io.ktor.client.engine.curl.*
import io.ktor.util.date.*
public actual val platformUtil: PlatformUtil get() = NativePlatform
public object NativePlatform : PlatformUtil {
override fun newHttpClient(block: HttpClientConfig<*>.() -> Unit): HttpClient {
return HttpClient(Curl) {
block()
}
}
override fun currentTimeMillis(): Long = getTimeMillis()
override val isNative: Boolean
get() = true
override val isNativeWindows: Boolean
get() = isWindows
override val isNativeMacOS: Boolean
get() = isMacOS
override val isNativeLinux: Boolean
get() = isLinux
}
public expect val NativePlatform.isWindows: Boolean
public expect val NativePlatform.isMacOS: Boolean
public expect val NativePlatform.isLinux: Boolean
| 0 |
Kotlin
|
0
| 0 |
a17bfa948433366c28acd99c7b34e295ef04eba7
| 857 |
yebi
|
MIT License
|
client/src/commonMain/kotlin/com/lightningkite/kiteui/forms/FormModule.kt
|
lightningkite
| 827,410,739 | false |
{"Kotlin": 333293, "CSS": 2281, "HTML": 2036, "JavaScript": 302}
|
package com.lightningkite.kiteui.forms
import com.lightningkite.kiteui.FileReference
import com.lightningkite.kiteui.models.SubtextSemantic
import com.lightningkite.kiteui.models.px
import com.lightningkite.kiteui.models.rem
import com.lightningkite.kiteui.reactive.Constant
import com.lightningkite.kiteui.reactive.Property
import com.lightningkite.kiteui.reactive.reactive
import com.lightningkite.kiteui.views.atTopEnd
import com.lightningkite.kiteui.views.direct.row
import com.lightningkite.kiteui.views.direct.select
import com.lightningkite.kiteui.views.direct.sizeConstraints
import com.lightningkite.kiteui.views.direct.stack
import com.lightningkite.kiteui.views.expanding
import com.lightningkite.lightningserver.files.ServerFile
import com.lightningkite.serialization.ClientModule
import kotlinx.serialization.descriptors.SerialKind
class FormModule {
var module = ClientModule
var fileUpload: (suspend (FileReference) -> ServerFile)? = null
var typeInfo: (type: String) -> FormTypeInfo<*, *>? = { _ -> println("WARN: Empty form context"); null }
private val form_others: ArrayList<FormRenderer.Generator> = ArrayList()
private val form_type: HashMap<String, ArrayList<FormRenderer.Generator>> = HashMap()
private val form_kind: HashMap<SerialKind, ArrayList<FormRenderer.Generator>> = HashMap()
private val form_annotation: HashMap<String, ArrayList<FormRenderer.Generator>> = HashMap()
fun <T> formCandidates(key: FormSelector<T>): Sequence<FormRenderer.Generator> = sequence {
form_type[key.serializer.descriptor.serialName]?.let { yieldAll(it) }
form_kind[key.serializer.descriptor.kind]?.let { yieldAll(it) }
key.annotations.forEach { anno ->
form_annotation[anno.fqn]?.let {
yieldAll(it)
}
}
yieldAll(form_others)
}
private val view_others: ArrayList<ViewRenderer.Generator> = ArrayList()
private val view_type: HashMap<String, ArrayList<ViewRenderer.Generator>> = HashMap()
private val view_kind: HashMap<SerialKind, ArrayList<ViewRenderer.Generator>> = HashMap()
private val view_annotation: HashMap<String, ArrayList<ViewRenderer.Generator>> = HashMap()
fun <T> viewCandidates(key: FormSelector<T>): Sequence<ViewRenderer.Generator> = sequence {
view_type[key.serializer.descriptor.serialName]?.let { yieldAll(it) }
view_kind[key.serializer.descriptor.kind]?.let { yieldAll(it) }
key.annotations.forEach { anno ->
view_annotation[anno.fqn]?.let {
yieldAll(it)
}
}
yieldAll(view_others)
}
fun <T> view(key: FormSelector<T>): ViewRenderer<T> {
val options = viewCandidates(key).filter { it.matches(this, key) }.sortedByDescending { it.priority(this, key) }.map { it.view(this, key) }.toList()
if (!key.withPicker) return options.first()
return ViewRenderer(this, null, key, size = options.first().size, handlesField = options.first().handlesField) { field, writable ->
val selected = Property(options.first())
row {
// spacing = 0.px
expanding - stack {
reactive {
val sel = selected()
clearChildren()
sel.render(this@stack, field, writable)
}
}
sizeConstraints(width = 0.75.rem, height = 0.75.rem) - SubtextSemantic.onNext - atTopEnd - select {
spacing = 0.px
bind(selected, Constant(options)) { (it.generator?.name ?: "-") + " (${it.generator?.priority(this@FormModule, key)}, ${it.size.approximateWidth} x ${it.size.approximateHeight})" }
}
}
}
}
fun <T> form(key: FormSelector<T>): FormRenderer<T> {
val options = formCandidates(key).filter { it.matches(this, key) }.sortedByDescending { it.priority(this, key) }.map { it.form(this, key) }.toList()
if (!key.withPicker) return options.first()
return FormRenderer(this, null, key, size = options.first().size, handlesField = options.first().handlesField) { field, writable ->
val selected = Property(options.first())
row {
// spacing = 0.px
expanding - stack {
reactive {
val sel = selected()
clearChildren()
sel.render(this@stack, field, writable)
}
}
sizeConstraints(width = 0.75.rem, height = 0.75.rem) - SubtextSemantic.onNext - atTopEnd - select {
spacing = 0.px
bind(selected, Constant(options)) { (it.generator?.name ?: "-") + " (${it.generator?.priority(this@FormModule, key)}, ${it.size.approximateWidth} x ${it.size.approximateHeight})" }
}
}
}
}
operator fun plusAssign(generator: FormRenderer.Generator) {
generator.annotation?.let { form_annotation.getOrPut(it) { ArrayList() }.add(generator) }
?: generator.type?.let { form_type.getOrPut(it) { ArrayList() }.add(generator) }
?: generator.kind?.let { form_kind.getOrPut(it) { ArrayList() }.add(generator) }
?: form_others.add(generator)
}
operator fun plusAssign(generator: ViewRenderer.Generator) {
generator.annotation?.let { view_annotation.getOrPut(it) { ArrayList() }.add(generator) }
?: generator.type?.let { view_type.getOrPut(it) { ArrayList() }.add(generator) }
?: generator.kind?.let { view_kind.getOrPut(it) { ArrayList() }.add(generator) }
?: view_others.add(generator)
}
init {
defaults()
}
}
| 0 |
Kotlin
|
0
| 0 |
90fea07a46182af99f17072bcf42d9d689722450
| 5,801 |
lightning-server-kiteui
|
Apache License 2.0
|
godotopenxrmeta/src/main/java/org/godotengine/openxr/vendors/meta/GodotOpenXRMeta.kt
|
GodotVR
| 538,513,308 | false |
{"C++": 189136, "C": 153472, "CMake": 10580, "Shell": 8518, "Python": 1208}
|
/**************************************************************************/
/* GodotOpenXRMeta.kt */
/**************************************************************************/
/* This file is part of: */
/* GODOT XR */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2022-present Godot XR contributors (see CONTRIBUTORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
package org.godotengine.openxr.vendors.meta
import android.app.Activity
import android.util.Log
import android.view.View
import org.godotengine.godot.Godot
import org.godotengine.godot.plugin.GodotPlugin
import org.godotengine.godot.utils.PermissionsUtil
/**
* Godot plugin for the Meta OpenXR loader.
*/
class GodotOpenXRMeta(godot: Godot?) : GodotPlugin(godot) {
companion object {
private val TAG = GodotOpenXRMeta::class.java.simpleName
private const val EYE_TRACKING_PERMISSION = "com.oculus.permission.EYE_TRACKING"
private const val FACE_TRACKING_PERMISSION = "com.oculus.permission.FACE_TRACKING"
private const val SCENE_PERMISSION = "com.oculus.permission.USE_SCENE"
init {
try {
Log.v(TAG, "Loading godotopenxrvendors library")
System.loadLibrary("godotopenxrvendors")
} catch (e: UnsatisfiedLinkError) {
Log.e(TAG, "Unable to load godotopenxrvendors shared library")
}
}
}
override fun getPluginName(): String {
return "GodotOpenXRMeta"
}
override fun getPluginGDExtensionLibrariesPaths() = setOf("res://addons/godotopenxrvendors/plugin.gdextension")
override fun onMainCreate(activity: Activity): View? {
// Request the eye tracking permission if it's included in the manifest
if (PermissionsUtil.hasManifestPermission(activity, EYE_TRACKING_PERMISSION)) {
Log.d(TAG, "Requesting permission '${EYE_TRACKING_PERMISSION}'")
PermissionsUtil.requestPermission(EYE_TRACKING_PERMISSION, activity)
}
// Request the face tracking permission if it's included in the manifest
if (PermissionsUtil.hasManifestPermission(activity, FACE_TRACKING_PERMISSION)) {
Log.d(TAG, "Requesting permission '${FACE_TRACKING_PERMISSION}'")
PermissionsUtil.requestPermission(FACE_TRACKING_PERMISSION, activity)
}
// Request the scene API permission if it's included in the manifest
if (PermissionsUtil.hasManifestPermission(activity, SCENE_PERMISSION)) {
Log.d(TAG, "Requesting permission '${SCENE_PERMISSION}'")
PermissionsUtil.requestPermission(SCENE_PERMISSION, activity)
}
return null
}
override fun supportsFeature(featureTag: String): Boolean {
if ("PERMISSION_XR_EXT_eye_gaze_interaction" == featureTag) {
val grantedPermissions = godot?.getGrantedPermissions()
if (grantedPermissions != null) {
for (permission in grantedPermissions) {
if (EYE_TRACKING_PERMISSION == permission) {
return true
}
}
}
}
return false
}
}
| 17 |
C++
|
14
| 56 |
75fc3e9292ce27368d2d3f144db5fb4bb76f0df5
| 4,961 |
godot_openxr_vendors
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/BookSection.kt
|
localhostov
| 808,861,591 | false |
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.BookSection: ImageVector
get() {
if (_bookSection != null) {
return _bookSection!!
}
_bookSection = Builder(name = "BookSection", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(5.0f, 18.0f)
lineTo(22.0f, 18.0f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 2.76f, -2.24f, 5.0f, -5.0f, 5.0f)
lineTo(5.0f, 24.0f)
curveToRelative(-1.66f, 0.0f, -3.0f, -1.34f, -3.0f, -3.0f)
reflectiveCurveToRelative(1.34f, -3.0f, 3.0f, -3.0f)
close()
moveTo(5.0f, 16.0f)
horizontalLineToRelative(1.0f)
lineTo(6.0f, 0.1f)
curveTo(3.67f, 0.58f, 2.0f, 2.62f, 2.0f, 5.0f)
verticalLineToRelative(12.02f)
curveToRelative(0.7f, -0.53f, 1.53f, -0.86f, 2.4f, -0.96f)
curveToRelative(0.2f, -0.04f, 0.4f, -0.06f, 0.6f, -0.06f)
close()
moveTo(16.0f, 9.0f)
curveToRelative(0.55f, 0.0f, 1.0f, -0.45f, 1.0f, -1.0f)
reflectiveCurveToRelative(-0.45f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-2.0f)
curveToRelative(-0.55f, 0.0f, -1.0f, 0.45f, -1.0f, 1.0f)
reflectiveCurveToRelative(0.45f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(2.0f)
close()
moveTo(22.0f, 5.0f)
verticalLineToRelative(11.0f)
lineTo(8.0f, 16.0f)
lineTo(8.0f, 0.0f)
horizontalLineToRelative(9.0f)
curveToRelative(2.76f, 0.0f, 5.0f, 2.24f, 5.0f, 5.0f)
close()
moveTo(19.0f, 8.0f)
curveToRelative(0.0f, -1.65f, -1.35f, -3.0f, -3.0f, -3.0f)
horizontalLineToRelative(-1.5f)
curveToRelative(-0.28f, 0.0f, -0.5f, -0.22f, -0.5f, -0.5f)
reflectiveCurveToRelative(0.22f, -0.5f, 0.5f, -0.5f)
horizontalLineToRelative(1.5f)
curveToRelative(0.55f, 0.0f, 1.0f, -0.45f, 1.0f, -1.0f)
reflectiveCurveToRelative(-0.45f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-1.5f)
curveToRelative(-1.38f, 0.0f, -2.5f, 1.12f, -2.5f, 2.5f)
curveToRelative(0.0f, 0.39f, 0.09f, 0.75f, 0.25f, 1.07f)
curveToRelative(-0.75f, 0.55f, -1.25f, 1.43f, -1.25f, 2.43f)
curveToRelative(0.0f, 1.65f, 1.35f, 3.0f, 3.0f, 3.0f)
horizontalLineToRelative(1.5f)
curveToRelative(0.28f, 0.0f, 0.5f, 0.22f, 0.5f, 0.5f)
reflectiveCurveToRelative(-0.22f, 0.5f, -0.5f, 0.5f)
horizontalLineToRelative(-1.5f)
curveToRelative(-0.55f, 0.0f, -1.0f, 0.45f, -1.0f, 1.0f)
reflectiveCurveToRelative(0.45f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(1.5f)
curveToRelative(1.38f, 0.0f, 2.5f, -1.12f, 2.5f, -2.5f)
curveToRelative(0.0f, -0.39f, -0.09f, -0.75f, -0.25f, -1.07f)
curveToRelative(0.75f, -0.55f, 1.25f, -1.43f, 1.25f, -2.43f)
close()
}
}
.build()
return _bookSection!!
}
private var _bookSection: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,262 |
icons
|
MIT License
|
src/main/kotlin/com/exactpro/th2/check1/rule/sequence/SilenceCheckTask.kt
|
th2-net
| 314,775,556 | false |
{"Kotlin": 339579, "Java": 47826, "Dockerfile": 293}
|
/*
* Copyright 2021-2023 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.th2.check1.rule.sequence
import com.exactpro.th2.check1.SessionKey
import com.exactpro.th2.check1.StreamContainer
import com.exactpro.th2.check1.entities.RuleConfiguration
import com.exactpro.th2.check1.grpc.PreFilter
import com.exactpro.th2.check1.rule.AbstractCheckTask
import com.exactpro.th2.check1.rule.MessageContainer
import com.exactpro.th2.check1.rule.SailfishFilter
import com.exactpro.th2.check1.rule.preFilterBy
import com.exactpro.th2.check1.util.VerificationUtil
import com.exactpro.th2.check1.utils.toRootMessageFilter
import com.exactpro.th2.common.event.Event
import com.exactpro.th2.common.event.EventUtils.createMessageBean
import com.exactpro.th2.common.grpc.EventBatch
import com.exactpro.th2.common.grpc.EventID
import com.exactpro.th2.common.grpc.EventStatus
import com.exactpro.th2.common.grpc.RootMessageFilter
import com.exactpro.th2.common.message.toReadableBodyCollection
import com.exactpro.th2.common.schema.message.MessageRouter
import io.reactivex.Observable
import java.time.Instant
import java.util.concurrent.atomic.AtomicBoolean
class SilenceCheckTask(
ruleConfiguration: RuleConfiguration,
protoPreFilter: PreFilter,
submitTime: Instant,
sessionKey: SessionKey,
parentEventID: EventID,
messageStream: Observable<StreamContainer>,
eventBatchRouter: MessageRouter<EventBatch>,
onTaskFinished: ((EventStatus) -> Unit) = EMPTY_STATUS_CONSUMER
) : AbstractCheckTask(ruleConfiguration, submitTime, sessionKey, parentEventID, messageStream, eventBatchRouter) {
protected class Refs(
rootEvent: Event,
onTaskFinished: ((EventStatus) -> Unit),
val protoPreMessageFilter: RootMessageFilter,
val messagePreFilter: SailfishFilter,
val metadataPreFilter: SailfishFilter?
) : AbstractCheckTask.Refs(rootEvent, onTaskFinished) {
val preFilterEvent: Event by lazy {
Event.start()
.type("preFiltering")
.bodyData(protoPreMessageFilter.toReadableBodyCollection())
}
val resultEvent: Event by lazy {
Event.start()
.type("noMessagesCheckResult")
}
}
override val refsKeeper = RefsKeeper(protoPreFilter.toRootMessageFilter().let { protoPreMessageFilter ->
Refs(
rootEvent = createRootEvent(),
onTaskFinished = onTaskFinished,
protoPreMessageFilter = protoPreMessageFilter,
messagePreFilter = SailfishFilter(
PROTO_CONVERTER.fromProtoPreFilter(protoPreMessageFilter),
protoPreMessageFilter.toCompareSettings()
),
metadataPreFilter = protoPreMessageFilter.metadataFilterOrNull()?.let {
SailfishFilter(
PROTO_CONVERTER.fromMetadataFilter(it, VerificationUtil.METADATA_MESSAGE_NAME),
it.toComparisonSettings()
)
}
)
})
private val refs get() = refsKeeper.refs
private var extraMessagesCounter: Int = 0
private val isCanceled = AtomicBoolean()
override fun onStartInit() {
val hasNextTask = hasNextTask()
if (isParentCompleted == false || hasNextTask) {
if (hasNextTask) {
LOGGER.info("Has subscribed task. Skip checking extra messages")
} else {
LOGGER.info("Parent task was not finished normally. Skip checking extra messages")
}
cancel()
return
}
with(refs) {
rootEvent.addSubEvent(preFilterEvent)
rootEvent.addSubEvent(resultEvent)
}
}
override fun onChainedTaskSubscription() {
if (started) { // because we cannot cancel task before it is actually started
cancel()
} else {
if (LOGGER.isInfoEnabled) {
LOGGER.info("The ${type()} task '$description' will be automatically canceled when it begins")
}
}
}
override val errorEventOnTimeout: Boolean
get() = false
override fun name(): String = "AutoSilenceCheck"
override fun type(): String = "AutoSilenceCheck"
override fun setup(rootEvent: Event) {
rootEvent.bodyData(createMessageBean("AutoSilenceCheck for session ${sessionKey.run { "$bookName $sessionAlias ($direction)" }}"))
}
override fun Observable<MessageContainer>.taskPipeline(): Observable<MessageContainer> =
preFilterBy(
this,
refs.protoPreMessageFilter,
refs.messagePreFilter,
refs.metadataPreFilter,
LOGGER
) { preFilterContainer -> // Update pre-filter state
with(preFilterContainer) {
refs.preFilterEvent.appendEventsWithVerification(preFilterContainer)
refs.preFilterEvent.messageID(holderActual.id)
}
}
override fun onNext(container: MessageContainer) {
container.messageHolder.apply {
extraMessagesCounter++
refs.resultEvent.messageID(id)
}
}
override fun completeEvent(taskState: State) {
if (skipPublication) {
return
}
refs.preFilterEvent.name("Prefilter: $extraMessagesCounter messages were filtered.")
if (extraMessagesCounter == 0) {
refs.resultEvent.status(Event.Status.PASSED).name("Check passed")
} else {
refs.resultEvent.status(Event.Status.FAILED)
.name("Check failed: $extraMessagesCounter extra messages were found.")
}
}
override val skipPublication: Boolean
get() = isCanceled.get()
private fun cancel() {
if (isCanceled.compareAndSet(false, true)) {
checkComplete()
} else {
LOGGER.debug("Task {} '{}' already canceled", type(), description)
}
}
}
| 5 |
Kotlin
|
2
| 1 |
b0c52b42dc2deeb31c58ac256ee48fa81b1d1487
| 6,527 |
th2-check1
|
Apache License 2.0
|
src/main/kotlin/no/nav/tilleggsstonader/sak/opplysninger/grunnlag/GrunnlagsdataBarn.kt
|
navikt
| 685,490,225 | false |
{"Kotlin": 1601009, "HTML": 39172, "Gherkin": 39138, "Shell": 924, "Dockerfile": 164}
|
package no.nav.tilleggsstonader.sak.opplysninger.grunnlag
import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.Navn
import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.PdlPersonForelderBarn
import no.nav.tilleggsstonader.sak.opplysninger.pdl.dto.gjeldende
import no.nav.tilleggsstonader.sak.util.antallÅrSiden
import java.time.LocalDate
data class GrunnlagsdataBarn(
val ident: String,
val navn: Navn,
val alder: Int?,
val dødsdato: LocalDate?,
)
fun Map<String, PdlPersonForelderBarn>.tilGrunnlagsdataBarn() = entries.map { (ident, barn) ->
GrunnlagsdataBarn(
ident = ident,
navn = barn.navn.gjeldende(),
alder = antallÅrSiden(barn.fødsel.gjeldende().fødselsdato),
dødsdato = barn.dødsfall.gjeldende()?.dødsdato,
)
}
| 3 |
Kotlin
|
1
| 0 |
dec60a5cdfb6162ad60c904d698883b08ce56c47
| 784 |
tilleggsstonader-sak
|
MIT License
|
app/src/main/kotlin/zenith/util/UNum.kt
|
DavidMacDonald11
| 674,797,283 | false | null |
package zenith
private val maxUByte = UByte.MAX_VALUE.toUInt()
private val maxUShort = UShort.MAX_VALUE.toUInt()
sealed interface UNum {
class UByte(val n: kotlin.UByte): UNum
class UShort(val n: kotlin.UShort): UNum
class UInt(val n: kotlin.UInt): UNum
fun toUInt() = when(this) {
is UByte -> this.n.toUInt()
is UShort -> this.n.toUInt()
is UInt -> this.n
}
operator fun plus(n: UNum) = new(toUInt() + n.toUInt())
operator fun plus(n: Int) = new(toUInt() + n.toUInt())
companion object {
fun new(n: kotlin.UInt) = when {
n <= maxUByte -> UByte(n.toUByte())
n <= maxUShort -> UShort(n.toUShort())
else -> UInt(n)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
92c4ff5c7270db1e39c48f82d22d902ffe60011f
| 736 |
Zenith-Compiler
|
MIT License
|
core/src/main/java/com/lumiwallet/android/core/bitcoinCash/transaction/Input.kt
|
lumiwallet
| 255,998,575 | false | null |
package com.lumiwallet.android.core.bitcoinCash.transaction
import com.lumiwallet.android.core.bitcoinCash.script.ScriptType
import com.lumiwallet.android.core.utils.btc_based.ErrorMessages
import com.lumiwallet.android.core.utils.btc_based.ValidationUtils.isHexString
import com.lumiwallet.android.core.utils.btc_based.ValidationUtils.isTransactionId
import com.lumiwallet.android.core.utils.btc_based.core.PrivateKey
import com.lumiwallet.android.core.utils.btc_based.types.OpSize
import com.lumiwallet.android.core.utils.btc_based.types.UInt
import com.lumiwallet.android.core.utils.btc_based.types.VarInt
import com.lumiwallet.android.core.utils.hex
import com.lumiwallet.android.core.utils.safeToByteArray
internal class Input(
val transaction: String,
val index: Int,
val lock: String,
val satoshi: Long,
val privateKey: PrivateKey
) {
companion object {
private val SEQUENCE = UInt.of(-0x1)
}
val transactionHash: ByteArray
get() = transaction.safeToByteArray()
val sequence: UInt
get() = SEQUENCE
init {
validateInputData(transaction, index, lock, satoshi)
}
fun fillTransaction(sigHash: ByteArray, transaction: Transaction) {
transaction.addHeader(" Input")
val unlocking = ScriptSigProducer.produceScriptSig(sigHash, privateKey)
transaction.addData(" Transaction out", transactionHash.hex)
transaction.addData(" Tout index", UInt.of(index).toString())
transaction.addData(
" Unlock length",
VarInt.of(unlocking.size.toLong()).asLitEndBytes().hex
)
transaction.addData(" Unlock", unlocking.hex)
transaction.addData(" Sequence", SEQUENCE.toString())
}
override fun toString(): String = "$transaction $index $lock $satoshi"
private fun validateInputData(
transaction: String,
index: Int,
lock: String,
satoshi: Long
) {
validateTransactionId(transaction)
validateOutputIndex(index)
validateLockingScript(lock)
validateAmount(satoshi)
}
private fun validateTransactionId(transaction: String) {
require(transaction.isNotEmpty()) { ErrorMessages.INPUT_TRANSACTION_EMPTY }
require(isTransactionId(transaction)) { ErrorMessages.INPUT_TRANSACTION_NOT_64_HEX }
}
private fun validateOutputIndex(index: Int) {
require(index >= 0) { ErrorMessages.INPUT_INDEX_NEGATIVE }
}
private fun validateLockingScript(lock: String) {
require(lock.isNotEmpty()) { ErrorMessages.INPUT_LOCK_EMPTY }
require(isHexString(lock)) { ErrorMessages.INPUT_LOCK_NOT_HEX }
when (ScriptType.forLock(lock)) {
ScriptType.P2PKH -> {
val lockBytes = lock.safeToByteArray()
val pubKeyHashSize = OpSize.ofByte(lockBytes[2])
require(pubKeyHashSize.toInt() == lockBytes.size - 5) {
String.format(
ErrorMessages.INPUT_WRONG_PKH_SIZE, lock
)
}
}
else -> throw IllegalArgumentException("Provided locking script is not P2PKH[$lock]")
}
}
private fun validateAmount(satoshi: Long) {
require(satoshi > 0) { ErrorMessages.INPUT_AMOUNT_NOT_POSITIVE }
}
}
| 0 |
Kotlin
|
1
| 4 |
f4ba3bf7b4cd934f25b5b0271e1170aae496b4e5
| 3,366 |
lumi-android-core
|
Apache License 2.0
|
src/main/kotlin/com/sourcegraph/cody/chat/actions/SmellCommand.kt
|
sourcegraph
| 702,947,607 | false |
{"Kotlin": 690009, "Java": 152855, "TypeScript": 5588, "Shell": 4631, "Nix": 1122, "JavaScript": 436, "HTML": 294}
|
package com.sourcegraph.cody.chat.actions
import com.sourcegraph.cody.commands.CommandId
class SmellCommand : BaseCommandAction() {
override val myCommandId = CommandId.Smell
}
| 358 |
Kotlin
|
22
| 67 |
437e3e2e53ae85edb7e445b2a0d412fbb7a54db0
| 182 |
jetbrains
|
Apache License 2.0
|
src/main/kotlin/org/jglrxavpok/kameboy/ui/Joystick.kt
|
jglrxavpok
| 123,712,183 | false | null |
package org.jglrxavpok.kameboy.ui
import org.lwjgl.glfw.GLFW.*
import java.nio.ByteBuffer
import java.nio.FloatBuffer
class Joystick(val id: Int) {
val name: String
get() = glfwGetJoystickName(id)!!
var hats: ByteBuffer = ByteBuffer.allocate(0)
internal set
var axes: FloatBuffer = FloatBuffer.allocate(0)
internal set
var buttons: ByteBuffer = ByteBuffer.allocate(0)
internal set
var connected: Boolean = false
internal set
private var previousHats: ByteBuffer = ByteBuffer.allocate(0)
private var previousAxes: FloatBuffer = FloatBuffer.allocate(0)
private var previousButtons: ByteBuffer = ByteBuffer.allocate(0)
fun button(index: Int): Boolean = buttons[index].toInt() == GLFW_PRESS
fun axis(index: Int): Float = axes[index]
fun hat(index: Int): Byte = hats[index]
fun savePreviousState() {
if(previousHats.capacity() < hats.capacity())
previousHats = ByteBuffer.allocate(hats.capacity())
if(previousAxes.capacity() < axes.capacity())
previousAxes = FloatBuffer.allocate(axes.capacity())
if(previousButtons.capacity() < buttons.capacity())
previousButtons = ByteBuffer.allocate(buttons.capacity())
for(i in 0 until buttons.capacity())
previousButtons.put(i, buttons[i])
for(i in 0 until hats.capacity())
previousHats.put(i, hats[i])
for(i in 0 until axes.capacity())
previousAxes.put(i, axes[i])
}
fun findFirstIntersection(): Pair<Int, Component>? {
val buttonID = (0 until previousButtons.capacity()).firstOrNull { previousButtons[it] != buttons[it] }
if(buttonID != null) return updateState(buttonID to Component.BUTTON)
val hatID = (0 until previousHats.capacity()).firstOrNull { previousHats[it] != hats[it] }
if(hatID != null) return updateState(hatID to Component.HAT)
val axisID = (0 until previousAxes.capacity()).firstOrNull { previousAxes[it] != axes[it] }
if(axisID != null) return updateState(axisID to Component.AXIS)
return null
}
private fun updateState(pair: Pair<Int, Component>): Pair<Int, Component> {
when(pair.second) {
Component.BUTTON -> previousButtons.put(pair.first, buttons[pair.first])
Component.AXIS -> previousAxes.put(pair.first, axes[pair.first])
Component.HAT -> previousHats.put(pair.first, hats[pair.first])
}
return pair
}
enum class Component {
HAT, AXIS, BUTTON
}
}
| 0 |
Kotlin
|
0
| 3 |
a07f8a8b402176cb00809377238c19a07039a177
| 2,582 |
KameBoy
|
MIT License
|
app/src/main/java/com/vultisig/wallet/presenter/common/UiEvent.kt
|
vultisig
| 789,965,982 | false |
{"Kotlin": 1403983, "Ruby": 1713}
|
package com.vultisig.wallet.presenter.common
import com.vultisig.wallet.ui.navigation.Screen
sealed class UiEvent {
data object PopBackStack : UiEvent()
data class NavigateTo(val screen: Screen) : UiEvent()
data class ScrollToNextPage(val screen: Screen) : UiEvent()
}
| 44 |
Kotlin
|
2
| 6 |
25c5824a4ff8b62077d1ee3e3f5ceab82757a583
| 282 |
vultisig-android
|
Apache License 2.0
|
wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/CardScreenshotTest.kt
|
androidx
| 256,589,781 | false |
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material3
import android.os.Build
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.testutils.assertAgainstGolden
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.unit.LayoutDirection
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import androidx.test.screenshot.AndroidXScreenshotTestRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestName
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
class CardScreenshotTest {
@get:Rule val rule = createComposeRule()
@get:Rule val screenshotRule = AndroidXScreenshotTestRule(SCREENSHOT_GOLDEN_PATH)
@get:Rule val testName = TestName()
@Test fun card_ltr() = verifyScreenshot(layoutDirection = LayoutDirection.Ltr) { TestCard() }
@Test
fun card_disabled() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) { TestCard(enabled = false) }
@Test fun card_rtl() = verifyScreenshot(layoutDirection = LayoutDirection.Rtl) { TestCard() }
@Test
fun card_image_background() = verifyScreenshot {
TestCard(
colors =
CardDefaults.imageCardColors(
containerPainter =
CardDefaults.imageWithScrimBackgroundPainter(
backgroundImagePainter =
painterResource(
id =
androidx.wear.compose.material3.test.R.drawable
.backgroundimage1
),
forcedSize = Size.Unspecified
)
),
contentPadding = CardDefaults.ImageContentPadding,
)
}
@Test
fun card_image_background_with_intrinsic_size() = verifyScreenshot {
TestCard(
colors =
CardDefaults.imageCardColors(
containerPainter =
CardDefaults.imageWithScrimBackgroundPainter(
backgroundImagePainter =
painterResource(
id =
androidx.wear.compose.material3.test.R.drawable
.backgroundimage1
),
forcedSize = null
),
),
contentPadding = CardDefaults.ImageContentPadding,
)
}
@Test
fun outlined_card_ltr() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) { TestOutlinedCard() }
@Test
fun outlined_card_disabled() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) {
TestOutlinedCard(enabled = false)
}
@Test
fun outlined_card_rtl() =
verifyScreenshot(layoutDirection = LayoutDirection.Rtl) { TestOutlinedCard() }
@Test
fun app_card_ltr() = verifyScreenshot(layoutDirection = LayoutDirection.Ltr) { TestAppCard() }
@Test
fun app_card_disabled() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) { TestAppCard(enabled = false) }
@Test
fun app_card_rtl() = verifyScreenshot(layoutDirection = LayoutDirection.Rtl) { TestAppCard() }
@Test
fun title_card_ltr() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) { TestTitleCard() }
@Test
fun title_card_disabled() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) { TestTitleCard(enabled = false) }
@Test
fun title_card_rtl() =
verifyScreenshot(layoutDirection = LayoutDirection.Rtl) { TestTitleCard() }
@Test
fun title_card_with_time_and_subtitle_ltr() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) {
TestTitleCardWithTimeAndSubtitle()
}
@Test
fun title_card_without_time_and_with_subtitle_ltr() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) {
TitleCard(
enabled = true,
onClick = {},
title = { Text("TitleCard") },
subtitle = { Text("Subtitle") },
modifier = Modifier.testTag(TEST_TAG),
)
}
@Test
fun title_card_with_time_and_subtitle_disabled() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) {
TestTitleCardWithTimeAndSubtitle(enabled = false)
}
@Test
fun title_card_with_time_and_subtitle_rtl() =
verifyScreenshot(layoutDirection = LayoutDirection.Rtl) {
TestTitleCardWithTimeAndSubtitle()
}
@Test
fun title_card_with_content_time_and_subtitle_ltr() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) {
TestTitleCardWithContentTimeAndSubtitle()
}
@Test
fun title_card_with_content_time_and_subtitle_disabled() =
verifyScreenshot(layoutDirection = LayoutDirection.Ltr) {
TestTitleCardWithContentTimeAndSubtitle(enabled = false)
}
@Test
fun title_card_with_content_time_and_subtitle_rtl() =
verifyScreenshot(layoutDirection = LayoutDirection.Rtl) {
TestTitleCardWithContentTimeAndSubtitle()
}
@Test
fun title_card_image_background() = verifyScreenshot {
TestTitleCard(
colors =
CardDefaults.imageCardColors(
containerPainter =
CardDefaults.imageWithScrimBackgroundPainter(
backgroundImagePainter =
painterResource(
id =
androidx.wear.compose.material3.test.R.drawable
.backgroundimage1
),
)
),
contentPadding = CardDefaults.ImageContentPadding,
)
}
@Composable
private fun TestCard(
enabled: Boolean = true,
colors: CardColors = CardDefaults.cardColors(),
contentPadding: PaddingValues = CardDefaults.ContentPadding
) {
Card(
enabled = enabled,
onClick = {},
colors = colors,
contentPadding = contentPadding,
modifier = Modifier.testTag(TEST_TAG).width(IntrinsicSize.Max),
) {
Text("Card: Some body content")
}
}
@Composable
private fun TestOutlinedCard(
enabled: Boolean = true,
) {
OutlinedCard(
enabled = enabled,
onClick = {},
modifier = Modifier.testTag(TEST_TAG).width(IntrinsicSize.Max),
) {
Text("Outlined Card: Some body content")
}
}
@Composable
private fun TestAppCard(
enabled: Boolean = true,
colors: CardColors = CardDefaults.cardColors()
) {
AppCard(
enabled = enabled,
onClick = {},
appName = { Text("AppName") },
appImage = { TestIcon() },
title = { Text("AppCard") },
colors = colors,
time = { Text("now") },
modifier = Modifier.testTag(TEST_TAG).width(IntrinsicSize.Max),
) {
Text("Some body content and some more body content")
}
}
@Composable
private fun TestTitleCard(
enabled: Boolean = true,
contentPadding: PaddingValues = CardDefaults.ContentPadding,
colors: CardColors = CardDefaults.cardColors()
) {
TitleCard(
enabled = enabled,
onClick = {},
title = { Text("TitleCard") },
time = { Text("now") },
colors = colors,
contentPadding = contentPadding,
modifier = Modifier.testTag(TEST_TAG).width(IntrinsicSize.Max),
) {
Text("Some body content and some more body content")
}
}
@Composable
private fun TestTitleCardWithTimeAndSubtitle(enabled: Boolean = true) {
TitleCard(
enabled = enabled,
onClick = {},
time = { Text("XXm") },
title = { Text("TitleCard") },
subtitle = { Text("Subtitle") },
modifier = Modifier.testTag(TEST_TAG),
)
}
@Composable
private fun TestTitleCardWithContentTimeAndSubtitle(enabled: Boolean = true) {
TitleCard(
enabled = enabled,
onClick = {},
time = { Text("XXm") },
title = { Text("TitleCard") },
subtitle = { Text("Subtitle") },
modifier = Modifier.testTag(TEST_TAG),
) {
Text("Card content")
}
}
private fun verifyScreenshot(
layoutDirection: LayoutDirection = LayoutDirection.Ltr,
content: @Composable () -> Unit
) {
rule.setContentWithTheme {
CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) { content() }
}
rule
.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertAgainstGolden(screenshotRule, testName.methodName)
}
}
| 30 |
Kotlin
|
974
| 5,321 |
98b929d303f34d569e9fd8a529f022d398d1024b
| 10,598 |
androidx
|
Apache License 2.0
|
protocol/notify/src/main/kotlin/com/reown/notify/engine/calls/GetAllActiveSubscriptionsUseCase.kt
|
reown-com
| 851,466,242 | false | null |
@file:JvmSynthetic
package com.reown.notify.engine.calls
import com.reown.android.internal.common.model.AppMetaDataType
import com.reown.android.internal.common.storage.metadata.MetadataStorageRepositoryInterface
import com.reown.notify.common.model.Subscription
import com.reown.notify.data.storage.SubscriptionRepository
internal class GetAllActiveSubscriptionsUseCase(
private val subscriptionRepository: SubscriptionRepository,
private val metadataStorageRepository: MetadataStorageRepositoryInterface,
) {
suspend operator fun invoke(): Map<String, Subscription.Active> =
subscriptionRepository.getAllActiveSubscriptions()
.map { subscription ->
val metadata = metadataStorageRepository.getByTopicAndType(subscription.topic, AppMetaDataType.PEER)
subscription.copy(dappMetaData = metadata)
}
.associateBy { subscription -> subscription.topic.value }
}
| 78 | null |
71
| 8 |
893084b3df91b47daa77f8f964e37f84a02843b1
| 949 |
reown-kotlin
|
Apache License 2.0
|
app/src/main/java/io/github/fate_grand_automata/ui/onboarding/OnboardingItems.kt
|
Fate-Grand-Automata
| 245,391,245 | false |
{"Kotlin": 772663, "Ruby": 714}
|
package io.github.fate_grand_automata.ui.onboarding
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import io.github.fate_grand_automata.BuildConfig
import io.github.fate_grand_automata.R
import io.github.fate_grand_automata.ui.Heading
import io.github.fate_grand_automata.ui.openLinkIntent
import io.github.fate_grand_automata.util.OpenDocTreePersistable
import io.github.fate_grand_automata.util.SupportImageExtractor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
abstract class OnboardingItem(val vm: OnboardingViewModel, val canSkip: Boolean = false) {
abstract fun shouldSkip(): Boolean
@Composable
abstract fun UI(onFinished: () -> Unit)
}
class WelcomeScreen(vm: OnboardingViewModel) : OnboardingItem(vm, true) {
override fun shouldSkip() = false
@Composable
override fun UI(onFinished: () -> Unit) {
Heading(stringResource(R.string.p_welcome))
Text(
text = stringResource(R.string.p_welcome_description),
style = MaterialTheme.typography.bodyLarge
)
}
}
class PickDirectory(vm: OnboardingViewModel) : OnboardingItem(vm) {
override fun shouldSkip(): Boolean {
return vm.prefsCore.dirRoot.get().isNotBlank() && !vm.storageProvider.shouldExtractSupportImages
}
@Composable
override fun UI(onFinished: () -> Unit) {
Heading(text = stringResource(R.string.p_choose_folder_title))
Text(
text = stringResource(R.string.p_choose_folder_message),
style = MaterialTheme.typography.bodyLarge
)
val context = LocalContext.current
val scope = rememberCoroutineScope()
val dirPicker = rememberLauncherForActivityResult(OpenDocTreePersistable()) {
if (it != null) {
vm.storageProvider.setRoot(it)
scope.launch(Dispatchers.IO) {
if (vm.storageProvider.shouldExtractSupportImages) {
scope.launch(Dispatchers.Main) {
// Toast needs to happen in the UI thread
val msg = context.getString(R.string.support_imgs_extracting)
Toast.makeText(context, msg, Toast.LENGTH_LONG).show()
}
SupportImageExtractor(context, vm.storageProvider).extract()
}
onFinished()
}
}
}
OutlinedButton(
onClick = { dirPicker.launch(Uri.EMPTY) },
modifier = Modifier.padding(vertical = 15.dp)
) {
Text(
text = stringResource(R.string.p_choose_folder_action),
style = MaterialTheme.typography.bodyLarge
)
}
}
}
class DisableBatteryOptimization(vm: OnboardingViewModel) : OnboardingItem(vm) {
override fun shouldSkip(): Boolean =
vm.powerManager.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID)
@Composable
override fun UI(onFinished: () -> Unit) {
Heading(text = stringResource(R.string.p_battery_optimization))
Text(
text = stringResource(R.string.p_battery_optimization_description),
style = MaterialTheme.typography.bodyLarge
)
val context = LocalContext.current
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
onFinished()
}
OutlinedButton(
onClick = {
val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
launcher.launch(intent)
},
modifier = Modifier.padding(vertical = 15.dp)
) {
Text(
text = stringResource(R.string.p_battery_optimization_action),
style = MaterialTheme.typography.bodyLarge
)
}
HighlightedText(
text = String.format(
stringResource(R.string.p_battery_optimization_dontkillmyapp),
stringResource(R.string.link_dontkillmyapp)
),
highlights = listOf(
Highlight(
text = "dontkillmyapp.com",
data = stringResource(R.string.link_dontkillmyapp),
onClick = { link ->
context.openLinkIntent(link)
}
)
),
style = MaterialTheme.typography.bodyLarge
)
}
}
class YoutubeVideo(vm: OnboardingViewModel) : OnboardingItem(vm, true) {
override fun shouldSkip(): Boolean {
// only show on first installation
return vm.prefsCore.onboardingCompletedVersion.get() > 0
}
@Composable
override fun UI(onFinished: () -> Unit) {
Heading(text = stringResource(R.string.p_youtube_guide))
Text(
text = stringResource(R.string.p_youtube_guide_description),
style = MaterialTheme.typography.bodyLarge
)
val context = LocalContext.current
OutlinedButton(
onClick = {
context.openLinkIntent(R.string.link_youtube)
},
modifier = Modifier.padding(vertical = 15.dp)
) {
Text(
text = stringResource(R.string.p_youtube_guide_action),
style = MaterialTheme.typography.bodyLarge
)
}
}
}
| 144 |
Kotlin
|
246
| 1,242 |
6091568f27f2544f605e563e5bdbbcc4873def3e
| 6,112 |
FGA
|
MIT License
|
extension/result/src/main/kotlin/cn/netdiscovery/http/extension/result/ProcessResult+Extension.kt
|
fengzhizi715
| 294,738,243 | false | null |
package cn.netdiscovery.http.extension.result
import cn.netdiscovery.http.core.ProcessResult
import cn.netdiscovery.result.Result
import cn.netdiscovery.result.resultFrom
/**
*
* @FileName:
* cn.netdiscovery.http.extension.result.`ProcessResult+Extension`
* @author: <NAME>
* @date: 2020-12-11 11:54
* @version: V1.0 <描述当前版本功能>
*/
fun <T> ProcessResult<out Any>.asResult():Result<T,Exception> = resultFrom {
async().get() as T
}
| 0 |
Kotlin
|
0
| 8 |
7bd08bbfec9890e10c8620c1d74d46a05de56513
| 450 |
okhttp-extension
|
Apache License 2.0
|
app/src/main/java/de/schnettler/scrobbler/screens/details/TrackDetails.kt
|
tchigher
| 298,243,088 | true |
{"Kotlin": 347370}
|
package de.schnettler.scrobbler.screens.details
import androidx.compose.foundation.Icon
import androidx.compose.foundation.ScrollableColumn
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.Stack
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Favorite
import androidx.compose.material.icons.rounded.FavoriteBorder
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import de.schnettler.database.models.EntityWithStatsAndInfo.TrackWithStatsAndInfo
import de.schnettler.scrobbler.UIAction
import de.schnettler.scrobbler.components.ExpandingInfoCard
import de.schnettler.scrobbler.components.ListeningStats
import de.schnettler.scrobbler.screens.AlbumCategory
import de.schnettler.scrobbler.screens.TagCategory
import de.schnettler.scrobbler.util.navigationBarsHeightPlus
import de.schnettler.scrobbler.util.navigationBarsPadding
import de.schnettler.scrobbler.util.statusBarsHeight
@Composable
fun TrackDetailScreen(
trackDetails: TrackWithStatsAndInfo,
actionHandler: (UIAction) -> Unit,
modifier: Modifier = Modifier,
) {
val (track, stats, info, album) = trackDetails
Stack(modifier.fillMaxSize()) {
ScrollableColumn(children = {
Spacer(modifier = Modifier.statusBarsHeight())
AlbumCategory(
album = album,
artistPlaceholder = track.artist,
actionHandler = actionHandler
)
ExpandingInfoCard(info = info?.wiki)
ListeningStats(item = stats)
if (info?.tags?.isNotEmpty() == true) {
TagCategory(tags = info.tags, actionHandler = actionHandler)
}
Spacer(modifier = Modifier.navigationBarsHeightPlus(8.dp))
})
info?.let {
FloatingActionButton(
onClick = {
actionHandler(UIAction.TrackLiked(track, info.copy(loved = !info.loved)))
},
Modifier.gravity(Alignment.BottomEnd).padding(end = 16.dp, bottom = 16.dp).navigationBarsPadding()
) {
if (info.loved) {
Icon(asset = Icons.Rounded.Favorite)
} else {
Icon(asset = Icons.Rounded.FavoriteBorder)
}
}
}
}
}
| 0 | null |
0
| 0 |
b4a4589d56363cb8ad1f6262c3f79a1e5e4b419a
| 2,601 |
Compose-Scrobbler
|
Apache License 2.0
|
kool-core/src/jsMain/kotlin/de/fabmax/kool/util/SystemClock.kt
|
fabmax
| 81,503,047 | false |
{"Kotlin": 4619123, "HTML": 1451, "JavaScript": 597}
|
package de.fabmax.kool.util
internal actual object SystemClock {
actual fun now(): Double = js("performance.now()") as Double / 1e3
}
| 9 |
Kotlin
|
13
| 210 |
d653679ea98290b42c8cd4a0580f3a67f4eeb07f
| 138 |
kool
|
Apache License 2.0
|
src/main/kotlin/com/kryszak/gwatlin/api/items/GWMaterialsClient.kt
|
Kryszak
| 214,791,260 | false | null |
package com.kryszak.gwatlin.api.items
import com.kryszak.gwatlin.api.ApiLanguage
import com.kryszak.gwatlin.api.items.model.material.Material
import com.kryszak.gwatlin.clients.items.MaterialsClient
/**
* Client for materials endpoints
* @see com.kryszak.gwatlin.api.exception.ApiRequestException for errors
*/
class GWMaterialsClient {
private val materialsClient: MaterialsClient = MaterialsClient()
/**
* Retrieves all material ids
*/
fun getMaterialIds(): List<Int> {
return materialsClient.getMaterialIds()
}
/**
* Retrieves specific materials
* @param ids od materials
* @param language of returned text (default=en)
* @see com.kryszak.gwatlin.api.items.model.material.Material
*/
@JvmOverloads
fun getMaterials(ids: List<Int>, language: ApiLanguage? = null): List<Material> {
return materialsClient.getMaterials(ids, language)
}
}
| 10 |
Kotlin
|
0
| 3 |
e86b74305df2b4af8deda8c0a5d2929d8110e41d
| 929 |
gwatlin
|
MIT License
|
shared/src/commonMain/kotlin/core/presentation/base/MovaBottomSheet.kt
|
tolgaprm
| 712,824,422 | false |
{"Kotlin": 281188, "Swift": 657, "Shell": 228}
|
package core.presentation.base
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.BottomSheetScaffold
import androidx.compose.material3.BottomSheetScaffoldState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.material3.rememberStandardBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import core.domain.model.movie.Movie
import core.domain.model.tv.TvSeries
import core.presentation.components.InfoBottomSheet
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MovaOptionalInfoBottomSheetScaffold(
modifier: Modifier = Modifier,
sheetPeekHeight: Dp = 0.dp,
sheetContainerColor: Color = MaterialTheme.colorScheme.background,
sheetContentColor: Color = MaterialTheme.colorScheme.onBackground,
scaffoldState: BottomSheetScaffoldState = rememberBottomSheetScaffoldState(
bottomSheetState = rememberStandardBottomSheetState(
skipHiddenState = false
)
),
selectedMovie: Movie? = null,
selectedTvSeries: TvSeries? = null,
isShowInfoBottomSheet: Boolean = selectedMovie != null || selectedTvSeries != null,
onClickCloseBottomSheet: () -> Unit,
onClickedDetails: () -> Unit,
topBar: @Composable (() -> Unit)? = null,
otherSheetContent: @Composable ColumnScope.() -> Unit,
content: @Composable (PaddingValues) -> Unit
) {
BottomSheetScaffold(
modifier = modifier,
scaffoldState = scaffoldState,
sheetContent = {
if (isShowInfoBottomSheet) {
InfoBottomSheet(
modifier = Modifier.fillMaxWidth(),
selectedMovie = selectedMovie,
selectedTvSeries = selectedTvSeries,
onClickClose = onClickCloseBottomSheet,
onClickedDetails = onClickedDetails
)
} else {
otherSheetContent()
}
},
sheetPeekHeight = sheetPeekHeight,
topBar = topBar,
sheetContainerColor = sheetContainerColor,
sheetContentColor = sheetContentColor,
content = content
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MovaInfoBottomSheetScaffold(
modifier: Modifier = Modifier,
sheetPeekHeight: Dp = 0.dp,
sheetContainerColor: Color = MaterialTheme.colorScheme.background,
sheetContentColor: Color = MaterialTheme.colorScheme.onBackground,
scaffoldState: BottomSheetScaffoldState = rememberBottomSheetScaffoldState(
bottomSheetState = rememberStandardBottomSheetState(
skipHiddenState = false
)
),
selectedMovie: Movie? = null,
selectedTvSeries: TvSeries? = null,
onClickCloseBottomSheet: () -> Unit,
onClickedDetails: () -> Unit,
topBar: @Composable (() -> Unit)? = null,
content: @Composable (PaddingValues) -> Unit
) {
BottomSheetScaffold(
modifier = modifier,
scaffoldState = scaffoldState,
sheetContent = {
InfoBottomSheet(
modifier = Modifier.fillMaxWidth(),
selectedMovie = selectedMovie,
selectedTvSeries = selectedTvSeries,
onClickClose = onClickCloseBottomSheet,
onClickedDetails = onClickedDetails
)
},
sheetPeekHeight = sheetPeekHeight,
topBar = topBar,
sheetContainerColor = sheetContainerColor,
sheetContentColor = sheetContentColor,
content = content
)
}
@OptIn(ExperimentalMaterial3Api::class)
fun CoroutineScope.expandBottomSheet(bottomSheetScaffoldState: BottomSheetScaffoldState) {
launch {
bottomSheetScaffoldState.bottomSheetState.expand()
}
}
@OptIn(ExperimentalMaterial3Api::class)
fun CoroutineScope.hideBottomSheet(bottomSheetScaffoldState: BottomSheetScaffoldState) {
launch {
bottomSheetScaffoldState.bottomSheetState.hide()
}
}
| 2 |
Kotlin
|
0
| 0 |
cfcb79b8234b6024b817df7632fc6fb7df8c64e5
| 4,394 |
MovaApp-compose-multiplatform
|
Apache License 2.0
|
kzen-auto-jvm/src/main/kotlin/tech/kzen/auto/server/api/RestHandler.kt
|
alexoooo
| 131,353,826 | false | null |
package tech.kzen.auto.server.api
import com.google.common.io.MoreFiles
import com.google.common.io.Resources
import kotlinx.coroutines.runBlocking
import org.springframework.core.io.InputStreamResource
import org.springframework.core.io.Resource
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.util.MultiValueMap
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.body
import reactor.core.publisher.Mono
import tech.kzen.auto.common.api.CommonRestApi
import tech.kzen.auto.common.paradigm.common.model.ExecutionRequest
import tech.kzen.auto.common.paradigm.common.model.ExecutionResult
import tech.kzen.auto.common.paradigm.common.v1.model.LogicExecutionId
import tech.kzen.auto.common.paradigm.common.v1.model.LogicRunId
import tech.kzen.auto.common.paradigm.common.v1.model.LogicRunResponse
import tech.kzen.auto.common.paradigm.dataflow.model.exec.VisualDataflowModel
import tech.kzen.auto.common.paradigm.dataflow.model.exec.VisualVertexModel
import tech.kzen.auto.common.paradigm.dataflow.model.exec.VisualVertexTransition
import tech.kzen.auto.common.paradigm.imperative.model.ImperativeModel
import tech.kzen.auto.common.paradigm.imperative.model.ImperativeResponse
import tech.kzen.auto.common.paradigm.task.model.TaskId
import tech.kzen.auto.common.paradigm.task.model.TaskModel
import tech.kzen.auto.common.util.AutoConventions
import tech.kzen.auto.common.util.RequestParams
import tech.kzen.auto.server.paradigm.detached.ExecutionDownloadResult
import tech.kzen.auto.server.service.ServerContext
import tech.kzen.lib.common.model.attribute.AttributeName
import tech.kzen.lib.common.model.attribute.AttributeNesting
import tech.kzen.lib.common.model.attribute.AttributePath
import tech.kzen.lib.common.model.attribute.AttributeSegment
import tech.kzen.lib.common.model.document.DocumentName
import tech.kzen.lib.common.model.document.DocumentPath
import tech.kzen.lib.common.model.locate.ObjectLocation
import tech.kzen.lib.common.model.locate.ResourceLocation
import tech.kzen.lib.common.model.obj.ObjectName
import tech.kzen.lib.common.model.obj.ObjectPath
import tech.kzen.lib.common.model.structure.notation.AttributeNotation
import tech.kzen.lib.common.model.structure.notation.ObjectNotation
import tech.kzen.lib.common.model.structure.notation.PositionRelation
import tech.kzen.lib.common.model.structure.notation.cqrs.*
import tech.kzen.lib.common.model.structure.resource.ResourcePath
import tech.kzen.lib.common.util.Digest
import tech.kzen.lib.common.util.ImmutableByteArray
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.stream.Collectors
// TODO: refactor
@Component
class RestHandler {
//-----------------------------------------------------------------------------------------------------------------
companion object {
val classPathRoots = listOf(
URI("classpath:/public/")
)
val resourceDirectories = discoverResourceDirectories()
private const val cssExtension = "css"
val allowedExtensions = listOf(
"html",
"js",
cssExtension,
"svg",
"png",
"ico"
)
private val cssMediaType = MediaType.valueOf("text/css")
private const val jvmSuffix = "-jvm"
private fun discoverResourceDirectories(): List<Path> {
val builder = mutableListOf<Path>()
// TODO: consolidate with GradleLocator?
val projectRoot =
if (Files.exists(Paths.get("src"))) {
".."
}
else {
"."
}
val projectName: String? = Files.list(Paths.get(projectRoot)).use { files ->
val list = files.collect(Collectors.toList())
val jvmModule = list.firstOrNull { it.fileName.toString().endsWith(jvmSuffix)}
if (jvmModule == null) {
null
}
else {
val filename = jvmModule.fileName.toString()
filename.substring(0 until filename.length - jvmSuffix.length)
}
}
if (projectName != null) {
// IntelliJ and typical commandline working dir is project root
builder.add(Paths.get("$projectName-jvm/src/main/resources/public/"))
builder.add(Paths.get("$projectName-js/build/distributions/"))
// Eclipse and Gradle default active working directory is the module
builder.add(Paths.get("src/main/resources/public/"))
builder.add(Paths.get("../$projectName-js/build/distributions/"))
}
else {
builder.add(Paths.get("static/"))
}
return builder
}
}
//-----------------------------------------------------------------------------------------------------------------
fun scan(serverRequest: ServerRequest): Mono<ServerResponse> {
val fresh = serverRequest.queryParams().containsKey(CommonRestApi.paramFresh)
if (fresh) {
ServerContext.notationMedia.invalidate()
}
val documentTree = runBlocking {
ServerContext.notationMedia.scan()
}
val asMap = mutableMapOf<String, Any>()
for (e in documentTree.documents.values) {
asMap[e.key.asRelativeFile()] = mapOf(
"documentDigest" to e.value.documentDigest.asString(),
"resources" to e.value.resources?.digests?.map {
it.key.asString() to it.value.asString()
}?.toMap()
)
}
return ServerResponse
.ok()
.body(Mono.just(asMap))
}
//-----------------------------------------------------------------------------------------------------------------
fun resourceRead(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val resourcePath: ResourcePath = serverRequest.getParam(
CommonRestApi.paramResourcePath, ResourcePath::parse)
val resourceLocation = ResourceLocation(documentPath, resourcePath)
val resourceContents = runBlocking {
ServerContext.notationMedia.readResource(resourceLocation)
}
return ServerResponse
.ok()
.body(Mono.just(resourceContents.toByteArray()))
}
//-----------------------------------------------------------------------------------------------------------------
fun notation(serverRequest: ServerRequest): Mono<ServerResponse> {
val encodedRequestSuffix = serverRequest.path().substring(CommonRestApi.notationPrefix.length)
val requestSuffix = URI(encodedRequestSuffix).path
val notationPath = DocumentPath.parse(requestSuffix)
val notationText = runBlocking {
ServerContext.notationMedia.readDocument(notationPath)
}
val responseBuilder = ServerResponse.ok()
return if (notationText.isEmpty()) {
responseBuilder.build()
}
else {
responseBuilder.body(Mono.just(notationText))
}
}
//-----------------------------------------------------------------------------------------------------------------
fun createDocument(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val documentBody = serverRequest.getParam(CommonRestApi.paramDocumentNotation) {
ServerContext.yamlParser.parseDocumentObjects(it)
}
return applyAndDigest(
CreateDocumentCommand(documentPath, documentBody))
}
fun deleteDocument(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
return applyAndDigest(
DeleteDocumentCommand(documentPath))
}
//-----------------------------------------------------------------------------------------------------------------
fun addObject(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val indexInDocument: PositionRelation = serverRequest.getParam(
CommonRestApi.paramPositionIndex, PositionRelation::parse)
val objectNotation: ObjectNotation = serverRequest.getParam(
CommonRestApi.paramObjectNotation, ServerContext.yamlParser::parseObject)
return applyAndDigest(
AddObjectCommand(
ObjectLocation(documentPath, objectPath),
indexInDocument,
objectNotation))
}
fun removeObject(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
return applyAndDigest(
RemoveObjectCommand(
ObjectLocation(documentPath, objectPath)))
}
fun shiftObject(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val indexInDocument: PositionRelation = serverRequest.getParam(
CommonRestApi.paramPositionIndex, PositionRelation::parse)
return applyAndDigest(
ShiftObjectCommand(
ObjectLocation(documentPath, objectPath),
indexInDocument))
}
fun renameObject(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val objectName: ObjectName = serverRequest.getParam(
CommonRestApi.paramObjectName, ::ObjectName)
return applyAndDigest(
RenameObjectCommand(
ObjectLocation(documentPath, objectPath),
objectName))
}
fun insertObjectInList(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val containingObjectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val containingList: AttributePath = serverRequest.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val indexInList: PositionRelation = serverRequest.getParam(
CommonRestApi.paramPositionIndex, PositionRelation::parse)
val objectName: ObjectName = serverRequest.getParam(
CommonRestApi.paramObjectName, ::ObjectName)
val positionInDocument: PositionRelation = serverRequest.getParam(
CommonRestApi.paramSecondaryPosition, PositionRelation::parse)
val objectNotation: ObjectNotation = serverRequest.getParam(
CommonRestApi.paramObjectNotation, ServerContext.yamlParser::parseObject)
return applyAndDigest(
InsertObjectInListAttributeCommand(
ObjectLocation(documentPath, containingObjectPath),
containingList,
indexInList,
objectName,
positionInDocument,
objectNotation))
}
fun removeObjectInAttribute(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val containingObjectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributePath: AttributePath = serverRequest.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
return applyAndDigest(
RemoveObjectInAttributeCommand(
ObjectLocation(documentPath, containingObjectPath),
attributePath))
}
//-----------------------------------------------------------------------------------------------------------------
fun upsertAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return upsertAttributeImpl(serverRequest.queryParams())
}
fun upsertAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
upsertAttributeImpl(body)
}
}
private fun upsertAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributeName: AttributeName = params.getParam(
CommonRestApi.paramAttributeName, AttributeName::parse)
val attributeNotation: AttributeNotation = params.getParam(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
return applyAndDigest(
UpsertAttributeCommand(
ObjectLocation(documentPath, objectPath),
attributeName,
attributeNotation))
}
fun updateInAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return updateInAttributeImpl(serverRequest.queryParams())
}
fun updateInAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
updateInAttributeImpl(body)
}
}
private fun updateInAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributePath: AttributePath = params.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val attributeNotation: AttributeNotation = params.getParam(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
return applyAndDigest(
UpdateInAttributeCommand(
ObjectLocation(documentPath, objectPath),
attributePath,
attributeNotation))
}
fun updateAllNestingsInAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return updateAllNestingsInAttributeImpl(serverRequest.queryParams())
}
fun updateAllNestingsInAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
updateAllNestingsInAttributeImpl(body)
}
}
private fun updateAllNestingsInAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributeName: AttributeName = params.getParam(
CommonRestApi.paramAttributeName, AttributeName::parse)
val attributeNestings: List<AttributeNesting> = params.getParamList(
CommonRestApi.paramAttributeNesting, AttributeNesting::parse)
val attributeNotation: AttributeNotation = params.getParam(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
return applyAndDigest(
UpdateAllNestingsInAttributeCommand(
ObjectLocation(documentPath, objectPath),
attributeName,
attributeNestings,
attributeNotation))
}
fun updateAllValuesInAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return updateAllValuesInAttributeImpl(serverRequest.queryParams())
}
fun updateAllValuesInAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
updateAllValuesInAttributeImpl(body)
}
}
private fun updateAllValuesInAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributeName: AttributeName = params.getParam(
CommonRestApi.paramAttributeName, AttributeName::parse)
val attributeNestings: List<AttributeNesting> = params.getParamList(
CommonRestApi.paramAttributeNesting, AttributeNesting::parse)
val attributeNotations: List<AttributeNotation> = params.getParamList(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
require(attributeNestings.size == attributeNotations.size)
val nestingNotations = attributeNestings.zip(attributeNotations).toMap()
return applyAndDigest(
UpdateAllValuesInAttributeCommand(
ObjectLocation(documentPath, objectPath),
attributeName,
nestingNotations))
}
fun insertListItemInAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return insertListItemInAttributeImpl(serverRequest.queryParams())
}
fun insertListItemInAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
insertListItemInAttributeImpl(body)
}
}
private fun insertListItemInAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val containingList: AttributePath = params.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val indexInList: PositionRelation = params.getParam(
CommonRestApi.paramPositionIndex, PositionRelation::parse)
val itemNotation: AttributeNotation = params.getParam(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
return applyAndDigest(
InsertListItemInAttributeCommand(
ObjectLocation(documentPath, objectPath),
containingList,
indexInList,
itemNotation))
}
fun insertAllListItemsInAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return insertAllListItemsInAttributeImpl(serverRequest.queryParams())
}
fun insertAllListItemsInAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
insertAllListItemsInAttributeImpl(body)
}
}
private fun insertAllListItemsInAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val containingList: AttributePath = params.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val indexInList: PositionRelation = params.getParam(
CommonRestApi.paramPositionIndex, PositionRelation::parse)
val itemNotations: List<AttributeNotation> = params.getParamList(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
return applyAndDigest(
InsertAllListItemsInAttributeCommand(
ObjectLocation(documentPath, objectPath),
containingList,
indexInList,
itemNotations))
}
fun insertMapEntryInAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return insertMapEntryInAttributeImpl(serverRequest.queryParams())
}
fun insertMapEntryInAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
insertMapEntryInAttributeImpl(body)
}
}
private fun insertMapEntryInAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val containingMap: AttributePath = params.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val indexInMap: PositionRelation = params.getParam(
CommonRestApi.paramPositionIndex, PositionRelation::parse)
val mapKey: AttributeSegment = params.getParam(
CommonRestApi.paramAttributeKey, AttributeSegment::parse)
val valueNotation: AttributeNotation = params.getParam(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
val createAncestorsIfAbsent: Boolean = params
.tryGetParam(CommonRestApi.paramAttributeCreateContainer) { value -> value == "true" }
?: false
return applyAndDigest(
InsertMapEntryInAttributeCommand(
ObjectLocation(documentPath, objectPath),
containingMap,
indexInMap,
mapKey,
valueNotation,
createAncestorsIfAbsent))
}
fun removeInAttribute(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributePath: AttributePath = serverRequest.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val removeContainerIfEmpty: Boolean = serverRequest
.tryGetParam(CommonRestApi.paramAttributeCleanupContainer) { i -> i == "true"}
?: false
return applyAndDigest(
RemoveInAttributeCommand(
ObjectLocation(documentPath, objectPath),
attributePath,
removeContainerIfEmpty
)
)
}
fun removeListItemInAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return removeListItemInAttributeImpl(serverRequest.queryParams())
}
fun removeListItemInAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
removeListItemInAttributeImpl(body)
}
}
private fun removeListItemInAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributePath: AttributePath = params.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val itemNotation: AttributeNotation = params.getParam(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
val removeContainerIfEmpty: Boolean = params
.tryGetParam(CommonRestApi.paramAttributeCleanupContainer) { i -> i == "true"}
?: false
return applyAndDigest(
RemoveListItemInAttributeCommand(
ObjectLocation(documentPath, objectPath),
attributePath,
itemNotation,
removeContainerIfEmpty))
}
fun removeAllListItemsInAttributeGet(serverRequest: ServerRequest): Mono<ServerResponse> {
return removeAllListItemsInAttributeImpl(serverRequest.queryParams())
}
fun removeAllListItemsInAttributePut(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { body ->
removeAllListItemsInAttributeImpl(body)
}
}
private fun removeAllListItemsInAttributeImpl(params: MultiValueMap<String, String>): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributePath: AttributePath = params.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val itemNotations: List<AttributeNotation> = params.getParamList(
CommonRestApi.paramAttributeNotation, ServerContext.yamlParser::parseAttribute)
val removeContainerIfEmpty: Boolean = params
.tryGetParam(CommonRestApi.paramAttributeCleanupContainer) { i -> i == "true"}
?: false
return applyAndDigest(
RemoveAllListItemsInAttributeCommand(
ObjectLocation(documentPath, objectPath),
attributePath,
itemNotations,
removeContainerIfEmpty))
}
fun shiftInAttribute(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val attributePath: AttributePath = serverRequest.getParam(
CommonRestApi.paramAttributePath, AttributePath::parse)
val newPosition: PositionRelation = serverRequest.getParam(
CommonRestApi.paramPositionIndex, PositionRelation::parse)
return applyAndDigest(
ShiftInAttributeCommand(
ObjectLocation(documentPath, objectPath),
attributePath,
newPosition))
}
//-----------------------------------------------------------------------------------------------------------------
fun refactorObjectName(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val newName: ObjectName = serverRequest.getParam(
CommonRestApi.paramObjectName, ::ObjectName)
return applyAndDigest(
RenameObjectRefactorCommand(
ObjectLocation(documentPath, objectPath),
newName))
}
fun refactorDocumentName(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val newName: DocumentName = serverRequest.getParam(
CommonRestApi.paramDocumentName, ::DocumentName)
return applyAndDigest(
RenameDocumentRefactorCommand(
documentPath,
newName))
}
//-----------------------------------------------------------------------------------------------------------------
fun addResource(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val resourcePath: ResourcePath = serverRequest.getParam(
CommonRestApi.paramResourcePath, ResourcePath::parse)
val contents = serverRequest.bodyToMono(ByteArray::class.java)
return contents.flatMap {
val command = AddResourceCommand(
ResourceLocation(documentPath, resourcePath),
ImmutableByteArray.wrap(it))
val digest = applyCommand(command)
ServerResponse
.ok()
.body(Mono.just(digest.asString()))
}
}
fun resourceDelete(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val resourcePath: ResourcePath = serverRequest.getParam(
CommonRestApi.paramResourcePath, ResourcePath::parse)
return applyAndDigest(
RemoveResourceCommand(
ResourceLocation(documentPath, resourcePath)))
}
//-----------------------------------------------------------------------------------------------------------------
fun benchmark(serverRequest: ServerRequest): Mono<ServerResponse> {
val iterations: Int = serverRequest.getParam(
"i", Integer::parseInt)
val startTime = System.currentTimeMillis()
// http://localhost:8080/command/object/insert-in-list?path=main%2FScript.yaml&object=main&in-attribute=steps&index=7&name=Escape&position=8&body=is%3A%20SendEscape
val addCommand = InsertObjectInListAttributeCommand(
ObjectLocation.parse("main/Script.yaml#main"),
AttributePath.parse("steps"),
PositionRelation.parse("7"),
ObjectName("Escape"),
PositionRelation.parse("8"),
ServerContext.yamlParser.parseObject("is: SendEscape"))
// http://localhost:8080/command/object/remove-in?path=main%2FScript.yaml&object=main&in-attribute=steps.7
val removeCommand = RemoveObjectInAttributeCommand(
ObjectLocation.parse("main/Script.yaml#main"),
AttributePath.parse("steps.7"))
for (i in 0 .. iterations) {
applyAndDigest(addCommand)
applyAndDigest(removeCommand)
}
val duration = System.currentTimeMillis() - startTime
return ServerResponse
.ok()
.body(Mono.just("$duration"))
}
//-----------------------------------------------------------------------------------------------------------------
fun applyAndDigest(command: NotationCommand): Mono<ServerResponse> {
val digest = applyCommand(command)
return ServerResponse
.ok()
.body(Mono.just(digest.asString()))
}
fun applyCommand(command: NotationCommand): Digest {
return runBlocking {
try {
ServerContext.graphStore.apply(command)
}
catch (e: Exception) {
e.printStackTrace()
}
ServerContext.graphStore.digest()
}
}
//-----------------------------------------------------------------------------------------------------------------
fun actionList(serverRequest: ServerRequest): Mono<ServerResponse> {
val activeScripts = ServerContext.executionRepository.activeScripts()
val encoded = activeScripts.map { it.asString() }
return ServerResponse
.ok()
.body(Mono.just(encoded))
}
fun actionModel(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse
)
val executionModel = runBlocking {
val graphStructure = ServerContext.graphStore.graphStructure()
ServerContext.executionRepository.executionModel(documentPath, graphStructure)
}
return ServerResponse
.ok()
.body(Mono.just(ImperativeModel.toCollection(executionModel)))
}
fun actionStart(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse
)
val digest = runBlocking {
val graphStructure = ServerContext.graphStore
.graphStructure()
.filter(AutoConventions.serverAllowed)
ServerContext.executionRepository.start(
documentPath, graphStructure
)
}
return ServerResponse
.ok()
.body(Mono.just(digest.asString()))
}
fun actionReturn(serverRequest: ServerRequest): Mono<ServerResponse> {
val hostDocumentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramHostDocumentPath, DocumentPath::parse
)
// val documentPath: DocumentPath = serverRequest.getParam(
// CommonRestApi.paramDocumentPath, DocumentPath.Companion::parse)
val digest = runBlocking {
val graphStructure = ServerContext.graphStore
.graphStructure()
.filter(AutoConventions.serverAllowed)
ServerContext.executionRepository.returnFrame(
hostDocumentPath, graphStructure
)
}
return ServerResponse
.ok()
.body(Mono.just(digest.asString()))
}
fun actionReset(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse
)
// val digest = runBlocking {
runBlocking {
ServerContext.executionRepository.reset(documentPath)
}
return ServerResponse
.ok()
.build()
// .body(Mono.just(digest.asString()))
}
fun actionPerform(serverRequest: ServerRequest): Mono<ServerResponse> {
val hostDocumentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramHostDocumentPath, DocumentPath::parse
)
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse
)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse
)
val objectLocation = ObjectLocation(documentPath, objectPath)
val execution: ImperativeResponse = runBlocking {
val graphStructure = ServerContext.graphStore.graphStructure()
ServerContext.executionRepository.execute(
hostDocumentPath, objectLocation, graphStructure
)
}
return ServerResponse
.ok()
.body(Mono.just(execution.toCollection()))
}
//-----------------------------------------------------------------------------------------------------------------
fun actionDetachedByQuery(serverRequest: ServerRequest): Mono<ServerResponse> {
return actionDetachedImpl(serverRequest, serverRequest.queryParams())
}
fun actionDetachedByForm(serverRequest: ServerRequest): Mono<ServerResponse> {
return serverRequest.formData().flatMap { params ->
actionDetachedImpl(serverRequest, params)
}
}
private fun actionDetachedImpl(
serverRequest: ServerRequest,
params: MultiValueMap<String, String>
): Mono<ServerResponse> {
val documentPath: DocumentPath = params.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = params.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val objectLocation = ObjectLocation(documentPath, objectPath)
val detachedParams = mutableMapOf<String, List<String>>()
for (e in params) {
if (e.key == CommonRestApi.paramDocumentPath ||
e.key == CommonRestApi.paramObjectPath
) {
continue
}
detachedParams[e.key] = e.value
}
return serverRequest
.bodyToMono(ByteArray::class.java)
.map { Optional.of(ImmutableByteArray.wrap(it)) }
.defaultIfEmpty(Optional.empty())
.flatMap { optionalBody ->
val body = optionalBody.orElse(null)
val detachedRequest = ExecutionRequest(RequestParams(detachedParams), body)
val execution: ExecutionResult = runBlocking {
ServerContext.detachedExecutor.execute(
objectLocation,
detachedRequest
)
}
ServerResponse
.ok()
.body(Mono.just(execution.toJsonCollection()))
}
}
fun actionDetachedDownload(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val objectLocation = ObjectLocation(documentPath, objectPath)
val params = mutableMapOf<String, List<String>>()
for (e in serverRequest.queryParams()) {
if (e.key == CommonRestApi.paramDocumentPath ||
e.key == CommonRestApi.paramObjectPath) {
continue
}
params[e.key] = e.value
}
return serverRequest
.bodyToMono(ByteArray::class.java)
.map { Optional.of(ImmutableByteArray.wrap(it)) }
.defaultIfEmpty(Optional.empty())
.flatMap { optionalBody ->
val body = optionalBody.orElse(null)
val detachedRequest = ExecutionRequest(RequestParams(params), body)
val execution: ExecutionDownloadResult = runBlocking {
ServerContext.detachedExecutor.executeDownload(
objectLocation, detachedRequest)
}
val contentType = MediaType.parseMediaType(execution.mimeType)
val attachmentFilename = "attachment; filename*=utf-8''" + execution.fileName
val resource: Resource = InputStreamResource(execution.data)
ServerResponse
.ok()
.contentType(contentType)
.header(HttpHeaders.CONTENT_DISPOSITION, attachmentFilename)
.body(Mono.just(resource))
}
}
//-----------------------------------------------------------------------------------------------------------------
fun execModel(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath? = serverRequest.tryGetParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val visualDataflowModel = runBlocking {
ServerContext.visualDataflowRepository.get(documentPath)
}
val result =
if (objectPath == null) {
VisualDataflowModel.toJsonCollection(visualDataflowModel)
}
else {
val objectLocation = ObjectLocation(documentPath, objectPath)
val visualVertexModel = visualDataflowModel.vertices[objectLocation]
?: throw IllegalArgumentException("Object location not found: $objectLocation")
VisualVertexModel.toJsonCollection(visualVertexModel)
}
return ServerResponse
.ok()
.body(Mono.just(result))
}
fun execReset(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val visualDataflowModel = runBlocking {
ServerContext.visualDataflowRepository.reset(documentPath)
}
return ServerResponse
.ok()
.body(Mono.just(VisualDataflowModel.toJsonCollection(visualDataflowModel)))
}
fun execPerform(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val objectLocation = ObjectLocation(documentPath, objectPath)
val transition: VisualVertexTransition = runBlocking {
ServerContext.visualDataflowRepository.execute(documentPath, objectLocation)
}
return ServerResponse
.ok()
.body(Mono.just(VisualVertexTransition.toCollection(transition)))
}
//-----------------------------------------------------------------------------------------------------------------
fun taskSubmit(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val objectLocation = ObjectLocation(documentPath, objectPath)
val params = mutableMapOf<String, List<String>>()
for (e in serverRequest.queryParams()) {
if (e.key == CommonRestApi.paramDocumentPath ||
e.key == CommonRestApi.paramObjectPath) {
continue
}
params[e.key] = e.value
}
return serverRequest
.bodyToMono(ByteArray::class.java)
.map { Optional.of(ImmutableByteArray.wrap(it)) }
.defaultIfEmpty(Optional.empty())
.flatMap { optionalBody ->
val body = optionalBody.orElse(null)
val detachedRequest = ExecutionRequest(RequestParams(params), body)
val execution: TaskModel = runBlocking {
ServerContext.modelTaskRepository.submit(
objectLocation,
detachedRequest)
}
ServerResponse
.ok()
.body(Mono.just(execution.toJsonCollection()))
}
}
fun taskQuery(serverRequest: ServerRequest): Mono<ServerResponse> {
val taskId: TaskId = serverRequest
.getParam(CommonRestApi.paramTaskId) { TaskId(it) }
val model: TaskModel = runBlocking {
ServerContext.modelTaskRepository.query(taskId)
}
?: return ServerResponse.noContent().build()
val result = model.toJsonCollection()
return ServerResponse
.ok()
.body(Mono.just(result))
}
fun taskCancel(serverRequest: ServerRequest): Mono<ServerResponse> {
val taskId: TaskId = serverRequest
.getParam(CommonRestApi.paramTaskId) { TaskId(it) }
val model: TaskModel = runBlocking {
ServerContext.modelTaskRepository.cancel(taskId)
}
?: return ServerResponse.noContent().build()
val result = model.toJsonCollection()
return ServerResponse
.ok()
.body(Mono.just(result))
}
fun taskLookup(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val objectLocation = ObjectLocation(documentPath, objectPath)
val tasks: Set<TaskId> = runBlocking {
ServerContext.modelTaskRepository.lookupActive(objectLocation)
}
return ServerResponse
.ok()
.body(Mono.just(tasks.map { it.identifier }))
}
//-----------------------------------------------------------------------------------------------------------------
fun logicStatus(serverRequest: ServerRequest): Mono<ServerResponse> {
val status = ServerContext.serverLogicController.status()
return ServerResponse
.ok()
.body(Mono.just(status.toCollection()))
}
fun logicStart(serverRequest: ServerRequest): Mono<ServerResponse> {
val documentPath: DocumentPath = serverRequest.getParam(
CommonRestApi.paramDocumentPath, DocumentPath::parse)
val objectPath: ObjectPath = serverRequest.getParam(
CommonRestApi.paramObjectPath, ObjectPath::parse)
val objectLocation = ObjectLocation(documentPath, objectPath)
val graphDefinitionAttempt = runBlocking {
ServerContext.graphStore.graphDefinition()
}
val logicRunId = runBlocking {
ServerContext.serverLogicController.start(objectLocation, graphDefinitionAttempt)
}
@Suppress("FoldInitializerAndIfToElvis")
if (logicRunId == null) {
return ServerResponse.badRequest().build()
}
val response = runBlocking {
ServerContext.serverLogicController.continueOrStart(logicRunId, graphDefinitionAttempt)
}
if (response != LogicRunResponse.Submitted) {
return ServerResponse.badRequest().build()
}
return ServerResponse
.ok()
.body(Mono.just(logicRunId.value))
}
fun logicRequest(serverRequest: ServerRequest): Mono<ServerResponse> {
val runId: LogicRunId = serverRequest.getParam(CommonRestApi.paramRunId) {
value -> LogicRunId(value)
}
val executionId: LogicExecutionId = serverRequest.getParam(CommonRestApi.paramExecutionId) {
value -> LogicExecutionId(value)
}
val params = mutableMapOf<String, List<String>>()
for (e in serverRequest.queryParams()) {
if (e.key == CommonRestApi.paramRunId ||
e.key == CommonRestApi.paramExecutionId) {
continue
}
params[e.key] = e.value
}
return serverRequest
.bodyToMono(ByteArray::class.java)
.map { Optional.of(ImmutableByteArray.wrap(it)) }
.defaultIfEmpty(Optional.empty())
.flatMap { optionalBody ->
val body = optionalBody.orElse(null)
val request = ExecutionRequest(RequestParams(params), body)
val result: ExecutionResult = runBlocking {
ServerContext.serverLogicController.request(
runId,
executionId,
request)
}
ServerResponse
.ok()
.body(Mono.just(result.toJsonCollection()))
}
}
fun logicCancel(serverRequest: ServerRequest): Mono<ServerResponse> {
val runId: LogicRunId = serverRequest.getParam(CommonRestApi.paramRunId) {
value -> LogicRunId(value)
}
val response = runBlocking {
ServerContext.serverLogicController.cancel(runId)
}
return ServerResponse
.ok()
.body(Mono.just(response.name))
}
fun logicRun(serverRequest: ServerRequest): Mono<ServerResponse> {
val runId: LogicRunId = serverRequest.getParam(CommonRestApi.paramRunId) {
value -> LogicRunId(value)
}
val response = runBlocking {
ServerContext.serverLogicController.continueOrStart(runId)
}
return ServerResponse
.ok()
.body(Mono.just(response.name))
}
//-----------------------------------------------------------------------------------------------------------------
// TODO: is this secure?
fun staticResource(serverRequest: ServerRequest): Mono<ServerResponse> {
val excludingInitialSlash = serverRequest.path().substring(1)
val resolvedPath =
if (excludingInitialSlash == "") {
"index.html"
}
else {
excludingInitialSlash
}
val path = Paths.get(resolvedPath).normalize()
val extension = MoreFiles.getFileExtension(path)
if (! isResourceAllowed(path)) {
return ServerResponse
.badRequest()
.build()
}
val bytes: ByteArray = readResource(path)
?: return ServerResponse
.notFound()
.build()
val responseBuilder = ServerResponse.ok()
val responseType: MediaType? = responseType(extension)
if (responseType !== null) {
responseBuilder.contentType(responseType)
}
return if (bytes.isEmpty()) {
responseBuilder.build()
}
else {
responseBuilder.body(Mono.just(bytes))
}
}
private fun responseType(extension: String): MediaType? {
return when (extension) {
cssExtension -> cssMediaType
else -> null
}
}
private fun isResourceAllowed(path: Path): Boolean {
if (path.isAbsolute) {
return false
}
val extension = MoreFiles.getFileExtension(path)
return allowedExtensions.contains(extension)
}
private fun readResource(relativePath: Path): ByteArray? {
// NB: moving up to help with auto-reload of js, TODO: this used to work below classPathRoots
for (root in resourceDirectories) {
val candidate = root.resolve(relativePath)
if (! Files.exists(candidate)) {
continue
}
return Files.readAllBytes(candidate)
}
for (root in classPathRoots) {
try {
val resourceLocation: URI = root.resolve(relativePath.toString())
val relativeResource = resourceLocation.path.substring(1)
val resourceUrl = Resources.getResource(relativeResource)
return Resources.toByteArray(resourceUrl)
}
catch (ignored: Exception) {}
}
// println("%%%%% not read: $relativePath")
return null
}
//-----------------------------------------------------------------------------------------------------------------
private fun <T> ServerRequest.getParam(
parameterName: String,
parser: (String) -> T
): T {
// return queryParam(parameterName)
// .map { parser(it) }
// .orElseThrow { IllegalArgumentException("'$parameterName' required") }
return queryParams().getParam(parameterName, parser)
}
private fun <T> MultiValueMap<String, String>.getParam(
parameterName: String,
parser: (String) -> T
): T {
val queryParamValues: List<String>? = get(parameterName)
require(! queryParamValues.isNullOrEmpty()) { "'$parameterName' required" }
return parser(queryParamValues.first())
}
private fun <T> ServerRequest.getParamList(
parameterName: String,
parser: (String) -> T
): List<T> {
// val itemNotations = queryParams()[parameterName]
// ?: throw IllegalArgumentException("'$parameterName' required")
// return itemNotations.map { i -> parser(i) }
return queryParams().getParamList(parameterName, parser)
}
private fun <T> MultiValueMap<String, String>.getParamList(
parameterName: String,
parser: (String) -> T
): List<T> {
val queryParamValues: List<String> = get(parameterName) ?: listOf()
return queryParamValues.map(parser)
}
private fun <T> ServerRequest.tryGetParam(
parameterName: String,
parser: (String) -> T
): T? {
// return queryParam(parameterName)
// .map { parser(it) }
// .orElse(null)
return queryParams().tryGetParam(parameterName, parser)
}
private fun <T> MultiValueMap<String, String>.tryGetParam(
parameterName: String,
parser: (String) -> T
): T? {
return get(parameterName)?.singleOrNull()?.let { parser(it) }
}
}
| 0 |
Kotlin
|
0
| 1 |
a4cec899d18e17b157fd20ebe3dceca9a85ce262
| 54,494 |
kzen-auto
|
MIT License
|
composeApp/src/commonMain/kotlin/apps/currency_converter_udemy/domain/model/ApiResponse.kt
|
vengateshm
| 818,708,913 | false |
{"Kotlin": 136686, "Swift": 1088, "HTML": 353, "CSS": 102}
|
package apps.currency_converter_udemy.domain.model
import io.realm.kotlin.types.RealmObject
import io.realm.kotlin.types.annotations.PrimaryKey
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.mongodb.kbson.ObjectId
@Serializable
data class ApiResponse(
val meta: MetaData,
val data: Map<String, Currency>
)
@Serializable
data class MetaData(
@SerialName("last_updated_at")
val lastUpdatedAt: String
)
@Serializable
data class Currency(
var code: String,
var value: Double
)
open class CurrencyEntity : RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var code: String = ""
var value: Double = 0.0
}
fun Currency.toCurrencyEntity() = CurrencyEntity()
.apply {
code = [email protected]
value = [email protected]
}
fun CurrencyEntity.toCurrency() = Currency(
code = this.code,
value = this.value
)
| 0 |
Kotlin
|
0
| 0 |
7a9cb5f525586ee81842db4d3b2870c6f13dbe81
| 945 |
ComposeMultiplatformSamples
|
Apache License 2.0
|
app/src/main/java/com/github/psm/moviedb/ui/widget/InnerScaffold.kt
|
Pidsamhai
| 371,868,606 | false |
{"Kotlin": 243787, "CMake": 1715}
|
package com.github.psm.moviedb.ui.widget
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun InnerScaffold(
modifier: Modifier,
appBar: @Composable () -> Unit,
innerPaddingValues: PaddingValues = PaddingValues(),
content: @Composable ColumnScope.() -> Unit
) {
Column(
modifier = modifier
) {
appBar()
Column(
modifier = Modifier.fillMaxSize()
.padding(innerPaddingValues)
) {
content()
}
}
}
| 1 |
Kotlin
|
1
| 3 |
6f4e67ee83349604b3396902469f4c3a83a68c3c
| 589 |
movie_db
|
Apache License 2.0
|
app/src/main/java/com/jiangkang/ktools/KApplication.kt
|
155zhang
| 123,068,902 | true |
{"Kotlin": 387549, "JavaScript": 14024, "HTML": 5095, "CMake": 3043, "CSS": 2570, "C++": 968, "Makefile": 689, "Shell": 429}
|
package com.jiangkang.ktools
import android.app.Application
import android.content.Context
import android.os.StrictMode
import android.support.multidex.MultiDex
import com.alibaba.android.arouter.launcher.ARouter
import com.facebook.stetho.Stetho
import com.jiangkang.tools.King
import com.jiangkang.weex.ImageAdapter
import com.taobao.weex.InitConfig
import com.taobao.weex.WXSDKEngine
import java.util.concurrent.Executors
/**
* @author jiangkang
* @date 2017/9/6
*/
class KApplication : Application() {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
// TODO: 2018/1/30 测试框架与MultiDex不兼容,待处理
MultiDex.install(this)
}
override fun onCreate() {
super.onCreate()
enableStrictMode()
initLeakCanary()
King.init(this)
Executors.newCachedThreadPool().execute {
if (BuildConfig.DEBUG) {
Stetho.initializeWithDefaults(this@KApplication)
}
initARouter()
}
initWeex()
}
private fun initLeakCanary() {
// if (LeakCanary.isInAnalyzerProcess(this)) {
// return;
// }
// LeakCanary.install(this);
}
private fun initWeex() {
val config = InitConfig.Builder()
.setImgAdapter(ImageAdapter())
.build()
WXSDKEngine.initialize(this, config)
}
private fun initARouter() {
if (BuildConfig.DEBUG) { // 这两行必须写在init之前,否则这些配置在init过程中将无效
ARouter.openLog() // 打印日志
ARouter.openDebug() // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
}
ARouter.init(this)
}
private fun enableStrictMode() {
if (BuildConfig.DEBUG) {
enableThreadPolicy()
enableVmPolicy()
}
}
private fun enableVmPolicy() {
StrictMode.setVmPolicy(
StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build()
)
}
private fun enableThreadPolicy() {
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build()
)
}
}
| 0 |
Kotlin
|
0
| 0 |
26ecade56fe1980722975a94b4aae1ad1783309f
| 2,381 |
KTools
|
MIT License
|
adapter-out/rdb/src/main/kotlin/com/yapp/bol/game/GameRepository.kt
|
YAPP-Github
| 634,125,780 | false | null |
package com.yapp.bol.game
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
interface GameRepository : JpaRepository<GameEntity, Long> {
@Query("FROM GameEntity e JOIN FETCH e.img")
fun getAll(): List<GameEntity>
}
| 4 |
Kotlin
|
0
| 9 |
0e61952c5f0b448737de1729f0df9a376875577e
| 289 |
22nd-Android-Team-2-BE
|
Apache License 2.0
|
adapter-out/rdb/src/main/kotlin/com/yapp/bol/game/GameRepository.kt
|
YAPP-Github
| 634,125,780 | false | null |
package com.yapp.bol.game
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
interface GameRepository : JpaRepository<GameEntity, Long> {
@Query("FROM GameEntity e JOIN FETCH e.img")
fun getAll(): List<GameEntity>
}
| 4 |
Kotlin
|
0
| 9 |
0e61952c5f0b448737de1729f0df9a376875577e
| 289 |
22nd-Android-Team-2-BE
|
Apache License 2.0
|
sqlkite-lint/src/main/java/com/frankegan/sqlkite/KiteIssueRegistry.kt
|
fegan104
| 424,252,059 | true |
{"Kotlin": 121111}
|
/*
* Copyright (C) 2017 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 com.frankegan.sqlkite
import com.android.tools.lint.client.api.IssueRegistry
import com.android.tools.lint.detector.api.Issue
class KiteIssueRegistry : IssueRegistry() {
override val issues: List<Issue> = listOf(SqlKiteArgCountDetector.ISSUE)
}
| 1 |
Kotlin
|
0
| 0 |
6f544f57a3df60572dc9cff0ef611f15a17a9fad
| 859 |
sqlkite
|
Apache License 2.0
|
cotta-server/src/main/kotlin/com/mgtriffid/games/cotta/server/impl/DataForClientsImpl.kt
|
mgtriffid
| 524,701,185 | false |
{"Kotlin": 478306, "Java": 9323}
|
package com.mgtriffid.games.cotta.server.impl
import com.mgtriffid.games.cotta.core.entities.CottaState
import com.mgtriffid.games.cotta.core.entities.Entities
import com.mgtriffid.games.cotta.core.entities.PlayerId
import com.mgtriffid.games.cotta.core.entities.impl.EntitiesInternal
import com.mgtriffid.games.cotta.core.input.PlayerInput
import com.mgtriffid.games.cotta.core.simulation.PlayersSawTicks
import com.mgtriffid.games.cotta.core.simulation.SimulationInputHolder
import com.mgtriffid.games.cotta.server.DataForClients
import com.mgtriffid.games.cotta.core.simulation.Players
import jakarta.inject.Inject
import jakarta.inject.Named
data class DataForClientsImpl @Inject constructor(
private val simulationInputHolder: SimulationInputHolder,
@Named("simulation") private val state: CottaState,
private val players: Players,
private val playersSawTicks: PlayersSawTicks,
) : DataForClients {
override fun playerInputs(): Map<PlayerId, PlayerInput> {
return simulationInputHolder.get().inputForPlayers()
}
override fun entities(tick: Long): EntitiesInternal {
return state.entities(tick)
}
override fun idSequence(tick: Long): Int {
return state.entities(tick).currentId()
}
override fun players(): Players {
return players
}
override fun playersSawTicks(): PlayersSawTicks {
return playersSawTicks
}
}
| 2 |
Kotlin
|
0
| 6 |
ee0bd897c67451b31f68a3a31a6ee8de756b2b52
| 1,416 |
cotta
|
MIT License
|
core/src/commonMain/kotlin/zakadabar/stack/data/builtin/account/LogoutAction.kt
|
kondorj
| 355,137,640 | true |
{"Kotlin": 577495, "HTML": 828, "JavaScript": 820, "Shell": 253}
|
/*
* Copyright © 2020, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.stack.data.builtin.account
import kotlinx.serialization.Serializable
import zakadabar.stack.data.action.ActionDto
import zakadabar.stack.data.action.ActionDtoCompanion
import zakadabar.stack.data.builtin.ActionStatusDto
@Serializable
class LogoutAction : ActionDto<ActionStatusDto> {
override suspend fun execute() = comm.action(this, serializer(), ActionStatusDto.serializer())
companion object : ActionDtoCompanion<ActionStatusDto>(SessionDto.recordType)
}
| 0 | null |
0
| 0 |
2379c0fb031f04a230e753a9afad6bd260f6a0b2
| 605 |
zakadabar-stack
|
Apache License 2.0
|
dataconnect/app/src/main/java/com/google/firebase/example/dataconnect/ui/components/ReviewCard.kt
|
firebase
| 57,147,349 | false |
{"Kotlin": 437384, "Java": 363276, "JavaScript": 6043, "HTML": 5293, "Python": 3911, "Shell": 2550}
|
package com.google.firebase.example.dataconnect.ui.components
import android.widget.Space
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.text
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.Date
import java.util.Locale
@Composable
fun ReviewCard(
userName: String,
date: Date,
rating: Double,
text: String
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Column(
modifier = Modifier
.background(color = MaterialTheme.colorScheme.secondaryContainer)
.padding(16.dp)
) {
Text(
text = userName,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.titleMedium
)
Row(
modifier = Modifier.padding(bottom = 8.dp)
) {
Text(
text = SimpleDateFormat(
"dd MMM, yyyy",
Locale.getDefault()
).format(date)
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = "Rating: ")
Text(text = "$rating")
}
Text(
text = text,
modifier = Modifier.fillMaxWidth()
)
}
}
}
| 69 |
Kotlin
|
7326
| 8,858 |
4d1e253dd1dd8052310e889fc1785084b1997aca
| 2,084 |
quickstart-android
|
Apache License 2.0
|
feature/main/src/main/java/com/goms/main/data/LateData.kt
|
team-haribo
| 740,096,241 | false |
{"Kotlin": 621219}
|
package com.goms.main.data
import androidx.compose.runtime.Immutable
import com.goms.model.enum.Gender
import com.goms.model.enum.Major
import com.goms.model.response.council.LateResponseModel
@Immutable
data class LateData(
val accountIdx: String,
val name: String,
val grade: Int,
val major: Major,
val gender: Gender,
val profileUrl: String?
)
fun LateResponseModel.toData() =
LateData(
accountIdx = accountIdx,
name = name,
grade = grade,
major = major,
gender = gender,
profileUrl = profileUrl
)
| 5 |
Kotlin
|
0
| 9 |
32b6b960f997e282a05c8409d6e045e6f95822d5
| 584 |
GOMS-Android-V2
|
MIT License
|
hms/src/main/java/com/tjl/hms/iap/HmsIapListener.kt
|
LazyBonesLZ
| 181,592,036 | false | null |
package com.tjl.hms.iap
interface HmsIapListener {
fun onUpdateListDataByType(data:ArrayList<Product>,type:Int)
fun onUpdateItemData(data:Product)
fun onHmsIapSupported(bSupported:Boolean)
}
| 1 | null |
2
| 2 |
26ec43cd3198b4f8342c06b93553b3aeb2be9f41
| 203 |
LazySDK
|
Apache License 2.0
|
src/main/kotlin/org/incendo/cloudbuildlogic/RevapiConventions.kt
|
Incendo
| 739,175,198 | false |
{"Kotlin": 44674}
|
package org.incendo.cloudbuildlogic
import com.palantir.gradle.revapi.RevapiShim
import com.palantir.gradle.revapi.RevapiExtension
import com.palantir.gradle.revapi.RevapiPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
abstract class RevapiConventions : Plugin<Project> {
override fun apply(target: Project) {
target.plugins.apply(RevapiPlugin::class)
target.extensions.configure(RevapiExtension::class) {
oldVersions.set(RevapiShim.oldVersionsProvider(target))
}
}
}
| 3 |
Kotlin
|
0
| 1 |
99e49b89ce01330111f6d9cca618220bef555713
| 607 |
cloud-build-logic
|
MIT License
|
app/src/main/java/app/tivi/showdetails/episodedetails/EpisodeDetailsEpoxyController.kt
|
SagarKisanAvhad
| 146,028,545 | false | null |
/*
* Copyright 2018 Google, 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 app.tivi.showdetails.episodedetails
import app.tivi.R
import app.tivi.epDetailsFirstAiredItem
import app.tivi.epDetailsSummary
import app.tivi.epDetailsWatchItem
import app.tivi.header
import app.tivi.ui.epoxy.TotalSpanOverride
import com.airbnb.epoxy.TypedEpoxyController
class EpisodeDetailsEpoxyController(
private val callbacks: Callbacks
) : TypedEpoxyController<EpisodeDetailsViewState>() {
interface Callbacks {
// TODO
}
override fun buildModels(viewState: EpisodeDetailsViewState) {
epDetailsSummary {
id("episode_summary")
episode(viewState.episode)
spanSizeOverride(TotalSpanOverride)
}
if (viewState.episode.firstAired != null) {
epDetailsFirstAiredItem {
id("first_aired")
episode(viewState.episode)
dateTimeFormatter(viewState.dateTimeFormatter)
spanSizeOverride(TotalSpanOverride)
}
}
if (viewState.watches.isNotEmpty()) {
header {
id("watches_header")
title(R.string.episode_watches)
spanSizeOverride(TotalSpanOverride)
}
for (entry in viewState.watches) {
epDetailsWatchItem {
id("watch_${entry.id}")
dateTimeFormatter(viewState.dateTimeFormatter)
watch(entry)
spanSizeOverride(TotalSpanOverride)
}
}
}
}
}
| 0 |
Kotlin
|
1
| 1 |
687191398bd42fc87d4f50c89f21228e89c3a523
| 2,145 |
tivi-master
|
Apache License 2.0
|
api-common/src/main/kotlin/gropius/graphql/GropiusFunctionDataFetcher.kt
|
ccims
| 487,996,394 | false |
{"Kotlin": 1063836, "TypeScript": 442524, "MDX": 61402, "JavaScript": 25165, "HTML": 17174, "CSS": 4796, "Shell": 2363}
|
package gropius.graphql
import com.expediagroup.graphql.generator.annotations.GraphQLIgnore
import com.expediagroup.graphql.server.spring.execution.SpringDataFetcher
import graphql.schema.DataFetchingEnvironment
import org.springframework.context.ApplicationContext
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.full.createType
import kotlin.reflect.full.hasAnnotation
import kotlin.reflect.full.isSubtypeOf
/**
* FunctionDataFetcher which handles files parameter mapping for parameters of GraphQL type JSON correctly
* Allows input classes to have `lateinit` properties which are correctly deserialized
* Extends [SpringDataFetcher]
*
* @param target if present, the object on which the function is invoked
* @param function the function the data fetcher calls
* @param applicationContext used to obtain Spring beans
*/
class GropiusFunctionDataFetcher(
target: Any?, function: KFunction<*>, applicationContext: ApplicationContext
) : SpringDataFetcher(target, function, applicationContext) {
override fun mapParameterToValue(param: KParameter, environment: DataFetchingEnvironment): Pair<KParameter, Any?>? {
return when {
param.hasAnnotation<GraphQLIgnore>() -> super.mapParameterToValue(param, environment)
param.type.isSubtypeOf(DataFetchingEnvironment::class.createType()) -> param to environment
else -> param to convertArgumentValueFromParam(param, environment.arguments)
}
}
}
| 3 |
Kotlin
|
1
| 0 |
3292f1b8f5c3159b33b9c61e4cb737a7b0a42fa7
| 1,500 |
gropius-backend
|
MIT License
|
kingmc-platform-common/src/main/kotlin/kingmc/platform/util/ChunkPosition.kt
|
Kingsthere
| 599,960,106 | false |
{"Kotlin": 1080096}
|
package kingmc.platform.util
/**
* A data class determines a two-dimension position to a chunk
*
* @since 0.0.8
* @author kingsthere
*/
data class ChunkPosition(
val x: Int,
val z: Int
)
| 0 |
Kotlin
|
0
| 1 |
9a010ff50677c7effbb941320108d2f25b2a154d
| 201 |
kingmc-platform
|
MIT License
|
app/src/main/java/com/moegirlviewer/util/shortcutAction.kt
|
GZGavinZhao
| 456,296,460 | false |
{"Kotlin": 857701}
|
package com.moegirlviewer.util
import android.content.Intent
val Intent.shortcutAction get(): ShortcutAction? {
val intentAction = Globals.activity.intent.action ?: ""
val regexPackageName = Regex.escape(Globals.context.packageName)
val getShortcutActionRegex = Regex("""^$regexPackageName\.(.+)$""")
return if (intentAction.contains(getShortcutActionRegex)){
val shortcutAction = getShortcutActionRegex.find(intentAction)!!.groupValues[1]
ShortcutAction.valueOf(shortcutAction)
} else {
null
}
}
enum class ShortcutAction {
SEARCH,
CONTINUE_READ,
RANDOM
}
| 0 |
Kotlin
|
5
| 12 |
002f56b75e6d657b5ca0cc858564153f00eefd87
| 590 |
Moegirl-plus-native
|
MIT License
|
common/src/main/kotlin/net/spaceeye/vsource/rendering/SynchronisedRenderingData.kt
|
SuperSpaceEye
| 751,999,893 | false | null |
package net.spaceeye.vmod.rendering
import com.google.common.base.Supplier
import io.netty.buffer.Unpooled
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.FriendlyByteBuf
import net.spaceeye.vmod.DLOG
import net.spaceeye.vmod.WLOG
import net.spaceeye.vmod.constraintsManaging.ConstraintManager
import net.spaceeye.vmod.events.AVSEvents
import net.spaceeye.vmod.networking.dataSynchronization.ClientSynchronisedData
import net.spaceeye.vmod.utils.*
import net.spaceeye.vmod.networking.dataSynchronization.ServerChecksumsUpdatedPacket
import net.spaceeye.vmod.networking.dataSynchronization.ServerSynchronisedData
import net.spaceeye.vmod.rendering.ReservedRenderingPages.reservedPagesList
import net.spaceeye.vmod.rendering.types.*
import org.valkyrienskies.core.impl.hooks.VSEvents
import org.valkyrienskies.mod.common.shipObjectWorld
import java.security.MessageDigest
import java.util.ConcurrentModificationException
object RenderingTypes {
private val strToIdx = mutableMapOf<String, Int>()
private val suppliers = mutableListOf<Supplier<BaseRenderer>>()
init {
register { RopeRenderer() }
register { A2BRenderer() }
register { TimedA2BRenderer() }
}
private fun register(supplier: Supplier<BaseRenderer>) {
suppliers.add(supplier)
strToIdx[supplier.get().getTypeName()] = suppliers.size - 1
}
fun typeToIdx(type: String) = strToIdx[type]
fun idxToSupplier(idx: Int) = suppliers[idx]
}
class ClientSynchronisedRenderingData(getServerInstance: () -> ServerSynchronisedData<BaseRenderer>): ClientSynchronisedData<BaseRenderer>("rendering_data", getServerInstance)
class ServerSynchronisedRenderingData(getClientInstance: () -> ClientSynchronisedData<BaseRenderer>): ServerSynchronisedData<BaseRenderer>("rendering_data", getClientInstance) {
//TODO switch from nbt to just directly writing to byte buffer?
fun nbtSave(tag: CompoundTag): CompoundTag {
val save = CompoundTag()
DLOG("SAVING RENDERING DATA")
val point = getNow_ms()
for ((pageId, items) in data) {
if (reservedPagesList.contains(pageId)) { continue }
if (!ConstraintManager.allShips!!.contains(pageId)) { continue }
val shipIdTag = CompoundTag()
for ((id, item) in items) {
val dataItemTag = CompoundTag()
val typeIdx = RenderingTypes.typeToIdx(item.getTypeName())
if (typeIdx == null) {
WLOG("RENDERING ITEM WITH TYPE ${item.getTypeName()} RETURNED NULL TYPE INDEX DURING SAVING")
continue
}
dataItemTag.putInt("typeIdx", typeIdx)
dataItemTag.putByteArray("data", item.serialize().accessByteBufWithCorrectSize())
shipIdTag.put(id.toString(), dataItemTag)
}
save.put(pageId.toString(), shipIdTag)
}
DLOG("FINISHING SAVING RENDERING DATA IN ${getNow_ms() - point} ms")
tag.put("server_synchronised_data_${id}", save)
return tag
}
fun nbtLoad(tag: CompoundTag) {
if (!tag.contains("server_synchronised_data_${id}")) {return}
val save = tag.get("server_synchronised_data_${id}") as CompoundTag
DLOG("LOADING RENDERING DATA")
val point = getNow_ms()
for (shipId in save.allKeys) {
val shipIdTag = save.get(shipId) as CompoundTag
val page = data.getOrPut(shipId.toLong()) { mutableMapOf() }
for (id in shipIdTag.allKeys) {
val dataItemTag = shipIdTag[id] as CompoundTag
val typeIdx = dataItemTag.getInt("typeIdx")
val item = RenderingTypes.idxToSupplier(typeIdx).get()
try {
item.deserialize(FriendlyByteBuf(Unpooled.wrappedBuffer(dataItemTag.getByteArray("data"))))
} catch (e: Exception) {
WLOG("FAILED TO DESERIALIZE RENDER COMMAND OF SHIP ${page} WITH IDX ${typeIdx} AND TYPE ${item.getTypeName()}")
continue
}
page[id.toInt()] = item
idToPage[id.toInt()] = shipId.toLong()
}
}
DLOG("FINISHING LOADING RENDERING DATA in ${getNow_ms() - point} ms")
}
var idToPage = mutableMapOf<Int, Long>()
//TODO think of a better way to expose this
fun addRenderer(shipId1: Long, shipId2: Long, id: Int, renderer: BaseRenderer) {
data.getOrPut(shipId2) { mutableMapOf() }
data.getOrPut(shipId1) { mutableMapOf() }
val idToUse = if (ServerLevelHolder.overworldServerLevel!!.shipObjectWorld.dimensionToGroundBodyIdImmutable.containsValue(shipId1)) {shipId2} else {shipId1}
val page = data[idToUse]!!
page[id] = renderer
idToPage[id] = idToUse
ConstraintManager.getInstance().setDirty()
serverChecksumsUpdatedConnection().sendToClients(ServerLevelHolder.server!!.playerList.players, ServerChecksumsUpdatedPacket(
idToUse, mutableListOf(Pair(id, renderer.hash()))
))
}
fun removeRenderer(id: Int): Boolean {
val pageId = idToPage[id] ?: return false
val page = data[pageId] ?: return false
page.remove(id)
serverChecksumsUpdatedConnection().sendToClients(ServerLevelHolder.server!!.playerList.players, ServerChecksumsUpdatedPacket(
pageId, mutableListOf(Pair(id, byteArrayOf()))
))
return true
}
fun getRenderer(id: Int): BaseRenderer? {
val pageId = idToPage[id] ?: return null
val page = data[pageId] ?: return null
return page[id]
}
var idCounter = 0
private fun trimTimedRenderers() {
val page = data[ReservedRenderingPages.TimedRenderingObjects] ?: return
if (page.isEmpty()) { return }
val toRemove = mutableListOf<Int>()
val current = getNow_ms()
try {
for ((k, item) in page) {
if (item !is TimedRenderer) {toRemove.add(k); continue}
if (item.timestampOfBeginning + item.activeFor_ms < current ) {
toRemove.add(k)
}
}
toRemove.forEach { page.remove(it) }
} catch (e: ConcurrentModificationException) {return}
}
//TODO trim timed objects
fun addTimedRenderer(renderer: BaseRenderer) {
trimTimedRenderers()
val page = data.getOrPut(ReservedRenderingPages.TimedRenderingObjects) { mutableMapOf() }
page[idCounter] = renderer
serverChecksumsUpdatedConnection().sendToClients(ServerLevelHolder.server!!.playerList.players, ServerChecksumsUpdatedPacket(
ReservedRenderingPages.TimedRenderingObjects, mutableListOf(Pair(idCounter, renderer.hash()))
))
idCounter++
}
override fun close() {
super.close()
idCounter = 0
idToPage.clear()
}
}
object SynchronisedRenderingData {
lateinit var clientSynchronisedData: ClientSynchronisedRenderingData
lateinit var serverSynchronisedData: ServerSynchronisedRenderingData
//MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512
val hasher = MessageDigest.getInstance("MD5")
init {
clientSynchronisedData = ClientSynchronisedRenderingData { serverSynchronisedData }
serverSynchronisedData = ServerSynchronisedRenderingData { clientSynchronisedData }
makeServerEvents()
}
private fun makeServerEvents() {
AVSEvents.serverShipRemoveEvent.on {
(shipData), handler ->
serverSynchronisedData.data.remove(shipData.id)
serverSynchronisedData.serverChecksumsUpdatedConnection()
.sendToClients(
ServerLevelHolder.overworldServerLevel!!.server.playerList.players,
ServerChecksumsUpdatedPacket(shipData.id, true)
)
}
VSEvents.shipLoadEvent.on {
(shipData), handler ->
serverSynchronisedData.data.getOrPut(shipData.id) { mutableMapOf() }
}
}
}
| 0 | null |
4
| 3 |
edb1c542dc4b39f642e42c373d122283e83eb3cf
| 8,120 |
VSource
|
MIT License
|
core/baseUi/src/main/java/ir/pooryadb/xappnamex/core/baseUi/BaseViewModel.kt
|
pooryadb
| 569,623,477 | false | null |
package ir.pooryadb.xappnamex.core.baseUi
import android.content.Context
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import ir.pooryadb.xappnamex.core.baseUi.utils.liveData.SingleLiveData
import ir.pooryadb.xappnamex.core.common.data.model.MyResult
import ir.pooryadb.xappnamex.core.common.data.model.MyResult.Loading.asResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
open class BaseViewModel : ViewModel() {
protected open val TAG = this::class.java.simpleName
protected val _liveMessage = SingleLiveData<MessageResult>()
val liveMessage: LiveData<MessageResult>
get() = _liveMessage
fun <T> observeFlow(
flow: Flow<T>,
observeFunction: (T) -> Unit,
) = viewModelScope.launch {
flow.collect {
observeFunction(it)
}
}
fun <T> observeResult(
flow: Flow<T>,
observeFunction: (T) -> Unit,
) = viewModelScope.launch {
flow.asResult().collect {
when (it) {
is MyResult.Error -> {
_liveMessage.postValue(MessageResult.Loading(show = false))
_liveMessage.postValue(
MessageResult.Error(msg = it.throwable.message ?: "Error")
)
}
MyResult.Loading -> _liveMessage.postValue(MessageResult.Loading(show = true))
is MyResult.Success -> {
_liveMessage.postValue(MessageResult.Loading(show = false))
observeFunction.invoke(it.data)
}
}
}
}
fun <T> vmsLaunch(
block: suspend CoroutineScope.() -> T
) = viewModelScope.launch { block() }
}
sealed class MessageResult {
data class Error(@StringRes val msgRes: Int? = null, val msg: String? = null) : MessageResult()
data class Loading(
val show: Boolean,
@StringRes val msgRes: Int? = null,
val msg: String = ""
) : MessageResult()
fun getMessage(context: Context): String = when (this) {
is Error -> if (msgRes != null) context.getString(msgRes) else msg ?: "-"
is Loading -> if (msgRes == null) msg else context.getString(msgRes)
}
}
| 0 |
Kotlin
|
0
| 0 |
5c617d2f8df0f88fe67ddb8385c83a291776eb5a
| 2,375 |
Modulated-Android-Project
|
Apache License 2.0
|
src/main/kotlin/io/battlerune/content/ClientDimensionChangeEventListener.kt
|
scape-tools
| 105,257,050 | false | null |
package io.battlerune.content
import com.google.common.eventbus.Subscribe
import io.battlerune.game.event.impl.ClientDimensionChangeEvent
import io.battlerune.game.widget.DisplayType
class ClientDimensionChangeEventListener {
@Subscribe
fun onEvent(event: ClientDimensionChangeEvent) {
val player = event.player
if (!player.inGame) {
return
}
if (event.resized) {
// if (player.displayType == DisplayType.FIXED) {
// player.displayType = DisplayType.RESIZABLE
// player.client.setRootInterface(player.displayType.root)
// .setInterfaceSets(548, 23, 161, 29)
// .setInterfaceSets(548, 20, 161, 13)
// .setInterfaceSets(548, 13, 161, 3)
// .setInterfaceSets(548, 15, 161, 6)
// .setInterfaceSets(548, 63, 161, 66)
// .setInterfaceSets(548, 65, 161, 68)
// .setInterfaceSets(548, 66, 161, 69)
// .setInterfaceSets(548, 67, 161, 70)
// .setInterfaceSets(548, 68, 161, 71)
// .setInterfaceSets(548, 69, 161, 72)
// .setInterfaceSets(548, 70, 161, 73)
// .setInterfaceSets(548, 71, 161, 74)
// .setInterfaceSets(548, 72, 161, 75)
// .setInterfaceSets(548, 73, 161, 76)
// .setInterfaceSets(548, 74, 161, 77)
// .setInterfaceSets(548, 75, 161, 78)
// .setInterfaceSets(548, 76, 161, 79)
// .setInterfaceSets(548, 77, 161, 80)
// .setInterfaceSets(548, 78, 161, 81)
// .setInterfaceSets(548, 14, 161, 4)
// .setInterfaceSets(548, 18, 161, 9)
// .setInterfaceSets(548, 10, 161, 28)
// .setInterfaceSets(548, 16, 161, 7)
// .setInterfaceSets(548, 17, 161, 8)
// .setInterfaceSets(548, 21, 161, 14)
// }
} else {
if (player.displayType != DisplayType.FIXED) {
player.displayType = DisplayType.FIXED
player.client.setRootInterface(player.displayType.root)
.setInterfaceSets(161, 29, 548, 23)
.setInterfaceSets(161, 13, 548, 20)
.setInterfaceSets(161, 3, 548, 13)
.setInterfaceSets(161, 6, 548, 15)
.setInterfaceSets(161, 66, 548, 63)
.setInterfaceSets(161, 68, 548, 65)
.setInterfaceSets(161, 69, 548, 66)
.setInterfaceSets(161, 70, 548, 67)
.setInterfaceSets(161, 71, 548, 68)
.setInterfaceSets(161, 72, 548, 69)
.setInterfaceSets(161, 73, 548, 70)
.setInterfaceSets(161, 74, 548, 71)
.setInterfaceSets(161, 75, 548, 72)
.setInterfaceSets(161, 76, 548, 73)
.setInterfaceSets(161, 77, 548, 74)
.setInterfaceSets(161, 78, 548, 75)
.setInterfaceSets(161, 79, 548, 76)
.setInterfaceSets(161, 80, 548, 77)
.setInterfaceSets(161, 81, 548, 78)
.setInterfaceSets(161, 4, 548, 14)
.setInterfaceSets(161, 9, 548, 18)
.setInterfaceSets(161, 28, 548, 10)
.setInterfaceSets(161, 7, 548, 16)
.setInterfaceSets(161, 8, 548, 17)
.setInterfaceSets(161, 14, 548, 21)
}
}
println("client dimension change event width ${event.width}, height ${event.height}, resized ${event.resized}")
}
}
| 0 |
Kotlin
|
12
| 9 |
dd711cf4c61cd0af99e8e2d51afee5f5c02bdbad
| 4,027 |
kotlin-osrs
|
MIT License
|
app/src/main/java/hibernate/v2/testyourandroid/ui/main/MainTestAdapter.kt
|
himphen
| 369,255,395 | false | null |
package hibernate.v2.testyourandroid.ui.main
import android.annotation.SuppressLint
import android.graphics.BlendMode
import android.graphics.BlendModeColorFilter
import android.graphics.PorterDuff
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import hibernate.v2.testyourandroid.R
import hibernate.v2.testyourandroid.databinding.ItemMainSectionAdBinding
import hibernate.v2.testyourandroid.databinding.ItemMainSectionIconBinding
import hibernate.v2.testyourandroid.databinding.ItemMainSectionRatingBinding
import hibernate.v2.testyourandroid.databinding.ItemMainSectionTitleBinding
import hibernate.v2.testyourandroid.model.GridItem
import hibernate.v2.testyourandroid.ui.main.item.MainTestAdItem
import hibernate.v2.testyourandroid.ui.main.item.MainTestRatingItem
import hibernate.v2.testyourandroid.ui.main.item.MainTestTitleItem
import hibernate.v2.testyourandroid.util.ext.slideUp
class MainTestAdapter(
private val itemClickListener: ItemClickListener
) : ListAdapter<Any, RecyclerView.ViewHolder>(DiffCallback()) {
class DiffCallback : DiffUtil.ItemCallback<Any>() {
override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean {
return if (oldItem is GridItem && newItem is GridItem) {
oldItem.text == newItem.text
} else if (oldItem is MainTestTitleItem && newItem is MainTestTitleItem) {
true
} else if (oldItem is MainTestRatingItem && newItem is MainTestRatingItem) {
true
} else {
false
}
}
}
interface ItemClickListener {
fun onItemClick(gridItem: GridItem)
fun onRatingSubmitClick()
}
companion object {
const val VIEW_TYPE_TITLE = 0
const val VIEW_TYPE_AD_VIEW = 1
const val VIEW_TYPE_ICON = 2
const val VIEW_TYPE_RATING = 3
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW_TYPE_TITLE -> TitleViewHolder(
ItemMainSectionTitleBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
VIEW_TYPE_AD_VIEW -> AdViewHolder(
ItemMainSectionAdBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
VIEW_TYPE_RATING -> RatingViewHolder(
ItemMainSectionRatingBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
else -> IconViewHolder(
ItemMainSectionIconBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
}
override fun getItemViewType(position: Int): Int {
return when (getItem(position)) {
is GridItem -> VIEW_TYPE_ICON
is MainTestTitleItem -> VIEW_TYPE_TITLE
is MainTestRatingItem -> VIEW_TYPE_RATING
else -> VIEW_TYPE_AD_VIEW
}
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is RatingViewHolder -> {
val itemBinding = holder.viewBinding
itemBinding.submitBtn.setOnClickListener {
val rating = itemBinding.ratingBar.rating
Firebase.analytics.logEvent("home_rating") {
param("value", rating.toString())
}
if (rating >= 4) {
itemClickListener.onRatingSubmitClick()
}
itemBinding.root.slideUp()
}
itemBinding.skipBtn.setOnClickListener {
itemBinding.root.slideUp()
}
}
is IconViewHolder -> {
val itemBinding = holder.viewBinding
val gridItem = getItem(position) as GridItem
itemBinding.mainIv.load(gridItem.image)
itemBinding.mainTv.text = gridItem.text
when (gridItem.badge) {
GridItem.Badge.NEW -> {
itemBinding.badgeTv.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
background.colorFilter = BlendModeColorFilter(
ContextCompat.getColor(
itemBinding.mainIv.context,
R.color.lineColor4
),
BlendMode.SRC_ATOP
)
} else {
background.setColorFilter(
ContextCompat.getColor(
itemBinding.mainIv.context,
R.color.lineColor4
),
PorterDuff.Mode.SRC_ATOP
)
}
text = "NEW"
visibility = View.VISIBLE
}
}
GridItem.Badge.BETA -> {
itemBinding.badgeTv.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
background.colorFilter = BlendModeColorFilter(
ContextCompat.getColor(
itemBinding.mainIv.context,
R.color.lineColor4
),
BlendMode.SRC_ATOP
)
} else {
background.setColorFilter(
ContextCompat.getColor(
itemBinding.mainIv.context,
R.color.lineColor4
),
PorterDuff.Mode.SRC_ATOP
)
}
text = "BETA"
visibility = View.VISIBLE
}
}
GridItem.Badge.NONE -> {
itemBinding.badgeTv.visibility = View.GONE
}
}
itemBinding.rootView.tag = gridItem
itemBinding.rootView.setOnClickListener { v ->
itemClickListener.onItemClick(v.tag as GridItem)
}
}
is TitleViewHolder -> {
val itemBinding = holder.viewBinding
val item = getItem(position) as MainTestTitleItem
itemBinding.titleTv.text = item.title
}
is AdViewHolder -> {
val itemBinding = holder.viewBinding
val item = getItem(position) as MainTestAdItem
if (itemBinding.rootView.childCount > 0) {
itemBinding.rootView.removeAllViews()
}
(item.adView.parent as? ViewGroup)?.removeView(item.adView)
itemBinding.rootView.addView(item.adView)
}
}
}
internal class TitleViewHolder(val viewBinding: ItemMainSectionTitleBinding) :
RecyclerView.ViewHolder(viewBinding.root)
internal class IconViewHolder(val viewBinding: ItemMainSectionIconBinding) :
RecyclerView.ViewHolder(viewBinding.root)
internal class AdViewHolder(val viewBinding: ItemMainSectionAdBinding) :
RecyclerView.ViewHolder(viewBinding.root)
internal class RatingViewHolder(val viewBinding: ItemMainSectionRatingBinding) :
RecyclerView.ViewHolder(viewBinding.root)
}
| 0 |
Kotlin
|
1
| 0 |
d9a0966651a1c6c48912b578fff9ade8d84dcb7b
| 8,844 |
TestYourAndroid
|
Apache License 2.0
|
server/server-app/src/main/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepository.kt
|
craigatk
| 226,096,594 | false |
{"Kotlin": 1053158, "TypeScript": 382254, "Groovy": 310183, "JavaScript": 224938, "Java": 20952, "HTML": 581, "Shell": 573, "Procfile": 260, "Dockerfile": 175, "Python": 72}
|
package projektor.testrun.attributes
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jooq.DSLContext
import org.jooq.exception.DataAccessException
import projektor.database.generated.Tables.TEST_RUN_SYSTEM_ATTRIBUTES
import projektor.server.api.PublicId
import projektor.server.api.attributes.TestRunSystemAttributes
class TestRunSystemAttributesDatabaseRepository(private val dslContext: DSLContext) : TestRunSystemAttributesRepository {
override suspend fun fetchAttributes(publicId: PublicId): TestRunSystemAttributes? =
withContext(Dispatchers.IO) {
dslContext
.select(TEST_RUN_SYSTEM_ATTRIBUTES.fields().toList())
.from(TEST_RUN_SYSTEM_ATTRIBUTES)
.where(TEST_RUN_SYSTEM_ATTRIBUTES.TEST_RUN_PUBLIC_ID.eq(publicId.id))
.fetchOneInto(TestRunSystemAttributes::class.java)
}
override suspend fun pin(publicId: PublicId) = upsertPinned(publicId, true)
override suspend fun unpin(publicId: PublicId) = upsertPinned(publicId, false)
private suspend fun upsertPinned(
publicId: PublicId,
newPinnedValue: Boolean,
): Int =
withContext(Dispatchers.IO) {
try {
dslContext
.insertInto(
TEST_RUN_SYSTEM_ATTRIBUTES,
TEST_RUN_SYSTEM_ATTRIBUTES.TEST_RUN_PUBLIC_ID,
TEST_RUN_SYSTEM_ATTRIBUTES.PINNED,
)
.values(publicId.id, newPinnedValue)
.onDuplicateKeyUpdate()
.set(TEST_RUN_SYSTEM_ATTRIBUTES.PINNED, newPinnedValue)
.execute()
} catch (e: DataAccessException) {
0
}
}
}
| 14 |
Kotlin
|
15
| 47 |
fcf94c701b6fefadaff89462ee99ac33d0502d74
| 1,810 |
projektor
|
MIT License
|
core-v4/core-v4-common/src/main/java/com/github/teracy/odpt/core/v4/common/request/OperatorArgument.kt
|
teracy
| 193,032,147 | false | null |
package com.github.teracy.odpt.core.v4.common.request
import com.github.teracy.odpt.model.OperatorId
/**
* 事業者情報検索引数
*/
sealed class OperatorArgument(
/**
* 固有識別子(ucode)のリスト
*/
val idList: List<String>? = null,
/**
* 固有識別子別名(事業者ID)のリスト
*/
val sameAsList: List<String>? = null
) {
/**
* 固有識別子による検索
*
* @param idList 固有識別子のリスト
*/
class ById(idList: List<String>) :
OperatorArgument(idList = idList)
/**
* 事業者IDによる検索
*
* @param operatorIdList 事業者IDのリスト
*/
class ByOperatorId(operatorIdList: List<OperatorId>) :
OperatorArgument(sameAsList = operatorIdList.map { it.id })
}
| 0 |
Kotlin
|
0
| 1 |
002554e4ca6e2f460207cfd1cb8265c2267f149d
| 683 |
odpt
|
Apache License 2.0
|
modules/version3/src/main/kotlin/com/uogames/dictinary/v3/provider/ImageProvider.kt
|
Gizcerbes
| 524,145,733 | false | null |
package com.uogames.dictinary.v3.provider
import com.uogames.dictinary.v3.db.dao.ImageService
import com.uogames.dictinary.v3.db.entity.Image
import com.uogames.dictinary.v3.db.entity.User
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.UUID
object ImageProvider {
private val imageService = ImageService
fun get(imageID: UUID) = transaction { imageService.get(imageID) }
fun getView(imageID: UUID) = transaction { imageService.getView(imageID) }
fun new(image: Image, user: User) = transaction { imageService.new(image, user) }
fun update(image: Image, user: User) = transaction { imageService.update(image, user) }
fun delete(id: UUID) = transaction { imageService.delete(id) }
fun cleanImage(id: UUID) = transaction { imageService.cleanImage(id) }
}
| 0 |
Kotlin
|
0
| 0 |
fc80d70d7c744b2308bf0de27b38127527e36e4f
| 817 |
RememberCardServer
|
Apache License 2.0
|
core/ui/src/main/java/ru/aleshin/core/ui/mappers/PriorityMapper.kt
|
v1tzor
| 638,022,252 | false |
{"Kotlin": 1688951}
|
/*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.aleshin.core.ui.mappers
import ru.aleshin.core.domain.entities.schedules.TaskPriority
import ru.aleshin.core.ui.views.MonogramPriority
/**
* @author <NAME> on 16.01.2024.
*/
fun TaskPriority.mapToUi() = when (this) {
TaskPriority.STANDARD -> MonogramPriority.STANDARD
TaskPriority.MEDIUM -> MonogramPriority.MEDIUM
TaskPriority.MAX -> MonogramPriority.MAX
}
| 7 |
Kotlin
|
31
| 262 |
4238f8d894ab51859b480d339e6b23ab89d79190
| 970 |
TimePlanner
|
Apache License 2.0
|
library/src/commonMain/kotlin/dev/kryptonreborn/ecdsa/EcKeyPair.kt
|
KryptonReborn
| 792,400,063 | false |
{"Kotlin": 28490}
|
package dev.kryptonreborn.ecdsa
import com.ionspin.kotlin.bignum.integer.BigInteger
/**
* A class to store public and private keys in a keypair.
*
* @property publicKey The public key corresponding to the private key
* @property privateKey The private key of the keypair.
*/
data class EcKeyPair(
val publicKey: EcPoint,
val privateKey: BigInteger,
)
| 1 |
Kotlin
|
0
| 0 |
ac91443a8ab99a1659c9a09fb1345fdf91866b73
| 366 |
kotlin-ecdsa
|
Apache License 2.0
|
app/src/main/java/com/ternaryop/photoshelf/customsearch/CustomSearchResult.kt
|
vaginessa
| 128,988,863 | true |
{"Kotlin": 478578}
|
package com.ternaryop.photoshelf.customsearch
import org.json.JSONException
import org.json.JSONObject
/**
* Created by dave on 01/05/17.
* Hold the custom search result
*/
@Suppress("MemberVisibilityCanBePrivate")
class CustomSearchResult @Throws(JSONException::class) constructor(json: JSONObject) {
var correctedQuery: String? = null
companion object {
@Throws(JSONException::class)
fun getCorrectedQuery(json: JSONObject): String? {
return if (!json.has("spelling")) {
null
} else json.getJSONObject("spelling").getString("correctedQuery")
}
}
init {
correctedQuery = getCorrectedQuery(json)
}
}
| 1 |
Kotlin
|
0
| 0 |
6762e4ea483d2079e005319acc039b1b27ad90d5
| 701 |
photoshelf
|
MIT License
|
android/app/src/main/kotlin/be/chiahpa/khiin/keyboard/KeyboardDsl.kt
|
OMAMA-Taioan
| 634,144,761 | false |
{"Rust": 354725, "Kotlin": 48490, "Swift": 45584, "Svelte": 12104, "Shell": 5204, "C": 4007, "PowerShell": 3819, "JavaScript": 1756, "TypeScript": 1623, "CSS": 721, "HTML": 371}
|
package be.chiahpa.khiin.keyboard
import android.view.KeyEvent
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import be.chiahpa.khiin.keyboard.components.KeyPosition
import be.chiahpa.khiin.utils.ImmutableList
interface KeyboardLayoutScope {
fun row(content: KeyboardRowScope.() -> Unit)
var rowHeight: Dp
}
class KeyboardLayoutScopeImpl : KeyboardLayoutScope {
val rows: MutableList<KeyboardRowData> = mutableListOf()
override var rowHeight = 0.dp
override fun row(content: KeyboardRowScope.() -> Unit) {
val scopeContent = KeyboardRowScopeImpl().apply(content)
rows.add(KeyboardRowData(scopeContent.keys))
}
fun toImmutable(): ImmutableList<ImmutableList<KeyData>> =
ImmutableList(rows.map { row ->
ImmutableList(row.keys.toList())
}.toList())
}
interface KeyboardRowScope {
fun alpha(
label: String,
weight: Float = 1f,
position: KeyPosition = KeyPosition.FULL_WEIGHT
)
fun shift(weight: Float = 1f)
fun backspace(weight: Float = 1f)
fun symbols(weight: Float = 1f)
fun spacebar(weight: Float = 1f)
fun enter(weight: Float = 1f)
}
class KeyboardRowScopeImpl : KeyboardRowScope {
val keys: MutableList<KeyData> = mutableListOf()
override fun alpha(label: String, weight: Float, position: KeyPosition) {
keys.add(
KeyData(
weight = weight,
label = label,
type = KeyType.LETTER,
position = position
)
)
}
override fun shift(weight: Float) {
keys.add(KeyData(weight = weight, type = KeyType.SHIFT))
}
override fun backspace(weight: Float) {
keys.add(KeyData(weight = weight, type = KeyType.BACKSPACE))
}
override fun symbols(weight: Float) {
keys.add(KeyData(weight = weight, type = KeyType.SYMBOLS))
}
override fun spacebar(weight: Float) {
keys.add(KeyData(weight = weight, type = KeyType.SPACEBAR))
}
override fun enter(weight: Float) {
keys.add(KeyData(weight = weight, type = KeyType.ENTER))
}
}
| 4 |
Rust
|
3
| 8 |
9a7ad181c68470817a887ba92282e481f3c41c38
| 2,160 |
khiin-rs
|
MIT License
|
app/src/main/java/com/celzero/bravedns/glide/RethinkGlideModule.kt
|
celzero
| 270,683,546 | false | null |
/*
Copyright 2021 RethinkDNS and its authors
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.celzero.bravedns.glide
import android.content.Context
import android.util.Log
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.module.AppGlideModule
import com.celzero.bravedns.ui.HomeScreenActivity.GlobalVariable.DEBUG
/**
* Defines the options to use when initializing Glide within an application.
* As of now, limit for memory cache and disk cache is added.
* By default, Glide uses LRUCache for both memory and disk.
* Ref - https://bumptech.github.io/glide/doc/configuration.html
*/
@GlideModule
class RethinkGlideModule : AppGlideModule() {
override fun applyOptions(context: Context, builder: GlideBuilder) {
val memoryCacheSizeBytes = 1024 * 1024 * 50 // 50mb
builder.setMemoryCache(LruResourceCache(memoryCacheSizeBytes.toLong()))
val diskCacheSizeBytes = 1024 * 1024 * 100 // 100 MB
builder.setDiskCache(InternalCacheDiskCacheFactory(context, diskCacheSizeBytes.toLong()))
if (DEBUG) {
builder.setLogLevel(Log.DEBUG)
} else {
builder.setLogLevel(Log.ERROR)
}
}
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
super.registerComponents(context, glide, registry)
}
}
| 169 | null |
47
| 557 |
161674b1cdbdd72fefee5edd953179a637e00f6f
| 2,077 |
rethink-app
|
Apache License 2.0
|
norm/src/testFixtures/kotlin/net/aholbrook/norm/models/LotSpace.kt
|
atholbro
| 463,315,697 | false | null |
package net.aholbrook.norm.models
import com.github.michaelbull.result.Result
import com.github.michaelbull.result.binding
import com.github.michaelbull.result.getOr
import net.aholbrook.norm.DbError
import net.aholbrook.norm.sql.result.RowData
data class LotSpace(
val lot: Lot,
val space: Space?,
) {
companion object {
fun decode(
row: RowData,
lotPrefix: String = "l_",
spacePrefix: String = "s_",
): Result<LotSpace, DbError> = binding {
LotSpace(
lot = Lot.table.entityDecoder(row, lotPrefix).bind(),
space = Space.table.entityDecoder(row, spacePrefix).getOr(null),
)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
7623b2918671d34328ceab7f0f36979d66a80ade
| 714 |
rates-service
|
MIT License
|
spigot/src/main/kotlin/me/mrkirby153/bridgebot/spigot/chat/ChatHandler.kt
|
mrkirby153
| 96,916,299 | false | null |
package me.mrkirby153.bridgebot.spigot.chat
import me.mrkirby153.bridgebot.spigot.Bridge
import net.md_5.bungee.api.ChatColor
import org.bukkit.Bukkit
import org.json.JSONArray
import org.json.JSONObject
object ChatHandler {
lateinit var plugin: Bridge
private val channels = mutableMapOf<String, Channel>()
fun loadChannels() {
val cfg = plugin.config
cfg.getConfigurationSection("channels").getKeys(false).forEach { key ->
plugin.logger.info("Loading channel $key")
val prefix = cfg.getString("channels.$key.prefix")
val nameColor = ChatColor.valueOf(cfg.getString("channels.$key.name_color"))
val nameFormat = cfg.getString("channels.$key.name_format")
val textColor = ChatColor.valueOf(cfg.getString("channels.$key.text_color"))
val server = cfg.getString("channels.$key.server")
val channel = cfg.getString("channels.$key.channel")
val twoWay = cfg.getBoolean("channels.$key.twoWay")
val joins = cfg.getBoolean("channels.$key.joins")
val deaths = cfg.getBoolean("channels.$key.deaths")
val chan = Channel(prefix, nameColor, nameFormat, textColor, server, channel, twoWay, joins, deaths)
plugin.logger.info("Loaded channel $chan")
channels["$server.$channel"] = chan
}
}
fun process(server: String, channel: String, data: JSONObject) {
val channelSettings = this.channels["$server.$channel"] ?: return
if (data.has("action")) {
val action = data.getString("action")
if (action == "playercount") {
val obj = JSONObject()
obj.put("action", "playercount_resp")
obj.put("players", JSONArray())
Bukkit.getOnlinePlayers().forEach {
obj.append("players", it.name)
}
plugin.redisConnector.publish("action:$server.$channel", obj.toString())
}
return
}
val message = buildString {
append(ChatColor.translateAlternateColorCodes('&', channelSettings.prefix))
append(ChatColor.RESET)
append(channelSettings.nameColor)
append(channelSettings.nameFormat.format(data.optString("author")))
append(channelSettings.textColor)
append(data.optString("content"))
}
if (Bukkit.getOnlinePlayers().isNotEmpty())
Bukkit.broadcastMessage(message)
}
fun getChannels(): Collection<Channel> {
return this.channels.values
}
fun reload(){
this.channels.clear()
this.loadChannels()
}
data class Channel(val prefix: String, val nameColor: ChatColor, val nameFormat: String, val textColor: ChatColor,
val server: String, val channel: String, val twoWay: Boolean, val sendJoin: Boolean, val sendDeaths: Boolean)
}
| 0 |
Kotlin
|
0
| 0 |
913836ddd5867200b9e94af58741caeec995c271
| 2,964 |
BridgeBot
|
MIT License
|
src/SimpleClassSample.kt
|
ederpadilla
| 93,013,152 | false | null |
/**
* Created by ederpadilla on 03/06/17.
*/
class SimpleClassSample(type : String , model : Int , price : Double , milesDrive : Int, owner : String){ //Digamos que es un carro
var owner : String ? = null
var price : Double ? = null
var miles : Int ? = null
init {
println("type $type")
println("model $model")
println("price $price")
println("miles drive $milesDrive")
println("owner $owner")
this.owner = owner
this.price = price
this.miles = milesDrive
}
fun GetOwner(): String ? {
return this.owner
}
fun GetPrice() : Double ? {
return this.price!! - (this.miles!!.toDouble()*10)
}
}
fun main (args : Array<String>){
var simpleClassObject = SimpleClassSample("Nuevo",2017,13.0,120,"Eder")
println("price of the first ${simpleClassObject.GetPrice()}")
var simpleClassObjectTwo = SimpleClassSample("Nuevo dos ",20172,14.0,140,"Eder dos")
println("Especificas propiedades de el segundo ejemplo ${simpleClassObjectTwo.GetPrice()} y el dueño ${simpleClassObjectTwo.GetOwner()}")
}
| 0 |
Kotlin
|
0
| 0 |
4b55212f7ba6ee76ecd4a046f8b17f5d82f45dc0
| 1,120 |
MyIntellijKotlinProject
|
Apache License 2.0
|
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/solid/Atlas.kt
|
DevSrSouza
| 311,134,756 | false | null |
package compose.icons.fontawesomeicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.fontawesomeicons.SolidGroup
public val SolidGroup.Atlas: ImageVector
get() {
if (_atlas != null) {
return _atlas!!
}
_atlas = Builder(name = "Atlas", defaultWidth = 448.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 448.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(318.38f, 208.0f)
horizontalLineToRelative(-39.09f)
curveToRelative(-1.49f, 27.03f, -6.54f, 51.35f, -14.21f, 70.41f)
curveToRelative(27.71f, -13.24f, 48.02f, -39.19f, 53.3f, -70.41f)
close()
moveTo(318.38f, 176.0f)
curveToRelative(-5.29f, -31.22f, -25.59f, -57.17f, -53.3f, -70.41f)
curveToRelative(7.68f, 19.06f, 12.72f, 43.38f, 14.21f, 70.41f)
horizontalLineToRelative(39.09f)
close()
moveTo(224.0f, 97.31f)
curveToRelative(-7.69f, 7.45f, -20.77f, 34.42f, -23.43f, 78.69f)
horizontalLineToRelative(46.87f)
curveToRelative(-2.67f, -44.26f, -15.75f, -71.24f, -23.44f, -78.69f)
close()
moveTo(182.92f, 105.59f)
curveToRelative(-27.71f, 13.24f, -48.02f, 39.19f, -53.3f, 70.41f)
horizontalLineToRelative(39.09f)
curveToRelative(1.49f, -27.03f, 6.53f, -51.35f, 14.21f, -70.41f)
close()
moveTo(182.92f, 278.41f)
curveToRelative(-7.68f, -19.06f, -12.72f, -43.38f, -14.21f, -70.41f)
horizontalLineToRelative(-39.09f)
curveToRelative(5.28f, 31.22f, 25.59f, 57.17f, 53.3f, 70.41f)
close()
moveTo(247.43f, 208.0f)
horizontalLineToRelative(-46.87f)
curveToRelative(2.66f, 44.26f, 15.74f, 71.24f, 23.43f, 78.69f)
curveToRelative(7.7f, -7.45f, 20.78f, -34.43f, 23.44f, -78.69f)
close()
moveTo(448.0f, 358.4f)
lineTo(448.0f, 25.6f)
curveToRelative(0.0f, -16.0f, -9.6f, -25.6f, -25.6f, -25.6f)
lineTo(96.0f, 0.0f)
curveTo(41.6f, 0.0f, 0.0f, 41.6f, 0.0f, 96.0f)
verticalLineToRelative(320.0f)
curveToRelative(0.0f, 54.4f, 41.6f, 96.0f, 96.0f, 96.0f)
horizontalLineToRelative(326.4f)
curveToRelative(12.8f, 0.0f, 25.6f, -9.6f, 25.6f, -25.6f)
verticalLineToRelative(-16.0f)
curveToRelative(0.0f, -6.4f, -3.2f, -12.8f, -9.6f, -19.2f)
curveToRelative(-3.2f, -16.0f, -3.2f, -60.8f, 0.0f, -73.6f)
curveToRelative(6.4f, -3.2f, 9.6f, -9.6f, 9.6f, -19.2f)
close()
moveTo(224.0f, 64.0f)
curveToRelative(70.69f, 0.0f, 128.0f, 57.31f, 128.0f, 128.0f)
reflectiveCurveToRelative(-57.31f, 128.0f, -128.0f, 128.0f)
reflectiveCurveTo(96.0f, 262.69f, 96.0f, 192.0f)
reflectiveCurveTo(153.31f, 64.0f, 224.0f, 64.0f)
close()
moveTo(384.0f, 448.0f)
lineTo(96.0f, 448.0f)
curveToRelative(-19.2f, 0.0f, -32.0f, -12.8f, -32.0f, -32.0f)
reflectiveCurveToRelative(16.0f, -32.0f, 32.0f, -32.0f)
horizontalLineToRelative(288.0f)
verticalLineToRelative(64.0f)
close()
}
}
.build()
return _atlas!!
}
private var _atlas: ImageVector? = null
| 17 | null |
25
| 571 |
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 4,346 |
compose-icons
|
MIT License
|
velocity/src/main/kotlin/net/azisaba/api/velocity/commands/APIKeyCommand.kt
|
AzisabaNetwork
| 510,787,122 | false |
{"Kotlin": 158104}
|
package net.azisaba.api.velocity.commands
import com.mojang.brigadier.arguments.BoolArgumentType
import com.mojang.brigadier.builder.LiteralArgumentBuilder
import com.velocitypowered.api.command.CommandSource
import com.velocitypowered.api.proxy.Player
import net.azisaba.api.velocity.DatabaseManager
import net.azisaba.api.schemes.APIKey
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.event.ClickEvent
import net.kyori.adventure.text.event.HoverEvent
import net.kyori.adventure.text.format.NamedTextColor
import net.kyori.adventure.text.format.TextDecoration
import java.util.UUID
object APIKeyCommand : AbstractCommand() {
override fun createBuilder(): LiteralArgumentBuilder<CommandSource> =
literal("apikey")
.requires { it is Player && it.hasPermission("azisabaapi.apikey") }
.then(argument("force", BoolArgumentType.bool())
.executes { execute(it.source as Player, BoolArgumentType.getBool(it, "force")) }
)
.executes { execute(it.source as Player, false) }
private fun execute(player: Player, force: Boolean): Int {
val existingAPIKey = APIKey.select("SELECT * FROM `api_keys` WHERE `player` = ? LIMIT 1", player.uniqueId.toString()).firstOrNull()
if (existingAPIKey != null) {
if (force) {
DatabaseManager.execute("DELETE FROM `api_keys` WHERE `player` = ?") {
it.setString(1, player.uniqueId.toString())
it.executeUpdate()
}
} else {
player.sendMessage(
Component.text("すでにAPIキーが存在します。", NamedTextColor.RED)
.append(Component.text("/apikey true", NamedTextColor.YELLOW))
.append(Component.text("で再発行できますが、元のAPIキーは使用できなくなります。", NamedTextColor.RED))
)
return 0
}
}
val newAPIKey = APIKey(0, UUID.randomUUID().toString(), player.uniqueId, System.currentTimeMillis(), 0)
APIKey.insertB("api_keys", newAPIKey) { put("id", null); put("0", null) }
// we can't just send the key as chat message because it is logged in client's latest.log
// however, `click_event`s are not logged (at least on vanilla), so we can use that to send the key.
player.sendMessage(
Component.text("APIキーを発行しました。コピーするには", NamedTextColor.GREEN)
.append(
Component.text("ここをクリック", NamedTextColor.AQUA)
.decorate(TextDecoration.UNDERLINED)
.hoverEvent(HoverEvent.showText(Component.text("クリックでコピー")))
.clickEvent(ClickEvent.copyToClipboard(newAPIKey.key))
)
.append(Component.text("してください。", NamedTextColor.GREEN)))
player.sendMessage(Component.text("再発行は/apikey trueで実行できます。実行すると元のAPIキーは使用できなくなります。", NamedTextColor.YELLOW))
return 0
}
}
| 7 |
Kotlin
|
0
| 5 |
b9bc72a5a9adf8e3c648cf118f327b37c0007d67
| 2,987 |
api
|
MIT License
|
app/src/main/java/com/duckduckgo/app/browser/webview/SslWarningLayout.kt
|
hojat72elect
| 822,396,044 | false |
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
|
package com.duckduckgo.app.browser.webview
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.webkit.SslErrorHandler
import android.widget.FrameLayout
import com.duckduckgo.app.browser.R
import com.duckduckgo.app.browser.SSLErrorType
import com.duckduckgo.app.browser.SSLErrorType.WRONG_HOST
import com.duckduckgo.app.browser.SslErrorResponse
import com.duckduckgo.app.browser.databinding.ViewSslWarningBinding
import com.duckduckgo.app.browser.webview.SslWarningLayout.Action.Advance
import com.duckduckgo.app.browser.webview.SslWarningLayout.Action.LeaveSite
import com.duckduckgo.app.browser.webview.SslWarningLayout.Action.Proceed
import com.duckduckgo.common.ui.view.gone
import com.duckduckgo.common.ui.view.show
import com.duckduckgo.common.ui.viewbinding.viewBinding
import com.duckduckgo.common.utils.extensions.applyBoldSpanTo
import com.duckduckgo.common.utils.extensions.html
import com.duckduckgo.common.utils.extractDomain
class SslWarningLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
) : FrameLayout(context, attrs, defStyle) {
sealed class Action {
data class Shown(val errorType: SSLErrorType) : Action()
object Proceed : Action()
object Advance : Action()
object LeaveSite : Action()
}
private val binding: ViewSslWarningBinding by viewBinding()
fun bind(
handler: SslErrorHandler,
errorResponse: SslErrorResponse,
actionHandler: (Action) -> Unit,
) {
resetViewState()
actionHandler.invoke(Action.Shown(errorResponse.errorType))
with(binding) {
configureCopy(errorResponse)
setListeners(handler, actionHandler)
}
}
private fun resetViewState() {
with(binding) {
sslErrorAdvancedCTA.show()
sslErrorAdvancedGroup.gone()
}
}
private fun configureCopy(errorResponse: SslErrorResponse) {
with(binding) {
sslErrorHeadline.text =
context.getString(R.string.sslErrorHeadline, errorResponse.error.url)
.applyBoldSpanTo(errorResponse.error.url)
sslErrorAcceptCta.text = context.getString(R.string.sslErrorExpandedCTA).html(context)
formatSecondaryCopy(errorResponse)
}
}
private fun formatSecondaryCopy(errorResponse: SslErrorResponse) {
with(binding) {
when (errorResponse.errorType) {
WRONG_HOST -> {
val url = errorResponse.error.url
val domain = url.extractDomain()
val text = if (domain != null) {
val urlDomain = "*.$domain"
context.getString(errorResponse.errorType.errorId, url, domain)
.applyBoldSpanTo(listOf(url, urlDomain))
} else {
context.getString(errorResponse.errorType.errorId, url, url)
.applyBoldSpanTo(url)
}
sslErrorExpandedMessage.text = text
}
else -> {
sslErrorExpandedMessage.text =
context.getString(errorResponse.errorType.errorId, errorResponse.error.url)
.applyBoldSpanTo(
errorResponse.error.url,
)
}
}
}
}
private fun setListeners(
handler: SslErrorHandler,
actionHandler: (Action) -> Unit,
) {
with(binding) {
sslErrorAcceptCta.setOnClickListener {
handler.proceed()
actionHandler.invoke(Proceed)
}
sslErrorLeaveSiteCTA.setOnClickListener {
handler.cancel()
actionHandler.invoke(LeaveSite)
}
sslErrorAdvancedCTA.setOnClickListener {
actionHandler.invoke(Advance)
sslErrorAdvancedCTA.gone()
sslErrorAdvancedGroup.show()
errorLayout.post {
errorLayout.fullScroll(View.FOCUS_DOWN)
}
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
b89591136b60933d6a03fac43a38ee183116b7f8
| 4,312 |
DuckDuckGo
|
Apache License 2.0
|
features/categorydetails/src/main/java/com/aliumujib/artic/categorydetails/presentation/CategoryDetailsIntent.kt
|
aliumujib
| 210,103,091 | false |
{"Kotlin": 448725}
|
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliumujib.artic.categorydetails.presentation
import com.aliumujib.artic.domain.models.Article
import com.aliumujib.artic.views.mvi.MVIIntent
sealed class CategoryDetailsIntent:MVIIntent {
data class SetArticleBookmarkStatusIntent(val article: Article, val isBookmarked :Boolean) : CategoryDetailsIntent()
data class LoadCategoryArticlesIntent(val categoryId: Int) : CategoryDetailsIntent()
data class FetchMoreArticlesForCategoryIntent(val categoryId: Int) : CategoryDetailsIntent()
}
| 0 |
Kotlin
|
6
| 47 |
ad986536632f532d0d24aa3847bdef33ab7a5d16
| 1,101 |
Artic
|
Apache License 2.0
|
FreshlyPressed/src/main/java/com/automattic/freshlypressed/model/datatransferobjects/responses/PostResponse.kt
|
informramiz
| 282,189,977 | false | null |
package com.automattic.freshlypressed.model.datatransferobjects.responses
import com.automattic.freshlypressed.model.db.entities.AuthorEntity
import com.automattic.freshlypressed.model.db.entities.PostEntity
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Ramiz Raja on 22/07/2020.
*/
@JsonClass(generateAdapter = true)
data class PostResponse(
@Json(name = "ID")
val id: Long,
@Json(name = "site_ID")
val siteId: Long,
@Json(name = "author")
val author: AuthorResponse,
@Json(name = "date")
val date: String,
@Json(name = "title")
val title: String,
@Json(name = "URL")
val url: String,
@Json(name = "excerpt")
val excerpt: String,
@Json(name = "featured_image")
val featuredImageUrl: String? = null
) {
val parsedDate: Date = DATE_FORMATTER.parse(date) ?: Calendar.getInstance().time
companion object {
private const val DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ"
val DATE_FORMATTER = SimpleDateFormat(DATE_FORMAT, Locale.US)
}
}
fun PostResponse.toPostEntity(page: Int): PostEntity {
return PostEntity(id, siteId, author.toAuthorEntity(), parsedDate.time, title, url, excerpt, featuredImageUrl, page = page)
}
fun AuthorResponse.toAuthorEntity(): AuthorEntity {
return AuthorEntity(id, name, url)
}
| 0 |
Kotlin
|
0
| 2 |
bbe57131064b460642a36f65b32dc3b77a02867b
| 1,393 |
FreshlyPressed
|
MIT License
|
app/src/main/java/com/example/hannapp/ui/button/FAB.kt
|
StefanElsnerDev
| 603,414,723 | false | null |
package com.example.hannapp.ui.button
import android.content.res.Configuration.UI_MODE_NIGHT_NO
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun FAB(
icon: @Composable () -> Unit,
onClick: () -> Unit,
) {
FloatingActionButton(
contentColor = MaterialTheme.colorScheme.onBackground,
content = icon,
onClick = onClick
)
}
@Preview(uiMode = UI_MODE_NIGHT_NO)
@Composable
fun FAB_LightMode() {
FAB({ Icon(Icons.Filled.Add, "") }){}
}
@Preview(uiMode = UI_MODE_NIGHT_YES)
@Composable
fun FAB_DarkMode() {
FAB({ Icon(Icons.Filled.Add, "") }){}
}
| 1 |
Kotlin
|
0
| 0 |
8dd2f38f2046b04d4bbcdd6766a416947cf87375
| 949 |
MemApp
|
MIT License
|
src/main/kotlin/md/elway/mapper/Bind.kt
|
ipleac
| 437,253,180 | false | null |
package md.elway.mapper
class Bind<S, T>(val prop: Pair<String, String>, val convert: Convert<S, T>? = null)
| 0 |
Kotlin
|
0
| 8 |
39c78b8099425c05f4d288699a953a3b4447c549
| 109 |
EVMapper
|
Apache License 2.0
|
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/FolderOpen.kt
|
DevSrSouza
| 311,134,756 | false | null |
package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.FolderOpen: ImageVector
get() {
if (_folderOpen != null) {
return _folderOpen!!
}
_folderOpen = Builder(name = "FolderOpen", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp,
viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(5.0f, 3.0f)
lineTo(5.0f, 27.8125f)
lineTo(5.7813f, 27.9688f)
lineTo(17.7813f, 30.4688f)
lineTo(19.0f, 30.7188f)
lineTo(19.0f, 28.0f)
lineTo(25.0f, 28.0f)
lineTo(25.0f, 15.4375f)
lineTo(26.7188f, 13.7188f)
lineTo(27.0f, 13.4063f)
lineTo(27.0f, 3.0f)
close()
moveTo(14.125f, 5.0f)
lineTo(25.0f, 5.0f)
lineTo(25.0f, 12.5625f)
lineTo(23.2813f, 14.2813f)
lineTo(23.0f, 14.5938f)
lineTo(23.0f, 26.0f)
lineTo(19.0f, 26.0f)
lineTo(19.0f, 17.0938f)
lineTo(18.7188f, 16.7813f)
lineTo(17.0f, 15.0625f)
lineTo(17.0f, 5.7188f)
close()
moveTo(7.0f, 5.2813f)
lineTo(15.0f, 7.2813f)
lineTo(15.0f, 15.9063f)
lineTo(15.2813f, 16.2188f)
lineTo(17.0f, 17.9375f)
lineTo(17.0f, 28.2813f)
lineTo(7.0f, 26.1875f)
close()
}
}
.build()
return _folderOpen!!
}
private var _folderOpen: ImageVector? = null
| 15 | null |
20
| 460 |
651badc4ace0137c5541f859f61ffa91e5242b83
| 2,411 |
compose-icons
|
MIT License
|
kcrypto/src/main/kotlin/org/bouncycastle/kcrypto/SignatureCalculator.kt
|
bcgit
| 196,159,414 | false |
{"Kotlin": 458444, "HTML": 419}
|
package org.bouncycastle.kcrypto
import java.io.Closeable
import java.io.OutputStream
interface SignatureCalculator<T>: Closeable
{
val algorithmIdentifier: T
val stream: OutputStream
fun signature(): ByteArray
}
| 0 |
Kotlin
|
15
| 69 |
dc86103f5fef1baf9f6e1cdff17bbf31927637ab
| 222 |
bc-kotlin
|
MIT License
|
library/src/test/kotlin/io/github/dmitrikudrenko/logger/LogTestUtils.kt
|
dmitrikudrenko
| 68,438,168 | false |
{"Gradle": 5, "Java Properties": 2, "Shell": 2, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 2, "XML": 7, "Java": 15, "Kotlin": 11}
|
package io.github.dmitrikudrenko.logger
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import java.util.logging.Formatter
class LogTestUtils {
private lateinit var logcatFormatter: Formatter
private lateinit var formatter: Formatter
@Before
fun `set up`() {
logcatFormatter = mock(Formatter::class.java)
formatter = mock(Formatter::class.java)
}
@Test
fun `should set default formatters 1`() {
Log.setFormatter(logcatFormatter, null)
Log.setup()
assertNotEquals(Log.logcatFormatter, logcatFormatter)
assertNotEquals(Log.formatter, formatter)
}
@Test
fun `should set default formatters 2`() {
Log.setFormatter(null, formatter)
Log.setup()
assertNotEquals(Log.logcatFormatter, logcatFormatter)
assertNotEquals(Log.formatter, formatter)
}
@Test
fun `should set default formatters 3`() {
Log.setFormatter(null, null)
Log.setup()
assertNotEquals(Log.logcatFormatter, logcatFormatter)
assertNotEquals(Log.formatter, formatter)
}
@Test
fun `should set default formatters 4`() {
Log.setFormatter(logcatFormatter, formatter)
Log.setup()
assertEquals(Log.logcatFormatter, logcatFormatter)
assertEquals(Log.formatter, formatter)
}
}
| 1 | null |
1
| 1 |
db368b3cf9727a2bc51f0235601f96cc21d2c1db
| 1,448 |
Logger
|
Apache License 2.0
|
app/src/main/java/org/stepik/android/remote/review_instruction/service/ReviewInstructionService.kt
|
StepicOrg
| 42,045,161 | false |
{"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618}
|
package org.stepik.android.remote.review_instruction.service
import org.stepik.android.remote.review_instruction.model.ReviewInstructionResponse
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Query
interface ReviewInstructionService {
@GET("api/instructions")
fun getReviewInstructions(@Query("ids[]") ids: List<Long>): Single<ReviewInstructionResponse>
}
| 13 |
Kotlin
|
54
| 189 |
dd12cb96811a6fc2a7addcd969381570e335aca7
| 393 |
stepik-android
|
Apache License 2.0
|
jvm/jvm-analysis-kotlin-tests/testData/codeInspection/unstableApiUsage/scheduledForRemoval/ScheduledForRemovalElementsTest.kt
|
hieuprogrammer
| 284,920,751 | false | null |
@file:Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE", "UNUSED_VALUE", "UNUSED_PARAMETER", "UNUSED_VARIABLE")
import pkg.<error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>
import pkg.<error descr="'pkg.ClassWithScheduledForRemovalTypeInSignature' is scheduled for removal because its signature references class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">ClassWithScheduledForRemovalTypeInSignature</error>
import pkg.OwnerOfMembersWithScheduledForRemovalTypesInSignature
import pkg.<error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>.<error descr="'NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</error>
import pkg.<error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>.<error descr="'staticNonAnnotatedMethodInAnnotatedClass()' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">staticNonAnnotatedMethodInAnnotatedClass</error>
import pkg.<error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>.<error descr="'ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is scheduled for removal in version 123.456">ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</error>
import pkg.<error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>.<error descr="'staticAnnotatedMethodInAnnotatedClass()' is scheduled for removal in version 123.456">staticAnnotatedMethodInAnnotatedClass</error>
import pkg.NonAnnotatedClass
import pkg.NonAnnotatedClass.NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS
import pkg.NonAnnotatedClass.staticNonAnnotatedMethodInNonAnnotatedClass
import pkg.NonAnnotatedClass.<error descr="'ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS' is scheduled for removal in version 123.456">ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS</error>
import pkg.NonAnnotatedClass.<error descr="'staticAnnotatedMethodInNonAnnotatedClass()' is scheduled for removal in version 123.456">staticAnnotatedMethodInNonAnnotatedClass</error>
import pkg.<error descr="'pkg.AnnotatedEnum' is scheduled for removal in version 123.456">AnnotatedEnum</error>
import pkg.NonAnnotatedEnum
import pkg.<error descr="'pkg.AnnotatedEnum' is scheduled for removal in version 123.456">AnnotatedEnum</error>.<error descr="'NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is declared in enum 'pkg.AnnotatedEnum' scheduled for removal in version 123.456">NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM</error>
import pkg.<error descr="'pkg.AnnotatedEnum' is scheduled for removal in version 123.456">AnnotatedEnum</error>.<error descr="'ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is scheduled for removal in version 123.456">ANNOTATED_VALUE_IN_ANNOTATED_ENUM</error>
import pkg.NonAnnotatedEnum.NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM
import pkg.NonAnnotatedEnum.<error descr="'ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM' is scheduled for removal in version 123.456">ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM</error>
import pkg.<error descr="'pkg.AnnotatedAnnotation' is scheduled for removal in version 123.456">AnnotatedAnnotation</error>
import pkg.NonAnnotatedAnnotation
import <error descr="'annotatedPkg' is scheduled for removal in version 123.456">annotatedPkg</error>.<error descr="'annotatedPkg.ClassInAnnotatedPkg' is declared in package 'annotatedPkg' scheduled for removal in version 123.456">ClassInAnnotatedPkg</error>
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE", "UNUSED_VALUE")
class ScheduledForRemovalElementsTest {
fun test() {
var s = <error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>.<error descr="'NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</error>
<error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>.<error descr="'staticNonAnnotatedMethodInAnnotatedClass()' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">staticNonAnnotatedMethodInAnnotatedClass</error>()
val annotatedClassInstanceViaNonAnnotatedConstructor : <error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error> = <error descr="'AnnotatedClass()' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456"><error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error></error>()
s = annotatedClassInstanceViaNonAnnotatedConstructor.<error descr="'nonAnnotatedFieldInAnnotatedClass' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">nonAnnotatedFieldInAnnotatedClass</error>
annotatedClassInstanceViaNonAnnotatedConstructor.<error descr="'nonAnnotatedMethodInAnnotatedClass()' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">nonAnnotatedMethodInAnnotatedClass</error>()
s = <error descr="'NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</error>
<error descr="'staticNonAnnotatedMethodInAnnotatedClass()' is declared in class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">staticNonAnnotatedMethodInAnnotatedClass</error>()
s = <error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>.<error descr="'ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is scheduled for removal in version 123.456">ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</error>
<error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>.<error descr="'staticAnnotatedMethodInAnnotatedClass()' is scheduled for removal in version 123.456">staticAnnotatedMethodInAnnotatedClass</error>()
val annotatedClassInstanceViaAnnotatedConstructor : <error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error> = <error descr="'AnnotatedClass(java.lang.String)' is scheduled for removal in version 123.456"><error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error></error>("")
s = annotatedClassInstanceViaAnnotatedConstructor.<error descr="'annotatedFieldInAnnotatedClass' is scheduled for removal in version 123.456">annotatedFieldInAnnotatedClass</error>
annotatedClassInstanceViaAnnotatedConstructor.<error descr="'annotatedMethodInAnnotatedClass()' is scheduled for removal in version 123.456">annotatedMethodInAnnotatedClass</error>()
s = <error descr="'ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is scheduled for removal in version 123.456">ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</error>
<error descr="'staticAnnotatedMethodInAnnotatedClass()' is scheduled for removal in version 123.456">staticAnnotatedMethodInAnnotatedClass</error>()
// ---------------------------------
s = NonAnnotatedClass.NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS
NonAnnotatedClass.staticNonAnnotatedMethodInNonAnnotatedClass()
val nonAnnotatedClassInstanceViaNonAnnotatedConstructor = NonAnnotatedClass()
s = nonAnnotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedFieldInNonAnnotatedClass
nonAnnotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedMethodInNonAnnotatedClass()
s = NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS
staticNonAnnotatedMethodInNonAnnotatedClass()
s = NonAnnotatedClass.<error descr="'ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS' is scheduled for removal in version 123.456">ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS</error>
NonAnnotatedClass.<error descr="'staticAnnotatedMethodInNonAnnotatedClass()' is scheduled for removal in version 123.456">staticAnnotatedMethodInNonAnnotatedClass</error>()
val nonAnnotatedClassInstanceViaAnnotatedConstructor = <error descr="'NonAnnotatedClass(java.lang.String)' is scheduled for removal in version 123.456">NonAnnotatedClass</error>("")
s = nonAnnotatedClassInstanceViaAnnotatedConstructor.<error descr="'annotatedFieldInNonAnnotatedClass' is scheduled for removal in version 123.456">annotatedFieldInNonAnnotatedClass</error>
nonAnnotatedClassInstanceViaAnnotatedConstructor.<error descr="'annotatedMethodInNonAnnotatedClass()' is scheduled for removal in version 123.456">annotatedMethodInNonAnnotatedClass</error>()
s = <error descr="'ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS' is scheduled for removal in version 123.456">ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS</error>
<error descr="'staticAnnotatedMethodInNonAnnotatedClass()' is scheduled for removal in version 123.456">staticAnnotatedMethodInNonAnnotatedClass</error>()
// ---------------------------------
var nonAnnotatedValueInAnnotatedEnum : <error descr="'pkg.AnnotatedEnum' is scheduled for removal in version 123.456">AnnotatedEnum</error> = <error descr="'pkg.AnnotatedEnum' is scheduled for removal in version 123.456">AnnotatedEnum</error>.<error descr="'NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is declared in enum 'pkg.AnnotatedEnum' scheduled for removal in version 123.456">NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM</error>
nonAnnotatedValueInAnnotatedEnum = <error descr="'NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is declared in enum 'pkg.AnnotatedEnum' scheduled for removal in version 123.456">NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM</error>
var annotatedValueInAnnotatedEnum : <error descr="'pkg.AnnotatedEnum' is scheduled for removal in version 123.456">AnnotatedEnum</error> = <error descr="'pkg.AnnotatedEnum' is scheduled for removal in version 123.456">AnnotatedEnum</error>.<error descr="'ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is scheduled for removal in version 123.456">ANNOTATED_VALUE_IN_ANNOTATED_ENUM</error>
annotatedValueInAnnotatedEnum = <error descr="'ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is scheduled for removal in version 123.456">ANNOTATED_VALUE_IN_ANNOTATED_ENUM</error>
var nonAnnotatedValueInNonAnnotatedEnum = NonAnnotatedEnum.NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM
nonAnnotatedValueInNonAnnotatedEnum = NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM
var annotatedValueInNonAnnotatedEnum = NonAnnotatedEnum.<error descr="'ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM' is scheduled for removal in version 123.456">ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM</error>
annotatedValueInNonAnnotatedEnum = <error descr="'ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM' is scheduled for removal in version 123.456">ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM</error>
// ---------------------------------
@<error descr="'pkg.AnnotatedAnnotation' is scheduled for removal in version 123.456">AnnotatedAnnotation</error> class C1
@<error descr="'pkg.AnnotatedAnnotation' is scheduled for removal in version 123.456">AnnotatedAnnotation</error>(<error descr="'nonAnnotatedAttributeInAnnotatedAnnotation' is declared in @interface 'pkg.AnnotatedAnnotation' scheduled for removal in version 123.456">nonAnnotatedAttributeInAnnotatedAnnotation</error> = "123") class C2
@<error descr="'pkg.AnnotatedAnnotation' is scheduled for removal in version 123.456">AnnotatedAnnotation</error>(<error descr="'annotatedAttributeInAnnotatedAnnotation' is scheduled for removal in version 123.456">annotatedAttributeInAnnotatedAnnotation</error> = "123") class C3
@NonAnnotatedAnnotation class C4
@NonAnnotatedAnnotation(nonAnnotatedAttributeInNonAnnotatedAnnotation = "123") class C5
@NonAnnotatedAnnotation(<error descr="'annotatedAttributeInNonAnnotatedAnnotation' is scheduled for removal in version 123.456">annotatedAttributeInNonAnnotatedAnnotation</error> = "123") class C6
}
}
open class DirectOverrideAnnotatedMethod : NonAnnotatedClass() {
override fun <error descr="Overridden method 'annotatedMethodInNonAnnotatedClass()' is scheduled for removal in version 123.456">annotatedMethodInNonAnnotatedClass</error>() {}
}
//No warning should be produced.
class IndirectOverrideAnnotatedMethod : DirectOverrideAnnotatedMethod() {
override fun annotatedMethodInNonAnnotatedClass() {}
}
class WarningsOfScheduledForRemovalTypesInSignature {
fun classUsage() {
<error descr="'pkg.ClassWithScheduledForRemovalTypeInSignature' is scheduled for removal because its signature references class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">ClassWithScheduledForRemovalTypeInSignature</error><<error descr="'pkg.AnnotatedClass' is scheduled for removal in version 123.456">AnnotatedClass</error>>()
}
fun membersUsages(owner: OwnerOfMembersWithScheduledForRemovalTypesInSignature) {
val field = owner.<error descr="'field' is scheduled for removal because its signature references class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">field</error>
owner.<error descr="'parameterType(pkg.AnnotatedClass)' is scheduled for removal because its signature references class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">parameterType</error>(null)
owner.<error descr="'returnType()' is scheduled for removal because its signature references class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">returnType</error>()
val fieldPkg = owner.<error descr="'field' is scheduled for removal because its signature references class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">field</error>
owner.<error descr="'parameterTypePkg(annotatedPkg.ClassInAnnotatedPkg)' is scheduled for removal because its signature references class 'annotatedPkg.ClassInAnnotatedPkg' scheduled for removal in version 123.456">parameterTypePkg</error>(null)
owner.<error descr="'returnTypePkg()' is scheduled for removal because its signature references class 'pkg.AnnotatedClass' scheduled for removal in version 123.456">returnTypePkg</error>()
}
}
| 214 | null |
4829
| 2 |
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 14,056 |
intellij-community
|
Apache License 2.0
|
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/IbanSpec.kt
|
stripe
| 6,926,049 | false | null |
package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import kotlinx.parcelize.Parcelize
@Parcelize
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
object IbanSpec : SectionFieldSpec(IdentifierSpec.Generic("iban")) {
fun transform(): SectionFieldElement =
IbanElement(
this.identifier,
SimpleTextFieldController(IbanConfig())
)
}
| 64 |
Kotlin
|
522
| 935 |
bec4fc5f45b5401a98a310f7ebe5d383693936ea
| 407 |
stripe-android
|
MIT License
|
org.librarysimplified.audiobook.tests.device/src/androidTest/java/org/librarysimplified/audiobook/tests/device/ExoManifestTest.kt
|
ThePalaceProject
| 379,956,255 | false |
{"Kotlin": 718883, "Java": 2554}
|
package org.librarysimplified.audiobook.tests.device
import android.content.Context
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import org.junit.runner.RunWith
import org.librarysimplified.audiobook.tests.open_access.ExoManifestContract
import org.slf4j.Logger
import org.slf4j.LoggerFactory
@RunWith(AndroidJUnit4::class)
@MediumTest
class ExoManifestTest : ExoManifestContract() {
override fun log(): Logger {
return LoggerFactory.getLogger(ExoManifestTest::class.java)
}
override fun context(): Context {
return this.instrumentationContext!!
}
}
| 1 |
Kotlin
|
1
| 1 |
d8e2d9dde4c20391075fcc6c527c9b9845b92a8e
| 617 |
android-audiobook
|
Apache License 2.0
|
Pokedex/app/src/main/java/com/ivettevaldez/pokedex/ui/common/toolbar/CustomToolbar.kt
|
ivettevaldez
| 635,742,104 | false | null |
package com.ivettevaldez.pokedex.ui.common.toolbar
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import com.ivettevaldez.pokedex.R
class CustomToolbar : Toolbar {
interface NavigateUpListener {
fun onNavigationUpClicked()
}
private var navigateUpListener: () -> Unit = {}
private lateinit var textTitle: TextView
private lateinit var buttonNavigateUp: ImageButton
constructor(context: Context) : super(context) {
init(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
init(context)
}
private fun init(context: Context) {
val view = LayoutInflater.from(context).inflate(R.layout.layout_toolbar, this, true)
setContentInsetsRelative(0, 0)
textTitle = view.findViewById(R.id.text_title)
buttonNavigateUp = view.findViewById(R.id.button_navigate_up)
buttonNavigateUp.setOnClickListener { navigateUpListener.invoke() }
}
fun setTitle(title: String) {
textTitle.text = title
}
fun setNavigateUpListener(navigateUpListener: () -> Unit) {
this.navigateUpListener = navigateUpListener
buttonNavigateUp.visibility = View.VISIBLE
}
}
| 0 |
Kotlin
|
0
| 0 |
d10862e346fbca70689cd0d54c04308437439440
| 1,577 |
pokedex
|
Apache License 2.0
|
core/src/main/kotlin/materialui/components/grid/enums/GridAlignItems.kt
|
subroh0508
| 167,797,152 | false | null |
package materialui.components.grid.enums
import kotlinx.html.AttributeEnum
@Suppress("EnumEntryName")
enum class GridAlignItems(override val realValue: String) : AttributeEnum {
flexStart("flex-start"),
center("center"),
flexEnd("flex-end"),
stretch("stretch"),
baseline("baseline");
override fun toString(): String = realValue
}
| 14 |
Kotlin
|
27
| 81 |
a959a951ace3b9bd49dc5405bea150d4d53cf162
| 356 |
kotlin-material-ui
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.