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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mvvm-dagger/src/main/java/com/nphau/android/shared/libs/CommonUtils.kt
|
ThanhHuong98
| 432,947,065
| false
| null |
package com.imstudio.android.shared.libs
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.AudioManager
import android.media.ToneGenerator
import android.net.Uri
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.provider.Settings
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.pm.PackageInfoCompat
import com.imstudio.android.shared.R
import java.util.*
object CommonUtils {
private const val URL_GOOGLE_PLAY_URI = "market://details?id=com.google.android.gms&hl=en"
private const val URL_GOOGLE_PLAY =
"https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en"
private const val ACTION_VIEW = Intent.ACTION_VIEW
private val toneG = ToneGenerator(AudioManager.STREAM_ALARM, 100)
@JvmStatic
fun playTone() {
if (toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD)) {
toneG.stopTone()
}
}
@JvmStatic
fun playToneAndVibrate(context: Context, milliseconds: Int) {
if (toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD))
toneG.stopTone()
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
vibrator?.let {
if (it.hasVibrator()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
it.vibrate(
VibrationEffect.createOneShot(
milliseconds.toLong(),
VibrationEffect.DEFAULT_AMPLITUDE
)
)
else
it.vibrate(milliseconds.toLong())
}
}
}
@JvmStatic
fun getAppFullVersion(context: Context): String {
return String.format(
"%s (%s)A",
getAppVersionName(context),
getAppVersionCode(context)
)
}
@JvmStatic
fun getAppVersionName(context: Context): String {
var versionName = ""
try {
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
versionName = packageInfo.versionName
} catch (e: Exception) {
e.printStackTrace()
}
return versionName
}
@JvmStatic
fun getAppVersionCode(context: Context): String {
var versionCode = ""
try {
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
versionCode = PackageInfoCompat.getLongVersionCode(packageInfo).toString()
} catch (e: Exception) {
e.printStackTrace()
}
return versionCode
}
@JvmStatic
@SuppressLint("HardwareIds")
fun getDeviceId(context: Context): String {
return Settings.Secure.getString(
context.contentResolver,
Settings.Secure.ANDROID_ID
)
}
@JvmStatic
fun formatWithFont(content: String, fontName: String, fontExt: String): String {
val addBodyEnd: Boolean = content.toLowerCase(Locale.getDefault()).contains("</body")
val addBodyStart: Boolean = content.toLowerCase(Locale.getDefault()).contains("<body>")
val font = "$fontName.$fontExt"
return "<style type=\"text/css\">@font-face {font-family: $fontName;" +
"src: url(\"file:///android_asset/fonts/$font\")}" +
"body {font-family: $fontName;text-align: justify;}</style>" +
(if (addBodyStart) "<body>" else "") + content + if (addBodyEnd) "</body>" else ""
}
@JvmStatic
fun makeVibrator(context: Context) {
val v = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v?.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
v?.vibrate(200)
}
}
@JvmStatic
fun openGpsSetting(activity: Activity, requestCode: Int) {
try {
activity.startActivityForResult(
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),
requestCode
)
} catch (e: Exception) {
e.printStackTrace()
}
}
@JvmStatic
fun openAppSetting(activity: Activity, requestCode: Int) {
try {
activity.startActivityForResult(Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
addCategory(Intent.CATEGORY_DEFAULT)
data = Uri.parse("package:" + activity.packageName)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
}, requestCode)
} catch (e: Exception) {
activity.startActivityForResult(
Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS),
requestCode
)
}
}
@JvmStatic
fun makeVibrator(context: Context, pattern: LongArray) {
val v = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v?.vibrate(VibrationEffect.createWaveform(pattern, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
v?.vibrate(1000)
}
}
fun isChromeOs(context: Context): Boolean {
return context.packageManager.hasSystemFeature("org.chromium.arc.device_management")
}
fun hasTelephony(context: Context): Boolean {
return context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
}
fun hasMicrophone(context: Context): Boolean {
return context.packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)
}
@RequiresApi(Build.VERSION_CODES.M)
fun hasFingerprint(context: Context): Boolean {
return context.packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)
}
fun hasBluetooth(context: Context): Boolean {
return context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)
}
@JvmStatic
fun copyTextToClipboard(context: Context, text: String?) {
(context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager)
?.setPrimaryClip(ClipData.newPlainText("code", text))
Toast.makeText(context, R.string.common_copied, Toast.LENGTH_LONG).show()
}
@JvmStatic
fun openApp(activity: Activity, packageClass: String) {
if (isAppInstalled(activity, packageClass)) {
activity.startActivity(activity.packageManager.getLaunchIntentForPackage(packageClass))
} else {
openGooglePlayIfAppNotBeInstalled(activity, packageClass)
}
}
@JvmStatic
fun openGooglePlayIfAppNotBeInstalled(activity: Activity, packageClass: String) {
try {
activity.startActivity(
Intent(
ACTION_VIEW, Uri.parse("market://details?id=$packageClass")
)
)
} catch (e: Exception) {
activity.startActivity(
Intent(
ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=$packageClass")
)
)
}
}
@JvmStatic
fun isAppInstalled(mActivity: Activity, packageClass: String): Boolean {
val pm = mActivity.packageManager
var isInstalled = false
try {
pm.getPackageInfo(packageClass, PackageManager.GET_ACTIVITIES)
isInstalled = true
} catch (e: Exception) {
}
return isInstalled
}
fun openNetworkSetting(activity: Activity) {
activity.startActivity(Intent(Settings.ACTION_SETTINGS))
}
@JvmStatic
fun updateGooglePlayServicesIfOutDated(context: Context) {
try {
context.startActivity(
Intent(Intent.ACTION_VIEW, Uri.parse(URL_GOOGLE_PLAY_URI))
)
} catch (e: Exception) {
context.startActivity(
Intent(Intent.ACTION_VIEW, Uri.parse(URL_GOOGLE_PLAY))
)
}
}
@JvmStatic
fun getFullAction(context: Context, name: String): String {
return context.packageName + ".action.$name"
}
fun isIntentAvailable(i: Intent, ctx: Context): Boolean {
return ctx.packageManager.queryIntentActivities(
i,
PackageManager.MATCH_DEFAULT_ONLY
).size > 0
}
}
| 0
| null |
0
| 1
|
ac0402ae4734285ef5e647d1f53a1f9f4a8d98cd
| 8,839
|
android.clean-architecture.mvvm
|
Apache License 2.0
|
core/src/jsMain/kotlin/Observations.kt
|
JuulLabs
| 293,227,216
| false
| null |
package com.juul.kable
internal actual fun Peripheral.observationHandler(): Observation.Handler = object : Observation.Handler {
override suspend fun startObservation(characteristic: Characteristic) {
(this@observationHandler as JsPeripheral).startObservation(characteristic)
}
override suspend fun stopObservation(characteristic: Characteristic) {
(this@observationHandler as JsPeripheral).stopObservation(characteristic)
}
}
| 33
|
Kotlin
|
59
| 503
|
6bbe8f96bd634eae41f162c2f50b4ff044fc95ad
| 461
|
kable
|
Apache License 2.0
|
buildSrc/src/main/java/com/vuxur/khayyam/ConfigurationData.kt
|
deghat-farhad
| 518,348,997
| false
|
{"Kotlin": 198678}
|
import org.gradle.api.JavaVersion
object ConfigurationData {
const val applicationId = "com.vuxur.khayyam"
const val compileSdk = 35
const val buildToolsVersion = "34.0.0"
const val minSdk = 21
const val targetSdk = 35
const val versionCode = 8
const val versionName = "1.2.2"
const val useSupportLibrary = true
const val multiDexEnabled = true
const val isMinifyEnabled = true
val javaVersion = JavaVersion.VERSION_17
}
| 21
|
Kotlin
|
0
| 0
|
e32cea9f0e098fdfa7315cfd8cc14dea72ef7785
| 466
|
khayam
|
MIT License
|
components/membership/membership-http-rpc-impl/src/main/kotlin/net/corda/membership/impl/httprpc/v1/MemberRegistrationRestResourceImpl.kt
|
corda
| 346,070,752
| false
| null |
package net.corda.membership.impl.httprpc.v1
import net.corda.httprpc.PluggableRestResource
import net.corda.httprpc.exception.ResourceNotFoundException
import net.corda.httprpc.exception.ServiceUnavailableException
import net.corda.lifecycle.Lifecycle
import net.corda.lifecycle.LifecycleCoordinatorFactory
import net.corda.lifecycle.LifecycleCoordinatorName
import net.corda.lifecycle.LifecycleStatus
import net.corda.membership.client.CouldNotFindMemberException
import net.corda.membership.client.MemberOpsClient
import net.corda.membership.client.RegistrationProgressNotFoundException
import net.corda.membership.httprpc.v1.MemberRegistrationRestResource
import net.corda.membership.httprpc.v1.types.request.MemberRegistrationRequest
import net.corda.membership.httprpc.v1.types.response.RegistrationRequestProgress
import net.corda.membership.httprpc.v1.types.response.RegistrationRequestStatus
import net.corda.membership.impl.httprpc.v1.lifecycle.RpcOpsLifecycleHandler
import net.corda.virtualnode.ShortHash
import net.corda.virtualnode.read.rpc.extensions.parseOrThrow
import org.osgi.service.component.annotations.Activate
import org.osgi.service.component.annotations.Component
import org.osgi.service.component.annotations.Reference
@Component(service = [PluggableRestResource::class])
class MemberRegistrationRestResourceImpl @Activate constructor(
@Reference(service = LifecycleCoordinatorFactory::class)
coordinatorFactory: LifecycleCoordinatorFactory,
@Reference(service = MemberOpsClient::class)
private val memberOpsClient: MemberOpsClient,
) : MemberRegistrationRestResource, PluggableRestResource<MemberRegistrationRestResource>, Lifecycle {
private interface InnerMemberRegistrationRpcOps {
fun startRegistration(
holdingIdentityShortHash: String,
memberRegistrationRequest: MemberRegistrationRequest,
): RegistrationRequestProgress
fun checkRegistrationProgress(holdingIdentityShortHash: String): List<RegistrationRequestStatus>
fun checkSpecificRegistrationProgress(
holdingIdentityShortHash: String,
registrationRequestId: String
): RegistrationRequestStatus?
}
override val protocolVersion = 1
private var impl: InnerMemberRegistrationRpcOps = InactiveImpl
private val coordinatorName = LifecycleCoordinatorName.forComponent<MemberRegistrationRestResource>(
protocolVersion.toString()
)
private val lifecycleHandler = RpcOpsLifecycleHandler(
::activate,
::deactivate,
setOf(LifecycleCoordinatorName.forComponent<MemberOpsClient>())
)
private val coordinator = coordinatorFactory.createCoordinator(coordinatorName, lifecycleHandler)
override val targetInterface: Class<MemberRegistrationRestResource> = MemberRegistrationRestResource::class.java
override val isRunning: Boolean
get() = coordinator.isRunning
override fun start() {
coordinator.start()
}
override fun stop() {
coordinator.stop()
}
override fun startRegistration(
holdingIdentityShortHash: String,
memberRegistrationRequest: MemberRegistrationRequest
) = impl.startRegistration(holdingIdentityShortHash, memberRegistrationRequest)
override fun checkRegistrationProgress(
holdingIdentityShortHash: String
) = impl.checkRegistrationProgress(holdingIdentityShortHash)
override fun checkSpecificRegistrationProgress(
holdingIdentityShortHash: String,
registrationRequestId: String,
) = impl.checkSpecificRegistrationProgress(holdingIdentityShortHash, registrationRequestId)
fun activate(reason: String) {
impl = ActiveImpl()
coordinator.updateStatus(LifecycleStatus.UP, reason)
}
fun deactivate(reason: String) {
coordinator.updateStatus(LifecycleStatus.DOWN, reason)
impl = InactiveImpl
}
private object InactiveImpl : InnerMemberRegistrationRpcOps {
override fun startRegistration(
holdingIdentityShortHash: String,
memberRegistrationRequest: MemberRegistrationRequest,
) =
throw ServiceUnavailableException(
"${MemberRegistrationRestResourceImpl::class.java.simpleName} is not running. Operation cannot be fulfilled."
)
override fun checkRegistrationProgress(holdingIdentityShortHash: String): List<RegistrationRequestStatus> =
throw ServiceUnavailableException(
"${MemberRegistrationRestResourceImpl::class.java.simpleName} is not running. Operation cannot be fulfilled."
)
override fun checkSpecificRegistrationProgress(
holdingIdentityShortHash: String,
registrationRequestId: String,
) =
throw ServiceUnavailableException(
"${MemberRegistrationRestResourceImpl::class.java.simpleName} is not running. Operation cannot be fulfilled."
)
}
private inner class ActiveImpl : InnerMemberRegistrationRpcOps {
override fun startRegistration(
holdingIdentityShortHash: String,
memberRegistrationRequest: MemberRegistrationRequest,
): RegistrationRequestProgress {
val dto = memberRegistrationRequest.toDto(holdingIdentityShortHash)
try {
return memberOpsClient.startRegistration(dto).fromDto()
} catch (e: CouldNotFindMemberException) {
throw ResourceNotFoundException(
"holdingIdentityShortHash",
holdingIdentityShortHash,
)
}
}
override fun checkRegistrationProgress(holdingIdentityShortHash: String): List<RegistrationRequestStatus> {
return try {
memberOpsClient.checkRegistrationProgress(
ShortHash.parseOrThrow(holdingIdentityShortHash)
).map { it.fromDto() }
} catch (e: RegistrationProgressNotFoundException) {
throw ResourceNotFoundException(e.message!!)
}
}
override fun checkSpecificRegistrationProgress(
holdingIdentityShortHash: String,
registrationRequestId: String,
): RegistrationRequestStatus? {
return try {
memberOpsClient.checkSpecificRegistrationProgress(
ShortHash.parseOrThrow(holdingIdentityShortHash),
registrationRequestId
)?.fromDto()
} catch (e: RegistrationProgressNotFoundException) {
throw ResourceNotFoundException(e.message!!)
}
}
}
}
| 82
|
Kotlin
|
7
| 24
|
17f5d2e5585a8ac56e559d1c099eaee414e6ec5a
| 6,706
|
corda-runtime-os
|
Apache License 2.0
|
app/src/main/kotlin/com/whereismymotivation/di/module/LocalDataModule.kt
|
unusualcodeorg
| 730,655,456
| false
|
{"Kotlin": 472092}
|
package com.whereismymotivation.di.module
import android.content.Context
import android.content.SharedPreferences
import androidx.room.Room
import com.whereismymotivation.data.local.db.DatabaseService
import com.whereismymotivation.di.qualifier.DatabaseInfo
import com.whereismymotivation.di.qualifier.PrefsInfo
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object LocalDataModule {
@Provides
@Singleton
@DatabaseInfo
fun provideDatabaseName(): String = "wimm-db"
@Provides
@Singleton
@PrefsInfo
fun providePreferenceName(): String = "wimm-prefs"
@Provides
@Singleton
fun provideSharedPreferences(
@ApplicationContext context: Context,
@PrefsInfo prefName: String
): SharedPreferences = context.getSharedPreferences(prefName, Context.MODE_PRIVATE)
@Provides
@Singleton
fun provideDatabaseService(
@ApplicationContext context: Context,
@DatabaseInfo dbName: String
): DatabaseService = Room.databaseBuilder(
context, DatabaseService::class.java,
dbName
).build()
}
| 0
|
Kotlin
|
4
| 38
|
5b77e6a6b14ae9ad21e8edd55e8c9b3cc2066f75
| 1,295
|
wimm-android-app
|
Apache License 2.0
|
src/main/kotlin/net/casual/arcade/utils/BorderUtils.kt
|
CasualChampionships
| 621,955,934
| false
|
{"Kotlin": 683110, "Java": 129189, "GLSL": 1008}
|
package net.casual.arcade.utils
import net.casual.arcade.border.LevelSpecificBorderBroadcaster
import net.casual.arcade.border.extensions.BorderSerializerExtension
import net.casual.arcade.config.ArcadeConfig
import net.casual.arcade.events.GlobalEventHandler
import net.casual.arcade.events.level.LevelCreatedEvent
import net.casual.arcade.events.server.ServerLoadedEvent
import net.casual.arcade.utils.LevelUtils.addExtension
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.level.border.BorderChangeListener
import net.minecraft.world.level.border.BorderChangeListener.DelegateBorderChangeListener
import org.jetbrains.annotations.ApiStatus.Internal
public object BorderUtils {
private val original = HashMap<ServerLevel, BorderChangeListener>()
private val replacement = HashMap<ServerLevel, BorderChangeListener>()
private var currentlySynced = true
@JvmStatic
public var synced: Boolean by ArcadeConfig.boolean("border_synced", false)
private set
@JvmStatic
public fun joinWorldBorders(): Boolean {
if (this.currentlySynced) {
return false
}
this.currentlySynced = true
this.synced = true
for ((level, listener) in this.replacement) {
level.worldBorder.removeListener(listener)
}
val border = LevelUtils.overworld().worldBorder
for (level in LevelUtils.levels()) {
border.addListener(this.original.getOrPut(level) { DelegateBorderChangeListener(level.worldBorder) })
}
return true
}
@JvmStatic
public fun isolateWorldBorders(): Boolean {
if (!this.currentlySynced) {
return false
}
this.currentlySynced = false
this.synced = false
val border = LevelUtils.overworld().worldBorder
for (listener in this.original.values) {
border.removeListener(listener)
}
for (level in LevelUtils.levels()) {
val broadcaster = this.replacement.getOrPut(level) { LevelSpecificBorderBroadcaster(level) }
level.worldBorder.addListener(broadcaster)
}
return true
}
@Internal
@JvmStatic
public fun addOriginalListener(level: ServerLevel, listener: BorderChangeListener) {
this.original[level] = listener
}
internal fun registerEvents() {
GlobalEventHandler.register<LevelCreatedEvent> { (level) ->
level.addExtension(BorderSerializerExtension(level))
}
GlobalEventHandler.register<ServerLoadedEvent> {
if (this.synced) {
this.isolateWorldBorders()
}
}
}
}
| 1
|
Kotlin
|
1
| 1
|
5ac1a66ccb442aed89577e83e8fef962cc4bab1e
| 2,686
|
arcade
|
MIT License
|
app/src/main/java/org/scottishtecharmy/soundscape/screens/onboarding/audiobeacons/AudioBeacons.kt
|
Scottish-Tech-Army
| 833,170,999
| false
|
{"Kotlin": 3492292, "C": 153623, "C++": 76956, "CMake": 2216, "Shell": 87}
|
package org.scottishtecharmy.soundscape.screens.onboarding.audiobeacons
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import org.scottishtecharmy.soundscape.R
import org.scottishtecharmy.soundscape.components.OnboardButton
import org.scottishtecharmy.soundscape.screens.onboarding.component.BoxWithGradientBackground
@Composable
fun AudioBeaconsScreen(
onNavigate: () -> Unit,
modifier: Modifier = Modifier,
viewModel: AudioBeaconsViewModel = hiltViewModel()
) {
val uiState: AudioBeaconsViewModel.AudioBeaconsUiState by viewModel.state.collectAsStateWithLifecycle()
AudioBeacons(
beacons = uiState.beaconTypes,
selectedBeacon = uiState.selectedBeacon,
onContinue = {
viewModel.silenceBeacon()
onNavigate()
},
onBeaconSelected = { beacon ->
// change the audio beacon
viewModel.setAudioBeaconType(beacon)
Log.d(
"AudioBeacon",
"Audio beacon category changed to $beacon")
},
modifier = modifier,
)
}
@Composable
fun AudioBeacons(
beacons: List<String>,
onBeaconSelected: (String) -> Unit,
selectedBeacon: String?,
onContinue: () -> Unit,
modifier: Modifier = Modifier,
) {
BoxWithGradientBackground(modifier = modifier){
Column(
modifier = Modifier
.padding(horizontal = 30.dp)
.padding(top = 30.dp)
.fillMaxWidth()
.fillMaxHeight()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
// TODO translations
Text(
text = stringResource(R.string.first_launch_beacon_title),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
textAlign = TextAlign.Center,
modifier = Modifier.semantics {
heading()
}
)
Spacer(modifier = Modifier.height(30.dp))
Text(
text = stringResource(R.string.first_launch_beacon_message_1),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimary,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(30.dp))
Text(
text = stringResource(R.string.first_launch_beacon_message_2),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimary,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(30.dp))
Text(
text = stringResource(R.string.first_launch_beacon_message_3),
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onPrimary,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(30.dp))
LazyColumn(
modifier = Modifier
.clip(RoundedCornerShape(5.dp))
.fillMaxWidth()
.heightIn(100.dp, 300.dp)
.background(Color.White)
) {
items(beacons) { beacon ->
AudioBeaconItem(
text = beacon,
isSelected = beacon == selectedBeacon,
onSelect = {
onBeaconSelected(beacon)
}
)
}
}
Column(
modifier = Modifier
.padding(horizontal = 20.dp, vertical = 60.dp)
.requiredHeight(40.dp)
) {
OnboardButton(
text = stringResource(R.string.ui_continue),
onClick = {
onContinue()
},
modifier = Modifier.fillMaxWidth(),
enabled = selectedBeacon != null,
)
}
}
}
}
// Data used by preview
data object MockHearingPreviewData {
val names = listOf(
"Original",
"Current",
"Tactile",
"Flare",
"Shimmer",
"Ping",
"Drop",
"Signal",
"Signal Slow",
"Signal Very Slow",
"Mallet",
"Mallet Slow",
"Mallet Very Slow"
)
}
@Preview(device = "spec:parent=pixel_5,orientation=landscape")
@Preview
@Composable
fun AudioBeaconPreview() {
AudioBeacons(
beacons = MockHearingPreviewData.names,
selectedBeacon = MockHearingPreviewData.names[0],
onBeaconSelected = {},
onContinue = {},
)
}
| 36
|
Kotlin
|
2
| 3
|
4a6b1edd4c680b22781c43f5194758544fd410d9
| 6,424
|
Soundscape-Android
|
Apache License 2.0
|
app/src/main/kotlin/com/alexrdclement/uiplayground/navigation/UiPlaygroundNavHost.kt
|
alexrdclement
| 661,077,963
| false
|
{"Kotlin": 204338}
|
package com.alexrdclement.uiplayground.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.alexrdclement.uiplayground.catalog.MainCatalogItem
import com.alexrdclement.uiplayground.catalog.navigation.mainCatalogRoute
import com.alexrdclement.uiplayground.catalog.navigation.mainCatalogScreen
import com.alexrdclement.uiplayground.demo.components.navigation.componentsGraph
import com.alexrdclement.uiplayground.demo.components.navigation.navigateToComponents
import com.alexrdclement.uiplayground.demo.experiments.navigation.experimentsGraph
import com.alexrdclement.uiplayground.demo.experiments.navigation.navigateToExperiments
import com.alexrdclement.uiplayground.demo.shaders.navigation.navigateToShaders
import com.alexrdclement.uiplayground.demo.shaders.navigation.shadersScreen
@Composable
fun UiPlaygroundNavHost() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = mainCatalogRoute,
) {
mainCatalogScreen(
onItemClick = { item ->
when (item) {
MainCatalogItem.Components -> navController.navigateToComponents()
MainCatalogItem.Experiments -> navController.navigateToExperiments()
MainCatalogItem.Shaders -> navController.navigateToShaders()
}
}
)
componentsGraph(
navController = navController,
)
experimentsGraph(
navController = navController,
)
shadersScreen()
}
}
| 0
|
Kotlin
|
0
| 0
|
4d19561487fbef5293bdaaefac9edc8ba82145ee
| 1,674
|
UiPlayground
|
Apache License 2.0
|
defitrack-protocol-contracts/src/main/java/io/defitrack/protocol/radiant/RadiantMultiFeeDistributor.kt
|
decentri-fi
| 426,174,152
| false
| null |
package io.defitrack.protocol.radiant
import io.defitrack.abi.TypeUtils
import io.defitrack.abi.TypeUtils.Companion.dynamicArray
import io.defitrack.abi.TypeUtils.Companion.toAddress
import io.defitrack.abi.TypeUtils.Companion.toUint256
import io.defitrack.evm.contract.BlockchainGateway
import io.defitrack.evm.contract.EvmContract
import org.web3j.abi.TypeReference
import org.web3j.abi.datatypes.Address
import org.web3j.abi.datatypes.DynamicArray
import org.web3j.abi.datatypes.Function
import org.web3j.abi.datatypes.StaticStruct
import org.web3j.abi.datatypes.generated.StaticArray7
import org.web3j.abi.datatypes.generated.Uint256
class RadiantMultiFeeDistributor(
blockchainGateway: BlockchainGateway, address: String
) : EvmContract(blockchainGateway, address) {
val stakingToken = constant<String>("stakingToken", TypeUtils.address())
fun getRewardFn(tokens: List<String>): ContractCall {
return createFunction(
"getReward",
tokens.map { it.toAddress() },
emptyList()
).toContractCall()
}
suspend fun rewardTokens(): List<String> {
return readMultiCall(
(0 until 10).map {
createFunction(
"rewardTokens",
listOf(it.toBigInteger().toUint256()),
listOf(TypeUtils.address())
)
}
).filter {
it.success
}.map { it.data[0].value as String }
.filter {
it != "0x0000000000000000000000000000000000000000"
}
}
fun getClaimableRewardFn(user: String): Function {
return createFunction(
"claimableRewards",
listOf(user.toAddress()),
listOf(object : TypeReference<DynamicArray<RadiantMultiFeeReward>>() {})
)
}
}
| 59
| null |
6
| 11
|
8b8d6713c9734d2b4015e7affe658e797c9a00be
| 1,842
|
defi-hub
|
MIT License
|
mbcarkit/src/main/java/com/daimler/mbcarkit/business/model/services/MissingAccountLinkage.kt
|
Daimler
| 199,815,262
| false
| null |
package com.daimler.mbcarkit.business.model.services
import android.os.Parcelable
import com.daimler.mbcarkit.business.model.accountlinkage.AccountType
import kotlinx.android.parcel.Parcelize
@Parcelize
data class MissingAccountLinkage(
val mandatory: Boolean,
val type: AccountType?
) : Parcelable
| 1
|
Kotlin
|
8
| 15
|
3721af583408721b9cd5cf89dd7b99256e9d7dda
| 309
|
MBSDK-Mobile-Android
|
MIT License
|
app/src/main/java/com/circle/w3s/sample/wallet/TransactionsActivity.kt
|
rachitag112
| 784,599,425
| false
|
{"Kotlin": 96377}
|
package com.circle.w3s.sample.wallet
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.circle.w3s.sample.wallet.databinding.TransactionspageBinding
import java.io.IOException
import okhttp3.OkHttpClient
import okhttp3.Request
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import com.google.gson.Gson
import android.content.Intent
import android.graphics.Color
import android.text.Html
import android.view.View
import com.circle.w3s.sample.wallet.ui.main.LoadingDialog
import android.widget.TableRow
import android.widget.TextView
import android.widget.Button
import java.text.SimpleDateFormat
import java.util.Date
import java.util.TimeZone
data class TransactionData(
val data: TransactionList
)
data class TransactionList(
val transactions: List<Transaction>
)
data class Transaction(
val id: String,
val blockchain: String,
val tokenId: String,
val walletId: String,
val sourceAddress: String,
val destinationAddress: String,
val transactionType: String,
val custodyType: String,
val state: String,
val amounts: List<String>,
val nfts: Any?, // Change to the appropriate type if needed
val txHash: String,
val blockHash: String,
val blockHeight: Long,
val networkFee: String,
val firstConfirmDate: String,
val operation: String,
val userId: String,
val abiParameters: Any?, // Change to the appropriate type if needed
val createDate: String,
val updateDate: String
)
// Define a data class to hold the selected fields
data class TransactionInfo(
val sourceAddress: String,
val destinationAddress: String,
val state: String,
val amount: String,
val txHash: String,
val userId: String,
val transactionType: String,
val blockchain: String,
val walletId: String,
val createDate: String,
val updateDate: String,
val tokenId: String,
)
class TransactionsActivity: AppCompatActivity() {
private var transactions: List<TransactionInfo> = emptyList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = TransactionspageBinding.inflate(layoutInflater)
setContentView(binding.root)
//button and table layouts
val backButton = binding.backBtn
val backToAllTransactionsBtn = binding.backToTransactionsTableButton
backToAllTransactionsBtn.visibility = View.INVISIBLE
val tableLayout = binding.tableLayout
//Scroll views
val transactionTableScrollView = binding.transactionTablescrollView
transactionTableScrollView.visibility = View.VISIBLE
val transactionDetailsScrollView = binding.transactionDetailsScrollView
transactionDetailsScrollView.visibility = View.INVISIBLE
//TextViews for displaying transaction details
val sourceAddressTextView = binding.sourceAddressTextView
val destinationAddressTextView = binding.destinationAddressTextView
val stateText = binding.stateTextView
val amountText = binding.amountTextView
val txHashTextView = binding.txHashTextView
val transactionTypeText = binding.transactionTypeTextView
val tokenTextView = binding.tokenTextView
val blockchainText = binding.blockchainTextView
val walletIdText = binding.walletIdTextView
val createDateText = binding.createDateTextView
val updateDateText = binding.updateDateTextView
// Retrieve apiKey and userId from the intent extras
val apiKey = intent.getStringExtra("apiKey")
val userToken = intent.getStringExtra("userToken")
val encryptionKey = intent.getStringExtra("encryptionKey")
val userId = intent.getStringExtra("userId")
val appId = intent.getStringExtra("appId")
val loadingDialog = LoadingDialog(this@TransactionsActivity, "Getting past transaction data, please wait...") // Specify the loading text here
loadingDialog.show()
//call API to get transaction data
GlobalScope.launch(Dispatchers.IO) {
// Step 7 - PASTE CODE HERE FOR "FETCH TRANSACTIONS" API
val client = OkHttpClient()
val request = Request.Builder() .url("https://api.circle.com/v1/w3s/transactions?blockchain=ETH-SEPOLIA&userId=$userId&pageSize=10")
.get()
.addHeader("accept", "application/json")
.addHeader("authorization", "Bearer $apiKey")
.build()
try {
val response = client.newCall(request).execute()
if (response.isSuccessful) {
val responseBody = response.body?.string()
// Use Gson to parse the JSON response into your data class
val gson = Gson()
val responseObject = gson.fromJson(responseBody, TransactionData::class.java)
val transactionsResponseData = responseObject.data.transactions
// Map the transactions to a new list with selected fields
val selectedFieldsList = transactionsResponseData.map { transaction ->
// Create a new object with the selected fields
TransactionInfo(
transaction.sourceAddress,
transaction.destinationAddress,
transaction.state,
transaction.amounts.firstOrNull() ?: "0", // Handle the case when amounts is empty
transaction.txHash,
transaction.userId,
transaction.transactionType,
transaction.blockchain,
transaction.walletId,
transaction.createDate,
transaction.updateDate,
transaction.tokenId,
)
}
transactions = selectedFieldsList
Log.d("TransactionsActivity", "Data response: $selectedFieldsList")
// Update the UI on the main thread
runOnUiThread {
for (transaction in transactions) {
val tokenName = if (transaction.tokenId == "979869da-9115-5f7d-917d-12d434e56ae7") {
"ETH-SEPOLIA"
} else {
"USD Coin"
}
val tableRow = TableRow(this@TransactionsActivity)
val tokenNameTextView = TextView(this@TransactionsActivity)
tokenNameTextView.text = tokenName
tokenNameTextView.layoutParams = TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT
)
tokenNameTextView.setPadding(15, 15, 15, 15) // Set padding to 15
tokenNameTextView.setBackgroundResource(R.drawable.table_border)
tokenNameTextView.setTextColor(Color.BLACK)
tableRow.addView(tokenNameTextView)
val amountTextView = TextView(this@TransactionsActivity)
amountTextView.text = transaction.amount
amountTextView.layoutParams = TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT
)
amountTextView.setPadding(15, 15, 15, 15) // Set padding to 15
amountTextView.setBackgroundResource(R.drawable.table_border)
amountTextView.setTextColor(Color.BLACK)
tableRow.addView(amountTextView)
val transactionTypeTextView = TextView(this@TransactionsActivity)
transactionTypeTextView.text = transaction.transactionType
transactionTypeTextView.layoutParams = TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT
)
transactionTypeTextView.setPadding(15, 15, 15, 15) // Set padding to 15
transactionTypeTextView.setBackgroundResource(R.drawable.table_border)
transactionTypeTextView.setTextColor(Color.BLACK)
tableRow.addView(transactionTypeTextView)
val viewDetailsBtn = Button(this@TransactionsActivity)
viewDetailsBtn.text = "View details"
viewDetailsBtn.textSize = 10f
viewDetailsBtn.layoutParams = TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT,
)
viewDetailsBtn.setPadding(15, 15, 15, 15)
viewDetailsBtn.setTextColor(Color.BLACK)
tableRow.addView(viewDetailsBtn)
viewDetailsBtn.setOnClickListener {
//set visibility of views
transactionTableScrollView.visibility = View.INVISIBLE
backButton.visibility = View.INVISIBLE
transactionDetailsScrollView.visibility = View.VISIBLE
backToAllTransactionsBtn.visibility = View.VISIBLE
//set text of textview
val sourceAddressTextHtml = "<b>Source Address:</b> ${transaction.sourceAddress}"
sourceAddressTextView.text = Html.fromHtml(sourceAddressTextHtml, Html.FROM_HTML_MODE_LEGACY)
val destinationAddressTextHtml = "<b>Destination Address:</b> ${transaction.destinationAddress}"
destinationAddressTextView.text = Html.fromHtml(destinationAddressTextHtml, Html.FROM_HTML_MODE_LEGACY)
val stateTextHtml = "<b>State:</b> ${transaction.state}"
stateText.text = Html.fromHtml(stateTextHtml, Html.FROM_HTML_MODE_LEGACY)
val amountTextHtml = "<b>Amount:</b> ${transaction.amount}"
amountText.text = Html.fromHtml(amountTextHtml, Html.FROM_HTML_MODE_LEGACY)
val txHashTextHtml = "<b>Transaction Hash:</b> ${transaction.txHash}"
txHashTextView.text = Html.fromHtml(txHashTextHtml, Html.FROM_HTML_MODE_LEGACY)
val transactionTypeTextHtml = "<b>Transaction Type:</b> ${transaction.transactionType}"
transactionTypeText.text = Html.fromHtml(transactionTypeTextHtml, Html.FROM_HTML_MODE_LEGACY)
val tokenName = if (transaction.tokenId == "979869da-9115-5f7d-917d-12d434e56ae7") {
"Avalanche-Fuji"
} else {
"USD Coin"
}
val tokenIdTextHtml = "<b>Token:</b> $tokenName"
tokenTextView.text = Html.fromHtml(tokenIdTextHtml, Html.FROM_HTML_MODE_LEGACY)
val blockchainTextHtml = "<b>Blockchain:</b> ${transaction.blockchain}"
blockchainText.text = Html.fromHtml(blockchainTextHtml, Html.FROM_HTML_MODE_LEGACY)
val walletIdTextHtml = "<b>Wallet Id:</b> ${transaction.walletId}"
walletIdText.text = Html.fromHtml(walletIdTextHtml, Html.FROM_HTML_MODE_LEGACY)
// Sample input strings
val createDate = transaction.createDate
val updateDate = transaction.updateDate
// Define the input format
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
inputFormat.timeZone = TimeZone.getTimeZone("UTC")
// Parse the create date and update date into Date objects
val createDateObject: Date = inputFormat.parse(createDate)
val updateDateObject: Date = inputFormat.parse(updateDate)
// Define the desired output format
val outputFormat = SimpleDateFormat("dd MMM yyyy HH:mm:ss")
outputFormat.timeZone = TimeZone.getDefault() // Use the device's time zone
// Format the Date objects into readable date-time strings
val formattedCreateDate = outputFormat.format(createDateObject)
val formattedUpdateDate = outputFormat.format(updateDateObject)
val createDateTextHtml = "<b>Created at:</b> $formattedCreateDate"
createDateText.text = Html.fromHtml(createDateTextHtml, Html.FROM_HTML_MODE_LEGACY)
val updateDateTextHtml = "<b>Updated at:</b> $formattedUpdateDate"
updateDateText.text = Html.fromHtml(updateDateTextHtml, Html.FROM_HTML_MODE_LEGACY)
}
tableLayout.addView(tableRow)
}
loadingDialog.dismiss()
}
} else {
// Update UI components
runOnUiThread {
Log.e("TransactionsActivity", "Error: $response")
loadingDialog.dismiss()
//show toast message
Toast.makeText(this@TransactionsActivity, "Error: ${response.message}", Toast.LENGTH_SHORT).show()
}
}
} catch (e: IOException) {
Log.e("TransactionsActivity", "Error: ${e.message}", e)
}
}
backButton.setOnClickListener{
//redirect to send tokens page
val intent = Intent(this@TransactionsActivity, HomePageActivity::class.java)
//pass data to next page
intent.putExtra("apiKey", apiKey)
intent.putExtra("userToken", userToken)
intent.putExtra("encryptionKey", encryptionKey)
intent.putExtra("appId", appId)
// Start the new activity
startActivity(intent)
// Finish the current activity if needed
finish()
}
backToAllTransactionsBtn.setOnClickListener{
transactionTableScrollView.visibility = View.VISIBLE
transactionDetailsScrollView.visibility = View.INVISIBLE
backToAllTransactionsBtn.visibility = View.INVISIBLE
backButton.visibility = View.VISIBLE
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f3e485133ea430038a682c2ea9cdfb8130d931f1
| 15,798
|
custom-wallet-circle
|
Apache License 2.0
|
custom-resource-status-clouddriver/src/test/kotlin/io/armory/plugin/kubernetes/handlers/CustomResourceHandlerIntegrationTest.kt
|
shlomodaari
| 640,066,907
| false
| null |
package io.armory.plugin.kubernetes.handlers
import com.netflix.spinnaker.clouddriver.api.test.clouddriverFixture
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import strikt.api.expectCatching
import strikt.assertions.isSuccess
class CustomResourceHandlerIntegrationTest : JUnit5Minutests {
fun tests() = rootContext<CustomResourceHandlerTestFixture> {
this.clouddriverFixture {
CustomResourceHandlerTestFixture()
}
test("can fetch handler from application context") {
expectCatching {
handlers.first { it.javaClass == CustomResourceHandler::class.java }
}.isSuccess()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5b449c5430afe5f639189441a283c43025b459d8
| 698
|
crdscheck
|
Info-ZIP License
|
src/main/kotlin/g1201_1300/s1201_ugly_number_iii/Solution.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g1201_1300.s1201_ugly_number_iii
// #Medium #Math #Binary_Search #Number_Theory #Binary_Search_II_Day_20
// #2023_06_09_Time_136_ms_(100.00%)_Space_33.1_MB_(100.00%)
class Solution {
private fun getLcm(a: Long, b: Long): Long {
var mx = a
var mn = b
if (a < b) {
mx = b
mn = a
}
while (mn != 0L) {
val tmp = mn
mn = mx % mn
mx = tmp
}
return a * b / mx
}
fun nthUglyNumber(n: Int, a: Int, b: Int, c: Int): Int {
val ab = getLcm(a.toLong(), b.toLong())
val ac = getLcm(a.toLong(), c.toLong())
val bc = getLcm(b.toLong(), c.toLong())
val abc = getLcm(a.toLong(), bc)
var left: Long = 1
var right: Long = 2000000001
if (a != 0 && b != 0 && c != 0 && bc != 0L) {
while (left < right) {
val mid = left + (right - left) / 2
if (mid / a + mid / b + mid / c - mid / ab - mid / ac - mid / bc + mid / abc >= n) {
right = mid
} else {
left = mid + 1
}
}
}
return left.toInt()
}
}
| 0
|
Kotlin
|
20
| 43
|
e8b08d4a512f037e40e358b078c0a091e691d88f
| 1,212
|
LeetCode-in-Kotlin
|
MIT License
|
src/org/jetbrains/r/inspections/MissingPackageInspection.kt
|
JetBrains
| 214,212,060
| false
|
{"Kotlin": 2849970, "Java": 814635, "R": 36890, "CSS": 23692, "Lex": 14307, "HTML": 10063, "Rez": 245, "Rebol": 64}
|
// Copyright (c) 2017, <NAME>, <NAME>
/*
* Copyright 2000-2019 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.r.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import org.jetbrains.r.RBundle
import org.jetbrains.r.hints.parameterInfo.RParameterInfoUtil
import org.jetbrains.r.intentions.InstallAllFilePackagesFix
import org.jetbrains.r.intentions.InstallPackagesFix
import org.jetbrains.r.interpreter.RInterpreterStateManager
import org.jetbrains.r.packages.RequiredPackage
import org.jetbrains.r.packages.RequiredPackageInstaller
import org.jetbrains.r.psi.RPsiUtil
import org.jetbrains.r.psi.RRecursiveElementVisitor
import org.jetbrains.r.psi.api.*
class MissingPackageInspection : RInspection() {
@Nls
override fun getDisplayName(): String {
return RBundle.message("inspection.missingPackage.name")
}
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
val problemsHolder = ProblemsHolder(manager, file, isOnTheFly)
checkFile(file, problemsHolder)
return problemsHolder.resultsArray
}
private fun checkFile(file: PsiFile, problemsHolder: ProblemsHolder) {
if (file !is RFile) return
file.accept(object : RRecursiveElementVisitor() {
override fun visitNamespaceAccessExpression(o: RNamespaceAccessExpression) {
checkPackage(o, false, problemsHolder)
}
override fun visitCallExpression(psiElement: RCallExpression) {
if (RPsiUtil.isImportStatement(psiElement)) {
val info = RParameterInfoUtil.getArgumentInfo(psiElement)
val packageArg = info?.getArgumentPassedToParameter("package")
val characterOnlyArg = info?.getArgumentPassedToParameter("character.only")
if (packageArg != null) {
checkPackage(packageArg, isCharacterOnly(characterOnlyArg), problemsHolder)
}
}
psiElement.acceptChildren(this)
}
})
}
private fun checkPackage(packageExpression: RExpression, isCharacterOnly: Boolean, problemsHolder: ProblemsHolder) {
// support quoted and unquoted method names here
val packageName: String?
val elementForReporting: PsiElement
when (packageExpression) {
is RStringLiteralExpression -> {
packageName = unquote(packageExpression.getText())
elementForReporting = packageExpression
}
is RIdentifierExpression -> {
if (isCharacterOnly) return
packageName = packageExpression.getText()
elementForReporting = packageExpression
}
is RNamespaceAccessExpression -> {
if (isCharacterOnly) return
packageName = packageExpression.namespaceName
elementForReporting = packageExpression.namespace
}
// could be a function RCallExpression or something weired, so ignore it
else -> return
}
val state = RInterpreterStateManager.getCurrentStateOrNull(packageExpression.project) ?: return
if (state.isUpdating || packageName == null) { // Note: also prevents false positives during interpreter's state update
return
}
// Note: don't trigger error if this package is either installed or loaded into global environment
if (!state.hasPackage(packageName) && !state.rInterop.isLibraryLoaded(packageName)) {
val descriptionTemplate = RBundle.message("inspection.missingPackage.description", packageName)
problemsHolder.registerProblem(elementForReporting, descriptionTemplate,
InstallPackagesFix(packageName), InstallAllFilePackagesFix())
} else {
checkImplicitDependenciesFor(packageName, elementForReporting, problemsHolder)
}
}
private fun checkImplicitDependenciesFor(packageName: String, element: PsiElement, problemsHolder: ProblemsHolder) {
findImplicitDependenciesFor(packageName, element.project)?.let { dependencies ->
val description = createImplicitDependenciesDescription(packageName, dependencies)
problemsHolder.registerProblem(element, description, ProblemHighlightType.WARNING, InstallPackagesFix(dependencies))
}
}
private fun findImplicitDependenciesFor(packageName: String, project: Project): List<RequiredPackage>? {
return packageName2Dependencies[packageName]?.let { dependencies ->
val installer = RequiredPackageInstaller.getInstance(project)
val missing = installer.getMissingPackages(dependencies)
missing.takeIf { it.isNotEmpty() }
}
}
private fun isCharacterOnly(characterOnlyArg: RExpression?): Boolean {
if (characterOnlyArg == null) return false // False by default
interpretAsBoolean(characterOnlyArg)?.let { return it }
if (characterOnlyArg is RIdentifierExpression || characterOnlyArg is RNamespaceAccessExpression) {
val value = (characterOnlyArg.reference?.multiResolve(false)?.firstOrNull()?.element as? RAssignmentStatement)?.assignedValue
value?.let { interpretAsBoolean(it)?.let { return it } }
}
return true // If the calculation failed, it is better to assume that true
}
private fun interpretAsBoolean(expression: RExpression): Boolean? {
return when (expression) {
is RBooleanLiteral -> expression.isTrue
is RIdentifierExpression -> when (expression.text) {
"T" -> true
"F" -> false
else -> null
}
else -> null
}
}
// http://stackoverflow.com/questions/41298164/how-to-remove-single-and-double-quotes-at-both-ends-of-a-string
private fun unquote(text: String): String {
return text.replace("^['\"]*".toRegex(), "").replace("['\"]*$".toRegex(), "")
}
companion object {
private val animateDependencies = listOf("gifski", "png").map { RequiredPackage(it) }
private val packageName2Dependencies = mapOf(
"gganimate" to animateDependencies
)
private fun createImplicitDependenciesDescription(packageName: String, dependencies: List<RequiredPackage>): String {
val dependencyString = dependencies.joinToString(", ") { it.toFormat(true) }
return RBundle.message("inspection.missingImplicitDependencies.description", packageName, dependencyString)
}
}
}
| 2
|
Kotlin
|
9
| 62
|
d4d5cf9c09804454f811df7de0c02506d6ef12d3
| 6,567
|
Rplugin
|
Apache License 2.0
|
core/network/src/main/java/dev/shushant/network/source/NetworkDataSourceImpl.kt
|
dev-shushant
| 665,347,929
| false
|
{"Kotlin": 99424, "Shell": 4127}
|
package dev.shushant.network.source
import dev.shushant.network.model.CurrenciesResponse
import dev.shushant.network.model.CurrencyExchangeRateResponse
import dev.shushant.network.service.CurrencyConverterNetworkApi
import dev.shushant.network.utils.safeApiCall
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.decodeFromJsonElement
import javax.inject.Inject
class NetworkDataSourceImpl
@Inject
constructor(
private val service: CurrencyConverterNetworkApi,
private val json: Json,
) : NetworkDataSource {
override suspend fun getCurrencies(): Result<CurrenciesResponse> {
return safeApiCall(json) {
service.getCurrencies()
}.mapCatching { it.toCurrencyResponse(json) }
}
override suspend fun getCurrencyExchangeRate(
base: String,
symbols: String,
): Result<CurrencyExchangeRateResponse> {
return safeApiCall(json) {
service.getCurrencyRates(base = base, symbols = symbols)
}
}
}
private fun JsonObject.toCurrencyResponse(json: Json): CurrenciesResponse {
return json.decodeFromJsonElement(json.parseToJsonElement(this.toString()))
}
| 0
|
Kotlin
|
0
| 0
|
5c8ac52e5f60353a1e7def649ee2bebd08f19ca9
| 1,289
|
CurrencyConverter
|
MIT License
|
usefetch/src/main/java/me/nikhilchaudhari/usefetch/Result.kt
|
CuriousNikhil
| 431,820,990
| false
| null |
package me.nikhilchaudhari.usefetch
import me.nikhilchaudhari.usefetch.network.ResponseData
/**
* Result class represents the state value of your network response
*/
sealed class Result {
/**
* [Response] state contains [ResponseData] object of a network request
* [ResponseData] object has properties to access all your response contents
*/
data class Response(val data: ResponseData) : Result()
/**
* [Error] state contains a [Throwable] object in case of any error
*/
data class Error(val error: Throwable?) : Result()
/**
* [Loading] state means the network request is in progress
*/
object Loading : Result()
}
| 0
|
Kotlin
|
1
| 15
|
552e6adbb8793dd05af1bfb7f165777e8c46016e
| 681
|
compose-hooks
|
Apache License 2.0
|
app/src/main/java/com/experiments/android/presentation/txn/legacy/list/LegacyTxnListViewModel.kt
|
mir47
| 541,152,535
| false
|
{"Kotlin": 176352, "Ruby": 3099, "Shell": 194}
|
package com.experiments.android.presentation.txn.legacy.list
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.map
import androidx.lifecycle.viewModelScope
import com.experiments.android.data.Result.Error
import com.experiments.android.data.Result.Success
import com.experiments.android.domain.repository.TxnRepository
import kotlinx.coroutines.launch
class LegacyTxnListViewModel(
private val txnRepository: TxnRepository
) : ViewModel() {
val transactions = txnRepository.observeTransactionsResult()
/**
* Variable that tells the Fragment to navigate to a specific
* [com.experiments.android.presentation.txn.legacy.add_edit.LegacyTxnAddEditFragment]
*
* This is private because we don't want to expose setting this value to the Fragment.
*/
private val _navigateToTxnAddEdit = MutableLiveData<Boolean>()
/**
* If this is true, immediately navigate to
* [com.experiments.android.presentation.txn.legacy.add_edit.LegacyTxnAddEditFragment]
* and call [doneNavigating]
*/
val navigateToTxnAddEdit: LiveData<Boolean>
get() = _navigateToTxnAddEdit
private val _dataLoading = MutableLiveData(false)
val dataLoading: LiveData<Boolean> = _dataLoading
val error: LiveData<Boolean> = transactions.map { it is Error }
val empty: LiveData<Boolean> = transactions.map { (it as? Success)?.data.isNullOrEmpty() }
/**
* Call this immediately after navigating to
* [com.experiments.android.presentation.txn.legacy.add_edit.LegacyTxnAddEditFragment]
* It will clear the navigation request, so if the device is rotated it won't navigate twice.
*/
fun doneNavigating() {
_navigateToTxnAddEdit.value = false
}
fun onFabClick() {
_navigateToTxnAddEdit.value = true
}
fun refresh() {
_dataLoading.value = true
viewModelScope.launch {
txnRepository.refreshTransactions()
_dataLoading.value = false
}
}
@Suppress("UNCHECKED_CAST")
class TxnListViewModelFactory (
private val txnRepository: TxnRepository
) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>) =
LegacyTxnListViewModel(txnRepository) as T
}
}
| 1
|
Kotlin
|
0
| 0
|
b4e78551c73ddd2c07cc4f157a66d8eacfeec9be
| 2,426
|
experiments
|
MIT License
|
app/src/main/java/com/alexandreladriere/formulix/utils/Const.kt
|
AlexandreLadriere
| 481,709,606
| false
| null |
package com.alexandreladriere.formulix.utils
const val BACKEND_ENDPOINT = "http://ergast.com"
const val FORMAT_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'"
const val FORMAT_HOUR_MINUTE = "HH:mm"
const val FORMAT_DAY = "dd"
const val FORMAT_MONTH = "MM"
val MAP_MONTH = mapOf("01" to "JAN", "02" to "FEB", "03" to "MAR", "04" to "APR", "05" to "MAY", "06" to "JUNE", "07" to "JULY", "08" to "AUG", "09" to "SEPT", "10" to "OCT", "11" to "NOV", "12" to "DEC")
const val TWITTER_PROFILE_NAME = "FormulixApp"
const val TWITTER_USERID = "1523344151818997762"
| 0
|
Kotlin
|
0
| 0
|
0418535d4bfcd092e6470957256df184917e5456
| 543
|
Android-Formulix-App
|
MIT License
|
presentation/profile/src/commonMain/kotlin/com/thomaskioko/tvmaniac/presentation/profile/ProfileActions.kt
|
thomaskioko
| 361,393,353
| false
|
{"Kotlin": 560203, "Swift": 94284}
|
package com.thomaskioko.tvmaniac.presentation.profile
sealed interface ProfileActions
data object ShowTraktDialog : ProfileActions
data object DismissTraktDialog : ProfileActions
data object TraktLogoutClicked : ProfileActions
data object TraktLoginClicked : ProfileActions
data object SettingsClicked : ProfileActions
| 4
|
Kotlin
|
16
| 136
|
625b1bbab9aba4e5031778ba5020639106d4b4e9
| 321
|
tv-maniac
|
Apache License 2.0
|
app/src/main/java/net/sarangnamu/testrequest/UriUtils.kt
|
aucd29
| 155,800,203
| false
| null |
package net.sarangnamu.testrequest
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.support.v4.content.FileProvider
import java.io.File
/**
* Created by <a href="mailto:<EMAIL>"><NAME></a> on 2018. 11. 2. <p/>
*/
object UriUtils {
// private static final org.slf4j.Logger mLog = org.slf4j.LoggerFactory.getLogger(UriUtils.class);
/** 파일 프로바이더 경로 */
private val AUTH = ".fileprovider"
/** 스키마 */
private val CONTENT = "content"
/** 전달 받은 uri 에서 split 할 기준 */
private val EXTERNAL_FILES = "external_files"
// https://developer.android.com/training/secure-file-sharing/setup-sharing.html
// https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en
// https://github.com/commonsguy/cw-omnibus/tree/master/ContentProvider/V4FileProvider
// http://stackoverflow.com/questions/1910608/android-action-image-capture-intent
/**
* 파일을 Uri 로 변경한다.
* @param context application context
* @param file file 객체
* @return uri 로 변환된 값
*/
fun fromFile(context: Context, file: File): Uri {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
FileProvider.getUriForFile(context, context.packageName + AUTH, file)
} else Uri.fromFile(file)
}
}
| 0
|
Kotlin
|
0
| 0
|
06d572f42ff609f402b9e5775cfdb65a72c6f2eb
| 1,377
|
test-request-install-package
|
Apache License 2.0
|
module/ui/src/test/kotlin/com/github/jameshnsears/chance/ui/zoom/ZoomAndroidViewModelUnitTest.kt
|
jameshnsears
| 725,514,594
| false
| null |
package com.github.jameshnsears.chance.ui.zoom
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.github.jameshnsears.chance.data.domain.core.bag.testdouble.BagDataTestDouble
import com.github.jameshnsears.chance.data.domain.core.roll.testdouble.RollHistoryDataTestDouble
import com.github.jameshnsears.chance.data.repository.RepositoryFactory
import com.github.jameshnsears.chance.utility.android.UtilityAndroidHelper
import io.mockk.spyk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ZoomAndroidViewModelUnitTest : UtilityAndroidHelper() {
@Test
fun refreshAfterImport() = runTest {
val zoomAndroidViewModel = zoomAndroidViewModel()
zoomAndroidViewModel.refreshAfterImport()
}
@Test
fun resizeView() = runTest {
val zoomAndroidViewModel = zoomAndroidViewModel()
zoomAndroidViewModel.resizeView(1)
assertEquals(60.0.dp, zoomAndroidViewModel.stateFlowZoom.value.resizeView)
zoomAndroidViewModel.resizeView(2)
assertEquals(64.0.dp, zoomAndroidViewModel.stateFlowZoom.value.resizeView)
zoomAndroidViewModel.resizeView(3)
assertEquals(72.0.dp, zoomAndroidViewModel.stateFlowZoom.value.resizeView)
zoomAndroidViewModel.resizeView(4)
assertEquals(80.0.dp, zoomAndroidViewModel.stateFlowZoom.value.resizeView)
zoomAndroidViewModel.resizeView(5)
assertEquals(88.0.dp, zoomAndroidViewModel.stateFlowZoom.value.resizeView)
zoomAndroidViewModel.resizeView(6)
assertEquals(96.0.dp, zoomAndroidViewModel.stateFlowZoom.value.resizeView)
zoomAndroidViewModel.resizeView(7)
assertEquals(100.0.dp, zoomAndroidViewModel.stateFlowZoom.value.resizeView)
}
@Test
fun sideImageShapeNumberFontSize() = runTest {
assertEquals(
17.0.sp,
zoomAndroidViewModel().sideImageShapeNumberFontSize()
)
}
@Test
fun diceContainsAtLeastOneSideWithDescription() = runTest {
assertFalse(
zoomAndroidViewModel()
.diceContainsAtLeastOneSideWithDescription(BagDataTestDouble().d2)
)
assertTrue(
zoomAndroidViewModel()
.diceContainsAtLeastOneSideWithDescription(BagDataTestDouble().diceStory)
)
}
@Test
fun sideImageShapeNumberShape() = runTest {
assertEquals(
com.github.jameshnsears.chance.data.R.drawable.d2,
zoomAndroidViewModel().sideImageShapeNumberShape(BagDataTestDouble().d2)
)
assertEquals(
com.github.jameshnsears.chance.data.R.drawable.d6,
zoomAndroidViewModel().sideImageShapeNumberShape(BagDataTestDouble().d6)
)
assertEquals(
com.github.jameshnsears.chance.data.R.drawable.d10,
zoomAndroidViewModel().sideImageShapeNumberShape(BagDataTestDouble().d10)
)
assertEquals(
com.github.jameshnsears.chance.data.R.drawable.d12,
zoomAndroidViewModel().sideImageShapeNumberShape(BagDataTestDouble().d12)
)
assertEquals(
com.github.jameshnsears.chance.data.R.drawable.d4_d8_d20,
zoomAndroidViewModel().sideImageShapeNumberShape(BagDataTestDouble().d4)
)
}
private fun zoomAndroidViewModel(
bagDataTestDouble: BagDataTestDouble = BagDataTestDouble(),
): ZoomAndroidViewModel {
val repositoryBag = RepositoryFactory().repositoryBag
runBlocking(Dispatchers.Main) {
// 8 dice = .allDice
repositoryBag.store(bagDataTestDouble.allDice)
}
val repositoryRoll = RepositoryFactory().repositoryRoll
runBlocking(Dispatchers.Main) {
// 2 rolls:
// 1st roll:
// d2
// d4
// d8
// d10
// d12
// d20
// 2nd roll:
// d4
// d4
// d4
repositoryRoll.store(RollHistoryDataTestDouble(bagDataTestDouble).rollHistory)
}
return spyk<ZoomAndroidViewModel>(
ZoomAndroidViewModel(
getApplication(),
RepositoryFactory().repositorySettings,
repositoryBag,
repositoryRoll
)
)
}
}
| 4
| null |
2
| 6
|
3abfa1d918d8d34dadc2498888793726cba508a0
| 4,671
|
Chance
|
Apache License 2.0
|
app/src/main/java/com/savvasdalkitsis/gameframe/feature/gameframe/view/DeepLinkActivity.kt
|
Goergepaul3
| 108,090,059
| true
|
{"Kotlin": 290313, "Java": 20519}
|
package com.savvasdalkitsis.gameframe.feature.gameframe.view
import android.app.Activity
import android.os.Bundle
import com.github.andrewlord1990.snackbarbuilder.toastbuilder.ToastBuilder
import com.savvasdalkitsis.gameframe.R
import com.savvasdalkitsis.gameframe.feature.widget.view.WidgetView
import com.savvasdalkitsis.gameframe.injector.presenter.PresenterInjector
class DeepLinkActivity : Activity(), WidgetView {
private val presenter = PresenterInjector.widgetPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter.bindView(this)
when (intent.data.host) {
"power" -> presenter.power()
"next" -> presenter.next()
"menu" -> presenter.menu()
}
finish()
}
override fun operationError() {
ToastBuilder(this)
.message(R.string.error_communicating)
.build()
.show()
}
}
| 0
|
Kotlin
|
0
| 0
|
429d1835492190cc0e8d3f1d690903a2d4e5cbe5
| 982
|
gameframe
|
Apache License 2.0
|
compiler/testData/diagnostics/tests/callableReference/resolve/kt35920.kt
|
JetBrains
| 3,432,266
| false
| null |
// SKIP_TXT
// !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_PARAMETER
// FILE: JavaClass.java
public class JavaClass<R> {
public static String baz(int x) { return ""; }
}
// FILE: main.kt
fun foo(x: (Int) -> String) {}
fun main() {
foo(JavaClass<*>::<!UNRESOLVED_REFERENCE!>baz<!>)
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 299
|
kotlin
|
Apache License 2.0
|
analysis/analysis-api/testData/components/compilerFacility/compilation/inlineFunctionsInSameFile.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}
|
// DUMP_IR
// MODULE: ui
// MODULE_KIND: LibraryBinary
// FILE: com/example/ui/Text.kt
package com.example.ui
fun Text(text: String) {}
// MODULE: module2
// TARGET_PLATFORM: Common
// FILE: com/example/module2/moduleClass2.kt
package com.example.module2
inline fun a(): String = "Hi" + b()
inline fun b(): String = "Hi" + c()
inline fun c(): String = "Hi"
inline fun d(): String = "Hi" + a()
// MODULE: module1(module2)
// TARGET_PLATFORM: Common
// FILE: com/example/module1/moduleClass1.kt
@file:JvmName("SpecialName")
package com.example.module1
import com.example.module2.a
class moduleClass1 {
companion object {
inline fun giveMeString(): String {
return secret() + a()
}
@PublishedApi
internal fun secret(): String {
return "what is up!!!!!!!"
}
}
}
// MODULE: main(module1, ui)
// TARGET_PLATFORM: JVM
// FILE: main.kt
package home
import com.example.module1.moduleClass1
import com.example.ui.Text
fun Greeting(name: String) {
Text(
text = "$name!" + moduleClass1.giveMeString()
)
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,092
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/br/com/manieri/mikoshi/model/SaveData.kt
|
JoaoManieri
| 798,898,226
| false
|
{"Kotlin": 9453}
|
package br.com.manieri.mikoshi.model
data class SaveData
(
val serialNumber: String,
val email: String,
val nome: String,
val hash: String
) {
fun getCsv() : String{
return "${this.nome}, ${this.email}, ${this.serialNumber}, ${this.hash} \n"
}
}
| 0
|
Kotlin
|
0
| 0
|
f00b8c8d548f6f36eadcfebed5ebcc62429c618a
| 283
|
mikoshi
|
Apache License 2.0
|
src/main/kotlin/com/atlassian/performance/tools/report/api/FullReport.kt
|
atlassian
| 171,860,470
| false
|
{"HTML": 661490, "Kotlin": 336680, "Java": 35695}
|
package com.atlassian.performance.tools.report.api
import com.atlassian.performance.tools.io.api.ensureDirectory
import com.atlassian.performance.tools.jiraactions.api.ActionMetricStatistics
import com.atlassian.performance.tools.report.api.action.EditedIssuesReport
import com.atlassian.performance.tools.report.api.action.SearchJqlReport
import com.atlassian.performance.tools.report.api.result.EdibleResult
import com.atlassian.performance.tools.report.chart.MeanLatencyChart
import com.atlassian.performance.tools.report.chart.TimelineChart
import com.atlassian.performance.tools.report.distribution.DistributionComparison
import com.atlassian.performance.tools.workspace.api.TestWorkspace
import com.atlassian.performance.tools.workspace.api.git.GitRepo
import org.apache.logging.log4j.LogManager
class FullReport {
private val repo = GitRepo.findFromCurrentDirectory()
private val logger = LogManager.getLogger(this::class.java)
/**
* Produce all known useful reports for both comparisons and individual results.
*
* ### Comparisons
* Compare different [results]. Each result is treated equally.
*
* #### Cohort summary
* Tabulate aggregated stats of all [results] in CSV and HTML formats.
*
* #### Distribution comparison
* Display the entire distribution of action metric durations.
* Break down per action type.
* Since 3.7.0, include the distribution of an entire result.
*
* ### Individual
* Report on each of the [results] in an isolated subdirectory in the [workspace].
*
* #### Timeline chart
* Plot action metrics, system metrics and VU stats over time.
*
* #### Waterfall highlight
* Chart waterfalls of characteristic action metrics, if captured.
*/
fun dump(
results: List<EdibleResult>,
workspace: TestWorkspace,
labels: List<String> = results.flatMap { it.actionLabels }.toSet().sorted()
) {
val stats = results.map { it.stats }
CohortStatsSummary(
output = workspace.directory.resolve("summary-per-cohort.csv").toFile(),
labels = labels
).report(stats)
CohortsSummaryTable(
output = workspace.directory.resolve("summary-per-cohort.html").toFile(),
labels = labels
).report(stats)
MeanLatencyChart().plot(
stats = stats,
labels = labels,
output = workspace.directory.resolve("mean-latency-chart.html").toFile()
)
DistributionComparison(repo).compare(
output = workspace.directory.resolve("distribution-comparison.html"),
results = results
)
EditedIssuesReport().report(
output = workspace.directory.resolve("edited-issues.csv"),
results = results
)
return results.forEach { result ->
val actionMetrics = result.actionMetrics
val cohortWorkspace = workspace.directory.resolve(result.cohort)
TimelineChart(repo).generate(
output = cohortWorkspace.resolve("time-series-chart.html"),
actionMetrics = actionMetrics,
systemMetrics = result.systemMetrics
)
val actionStats = ActionMetricStatistics(result.actionMetrics)
val plaintextReport = PlaintextReport(actionStats).generate()
val csvReport = CSVReport(actionStats).generate()
logger.info("Plain text report:\n$plaintextReport")
logger.info("CSV report:\n$csvReport")
SearchJqlReport(
allMetrics = actionMetrics
).report(cohortWorkspace)
WaterfallHighlightReport().report(
metrics = actionMetrics,
workspace = TestWorkspace(cohortWorkspace.resolve("WaterfallHighlight").ensureDirectory())
)
}
}
}
| 0
|
HTML
|
25
| 6
|
49bb05fc540d4ee3133bbc9e85db796f141a93a1
| 3,922
|
report
|
Apache License 2.0
|
src/main/kotlin/com/geovannycode/Application.kt
|
Geovanny0401
| 615,122,233
| false
| null |
package com.geovannycode
import com.geovannycode.Security.configureSecurity
import com.geovannycode.config.configureContentNegotiation
import com.geovannycode.config.configureDatabase
import com.geovannycode.config.configureRouting
import io.ktor.server.application.*
fun main(args: Array<String>): Unit =
io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused.
fun Application.module() {
configureDatabase()
configureContentNegotiation()
configureSecurity()
configureRouting()
}
| 0
|
Kotlin
|
0
| 1
|
695d7c7efdeed9ffb4b55ad55425c6baf32e29c3
| 620
|
ktor-rest-api
|
Apache License 2.0
|
app/src/main/java/com/dbsrm/evo/ui/share/ShareViewModel.kt
|
DevBahl
| 256,489,535
| false
| null |
package com.dbsrm.evo.ui.share
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class ShareViewModel : ViewModel() {
private val mText: MutableLiveData<String?>
val text: LiveData<String?>
get() = mText
init {
mText = MutableLiveData()
mText.value = "This is share fragment"
}
}
| 0
|
Kotlin
|
0
| 0
|
33a574343017c3d824179f310edcfbf315902eb3
| 385
|
Evo
|
MIT License
|
app/src/main/java/br/com/wakim/eslpodclient/android/widget/SpacingItemDecoration.kt
|
wakim
| 52,843,851
| false
|
{"Git Config": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 1, "XML": 63, "JSON": 1, "Kotlin": 84}
|
package br.com.wakim.eslpodclient.android.widget
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
class SpacingItemDecoration(val left: Int = 0, val top: Int = 0, val right: Int = 0, val bottom: Int = 0) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View?, parent: RecyclerView, state: RecyclerView.State?) {
outRect.set(left, top, right, bottom)
}
}
| 0
|
Kotlin
|
1
| 6
|
a92dad2832f087f97fcbf9b2b7973a31efde551c
| 457
|
esl-pod-client
|
Apache License 2.0
|
src/main/kotlin/com/github/simiacryptus/aicoder/actions/generic/RedoLast.kt
|
SimiaCryptus
| 580,649,146
| false
| null |
package com.github.simiacryptus.aicoder.actions.generic
import com.github.simiacryptus.aicoder.actions.BaseAction
import com.github.simiacryptus.aicoder.util.UITools
import com.github.simiacryptus.aicoder.util.UITools.retry
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.simiacryptus.openai.APIClientBase
/**
* The RedoLast action is an IntelliJ action that allows users to redo the last AI Coder action they performed in the editor.
* To use this action, open the editor and select the RedoLast action from the editor context menu.
* This will redo the last action that was performed in the editor.
*/
class RedoLast : BaseAction() {
override fun handle(e: AnActionEvent) {
retry[e.getRequiredData(CommonDataKeys.EDITOR).document]!!.run()
}
override fun isEnabled(e: AnActionEvent): Boolean {
if (UITools.isSanctioned()) return false
return null != retry[e.getRequiredData(CommonDataKeys.EDITOR).document]
}
}
| 8
| null |
14
| 43
|
3c5dbf1c5de04841d33e380760122a63b633e805
| 1,036
|
intellij-aicoder
|
Apache License 2.0
|
app/src/main/java/com/mathewsachin/fategrandautomata/scripts/modules/Battle.kt
|
pkurteev
| 280,206,378
| true
|
{"Kotlin": 210364}
|
package com.mathewsachin.fategrandautomata.scripts.modules
import com.mathewsachin.libautomata.*
import com.mathewsachin.fategrandautomata.scripts.ImageLocator
import com.mathewsachin.fategrandautomata.scripts.prefs.Preferences
import kotlin.time.seconds
class Battle {
private var hasTakenFirstStageSnapshot = false
var hasClickedAttack = false
private set
var hasChosenTarget = false
private set
var currentStage = -1
private set
var currentTurn = -1
private set
private lateinit var autoSkill: AutoSkill
private lateinit var card: Card
fun init(AutoSkillModule: AutoSkill, CardModule: Card) {
autoSkill = AutoSkillModule
card = CardModule
resetState()
}
fun resetState() {
autoSkill.resetState()
currentStage = -1
currentTurn = -1
hasTakenFirstStageSnapshot = false
hasChosenTarget = false
hasClickedAttack = false
}
fun isIdle() = Game.BattleScreenRegion.exists(ImageLocator.Battle)
fun clickAttack() {
Game.BattleAttackClick.click()
// TODO: This was added extra in Kotlin impl
// Wait for Attack button to disappear
Game.BattleScreenRegion.waitVanish(ImageLocator.Battle, 5.seconds)
// Although it seems slow, make it no shorter than 1 sec to protect user with less processing power devices.
1.5.seconds.wait()
hasClickedAttack = true
card.readCommandCards()
}
private fun isPriorityTarget(Target: Region): Boolean {
val isDanger = Target.exists(ImageLocator.TargetDanger)
val isServant = Target.exists(ImageLocator.TargetServant)
return isDanger || isServant
}
private fun chooseTarget(Index: Int) {
Game.BattleTargetClickArray[Index].click()
0.5.seconds.wait()
Game.BattleExtrainfoWindowCloseClick.click()
hasChosenTarget = true
}
private fun onStageChanged() {
++currentStage
currentTurn = -1
hasChosenTarget = false
}
private fun autoChooseTarget() {
// from my experience, most boss stages are ordered like(Servant 1)(Servant 2)(Servant 3),
// where(Servant 3) is the most powerful one. see docs/ boss_stage.png
// that's why the table is iterated backwards.
for ((i, target) in Game.BattleTargetRegionArray.withIndex().reversed()) {
if (isPriorityTarget(target)) {
chooseTarget(i)
return
}
}
}
fun performBattle() {
ScreenshotManager.useSameSnapIn { onTurnStarted() }
2.seconds.wait()
var wereNpsClicked = false
if (Preferences.EnableAutoSkill) {
wereNpsClicked = autoSkill.execute()
autoSkill.resetNpTimer()
}
if (!hasClickedAttack) {
clickAttack()
}
if (card.canClickNpCards) {
// We shouldn't do the long wait due to NP spam/danger modes
// They click on NPs even when not charged
// So, don't assign wereNpsClicked here
card.clickNpCards()
}
card.clickCommandCards(5)
card.resetCommandCards()
(if (wereNpsClicked) 25 else 5).seconds.wait()
}
private fun onTurnStarted() {
checkCurrentStage()
++currentTurn
hasClickedAttack = false
if (!hasChosenTarget && Preferences.BattleAutoChooseTarget) {
autoChooseTarget()
}
}
private fun checkCurrentStage() {
if (!hasTakenFirstStageSnapshot || didStageChange()) {
onStageChanged()
takeStageSnapshot()
}
}
private var generatedStageCounterSnapshot: IPattern? = null
fun didStageChange(): Boolean {
// Alternative fix for different font of stage count number among different regions, worked pretty damn well tho.
// This will compare last screenshot with current screen, effectively get to know if stage changed or not.
val snapshot = generatedStageCounterSnapshot
?: return true
return !Game.BattleStageCountRegion.exists(snapshot, Similarity = 0.85)
}
fun takeStageSnapshot() {
generatedStageCounterSnapshot?.close()
// It is important that the image gets cloned here.
generatedStageCounterSnapshot = Game.BattleStageCountRegion.getPattern()
hasTakenFirstStageSnapshot = true
}
}
| 0
|
Kotlin
|
0
| 0
|
45ba006f36b422a7f99b3f898d4987260bb4f949
| 4,509
|
Fate-Grand-Automata
|
MIT License
|
src/main/kotlin/org/crystal/intellij/stubs/impl/CrCFieldStubImpl.kt
|
asedunov
| 353,165,557
| false
| null |
package org.crystal.intellij.stubs.impl
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.stubs.StubElement
import org.crystal.intellij.psi.CrCField
import org.crystal.intellij.stubs.api.CrCFieldStub
class CrCFieldStubImpl(
parent: StubElement<*>?,
elementType: IStubElementType<out StubElement<*>, *>,
) : CrStubElementImpl<CrCField>(parent, elementType), CrCFieldStub
| 1
|
Kotlin
|
0
| 4
|
a2dd8bb0837aa411fe13e94a0efd255b074445da
| 400
|
intellij-crystal-lang
|
Apache License 2.0
|
OfficialSite/Collections/Map/PlusMinus.kt
|
kazenetu
| 238,936,555
| false
| null |
/*
* コレクション:Map
*/
fun main() {
// 追加と削除
println("---Map : plus and minus---")
println("> plus")
println("mapOf(\"key1\" to 1, \"key2\" to 2) + Pair(\"Key3\", 3) = ${ mapOf("key1" to 1, "key2" to 2) + Pair("Key3", 3) }")
println("mapOf(\"key1\" to 1, \"key2\" to 2) + mapOf(\"Key3\" to 3, \"a\" to 10) = ${ mapOf("key1" to 1, "key2" to 2) + mapOf("Key3" to 3, "a" to 10) }")
println(" ")
println("> plus : update")
println("mapOf(\"key1\" to 1, \"key2\" to 2) + Pair(\"key1\", 11) = ${ mapOf("key1" to 1, "key2" to 2) + Pair("key1", 11) }")
println("mapOf(\"key1\" to 1, \"key2\" to 2) + mapOf(\"key1\" to 50, \"key3\" to 3) = ${ mapOf("key1" to 1, "key2" to 2) + mapOf("key1" to 50, "key3" to 3) }")
println(" ")
println("> minus")
println("mapOf(\"key1\" to 1, \"key2\" to 2, \"key3\" to 3) - \"key2\" = ${ mapOf("key1" to 1, "key2" to 2, "key3" to 3) - "key2" }")
println("mapOf(\"key1\" to 1, \"key2\" to 2, \"key3\" to 3) - listOf(\"key3\", \"key1\") = ${ mapOf("key1" to 1, "key2" to 2, "key3" to 3) - listOf("key3", "key1") }")
}
// 出力:
// ---Map : plus and minus---
// > plus
// mapOf("key1" to 1, "key2" to 2) + Pair("Key3", 3) = {key1=1, key2=2, Key3=3}
// mapOf("key1" to 1, "key2" to 2) + mapOf("Key3" to 3, "a" to 10) = {key1=1, key2=2, Key3=3, a=10}
//
// > plus : update
// mapOf("key1" to 1, "key2" to 2) + Pair("key1", 11) = {key1=11, key2=2}
// mapOf("key1" to 1, "key2" to 2) + mapOf("key1" to 50, "key3" to 3) = {key1=50, key2=2, key3=3}
//
// > minus
// mapOf("key1" to 1, "key2" to 2, "key3" to 3) - "key2" = {key1=1, key3=3}
// mapOf("key1" to 1, "key2" to 2, "key3" to 3) - listOf("key3", "key1") = {key2=2}
| 0
|
Kotlin
|
0
| 0
|
77df823ed3131e45d6aadd325a4726e106c6ef60
| 1,707
|
kotlin-practice
|
MIT License
|
core/utils/src/main/java/ru/aleshin/core/utils/extensions/Date.kt
|
v1tzor
| 638,022,252
| false
| null |
/*
* Copyright 2023 Stanislav Aleshin
*
* 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
* imitations under the License.
*/
package ru.aleshin.core.utils.extensions
import ru.aleshin.core.utils.functional.Constants
import ru.aleshin.core.utils.functional.TimeRange
import java.util.*
import kotlin.math.ceil
/**
* @author Stanislav Aleshin on 22.02.2023.
*/
fun Date.shiftDay(amount: Int, locale: Locale = Locale.getDefault()): Date {
val calendar = Calendar.getInstance(locale).also {
it.time = this@shiftDay
startThisDay()
it.add(Calendar.DAY_OF_YEAR, amount)
}
return calendar.time
}
fun Date.shiftMinutes(amount: Int, locale: Locale = Locale.getDefault()): Date {
val calendar = Calendar.getInstance(locale).also {
it.time = this@shiftMinutes
it.add(Calendar.MINUTE, amount)
}
return calendar.time
}
fun Date.shiftMillis(amount: Int, locale: Locale = Locale.getDefault()): Date {
val calendar = Calendar.getInstance(locale).also {
it.time = this@shiftMillis
it.add(Calendar.MILLISECOND, amount)
}
return calendar.time
}
fun Date.isCurrentDay(date: Date): Boolean {
val currentDate = Calendar.getInstance().apply { time = date }.get(Calendar.DAY_OF_YEAR)
val compareDate =
Calendar.getInstance().apply { time = this@isCurrentDay }.get(Calendar.DAY_OF_YEAR)
return currentDate == compareDate
}
fun Date.compareByHoursAndMinutes(compareDate: Date): Boolean {
val firstCalendar = Calendar.getInstance().apply { time = this@compareByHoursAndMinutes }
val secondCalendar = Calendar.getInstance().apply { time = compareDate }
val hoursEquals = firstCalendar.get(Calendar.HOUR_OF_DAY) == secondCalendar.get(Calendar.HOUR_OF_DAY)
val minutesEquals = firstCalendar.get(Calendar.MINUTE) == secondCalendar.get(Calendar.MINUTE)
return hoursEquals && minutesEquals
}
fun Date.startThisDay(): Date {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar.setStartDay().time
}
fun Date.endThisDay(): Date {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar.setEndDay().time
}
fun Calendar.setStartDay() = this.apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
fun Calendar.setEndDay() = this.apply {
set(Calendar.HOUR_OF_DAY, 23)
set(Calendar.MINUTE, 59)
set(Calendar.SECOND, 59)
set(Calendar.MILLISECOND, 59)
}
fun Date.changeDay(date: Date): Date {
val changedDateCalendar = Calendar.getInstance().apply {
time = this@changeDay
}
val newDateCalendar = Calendar.getInstance().apply {
time = date.startThisDay()
set(Calendar.HOUR_OF_DAY, changedDateCalendar.get(Calendar.HOUR_OF_DAY))
set(Calendar.MINUTE, changedDateCalendar.get(Calendar.MINUTE))
set(Calendar.SECOND, changedDateCalendar.get(Calendar.SECOND))
set(Calendar.MILLISECOND, changedDateCalendar.get(Calendar.MILLISECOND))
}
return newDateCalendar.time
}
fun duration(start: Date, end: Date): Long {
return end.time - start.time
}
fun Date.isNotZeroDifference(end: Date): Boolean {
return duration(this, end) > 0L
}
fun duration(timeRange: TimeRange): Long {
return timeRange.to.time - timeRange.from.time
}
fun durationOrZero(start: Date?, end: Date?) = if (start != null && end != null) {
duration(start, end)
} else {
Constants.Date.EMPTY_DURATION
}
fun Long?.mapToDateOrDefault(defualt: Date): Date {
val calendar = Calendar.getInstance().also {
it.timeInMillis = this ?: defualt.time
}
return calendar.time
}
fun Long.mapToDate(): Date {
val calendar = Calendar.getInstance().also {
it.timeInMillis = this
}
return calendar.time
}
fun Long.toSeconds(): Long {
return this / Constants.Date.MILLIS_IN_SECONDS
}
fun Long.toMinutes(): Long {
return toSeconds() / Constants.Date.SECONDS_IN_MINUTE
}
fun Long.toMinutesInHours(): Long {
val hours = toHorses()
val minutes = toMinutes()
return minutes - hours * Constants.Date.MINUTES_IN_HOUR
}
fun Long.toHorses(): Long {
return toMinutes() / Constants.Date.MINUTES_IN_HOUR
}
fun Int.minutesToMillis(): Long {
return this * Constants.Date.MILLIS_IN_MINUTE
}
fun Int.hoursToMillis(): Long {
return this * Constants.Date.MILLIS_IN_HOUR
}
fun Long.toMinutesOrHoursString(minutesSymbol: String, hoursSymbol: String): String {
val minutes = this.toMinutes()
val hours = this.toHorses()
return if (minutes == 0L) {
Constants.Date.minutesFormat.format("1", minutesSymbol)
} else if (minutes in 1L..59L) {
Constants.Date.minutesFormat.format(minutes.toString(), minutesSymbol)
} else if (minutes > 59L && (minutes % 60L) != 0L) {
Constants.Date.hoursAndMinutesFormat.format(
hours.toString(),
hoursSymbol,
toMinutesInHours().toString(),
minutesSymbol,
)
} else {
Constants.Date.hoursFormat.format(hours.toString(), hoursSymbol)
}
}
fun Long.toMinutesAndHoursString(minutesSymbol: String, hoursSymbol: String): String {
val minutes = this.toMinutes()
val hours = this.toHorses()
return Constants.Date.hoursAndMinutesFormat.format(
hours.toString(),
hoursSymbol,
(minutes - hours * Constants.Date.MINUTES_IN_HOUR).toString(),
minutesSymbol,
)
}
fun Date.setZeroSecond(): Date {
val calendar = Calendar.getInstance().apply {
time = this@setZeroSecond
set(Calendar.SECOND, 0)
}
return calendar.time
}
fun TimeRange.isIncludeTime(time: Date): Boolean {
return time >= this.from && time <= this.to
}
fun TimeRange.toDaysTitle(): String {
val calendar = Calendar.getInstance()
val dayStart = calendar.apply { time = from }.get(Calendar.DAY_OF_MONTH)
val dayEnd = calendar.apply { time = to }.get(Calendar.DAY_OF_MONTH)
return "$dayStart-$dayEnd"
}
fun TimeRange.toMonthTitle(): String {
val calendar = Calendar.getInstance()
val month = calendar.apply { time = from }.get(Calendar.MONTH) + 1
return month.toString()
}
fun countWeeksByDays(days: Int): Int {
return ceil(days.toDouble() / Constants.Date.DAYS_IN_WEEK).toInt()
}
fun countMonthByDays(days: Int): Int {
return ceil(days.toDouble() / Constants.Date.DAYS_IN_MONTH).toInt()
}
| 7
| null |
8
| 99
|
0762559e4dabea2971df1573472216f554ab8577
| 6,918
|
TimePlanner
|
Apache License 2.0
|
gaia/src/main/kotlin/dev/pooq/ichor/gaia/entity/player/Player.kt
|
kxmpxtxnt
| 586,376,008
| false
| null |
package dev.pooq.ichor.gaia.entity.player
import dev.pooq.ichor.gaia.entity.Entity
import dev.pooq.ichor.gaia.networking.packet.PacketHandle
import java.util.*
class Player(
val uuid: UUID,
val name: String,
val handle: PacketHandle
) : Entity.Creature
| 0
|
Kotlin
|
0
| 3
|
1451ae9c7d1a67d2b85d013aa1dec72cfce7e045
| 260
|
ichor
|
Apache License 2.0
|
app/src/main/java/se/barsk/park/fcm/Notification.kt
|
nibarius
| 94,821,344
| false
| null |
package se.barsk.park.fcm
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.TaskStackBuilder
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import org.json.JSONObject
import se.barsk.park.R
import se.barsk.park.mainui.ParkActivity
/**
* Base class for notifications.
*/
abstract class Notification(protected val context: Context, protected val data: JSONObject) {
protected abstract val id: String
protected abstract val timeout: Long
abstract fun show()
protected fun makeNotification(title: String, text: String) {
val mBuilder = NotificationCompat.Builder(context, id)
.setSmallIcon(R.mipmap.notif_icon)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setTimeoutAfter(timeout)
// Creates an explicit intent for an Activity in your app
val resultIntent = Intent(context, ParkActivity::class.java)
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your app to the Home screen.
val stackBuilder = TaskStackBuilder.create(context)
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ParkActivity::class.java)
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent)
val resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
)
mBuilder.setContentIntent(resultPendingIntent)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// mNotificationId is a unique integer your app uses to identify the
// notification. For example, to cancel the notification, you can pass its ID
// number to NotificationManager.cancel().
mNotificationManager.notify(0, mBuilder.build())
}
}
| 0
|
Kotlin
|
0
| 0
|
dbadadcfe717928c6b833a26c72a5ab07faccb04
| 2,312
|
opera-park-android
|
MIT License
|
app/src/main/java/com/eynnzerr/yuukatalk/ui/component/PhotoBubble.kt
|
Eynnzerr
| 725,178,988
| false
| null |
package com.eynnzerr.yuukatalk.ui.component
import android.util.Base64
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
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.CardDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import coil.transform.RoundedCornersTransformation
import com.eynnzerr.yuukatalk.utils.ImageUtils
@Composable
fun PhotoBubble(
uri: String,
isMyMessage: Boolean,
modifier: Modifier = Modifier,
size: Dp = 192.dp
) {
Log.d(TAG, "PhotoBubble: uri: $uri")
Column(
modifier = Modifier.fillMaxWidth()
) {
Card(
modifier = modifier
.align(if (isMyMessage) Alignment.End else Alignment.Start)
.padding(bottom = 8.dp)
.width(size),
colors = CardDefaults.cardColors(containerColor = Color.White)
) {
// 无意发现AsyncImage一个bug:只有外面被row/column包一层后,才能在bitmap上绘制出来
AsyncImage(
model = ImageRequest
.Builder(LocalContext.current)
.data(if (ImageUtils.isImageBase64(uri)) Base64.decode(uri, Base64.DEFAULT) else uri)
.crossfade(true)
.transformations(RoundedCornersTransformation())
.build(),
contentScale = ContentScale.Crop,
contentDescription = "",
modifier = Modifier
.padding(8.dp)
.fillMaxSize(),
)
}
}
}
private const val TAG = "PhotoBubble"
| 0
| null |
0
| 8
|
7bc939080f38d1e647f4ec3f1a2c33e576b77dbf
| 2,134
|
YuukaTalk
|
MIT License
|
feature/account/src/main/java/little/goose/account/ui/analysis/AccountAnalysisRoute.kt
|
MReP1
| 525,822,587
| false
| null |
package little.goose.account.ui.analysis
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import com.google.accompanist.navigation.animation.composable
import little.goose.account.data.constants.MoneyType
import little.goose.common.utils.TimeType
import java.util.Date
const val ROUTE_ACCOUNT_ANALYSIS = "account_analysis"
fun NavController.navigateToAccountAnalysis() {
navigate(ROUTE_ACCOUNT_ANALYSIS) {
launchSingleTop = true
}
}
fun NavGraphBuilder.accountAnalysisRoute(
onNavigateToTransactionExample: (
time: Date, timeType: TimeType, moneyType: MoneyType, content: String?
) -> Unit,
onBack: () -> Unit
) = composable(
route = ROUTE_ACCOUNT_ANALYSIS,
enterTransition = {
fadeIn(
animationSpec = tween(200, easing = LinearOutSlowInEasing)
) + slideIntoContainer(
towards = AnimatedContentScope.SlideDirection.Up,
animationSpec = tween(200, easing = LinearOutSlowInEasing),
initialOffset = { it / 6 }
)
},
exitTransition = null,
popExitTransition = {
fadeOut(
animationSpec = tween(200, easing = FastOutLinearInEasing)
) + slideOutOfContainer(
towards = AnimatedContentScope.SlideDirection.Down,
animationSpec = tween(200, easing = FastOutLinearInEasing),
targetOffset = { it / 6 }
)
},
popEnterTransition = null
) {
AccountAnalysisRoute(
modifier = Modifier
.fillMaxSize()
.shadow(36.dp, clip = false),
onNavigateToTransactionExample = onNavigateToTransactionExample,
onBack = onBack
)
}
@Composable
fun AccountAnalysisRoute(
modifier: Modifier,
onNavigateToTransactionExample: (
time: Date, timeType: TimeType, moneyType: MoneyType, content: String?
) -> Unit,
onBack: () -> Unit
) {
val viewModel = hiltViewModel<TransactionAnalysisViewModel>()
val topBarState by viewModel.topBarState.collectAsStateWithLifecycle()
val contentState by viewModel.contentState.collectAsStateWithLifecycle()
val bottomBarState by viewModel.bottomBarState.collectAsStateWithLifecycle()
val timeSelectorState = viewModel.timeSelectorState
TransactionAnalysisScreen(
modifier = modifier,
topBarState = topBarState,
contentState = contentState,
bottomBarState = bottomBarState,
timeSelectorState = timeSelectorState,
onBack = onBack,
onNavigateToTransactionExample = onNavigateToTransactionExample
)
}
| 1
| null |
27
| 99
|
a6ee70d1b3dcf4b9b24ca00bbed725e8374e105a
| 3,268
|
LittleGooseOffice
|
MIT License
|
circularcardsstackview/src/main/java/com/mindinventory/circularcardsstackview/listener/CardActionListener.kt
|
Mindinventory
| 396,811,810
| false
| null |
package com.mindinventory.circularcardsstackview.listener
interface CardActionListener {
fun onFirstButtonOptionClick(position: Int)
fun onSecondButtonOptionClick(position: Int)
}
| 0
|
Kotlin
|
2
| 30
|
315c7d767509bc43dd8d5fe2f93e57e9818b1be2
| 188
|
CircularCardsStackView
|
MIT License
|
app/src/main/java/com/jim/moviecritics/ext/FragmentExt.kt
|
MIN-JING
| 503,330,525
| false
|
{"Kotlin": 286084}
|
package com.jim.moviecritics.ext
import androidx.fragment.app.Fragment
import com.jim.moviecritics.MovieApplication
import com.jim.moviecritics.data.Comment
import com.jim.moviecritics.data.Movie
import com.jim.moviecritics.data.User
import com.jim.moviecritics.factory.CommentViewModelFactory
import com.jim.moviecritics.factory.MovieViewModelFactory
import com.jim.moviecritics.factory.UserViewModelFactory
import com.jim.moviecritics.factory.ViewModelFactory
fun Fragment.getVmFactory(): ViewModelFactory {
val repository = (requireContext().applicationContext as MovieApplication).applicationRepository
return ViewModelFactory(repository)
}
fun Fragment.getVmFactory(movie: Movie): MovieViewModelFactory {
val repository = (requireContext().applicationContext as MovieApplication).applicationRepository
return MovieViewModelFactory(repository, movie)
}
fun Fragment.getVmFactory(user: User?): UserViewModelFactory {
val repository = (requireContext().applicationContext as MovieApplication).applicationRepository
return UserViewModelFactory(repository, user)
}
fun Fragment.getVmFactory(comment: Comment): CommentViewModelFactory {
val repository = (requireContext().applicationContext as MovieApplication).applicationRepository
return CommentViewModelFactory(repository, comment)
}
| 1
|
Kotlin
|
0
| 0
|
9818ae1ed3bd7f80e230c611600d532712306eb1
| 1,324
|
MovieCritics
|
Apache License 2.0
|
src/main/kotlin/xyz/webo/plugins/Routing.kt
|
believemanasseh
| 609,058,470
| false
|
{"Kotlin": 30510, "Handlebars": 4491, "CSS": 1271, "HTML": 789}
|
package xyz.webo.plugins
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import xyz.webo.routes.adminRouting
import xyz.webo.routes.authRouting
import xyz.webo.routes.postRouting
import xyz.webo.routes.userRouting
import java.io.File
fun Application.configureRouting() {
routing {
get("") {
call.respondFile(File("src/main/resources/openapi/swagger/index.html"))
}
get("/documentation.yaml") {
call.respondFile(File("src/main/resources/openapi/documentation.yaml"))
}
authRouting()
adminRouting()
userRouting()
postRouting()
}
}
| 0
|
Kotlin
|
0
| 0
|
d22b9dcf506bd1b749f34d6046dd21f28820d4f1
| 683
|
webo-server
|
Apache License 2.0
|
presentation/base/src/main/java/com/bateng/jikan/api/presentation/base/navigation/navigator/NavigatorEvent.kt
|
bat-eng
| 516,289,173
| false
| null |
package com.bateng.jikan.api.presentation.base.navigation.navigator
import androidx.navigation.NavOptionsBuilder
sealed class NavigatorEvent {
object NavigateUp : NavigatorEvent()
class Directions(val destination: String, val builder: NavOptionsBuilder.() -> Unit) : NavigatorEvent()
}
| 0
|
Kotlin
|
0
| 0
|
b9ca169141c605dfc0693a076abd065bceecccc3
| 295
|
JikanApi
|
Apache License 2.0
|
codebase/android/core-database/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/database/transaction/usecase/GetRecentTransactionDataUseCase.kt
|
Abhimanyu14
| 429,663,688
| false
| null |
package com.makeappssimple.abhimanyu.financemanager.android.core.database.transaction.usecase
import com.makeappssimple.abhimanyu.financemanager.android.core.database.transaction.model.TransactionData
import com.makeappssimple.abhimanyu.financemanager.android.core.database.transaction.repository.TransactionRepository
import kotlinx.coroutines.flow.Flow
interface GetRecentTransactionDataUseCase {
operator fun invoke(
numberOfTransactions: Int = 10,
): Flow<List<TransactionData>>
}
class GetRecentTransactionDataUseCaseImpl(
private val transactionRepository: TransactionRepository,
) : GetRecentTransactionDataUseCase {
override operator fun invoke(
numberOfTransactions: Int,
): Flow<List<TransactionData>> {
return transactionRepository.getRecentTransactionData(
numberOfTransactions = numberOfTransactions,
)
}
}
| 0
|
Kotlin
|
0
| 0
|
29afaec0cf4e95ba4d6c0dcc32cba3fea6a088cb
| 891
|
finance-manager
|
Apache License 2.0
|
app/src/main/java/com/octopus/sample/ui/main/home/HomePagedAdapter.kt
|
JonDoe-297
| 247,462,407
| false
| null |
package com.octopus.sample.ui.main.home
import android.content.Intent
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.request.RequestOptions
import com.qingmei2.architecture.core.image.GlideApp
import com.octopus.sample.R
import com.octopus.sample.entity.ReceivedEvent
import com.octopus.sample.ui.detail.DetailActivity
import com.octopus.sample.utils.TimeConverter
class HomePagedAdapter : PagedListAdapter<ReceivedEvent, HomePagedViewHolder>(diffCallback) {
private val itemEventObservable: MutableLiveData<String> = MutableLiveData()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomePagedViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_home_received_event, parent, false)
return HomePagedViewHolder(view)
}
override fun onBindViewHolder(holder: HomePagedViewHolder, position: Int) {
holder.binds(getItem(position)!!, position, itemEventObservable)
}
fun observeItemEvent(): LiveData<String> {
return itemEventObservable
}
companion object {
private val diffCallback: DiffUtil.ItemCallback<ReceivedEvent> =
object : DiffUtil.ItemCallback<ReceivedEvent>() {
override fun areItemsTheSame(oldItem: ReceivedEvent, newItem: ReceivedEvent): Boolean {
return oldItem.classid == newItem.classid
}
override fun areContentsTheSame(oldItem: ReceivedEvent, newItem: ReceivedEvent): Boolean {
return oldItem == newItem
}
}
}
}
class HomePagedViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
private val tvEventContent: TextView = view.findViewById(R.id.tvEventContent)
private val tvEventTime: TextView = view.findViewById(R.id.tvEventTime)
fun binds(data: ReceivedEvent, position: Int, liveData: MutableLiveData<String>) {
tvEventContent.text = data.classname
view.setOnClickListener {
view.context.startActivity(Intent(view.context, DetailActivity::class.java)
.putExtra(DetailActivity.CLASS_NUM, data.classnum))
}
}
}
| 0
|
Kotlin
|
0
| 1
|
bc9d26bda6b6f309df9dfb907ffd1a46da206f78
| 2,838
|
presentCloud-mobileUI
|
Apache License 2.0
|
src/main/java/jukebot/utils/RequestUtil.kt
|
cyberfox1998
| 214,037,373
| false
|
{"Text": 2, "Gradle": 2, "XML": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 1, "Kotlin": 61, "Java": 4}
|
package jukebot.utils
import okhttp3.*
import org.slf4j.LoggerFactory
import java.io.IOException
class RequestUtil {
private val httpClient = OkHttpClient()
private val logger = LoggerFactory.getLogger(this.javaClass)
inner class PendingRequest(private val request: Request) {
fun block(): Response {
return httpClient.newCall(request).execute()
}
fun queue(success: (Response) -> Unit, failure: (IOException) -> Unit) {
httpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
logger.error("An error occurred during a HTTP request to ${call.request().url()}", e)
failure(e)
}
override fun onResponse(call: Call, response: Response) {
success(response)
}
})
}
}
public fun get(url: String, headers: Headers = Headers.of()): PendingRequest {
return makeRequest("GET", url, null, headers)
}
public fun makeRequest(method: String, url: String, body: RequestBody? = null, headers: Headers): PendingRequest {
val request = Request.Builder()
.method(method.toUpperCase(), body)
.header("User-Agent", "JukeBot (https://github.com/Devoxin/JukeBot)")
.headers(headers)
.url(url)
return PendingRequest(request.build())
}
public fun makeRequest(request: Request): PendingRequest {
return PendingRequest(request)
}
}
| 0
|
Kotlin
|
0
| 0
|
2c29200358bf5059df5115f52e4aca0de15b3739
| 1,595
|
lond
|
Apache License 2.0
|
kotlinpoet-dsl/src/test/kotlin/com/hendraanggrian/kotlinpoet/collections/PropertySpecListTest.kt
|
hendraanggrian
| 209,613,746
| false
| null |
package com.hendraanggrian.kotlinpoet.collections
import com.example.Property1
import com.example.Property2
import com.example.Property3
import com.example.Property4
import com.example.Property5
import com.example.Property6
import com.example.Property7
import com.example.Property8
import com.google.common.truth.Truth.assertThat
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.asTypeName
import kotlin.test.Test
class PropertySpecListTest {
private val list = PropertySpecList(mutableListOf())
private fun list(configuration: PropertySpecListScope.() -> Unit) =
PropertySpecListScope(list).configuration()
@Test
fun add() {
list.add("property1", Property1::class.asTypeName())
list.add("property2", Property2::class.asTypeName()) { initializer("value2") }
list.add("property3", Property3::class.java)
list.add("property4", Property4::class.java) { initializer("value4") }
list.add("property5", Property5::class)
list.add("property6", Property6::class) { initializer("value6") }
list.add<Property7>("property7")
list.add<Property8>("property8") { initializer("value8") }
assertThat(list).containsExactly(
PropertySpec.builder("property1", Property1::class.java).build(),
PropertySpec.builder("property2", Property2::class.java).initializer("value2").build(),
PropertySpec.builder("property3", Property3::class.java).build(),
PropertySpec.builder("property4", Property4::class.java).initializer("value4").build(),
PropertySpec.builder("property5", Property5::class.java).build(),
PropertySpec.builder("property6", Property6::class.java).initializer("value6").build(),
PropertySpec.builder("property7", Property7::class.java).build(),
PropertySpec.builder("property8", Property8::class.java).initializer("value8").build()
)
}
@Test
fun set() {
list["field1"] = Property1::class.asTypeName()
list["field2"] = Property2::class.java
list["field3"] = Property3::class
assertThat(list).containsExactly(
PropertySpec.builder("field1", Property1::class.java).build(),
PropertySpec.builder("field2", Property2::class.java).build(),
PropertySpec.builder("field3", Property3::class.java).build()
)
}
@Test
@Suppress("UNUSED_VARIABLE")
fun adding() {
val property1 by list.adding(Property1::class.asTypeName())
val property2 by list.adding(Property2::class.asTypeName()) { initializer("value2") }
val property3 by list.adding(Property3::class.java)
val property4 by list.adding(Property4::class.java) { initializer("value4") }
val property5 by list.adding(Property5::class)
val property6 by list.adding(Property6::class) { initializer("value6") }
assertThat(list).containsExactly(
PropertySpec.builder("property1", Property1::class.java).build(),
PropertySpec.builder("property2", Property2::class.java).initializer("value2").build(),
PropertySpec.builder("property3", Property3::class.java).build(),
PropertySpec.builder("property4", Property4::class.java).initializer("value4").build(),
PropertySpec.builder("property5", Property5::class.java).build(),
PropertySpec.builder("property6", Property6::class.java).initializer("value6").build(),
)
}
@Test
fun invoke() {
list {
"property1"(Property1::class.asTypeName()) { initializer("value1") }
"property2"(Property2::class.java) { initializer("value2") }
"property3"(Property3::class) { initializer("value3") }
}
assertThat(list).containsExactly(
PropertySpec.builder("property1", Property1::class.java).initializer("value1").build(),
PropertySpec.builder("property2", Property2::class.java).initializer("value2").build(),
PropertySpec.builder("property3", Property3::class.java).initializer("value3").build(),
)
}
}
| 1
|
Kotlin
|
0
| 3
|
98f4ea811ea25b6a85334a15ae90bddd5f015592
| 4,147
|
kotlinpoet-ktx
|
Apache License 2.0
|
plugins/kapt3/kapt3-base/src/org/jetbrains/kotlin/kapt3/base/javac/KaptJavaFileManager.kt
|
arrow-kt
| 109,678,056
| true
| null |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.kapt3.base.javac
import com.sun.tools.javac.file.JavacFileManager
import com.sun.tools.javac.main.Option
import com.sun.tools.javac.util.Context
import javax.tools.JavaFileManager
class KaptJavaFileManager(context: Context) : JavacFileManager(context, true, null) {
fun handleOptionJavac9(option: Option, value: String) {
val handleOptionMethod = JavacFileManager::class.java
.getMethod("handleOption", Option::class.java, String::class.java)
handleOptionMethod.invoke(this, option, value)
}
companion object {
internal fun preRegister(context: Context) {
context.put(JavaFileManager::class.java, Context.Factory<JavaFileManager> { KaptJavaFileManager(it) })
}
}
}
| 12
|
Kotlin
|
1
| 43
|
d2a24985b602e5f708e199aa58ece652a4b0ea48
| 933
|
kotlin
|
Apache License 2.0
|
cardview/src/main/java/com/harreke/easyapp/skin/cardview/SkinCardViewStainerWrapper.kt
|
Harreke
| 547,880,574
| false
|
{"Kotlin": 99993}
|
package com.harreke.easyapp.skin.cardview
import android.util.AttributeSet
import android.view.View
import androidx.cardview.widget.CardView
import com.harreke.easyapp.skin.core.ISkinStainerWrapper
import com.harreke.easyapp.skin.cardview.stainer.SkinCardViewStainer
class SkinCardViewStainerWrapper : ISkinStainerWrapper {
override fun wrapView(view: View, attrs: AttributeSet) = when (view) {
is CardView -> SkinCardViewStainer(view, attrs)
else -> null
}
}
| 0
|
Kotlin
|
0
| 0
|
248e6b78a0bb8871021de63ee8da4572ee66c13f
| 485
|
EasyApp-Skin
|
MIT License
|
idea/testData/inspectionsLocal/redundantLambdaArrow/simple.kt
|
JakeWharton
| 99,388,807
| false
| null |
fun foo(f: () -> Unit) {}
fun bar() {
foo { <caret>-> }
}
| 0
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 62
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/pokedex/data/model/TypeX.kt
|
anubhav-auth
| 822,822,462
| false
|
{"Kotlin": 135857}
|
package com.example.pokedex.data.model
data class TypeX(
val name: String,
val url: String
)
| 0
|
Kotlin
|
0
| 0
|
5d7db709c2ebdaa0968704fc16264ccbf290be64
| 101
|
PokeDex
|
MIT License
|
app/src/main/java/com/realitix/nectar/database/entity/Receipe.kt
|
Nectar-Project
| 247,032,480
| false
| null |
package com.realitix.nectar.database.entity
import android.util.Log
import androidx.room.*
import com.realitix.nectar.repository.ReceipeStepRepository
import com.realitix.nectar.util.NectarUtil
import kotlinx.coroutines.runBlocking
// Receipe without steps to prevent cycle in ReceipeStepReceipe
class Receipe(uuid: String, nameUuid: String, stars: Int):
ReceipeRaw(uuid, nameUuid, stars) {
@Relation(parentColumn = "nameUuid", entityColumn = "uuid", entity = StringKeyRaw::class)
lateinit var name: StringKey
@Relation(parentColumn = "uuid", entityColumn = "receipeUuid", entity = ReceipeTagRaw::class)
lateinit var tags: List<ReceipeTag>
@Relation(parentColumn = "uuid", entityColumn = "receipeUuid", entity = ReceipeUtensilRaw::class)
lateinit var utensils: List<ReceipeUtensil>
@Relation(parentColumn = "uuid", entityColumn = "receipeUuid", entity = ReceipeImageRaw::class)
lateinit var images: List<ReceipeImage>
@Relation(parentColumn = "uuid", entityColumn = "receipeUuid", entity = ReceipeMeasureRaw::class)
lateinit var measures: List<ReceipeMeasure>
// Bug with room preventing nested relation
fun getSteps(rReceipeStep: ReceipeStepRepository): List<ReceipeStep> {
var res = listOf<ReceipeStep>()
runBlocking {
res = rReceipeStep.listByReceipeSuspend(uuid)
}
return res
}
fun getStepsOrdered(rReceipeStep: ReceipeStepRepository): List<ReceipeStep> =
recursiveAddOrdered(rReceipeStep, getSteps(rReceipeStep).toMutableList(), null)
private fun recursiveAddOrdered(
rReceipeStep: ReceipeStepRepository,
stepsToTreat: MutableList<ReceipeStep>,
currentStep: ReceipeStep?): List<ReceipeStep> {
val outSteps = mutableListOf<ReceipeStep>()
val depSteps = stepsToTreat.filter { it.getPreviousStep(rReceipeStep) == currentStep }
stepsToTreat.removeAll(depSteps)
for(s in depSteps) {
outSteps.add(s)
outSteps.addAll(recursiveAddOrdered(rReceipeStep, stepsToTreat, s))
}
return outSteps
}
// Return all steps and steps in receipe
// The previous step is set to the dependancy step
private fun getStepsRecursive(rReceipeStep: ReceipeStepRepository, receipe: Receipe): List<ReceipeStep> {
val steps = receipe.getSteps(rReceipeStep).toMutableList()
for(step in steps) {
for(r in step.receipes) {
// All dependancy steps take this step as dependancy
val dependancySteps = getStepsRecursive(rReceipeStep, r.receipe)
for(ds in dependancySteps) {
if(ds.previousStepUuid == null) {
ds.previousStepUuid = step.uuid
}
}
steps.addAll(dependancySteps)
}
}
return steps
}
fun getStepsWithTimestamp(rReceipeStep: ReceipeStepRepository, startTimestamp: Long): List<Pair<Long, ReceipeStep>> {
val steps = getStepsRecursive(rReceipeStep, this)
val stepsTotalDuration = mutableListOf<Pair<Int, ReceipeStep>>()
for(step in steps) {
val duration = getAccumulateStepDuration(steps, step)
stepsTotalDuration.add(duration to step)
}
val stepsWithTimestamp = mutableListOf<Pair<Long, ReceipeStep>>()
for(s in stepsTotalDuration) {
stepsWithTimestamp.add(startTimestamp - s.first*60 to s.second)
}
stepsWithTimestamp.sortBy { it.first }
return stepsWithTimestamp
}
// Return the duration of the step with accumulation of the next step duration
private fun getAccumulateStepDuration(allSteps: List<ReceipeStep>, currentStep: ReceipeStep): Int {
// Get all depending steps
val depSteps = allSteps.filter { it.uuid == currentStep.previousStepUuid }
val depStep = if(depSteps.isNotEmpty()) depSteps[0] else null
val depDuration = if(depStep == null) 0 else getAccumulateStepDuration(allSteps, depStep)
return currentStep.duration + depDuration
}
fun getName(): String = name.getValue()
fun listAliments(receipeStepRepository: ReceipeStepRepository, proportion: Float = 1f): List<Pair<AlimentState, Int>> {
val out = mutableListOf<Pair<AlimentState, Int>>()
for(step in getSteps(receipeStepRepository)) {
for(aliment in step.aliments) {
NectarUtil.addAlimentStateToList(out, aliment.alimentState, (aliment.weight*proportion).toInt())
}
for(receipe in step.receipes) {
val p = receipe.proportion * proportion
NectarUtil.addAlimentStateListToList(out, receipe.receipe.listAliments(receipeStepRepository, p))
}
}
return out
}
}
@Entity(
foreignKeys = [ForeignKey(
entity = StringKeyRaw::class,
parentColumns = ["uuid"],
childColumns = ["nameUuid"],
onDelete = ForeignKey.CASCADE
)],
indices = [
Index(value=["nameUuid"])
]
)
open class ReceipeRaw(
@PrimaryKey
var uuid: String,
var nameUuid: String,
var stars: Int
): UuidInterface {
override fun getEntityUuid() = uuid
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ReceipeRaw
if (uuid != other.uuid) return false
if (nameUuid != other.nameUuid) return false
if (stars != other.stars) return false
return true
}
override fun hashCode(): Int {
var result = uuid.hashCode()
result = 31 * result + nameUuid.hashCode()
result = 31 * result + stars
return result
}
}
| 2
|
Kotlin
|
0
| 0
|
f220b9007fc5d3faf1d3fd9a842154de2a7d0cdf
| 5,818
|
nectar-android
|
Apache License 2.0
|
src/ko/newtoki/src/eu/kanade/tachiyomi/extension/ko/newtoki/NewToki.kt
|
komikku-app
| 720,497,299
| false
|
{"Kotlin": 6775539, "JavaScript": 2160}
|
package eu.kanade.tachiyomi.extension.ko.newtoki
import android.content.SharedPreferences
import android.util.Log
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.network.interceptor.rateLimit
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Response
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.TimeUnit
/**
* NewToki Source
*
* Based on https://github.com/gnuboard/gnuboard5
**/
abstract class NewToki(
override val name: String,
private val boardName: String,
private val preferences: SharedPreferences,
) : ParsedHttpSource(), ConfigurableSource {
override val lang: String = "ko"
override val supportsLatest = true
override val client by lazy { buildClient(withRateLimit = false) }
private val rateLimitedClient by lazy { buildClient(withRateLimit = true) }
private fun buildClient(withRateLimit: Boolean) =
network.cloudflareClient.newBuilder()
.apply { if (withRateLimit) rateLimit(1, preferences.rateLimitPeriod.toLong()) }
.addInterceptor(DomainInterceptor) // not rate-limited
.connectTimeout(10, TimeUnit.SECONDS) // fail fast
.build()
override fun headersBuilder() = super.headersBuilder()
.add("Referer", "$baseUrl/")
override fun popularMangaSelector() = "div#webtoon-list > ul > li"
override fun popularMangaFromElement(element: Element): SManga {
val linkElement = element.getElementsByTag("a").first()!!
val manga = SManga.create()
manga.url = getUrlPath(linkElement.attr("href"))
manga.title = element.select("span.title").first()!!.ownText()
manga.thumbnail_url = linkElement.getElementsByTag("img").attr("src")
return manga
}
override fun popularMangaNextPageSelector() = "ul.pagination > li:last-child:not(.disabled)"
// Do not add page parameter if page is 1 to prevent tracking.
override fun popularMangaRequest(page: Int) = GET("$baseUrl/$boardName" + if (page > 1) "/p$page" else "", headers)
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return if (query.startsWith(PREFIX_ID_SEARCH)) {
val realQuery = query.removePrefix(PREFIX_ID_SEARCH)
val urlPath = "/$boardName/$realQuery"
rateLimitedClient.newCall(GET("$baseUrl$urlPath", headers))
.asObservableSuccess()
.map { response ->
// the id is matches any of 'post' from their CMS board.
// Includes Manga Details Page, Chapters, Comments, and etcs...
actualMangaParseById(urlPath, response)
}
} else {
super.fetchSearchManga(page, query, filters)
}
}
private fun actualMangaParseById(urlPath: String, response: Response): MangasPage {
val document = response.asJsoup()
// Only exists on detail page.
val firstChapterButton = document.select("tr > th > button.btn-blue").first()
// only exists on chapter with proper manga detail page.
val fullListButton = document.select(".comic-navbar .toon-nav a").last()
val list: List<SManga> = when {
firstChapterButton?.text()?.contains("첫회보기") == true -> { // Check this page is detail page
val details = mangaDetailsParse(document)
details.url = urlPath
listOf(details)
}
fullListButton?.text()?.contains("전체목록") == true -> { // Check this page is chapter page
val url = fullListButton.attr("abs:href")
val details = mangaDetailsParse(rateLimitedClient.newCall(GET(url, headers)).execute())
details.url = getUrlPath(url)
listOf(details)
}
else -> emptyList()
}
return MangasPage(list, false)
}
override fun mangaDetailsParse(document: Document): SManga {
val info = document.select("div.view-title > .view-content").first()!!
val title = document.select("div.view-content > span > b").text()
val thumbnail = document.select("div.row div.view-img > img").attr("src")
val descriptionElement = info.select("div.row div.view-content:not([style])")
val description = descriptionElement.map {
it.text().trim()
}
val prefix = if (isCleanPath(document.location())) "" else needMigration()
val manga = SManga.create()
manga.title = title
manga.description = description.joinToString("\n", prefix = prefix)
manga.thumbnail_url = thumbnail
descriptionElement.forEach {
val text = it.text()
when {
"작가" in text -> manga.author = it.getElementsByTag("a").text()
"분류" in text -> {
val genres = mutableListOf<String>()
it.getElementsByTag("a").forEach { item ->
genres.add(item.text())
}
manga.genre = genres.joinToString(", ")
}
"발행구분" in text -> manga.status = parseStatus(it.getElementsByTag("a").text())
}
}
return manga
}
private fun parseStatus(status: String) = when (status.trim()) {
"주간", "격주", "월간", "격월/비정기", "단행본" -> SManga.ONGOING
"단편", "완결" -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "div.serial-list > ul.list-body > li.list-item"
override fun chapterFromElement(element: Element): SChapter {
val linkElement = element.select(".wr-subject > a.item-subject").last()!!
val rawName = linkElement.ownText().trim()
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(linkElement.attr("href"))
chapter.chapter_number = parseChapterNumber(rawName)
chapter.name = rawName
chapter.date_upload = parseChapterDate(element.select(".wr-date").last()!!.text().trim())
return chapter
}
private fun parseChapterNumber(name: String): Float {
try {
if (name.contains("[단편]")) return 1f
// `특별` means `Special`, so It can be buggy. so pad `편`(Chapter) to prevent false return
if (name.contains("번외") || name.contains("특별편")) return -2f
val regex = chapterNumberRegex
val (ch_primal, ch_second) = regex.find(name)!!.destructured
return (ch_primal + if (ch_second.isBlank()) "" else ".$ch_second").toFloatOrNull()
?: -1f
} catch (e: Exception) {
Log.e("NewToki", "failed to parse chapter number '$name'", e)
return -1f
}
}
private fun mangaDetailsParseWithTitleCheck(manga: SManga, document: Document) =
mangaDetailsParse(document).apply {
// TODO: don't throw when there is download folder rename feature
if (manga.description.isNullOrEmpty() && title.removeSuffix("…") !in manga.title) {
throw Exception(titleNotMatch(title))
}
}
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return rateLimitedClient.newCall(mangaDetailsRequest(manga))
.asObservableSuccess()
.map { response ->
val document = response.asJsoup()
mangaDetailsParseWithTitleCheck(manga, document).apply { initialized = true }
}
}
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
return rateLimitedClient.newCall(chapterListRequest(manga))
.asObservableSuccess()
.map { response ->
val document = response.asJsoup()
val title = mangaDetailsParseWithTitleCheck(manga, document).title
document.select(chapterListSelector()).map {
chapterFromElement(it).apply {
name = name.removePrefix(title).trimStart()
}
}
}
}
// not thread-safe
private val dateFormat by lazy { SimpleDateFormat("yyyy.MM.dd", Locale.ENGLISH) }
private fun parseChapterDate(date: String): Long {
return try {
if (date.contains(":")) {
val calendar = Calendar.getInstance()
val splitDate = date.split(":")
val hours = splitDate.first().toInt()
val minutes = splitDate.last().toInt()
val calendarHours = calendar.get(Calendar.HOUR)
val calendarMinutes = calendar.get(Calendar.MINUTE)
if (calendarHours >= hours && calendarMinutes > minutes) {
calendar.add(Calendar.DATE, -1)
}
calendar.timeInMillis
} else {
dateFormat.parse(date)?.time ?: 0
}
} catch (e: Exception) {
Log.e("NewToki", "failed to parse chapter date '$date'", e)
0
}
}
override fun pageListParse(document: Document): List<Page> {
val script = document.select("script:containsData(html_data)").firstOrNull()?.data()
?: throw Exception("data script not found")
val loadScript = document.select("script:containsData(data_attribute)").firstOrNull()?.data()
?: throw Exception("load script not found")
val dataAttr = "abs:data-" + loadScript.substringAfter("data_attribute: '").substringBefore("',")
return htmlDataRegex.findAll(script).map { it.groupValues[1] }
.asIterable()
.flatMap { it.split(".") }
.joinToString("") { it.toIntOrNull(16)?.toChar()?.toString() ?: "" }
.let { Jsoup.parse(it) }
.select("img[src=/img/loading-image.gif], .view-img > img[itemprop]")
.mapIndexed { i, img -> Page(i, "", if (img.hasAttr(dataAttr)) img.attr(dataAttr) else img.attr("abs:content")) }
}
override fun latestUpdatesSelector() = ".media.post-list"
override fun latestUpdatesFromElement(element: Element) = ManaToki.latestUpdatesElementParse(element)
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/page/update?hid=update&page=$page", headers)
override fun latestUpdatesNextPageSelector() = ".pg_end"
// We are able to get the image URL directly from the page list
override fun imageUrlParse(document: Document) = throw UnsupportedOperationException()
override fun setupPreferenceScreen(screen: androidx.preference.PreferenceScreen) {
getPreferencesInternal(screen.context).map(screen::addPreference)
}
protected fun getUrlPath(orig: String): String {
val url = baseUrl.toHttpUrl().resolve(orig) ?: return orig
val pathSegments = url.pathSegments
return "/${pathSegments[0]}/${pathSegments[1]}"
}
private fun isCleanPath(absUrl: String): Boolean {
val url = absUrl.toHttpUrl()
return url.pathSegments.size == 2 && url.querySize == 0 && url.fragment == null
}
companion object {
const val PREFIX_ID_SEARCH = "id:"
private val chapterNumberRegex by lazy { Regex("([0-9]+)(?:[-.]([0-9]+))?화") }
private val htmlDataRegex by lazy { Regex("""html_data\+='([^']+)'""") }
}
}
| 9
|
Kotlin
|
99
| 97
|
7fc1d11ee314376fe0daa87755a7590a03bc11c0
| 12,220
|
komikku-extensions
|
Apache License 2.0
|
compiler/testData/codegen/boxAgainstJava/enum/simpleJavaEnumWithStaticImport.kt
|
JakeWharton
| 99,388,807
| true
| null |
// FILE: test/En.java
package test;
public enum En {
A;
}
// FILE: 1.kt
import test.En.A
fun box() =
if (A.toString() == "A") "OK"
else "fail"
| 0
|
Kotlin
|
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 160
|
kotlin
|
Apache License 2.0
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListData.kt
|
androidports
| 115,100,208
| true
|
{"Java": 168074327, "Python": 25851822, "Kotlin": 6237300, "Groovy": 3448233, "HTML": 1962706, "C": 214338, "C++": 180382, "CSS": 172743, "JavaScript": 148969, "Lex": 148787, "XSLT": 113040, "Jupyter Notebook": 93222, "Shell": 60321, "NSIS": 57796, "Batchfile": 51257, "Roff": 37534, "Objective-C": 27309, "TeX": 25473, "AMPL": 20665, "TypeScript": 9469, "J": 5050, "PHP": 2699, "Makefile": 2352, "Thrift": 1846, "CoffeeScript": 1759, "CMake": 1675, "Ruby": 1217, "Perl": 962, "Smalltalk": 906, "C#": 696, "AspectJ": 182, "Visual Basic": 77, "HLSL": 57, "Erlang": 10}
|
// Copyright 2000-2017 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.util.text.StringUtil
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.xmlb.XmlSerializer
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Tag
import com.intellij.vcs.log.VcsUser
import com.intellij.vcs.log.impl.VcsUserImpl
import org.jdom.Element
import java.util.*
import kotlin.collections.ArrayList
private const val CHANGELIST_DATA: String = "changelist_data"
open class ChangeListData @JvmOverloads constructor(val author: VcsUser? = null, val date: Date? = null) {
private constructor(state: State) : this(VcsUserImpl(state.name ?: "", state.email ?: ""), state.date)
private var myState: State = State(author?.name, author?.email, date)
fun getPresentation(): String {
val lines = ArrayList<String>()
author?.let { lines.add("Author: $author") }
date?.let { lines.add("Date: ${DateFormatUtil.formatDateTime(date)}") }
return StringUtil.join(lines, "\n")
}
@Tag(CHANGELIST_DATA)
class State @JvmOverloads constructor(@Attribute("name") var name: String? = null,
@Attribute("email") var email: String? = null,
@Attribute("date") var date: Date? = null)
companion object {
@JvmStatic
fun writeExternal(listData: ChangeListData): Element = XmlSerializer.serialize(listData.myState)
@JvmStatic
fun readExternal(parent: Element): ChangeListData? {
val element = parent.getChild(CHANGELIST_DATA)
return if (element != null) ChangeListData(XmlSerializer.deserialize(element, State::class.java)) else null
}
}
}
| 6
|
Java
|
4829
| 4
|
6e4f7135c5843ed93c15a9782f29e4400df8b068
| 2,155
|
intellij-community
|
Apache License 2.0
|
plugins/parcelize/parcelize-compiler/testData/box/customParcelable.kt
|
JetBrains
| 3,432,266
| false
| null |
// IGNORE_BACKEND: JVM
// See KT-38105
// Throws IllegalAccessError, since the code tries to access the private companion field directly from the generated User$Creator class.
// WITH_RUNTIME
@file:JvmName("TestKt")
package test
import kotlinx.parcelize.*
import android.os.Parcel
import android.os.Parcelable
data class User(val name: String, val age: Int)
@Parcelize
data class UserParcelable(val user: User) : Parcelable {
private companion object : Parceler<UserParcelable> {
override fun UserParcelable.write(parcel: Parcel, flags: Int) {
parcel.writeString(user.name)
}
override fun create(parcel: Parcel) = UserParcelable(User(parcel.readString(), 0))
}
}
fun box() = parcelTest { parcel ->
val userParcelable = UserParcelable(User("John", 20))
userParcelable.writeToParcel(parcel, 0)
val bytes = parcel.marshall()
parcel.unmarshall(bytes, 0, bytes.size)
parcel.setDataPosition(0)
val userParcelable2 = readFromParcel<UserParcelable>(parcel)
assert(userParcelable.user.name == userParcelable2.user.name)
assert(userParcelable2.user.age == 0)
}
| 182
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,136
|
kotlin
|
Apache License 2.0
|
spi/src/main/kotlin/com/atlassian/migration/datacenter/spi/fs/reporting/FileSystemMigrationReport.kt
|
moveworkforward
| 321,496,207
| false
| null |
/*
* Copyright 2020 Atlassian
*
* 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.atlassian.migration.datacenter.spi.fs.reporting
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import java.time.Duration
@JsonSerialize(`as` = FileSystemMigrationReport::class)
interface FileSystemMigrationReport : FileSystemMigrationErrorReport, FileSystemMigrationProgress {
var status: FilesystemMigrationStatus
val elapsedTime: Duration
/**
* Text representation of filesystem migration report. This can be used to consume the report in the logs.
*
* @return human readable representation of the migration report
*/
override fun toString(): String
}
| 1
| null |
1
| 1
|
3f7ce88e618750c0c7f57bd5ce3c4fbb4563a467
| 1,213
|
dc-migration-assistant
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/MessageArrowUp.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.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.Outline.MessageArrowUp: ImageVector
get() {
if (_messageArrowUp != null) {
return _messageArrowUp!!
}
_messageArrowUp = Builder(name = "MessageArrowUp", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(20.0f, 0.0f)
lineTo(4.0f, 0.0f)
curveTo(1.794f, 0.0f, 0.0f, 1.794f, 0.0f, 4.0f)
verticalLineToRelative(12.0f)
curveToRelative(0.0f, 2.206f, 1.794f, 4.0f, 4.0f, 4.0f)
horizontalLineToRelative(2.923f)
lineToRelative(3.748f, 3.156f)
curveToRelative(0.382f, 0.34f, 0.862f, 0.509f, 1.338f, 0.509f)
curveToRelative(0.467f, 0.0f, 0.931f, -0.163f, 1.292f, -0.485f)
lineToRelative(3.847f, -3.18f)
horizontalLineToRelative(2.852f)
curveToRelative(2.206f, 0.0f, 4.0f, -1.794f, 4.0f, -4.0f)
lineTo(24.0f, 4.0f)
curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f)
close()
moveTo(22.0f, 16.0f)
curveToRelative(0.0f, 1.103f, -0.897f, 2.0f, -2.0f, 2.0f)
horizontalLineToRelative(-3.211f)
curveToRelative(-0.232f, 0.0f, -0.458f, 0.081f, -0.637f, 0.229f)
lineToRelative(-4.172f, 3.415f)
lineToRelative(-4.047f, -3.409f)
curveToRelative(-0.18f, -0.152f, -0.408f, -0.235f, -0.644f, -0.235f)
horizontalLineToRelative(-3.289f)
curveToRelative(-1.103f, 0.0f, -2.0f, -0.897f, -2.0f, -2.0f)
lineTo(2.0f, 4.0f)
curveToRelative(0.0f, -1.103f, 0.897f, -2.0f, 2.0f, -2.0f)
horizontalLineToRelative(16.0f)
curveToRelative(1.103f, 0.0f, 2.0f, 0.897f, 2.0f, 2.0f)
verticalLineToRelative(12.0f)
close()
moveTo(16.707f, 8.412f)
curveToRelative(0.391f, 0.391f, 0.391f, 1.023f, 0.0f, 1.414f)
reflectiveCurveToRelative(-1.023f, 0.391f, -1.414f, 0.0f)
lineToRelative(-2.293f, -2.293f)
verticalLineToRelative(7.467f)
curveToRelative(0.0f, 0.553f, -0.448f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.447f, -1.0f, -1.0f)
verticalLineToRelative(-7.367f)
lineToRelative(-2.293f, 2.293f)
curveToRelative(-0.195f, 0.195f, -0.451f, 0.293f, -0.707f, 0.293f)
reflectiveCurveToRelative(-0.512f, -0.098f, -0.707f, -0.293f)
curveToRelative(-0.391f, -0.391f, -0.391f, -1.023f, 0.0f, -1.414f)
lineToRelative(2.636f, -2.637f)
curveToRelative(1.17f, -1.17f, 3.072f, -1.17f, 4.242f, 0.0f)
lineToRelative(2.536f, 2.536f)
close()
}
}
.build()
return _messageArrowUp!!
}
private var _messageArrowUp: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,896
|
icons
|
MIT License
|
app/src/main/java/ch/abwesend/privatecontacts/infrastructure/repository/ToastRepository.kt
|
fgubler
| 462,182,037
| false
|
{"Kotlin": 1159351, "Java": 369326}
|
/*
* Private Contacts
* Copyright (c) 2022.
* Florian Gubler
*/
package ch.abwesend.privatecontacts.infrastructure.repository
import android.content.Context
import android.os.Looper
import android.widget.Toast
import ch.abwesend.privatecontacts.domain.lib.logging.logger
import ch.abwesend.privatecontacts.domain.util.applicationScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class ToastRepository {
/**
* Allows showing a toast from a background service.
*/
fun showToastNotification(
context: Context,
message: String,
length: Int = Toast.LENGTH_LONG,
) {
applicationScope.launch(Dispatchers.Main.immediate) {
try {
Toast.makeText(context.applicationContext, message, length).show()
} catch (t: Throwable) {
logger.warning("Failed to show toast message for incoming call. Try with java-style.", t)
showToastNotificationJavaStyle(context, message, length)
}
}
}
/**
* Same as [showToastNotification] but without kotlin and coroutines
*/
private fun showToastNotificationJavaStyle(
context: Context,
message: String,
length: Int = Toast.LENGTH_LONG,
) {
Thread {
try {
Looper.prepare()
Toast.makeText(context.applicationContext, message, length).show()
Looper.loop()
} catch (t: Throwable) {
logger.warning("Failed to show toast message for incoming call", t)
}
}.start()
}
}
| 1
|
Kotlin
|
1
| 9
|
52f679a7803883e6c2530e0fb642049631201656
| 1,630
|
PrivateContacts
|
Apache License 2.0
|
inspektifySample/composeApp/src/commonMain/kotlin/sp/bvantur/inspektify/sample/domain/model/User.kt
|
BVantur
| 844,048,160
| false
|
{"Kotlin": 169455, "Swift": 1303}
|
package sp.bvantur.inspektify.sample.domain.model
data class User(val firstName: String?, val lastName: String? = null, val email: String? = null)
| 2
|
Kotlin
|
4
| 88
|
f824a3fe4eb81d35400dab76ce39e14dca84edf0
| 148
|
inspektify
|
MIT License
|
lib/src/main/java/at/naske/microdo/lib/parking/ParkingItemReturnListener.kt
|
lukasnaske
| 234,505,192
| false
| null |
package at.naske.microdo.lib.parking
import android.view.View
import at.naske.microdo.lib.ItemDropFailedHandler
import at.naske.microdo.lib.MicroDoDragEvent
/**
* If a view was not dropped on any other view it is readded to the ParkingLayout if it originated from
* there. This readdition is handled by the ParkingItemReturnListener
*/
class ParkingItemReturnListener : ItemDropFailedHandler {
@Synchronized
override fun onFailedDrop(view: View, microDoDragEvent: MicroDoDragEvent): Boolean {
microDoDragEvent.mView.visibility = View.VISIBLE
return true
}
}
| 0
|
Kotlin
|
0
| 1
|
2800b3870220e34c6f50cbc094b0a7fc9c88eeea
| 592
|
microdo
|
MIT License
|
app/src/main/java/com/rootstrap/android/network/services/AuthenticationInterceptor.kt
|
rootstrap
| 184,807,903
| false
| null |
package com.rootstrap.android.network.services
import com.rootstrap.android.util.Prefs
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import javax.inject.Inject
class AuthenticationInterceptor @Inject constructor(private val prefs: Prefs) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val builder = chain.request().newBuilder()
if (hasHeaders()) {
builder
.addHeader(prefs.ACCESS_TOKEN, prefs.accessToken)
.addHeader(prefs.CLIENT, prefs.client)
.addHeader(prefs.UID, prefs.uid)
}
return chain.proceed(builder.build())
}
private fun hasHeaders(): Boolean {
return prefs.accessToken != "" &&
prefs.client != "" &&
prefs.uid != ""
}
}
| 13
|
Kotlin
|
5
| 35
|
8b06b7f8c8a646cb029103781cf6e24e765b3746
| 880
|
android-base
|
MIT License
|
app/src/main/java/com/yvkalume/gifapp/ui/screen/favorite/FavoriteScreen.kt
|
yveskalume
| 604,632,872
| false
| null |
package com.yvkalume.gifapp.ui.screen.favorite
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import com.airbnb.mvrx.Async
import com.airbnb.mvrx.Fail
import com.airbnb.mvrx.Loading
import com.airbnb.mvrx.Success
import com.airbnb.mvrx.Uninitialized
import com.airbnb.mvrx.compose.collectAsState
import com.airbnb.mvrx.compose.mavericksViewModel
import com.yvkalume.gifapp.domain.entity.Gif
import com.yvkalume.gifapp.ui.components.EmptyView
import com.yvkalume.gifapp.ui.components.GifListView
import com.yvkalume.gifapp.ui.components.LoadingView
import com.yvkalume.gifapp.ui.screen.favorite.logic.FavoriteUiState
import com.yvkalume.gifapp.ui.screen.favorite.logic.FavoriteViewModel
@Composable
fun FavoriteRoute(homeViewModel: FavoriteViewModel = mavericksViewModel()) {
val gifsState by homeViewModel.collectAsState(FavoriteUiState::gifs)
FavoriteScreen(gifsState = gifsState, onFavoriteClick = { homeViewModel.removeFavorite(it) })
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FavoriteScreen(
gifsState: Async<List<Gif>>,
onFavoriteClick: (Gif) -> Unit
) {
Box(contentAlignment = Alignment.Center) {
when (gifsState) {
is Fail -> {
EmptyView()
}
is Loading -> {
LoadingView()
}
is Success -> {
val gifs = gifsState.invoke()
if (gifs.isNotEmpty()) {
GifListView(
gifs = gifs,
onFavoriteClick = onFavoriteClick
)
} else {
EmptyView()
}
}
Uninitialized -> {}
}
}
}
| 0
|
Kotlin
|
0
| 11
|
5fe6fe4b023d09277e3721b76e62193a97e7f8fb
| 1,894
|
gif-app
|
Apache License 2.0
|
app/src/main/java/com/zhongya/havefun/viewmodel/project/ProjectChildViewModel.kt
|
zhongya666
| 392,348,712
| false
| null |
package com.zhongya.havefun.viewmodel.project
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.zhongya.havefun.app.net.repo.PersonalRepo
import com.zhongya666.library.base.viewmodel.BaseViewModel
import com.zhongya666.project.bean.ProjectContent
import com.zhongya.havefun.app.net.repo.ProjectRepository
import com.zhongya666.library.network.StateLiveData
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
class ProjectChildViewModel(
val repo : PersonalRepo,
val repo_project : ProjectRepository,
) : BaseViewModel() {
val collectLiveData = StateLiveData<Any?>()
val unCollectLiveData = StateLiveData<Any?>()
fun loadProjectList(id: Int) : Flow<PagingData<ProjectContent>> =
repo_project.loadProjectList(id).cachedIn(viewModelScope)
fun collect(
id: Int,
) {
viewModelScope.launch {
repo.collect(
id,
collectLiveData
)
}
}
fun unCollect(
id: Int,
) {
viewModelScope.launch {
repo.unCollect(
id,
unCollectLiveData
)
}
}
}
| 1
|
Kotlin
|
1
| 9
|
a3cbba971479fe840b51870b42244af646deda62
| 1,234
|
WanApk
|
Apache License 2.0
|
helm-publish-plugin/src/main/kotlin/com/citi/gradle/plugins/helm/publishing/HelmPublishPlugin.kt
|
2lambda123
| 748,592,455
| false
|
{"Kotlin": 549953, "Batchfile": 87, "Shell": 80}
|
package com.citi.gradle.plugins.helm.publishing
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.internal.HasConvention
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.tasks.TaskDependency
import org.gradle.internal.reflect.Instantiator
import com.citi.gradle.plugins.helm.HELM_GROUP
import com.citi.gradle.plugins.helm.HelmPlugin
import com.citi.gradle.plugins.helm.command.HelmCommandsPlugin
import com.citi.gradle.plugins.helm.dsl.HelmChart
import com.citi.gradle.plugins.helm.dsl.internal.charts
import com.citi.gradle.plugins.helm.dsl.internal.helm
import com.citi.gradle.plugins.helm.publishing.dsl.HelmChartPublishConvention
import com.citi.gradle.plugins.helm.publishing.dsl.HelmPublishingExtension
import com.citi.gradle.plugins.helm.publishing.dsl.createHelmChartPublishConvention
import com.citi.gradle.plugins.helm.publishing.dsl.createHelmPublishingExtension
import com.citi.gradle.plugins.helm.publishing.dsl.internal.repositories
import com.citi.gradle.plugins.helm.publishing.rules.HelmPublishChartTaskRule
import com.citi.gradle.plugins.helm.publishing.rules.HelmPublishChartToRepositoryTaskRule
import com.citi.gradle.plugins.helm.publishing.rules.publishTaskName
import javax.inject.Inject
/**
* A Gradle plugin that adds publishing capabilities for Helm charts.
*/
class HelmPublishPlugin
@Inject constructor(
private val instantiator: Instantiator
) : Plugin<Project> {
override fun apply(project: Project) {
project.plugins.apply(HelmCommandsPlugin::class.java)
val publishingExtension = createPublishingExtension(project)
project.plugins.withType(HelmPlugin::class.java) {
val charts = project.helm.charts
charts.all { chart ->
addChartPublishConvention(chart, project)
}
project.tasks.run {
val repositories = publishingExtension.repositories
addRule(HelmPublishChartToRepositoryTaskRule(this, charts, repositories))
addRule(HelmPublishChartTaskRule(this, charts, repositories))
}
createPublishAllTask(project, charts)
}
}
/**
* Creates and registers a `helm.publishing` sub-extension with the DSL.
*/
private fun createPublishingExtension(project: Project) =
project.objects.createHelmPublishingExtension(instantiator)
.apply {
(project.helm as ExtensionAware).extensions.add(
HelmPublishingExtension::class.java,
HELM_PUBLISHING_EXTENSION_NAME,
this
)
}
/**
* Adds a convention object to a chart for holding publishing-related properties.
*
* @see HelmChartPublishConvention
*/
private fun addChartPublishConvention(chart: HelmChart, project: Project) {
(chart as HasConvention).convention.plugins[HELM_CHART_PUBLISHING_CONVENTION_NAME] =
project.objects.createHelmChartPublishConvention()
}
/**
* Create a task that publishes all charts in the project to all publishing repositories.
*/
private fun createPublishAllTask(project: Project, charts: NamedDomainObjectContainer<HelmChart>) {
project.tasks.register("helmPublish") { task ->
task.group = HELM_GROUP
task.description = "Publishes all Helm charts."
task.dependsOn(TaskDependency {
charts.map { chart -> project.tasks.getByName(chart.publishTaskName) }
.toSet()
})
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4335722bca8a61d605ee79e548758e2e2ebdba35
| 3,670
|
Citi-gradle-helm-plugin
|
MIT License
|
thelema-teavm/src/test/kotlin/org/ksdfv/thelema/teavm/test/MainTeaVMSingleTest.kt
|
cybernetics
| 365,452,918
| true
|
{"Kotlin": 3356187, "C": 552354, "Java": 355550, "HTML": 6211, "Makefile": 260}
|
/*
* 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 org.ksdfv.thelema.teavm.test
import org.ksdfv.thelema.phys.PHYS
import org.ksdfv.thelema.phys.ode4j.OdePhys
import org.ksdfv.thelema.teavm.TeaVMApp
import org.ksdfv.thelema.test.phys.BoxShapeTest
object MainTeaVMSingleTest {
@JvmStatic
fun main(args: Array<String>) {
TeaVMApp {
PHYS.proxy = OdePhys()
BoxShapeTest().testMain()
}
}
}
| 0
| null |
0
| 0
|
c274a903f0a4d17e5ef14773efa144ee8c8809dd
| 988
|
thelema-engine
|
Apache License 2.0
|
ktlint-core/src/test/kotlin/com/github/shyiko/ktlint/core/ErrorSuppressionTest.kt
|
ubiratansoares
| 168,267,740
| false
| null |
package com.github.shyiko.ktlint.core
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.psi.KtImportDirective
import org.testng.annotations.Test
import java.util.ArrayList
class ErrorSuppressionTest {
@Test
fun testErrorSuppression() {
class NoWildcardImportsRule : Rule("no-wildcard-imports") {
override fun visit(node: ASTNode, autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, corrected: Boolean) -> Unit) {
if (node is LeafPsiElement && node.textMatches("*") &&
PsiTreeUtil.getNonStrictParentOfType(node, KtImportDirective::class.java) != null) {
emit(node.startOffset, "Wildcard import", false)
}
}
}
fun lint(text: String) =
ArrayList<LintError>().apply {
KtLint.lint(text, listOf(RuleSet("standard", NoWildcardImportsRule()))) { e -> add(e) }
}
assertThat(lint(
"""
import a.* // ktlint-disable
import a.* // will trigger an error
""".trimIndent()
)).isEqualTo(listOf(
LintError(2, 10, "no-wildcard-imports", "Wildcard import")
))
assertThat(lint(
"""
import a.* // ktlint-disable no-wildcard-imports
import a.* // will trigger an error
""".trimIndent()
)).isEqualTo(listOf(
LintError(2, 10, "no-wildcard-imports", "Wildcard import")
))
assertThat(lint(
"""
/* ktlint-disable */
import a.*
import a.*
/* ktlint-enable */
import a.* // will trigger an error
""".trimIndent()
)).isEqualTo(listOf(
LintError(5, 10, "no-wildcard-imports", "Wildcard import")
))
assertThat(lint(
"""
/* ktlint-disable no-wildcard-imports */
import a.*
import a.*
/* ktlint-enable no-wildcard-imports */
import a.* // will trigger an error
""".trimIndent()
)).isEqualTo(listOf(
LintError(5, 10, "no-wildcard-imports", "Wildcard import")
))
}
}
| 0
| null |
0
| 2
|
bc92b177e1630dbe53bdff871545ba03dd9a3f9a
| 2,470
|
ktlint
|
MIT License
|
app/src/main/java/ch/lock/mobile/android/deviceinfo/di/FragmentModule.kt
|
lock-user
| 578,061,187
| false
| null |
package ch.lock.mobile.android.deviceinfo.di
import ch.lock.mobile.android.deviceinfo.ui.screen.main.deviceinfo.DeviceInfoFragment
import ch.lock.mobile.android.deviceinfo.ui.screen.main.siminfo.SimInfoFragment
import org.koin.androidx.fragment.dsl.fragment
import org.koin.core.module.Module
import org.koin.dsl.module
object FragmentModule {
val INSTANCE: Module = module {
fragment {
DeviceInfoFragment()
}
fragment {
SimInfoFragment()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c50fe9075a0006fdca5b169b5bbd7dadfabeae01
| 512
|
device-info
|
MIT License
|
core/src/main/kotlin/com/kroegerama/kaiteki/Progress.kt
|
kroegerama
| 133,562,779
| false
|
{"Kotlin": 263903}
|
package com.kroegerama.kaiteki
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.kroegerama.kaiteki.architecture.launchAndCollectWithLifecycleState
import com.kroegerama.kaiteki.databinding.ProgressBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.UUID
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
class Progress : DialogFragment() {
init {
isCancelable = false
}
override fun onCreateDialog(savedInstanceState: Bundle?) = MaterialAlertDialogBuilder(
requireContext(),
requireContext().resolveResourceIdAttribute(
R.attr.progressDialogThemeOverlay
).takeUnless { it == 0 } ?: R.style.ThemeOverlay_Kaiteki_ProgressDialog
).setView(
ProgressBinding.inflate(layoutInflater).apply {
val title = arguments?.getCharSequence(ARG_TITLE, null)
tvTitle.isVisible = title != null
tvTitle.text = title
}.root
).setCancelable(false).create().apply {
window?.attributes?.alpha = .96f
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dismissSignal.filter {
it == tag
}.launchAndCollectWithLifecycleState(this) {
dismissAllowingStateLoss()
}
}
companion object {
const val ARG_TITLE = "arg.progress.modal.title"
val dismissSignal = MutableSharedFlow<String>(replay = 2, extraBufferCapacity = 5)
suspend operator fun <T> invoke(
fragmentManager: FragmentManager,
title: CharSequence? = null,
block: suspend CoroutineScope.() -> T
): T = coroutineScope {
val tag = UUID.randomUUID().toString()
val dlg = Progress().apply {
arguments = bundle {
putCharSequence(ARG_TITLE, title)
}
}
val minDismiss = System.currentTimeMillis() + 300
try {
withContext(Dispatchers.Main.immediate) {
dlg.show(fragmentManager, tag)
}
block()
} catch (e: Exception) {
throw e
} finally {
withContext(NonCancellable) {
val delta = minDismiss - System.currentTimeMillis()
if (delta > 50) {
delay(delta)
}
dismissSignal.emit(tag)
}
}
}
}
}
@DslMarker
annotation class ProgressDSL
class ProgressContext<T> internal constructor(
private val context: CoroutineContext,
private val fragmentManager: FragmentManager,
private val title: CharSequence? = null,
private val checkAllowPost: () -> Boolean,
private val block: suspend CoroutineScope.() -> T
) {
@ProgressDSL
fun start() = startAndThen {}
@ProgressDSL
fun startAndThen(post: (T) -> Unit) {
ProcessLifecycleOwner.get().lifecycleScope.launch(
context
) {
val result = Progress(fragmentManager, title, block)
withContext(Dispatchers.Main.immediate) {
if (checkAllowPost()) {
post(result)
}
}
}
}
}
@ProgressDSL
fun <T> Fragment.prepareLaunchWithProgress(
context: CoroutineContext = EmptyCoroutineContext,
title: CharSequence? = null,
block: suspend CoroutineScope.() -> T
): ProgressContext<T> = ProgressContext(
context = context,
fragmentManager = childFragmentManager,
title = title,
checkAllowPost = {
val viewLifecycleState = viewLifecycleOwnerLiveData.value?.lifecycle?.currentState ?: Lifecycle.State.DESTROYED
viewLifecycleState.isAtLeast(Lifecycle.State.CREATED)
},
block = block
)
@ProgressDSL
fun <T> Fragment.launchWithProgress(
context: CoroutineContext = EmptyCoroutineContext,
title: CharSequence? = null,
block: suspend CoroutineScope.() -> T
) = prepareLaunchWithProgress(context, title, block).start()
@ProgressDSL
fun <T> AppCompatActivity.prepareLaunchWithProgress(
context: CoroutineContext = EmptyCoroutineContext,
title: CharSequence? = null,
block: suspend CoroutineScope.() -> T
): ProgressContext<T> = ProgressContext(
context = context,
fragmentManager = supportFragmentManager,
title = title,
checkAllowPost = { lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED) },
block = block
)
@ProgressDSL
fun <T> AppCompatActivity.launchWithProgress(
context: CoroutineContext = EmptyCoroutineContext,
title: CharSequence? = null,
block: suspend CoroutineScope.() -> T
) = prepareLaunchWithProgress(context, title, block).start()
| 1
|
Kotlin
|
3
| 8
|
2c0e2394779571c91864a097fc199e587baaeee8
| 5,497
|
android-kaiteki
|
Apache License 2.0
|
scalableimageview/src/main/java/com/jiedian/scalableimageview/ScalableImageView.kt
|
hikobe8
| 124,027,713
| false
|
{"Java": 356285, "Kotlin": 111425, "GLSL": 7873, "Groovy": 2252, "Shell": 1666}
|
package com.jiedian.scalableimageview
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import android.widget.OverScroller
import com.jiedian.scaleableimageview.R
/**
* Author : Ray
* Time : 2020/10/11 11:25 PM
* Description :
*/
class ScalableImageView(context: Context?, attrs: AttributeSet?) : View(context, attrs), GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
companion object {
const val BIG_SCALE_FACTOR = 1.5f
}
private val bitmap = BitmapFactory.decodeResource(resources, R.drawable.ray)
private var originalOffsetX = 0f
private var originalOffsetY = 0f
private var bigScale = 0f
private var smallScale = 0f
private val gestureDetector: GestureDetector = GestureDetector(context, this)
private var big = false
var currentScale = 0f
set(value) {
field = value
invalidate()
}
private var scaleAnimator: ObjectAnimator? = null
private var offsetX = 0f
private var offsetY = 0f
private var maxOffsetX = 0f
private var maxOffsetY = 0f
//Scroller匀速滑动, 不能惯性滑动,所以使用OverScroller
private var scroller: OverScroller = OverScroller(context)
private val scaleGestureDetector = ScaleGestureDetector(context, RayOnScaleGestureListener())
init {
gestureDetector.setOnDoubleTapListener(this)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
var result = scaleGestureDetector.onTouchEvent(event)
if (!scaleGestureDetector.isInProgress) {
result = gestureDetector.onTouchEvent(event)
}
return result
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
originalOffsetX = (w - bitmap.width) / 2f
originalOffsetY = (h - bitmap.height) / 2f
val viewRatio = w.toFloat() / h
val imageRatio = bitmap.width.toFloat() / h
if (imageRatio > viewRatio) {
bigScale = width / bitmap.width.toFloat()
smallScale = height / bitmap.height.toFloat()
} else {
bigScale = height / bitmap.height.toFloat()
smallScale = width / bitmap.width.toFloat()
}
bigScale *= BIG_SCALE_FACTOR
scaleAnimator = ObjectAnimator.ofFloat(this, "currentScale", smallScale, bigScale)
currentScale = smallScale
maxOffsetX = (bitmap.width * bigScale - w) / 2f
maxOffsetY = (bitmap.height * bigScale - h) / 2f
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.apply {
val scale = (currentScale - smallScale) / (bigScale - smallScale)
translate(offsetX * scale, offsetY * scale)
scale(currentScale, currentScale, width / 2f, height / 2f)
drawBitmap(bitmap, originalOffsetX, originalOffsetY, null)
}
}
override fun onShowPress(e: MotionEvent?) {
}
override fun onSingleTapUp(e: MotionEvent?): Boolean {
return false
}
override fun onDown(e: MotionEvent?): Boolean {
return true
}
override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
//建立滚动坐标系
scroller.fling(offsetX.toInt(), offsetY.toInt(), velocityX.toInt(), velocityY.toInt(),
(-maxOffsetX).toInt(), maxOffsetX.toInt(), (-maxOffsetY).toInt(), maxOffsetY.toInt(),
50.dp2px().toInt(), 50.dp2px().toInt())
postOnAnimation(this::animationRunner)
return false
}
private fun animationRunner() {
if (scroller.computeScrollOffset()) {
offsetX = scroller.currX.toFloat()
offsetY = scroller.currY.toFloat()
invalidate()
postOnAnimation(this::animationRunner)
}
}
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {
if (big) {
offsetX -= distanceX
offsetY -= distanceY
fixMoveBoundary()
invalidate()
}
return false
}
private fun fixMoveBoundary() {
if (offsetX > maxOffsetX) {
offsetX = maxOffsetX
}
if (offsetX < -maxOffsetX) {
offsetX = -maxOffsetX
}
if (offsetY > maxOffsetY) {
offsetY = maxOffsetY
}
if (offsetY < -maxOffsetY) {
offsetY = -maxOffsetY
}
}
override fun onLongPress(e: MotionEvent?) {
}
override fun onDoubleTap(e: MotionEvent?): Boolean {
if (big) {
scaleAnimator?.reverse()
} else {
offsetX = (e!!.x - width / 2f) * (1 - bigScale / smallScale)
offsetY = (e.y - height / 2f) * (1 - bigScale / smallScale)
fixMoveBoundary()
scaleAnimator?.start()
}
big = big.not()
return false
}
override fun onDoubleTapEvent(e: MotionEvent?): Boolean {
return false
}
override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
return false
}
inner class RayOnScaleGestureListener : ScaleGestureDetector.OnScaleGestureListener {
private var initScale = 0f
override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {
initScale = currentScale
return true
}
override fun onScaleEnd(detector: ScaleGestureDetector?) {
}
override fun onScale(detector: ScaleGestureDetector?): Boolean {
val scaleFactor = detector?.scaleFactor
currentScale = initScale * scaleFactor!!
invalidate()
return false
}
}
}
| 1
|
Java
|
1
| 1
|
06e5c36bc6c2b9684009f537f73ef792ec8b1e0b
| 5,998
|
AndroidReview
|
Apache License 2.0
|
src/main/kotlin/io/github/leandroborgesferreira/dagcommand/domain/Config.kt
|
leandroBorgesFerreira
| 268,720,218
| false
|
{"Kotlin": 41837}
|
package io.github.leandroborgesferreira.dagcommand.domain
import io.github.leandroborgesferreira.dagcommand.enums.OutputType
data class Config(
val defaultBranch: String,
val outputType: OutputType,
val outputPath: String?,
val printModulesInfo: Boolean,
val filterModules: Set<String>,
)
| 6
|
Kotlin
|
11
| 39
|
7698989bf0b94875308e311fd7216dcb707cb968
| 311
|
dag-command
|
Apache License 2.0
|
AreaTriangulo.kt
|
10419
| 357,930,900
| false
|
{"Java": 10042, "Python": 397, "Go": 368, "Scala": 368, "C": 360, "Dart": 336, "Kotlin": 232, "Ruby": 161}
|
fun main(args: Array<String>){
print("ejercicio 01:Area Triangulo")
// ingreso de variables
print("ingrese base:")
val b=Int
print("ingrese altura:")
val h=Int
area=b*h/2
println("el area del triangulo es: $area")
}
| 1
| null |
1
| 1
|
1fe2d5a38625fab11f9c5cc71045d536527404c4
| 232
|
FP-LuisM-2021-G2
|
Apache License 2.0
|
client/android/rubyPark/app/src/main/java/io/rubypark/app/IndexActivity.kt
|
yoshikizh
| 151,821,747
| false
| null |
package io.rubypark.app
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.util.TypedValue
import android.view.Gravity
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import io.rubypark.app.Fragment.ChatsFragment
import io.rubypark.app.helper.adjustWindowSizeForNavigationBar
import io.rubypark.app.helper.render
import io.rubypark.app.helper.setViewPager
import io.rubypark.app.view.BottomNavigationView
import module.LINEAR_LAYOUT_PARAMS_MATCH
import module.dp
import org.json.JSONObject
class IndexActivity : AppCompatActivity() {
lateinit var mLayout: LinearLayout // => 主容器
lateinit var mHeaderLayout: LinearLayout // => Header 主容器
lateinit var mBodyLayout: LinearLayout // => Body 主容器
lateinit var mFooterLayout: LinearLayout // => Footer 主容器
private val mFragmens: ArrayList<Fragment> = ArrayList()
private lateinit var mViewPager: ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initializeViews()
render(mLayout)
}
// 初始化界面所需 UI 组件
private fun initializeViews(){
// 主容器
mLayout = LinearLayout(this)
mLayout.orientation = LinearLayout.VERTICAL
mLayout.layoutParams = LinearLayout.LayoutParams(LINEAR_LAYOUT_PARAMS_MATCH,LINEAR_LAYOUT_PARAMS_MATCH)
initHeaderView()
//initBodyViews()
initFooterViews()
wrapViews()
}
// 包装 Views
private fun wrapViews(){
mLayout.addView(mHeaderLayout)
//mLayout.addView(mBodyLayout)
mLayout.addView(mFooterLayout)
}
// 初始化 Header view
private fun initHeaderView(){
mHeaderLayout = LinearLayout(this)
mHeaderLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 40.dp )
mHeaderLayout.gravity = Gravity.CENTER
val text_title = TextView(this)
text_title.gravity = Gravity.CENTER
text_title.text = resources.getString(R.string.chatlist_title)
text_title.setTextColor(resources.getColor(R.color.theme01_textColorMain))
text_title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,12f)
mHeaderLayout.addView(text_title)
}
// 初始化 Body views
private fun initBodyViews(){
mViewPager = ViewPager(this)
initFragments()
setViewPager(0,mViewPager,mFragmens)
}
// 初始化 Foot View
private fun initFooterViews(){
mFooterLayout = BottomNavigationView(this).init()
}
// 设置 添加 Fragments
private fun initFragments(){
// REMARK:marketInfo 参数为 nil,说明为自选市场。
mFragmens.add(ChatsFragment())
mFragmens.add(ChatsFragment())
mFragmens.add(ChatsFragment())
mFragmens.add(ChatsFragment())
}
}
| 0
|
Kotlin
|
0
| 0
|
4007b0a0fe125295b91a017617c6ce993c931547
| 3,000
|
rubyPark
|
MIT License
|
Android/app/src/main/java/xyz/janficko/apphub/util/SnackbarHelper.kt
|
JanFicko
| 174,291,580
| false
|
{"CSS": 266964, "Kotlin": 72364, "JavaScript": 50798, "TypeScript": 36319, "HTML": 28239, "Swift": 13023, "Ruby": 340}
|
package xyz.janficko.apphub.util
import android.annotation.SuppressLint
import android.view.View
import androidx.annotation.IntegerRes
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar
@SuppressLint("ResourceType")
inline fun View.snack(@StringRes messageRes: Int, length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
snack(resources.getString(messageRes), length, f)
}
@SuppressLint("ResourceType")
fun View.snack(@StringRes messageRes: Int, length: Int = Snackbar.LENGTH_LONG) {
snack(resources.getString(messageRes), length)
}
inline fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, message, length)
snack.f()
snack.show()
}
fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG) {
val snack = Snackbar.make(this, message, length)
snack.show()
}
@SuppressLint("ResourceType")
fun Snackbar.action(@IntegerRes actionRes: Int, color: Int? = null, listener: (View) -> Unit) {
action(view.resources.getString(actionRes), color, listener)
}
fun Snackbar.action(action: String, color: Int? = null, listener: (View) -> Unit) {
setAction(action, listener)
color?.let { setActionTextColor(color) }
}
| 33
|
CSS
|
0
| 0
|
9218b848098b1d7e0e7f839f31ec738bc0454ca9
| 1,278
|
app-hub
|
MIT License
|
ivy-design/src/main/java/com/ivy/design/l2_components/ButtonWithIcon.kt
|
ILIYANGERMANOV
| 442,188,120
| false
| null |
package com.ivy.design.l2_components
import androidx.annotation.DrawableRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.ivy.design.R
import com.ivy.design.l0_system.Transparent
import com.ivy.design.l0_system.UI
import com.ivy.design.l0_system.White
import com.ivy.design.l0_system.style
import com.ivy.design.l1_buildingBlocks.IvyIcon
import com.ivy.design.l1_buildingBlocks.SpacerH
import com.ivy.design.l1_buildingBlocks.data.Background
import com.ivy.design.l1_buildingBlocks.data.background
import com.ivy.design.l1_buildingBlocks.data.clipBackground
import com.ivy.design.utils.IvyComponentPreview
import com.ivy.design.utils.padding
@Composable
fun Button(
modifier: Modifier = Modifier,
text: String,
mode: Mode = Mode.WRAP_CONTENT,
background: Background = Background.Solid(
color = UI.colors.primary,
shape = UI.shapes.rFull,
padding = padding(
horizontal = 24.dp,
vertical = 12.dp
)
),
textStyle: TextStyle = UI.typo.b1.style(
color = White,
textAlign = TextAlign.Center
),
@DrawableRes iconLeft: Int? = null,
@DrawableRes iconRight: Int? = null,
iconTint: Color = White,
iconPadding: Dp = 12.dp,
onClick: () -> Unit
) {
Row(
modifier = modifier
.clipBackground(background)
.clickable(
onClick = onClick
)
.background(background),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
val icon = iconLeft ?: iconRight ?: error("If you don't add icon, use Button()")
if (mode != Mode.WRAP_CONTENT || iconLeft != null) {
IvyIcon(
icon = icon,
tint = if (iconLeft != null) iconTint else Transparent
)
SpacerH(width = iconPadding)
}
Text(
text = text,
style = textStyle
)
if (mode != Mode.WRAP_CONTENT || iconRight != null) {
SpacerH(width = iconPadding)
IvyIcon(
icon = icon,
tint = if (iconRight != null) iconTint else Transparent
)
}
}
}
enum class Mode {
WRAP_CONTENT, FILL_MAX_WIDTH
}
@Preview
@Composable
private fun Preview_IconLeft_Wrap() {
IvyComponentPreview {
Button(
text = "Button",
mode = Mode.WRAP_CONTENT,
iconLeft = R.drawable.ic_android_black_24dp
) {
}
}
}
@Preview
@Composable
private fun Preview_IconRight_Wrap() {
IvyComponentPreview {
Button(
text = "Button",
mode = Mode.WRAP_CONTENT,
iconRight = R.drawable.ic_android_black_24dp
) {
}
}
}
@Preview
@Composable
private fun Preview_IconLeft_FillMax() {
IvyComponentPreview {
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp),
text = "Button",
mode = Mode.FILL_MAX_WIDTH,
iconLeft = R.drawable.ic_android_black_24dp
) {
}
}
}
@Preview
@Composable
private fun Preview_IconRight_FillMax() {
IvyComponentPreview {
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp),
text = "Button",
mode = Mode.FILL_MAX_WIDTH,
iconRight = R.drawable.ic_android_black_24dp
) {
}
}
}
| 0
|
Kotlin
|
1
| 1
|
eab596d90f3580dea527d404a0f453e5b9d2167e
| 4,173
|
ivy-design-android
|
MIT License
|
src/test/kotlin/com/misterpemodder/aoc2022/ConfigurationTests.kt
|
MisterPeModder
| 573,061,300
| false
| null |
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.misterpemodder.aoc2022
import com.misterpemodder.aoc2022.Configuration.Companion.DEFAULT
import org.junit.jupiter.api.Test
import java.io.File
import kotlin.test.assertEquals
internal object ConfigurationTests {
@Test
fun defaultConfig() {
assertEquals(null, DEFAULT.token)
assertEquals(2022, DEFAULT.year)
assertEquals(1, DEFAULT.day)
}
@Test
fun loadNonExisting() {
val path = File.createTempFile("aoc2022_", "_empty").toPath()
assertEquals(DEFAULT, Configuration.load(path))
}
@Test
fun saveAndLoad() {
val path = File.createTempFile("aoc2022_", "_save_and_load").toPath()
val source = Configuration(token = "<PASSWORD>", year = 2042, day = 2)
source.save(path)
val loaded = Configuration.load(path)
assertEquals(source, loaded)
}
}
| 0
|
Kotlin
|
0
| 0
|
af1b258325a7bd036a47b5395c90bbac42bbd337
| 1,461
|
AdventOfCode2022
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/medialive/CfnCloudWatchAlarmTemplateGroupDsl.kt
|
F43nd1r
| 643,016,506
| false
|
{"Kotlin": 5496940}
|
package com.faendir.awscdkkt.generated.services.medialive
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.String
import kotlin.Unit
import software.amazon.awscdk.services.medialive.CfnCloudWatchAlarmTemplateGroup
import software.amazon.awscdk.services.medialive.CfnCloudWatchAlarmTemplateGroupProps
import software.constructs.Construct
@Generated
public fun Construct.cfnCloudWatchAlarmTemplateGroup(
id: String,
props: CfnCloudWatchAlarmTemplateGroupProps,
initializer: @AwsCdkDsl CfnCloudWatchAlarmTemplateGroup.() -> Unit = {},
): CfnCloudWatchAlarmTemplateGroup = CfnCloudWatchAlarmTemplateGroup(this, id,
props).apply(initializer)
@Generated
public fun Construct.buildCfnCloudWatchAlarmTemplateGroup(id: String, initializer: @AwsCdkDsl
CfnCloudWatchAlarmTemplateGroup.Builder.() -> Unit = {}): CfnCloudWatchAlarmTemplateGroup =
CfnCloudWatchAlarmTemplateGroup.Builder.create(this, id).apply(initializer).build()
| 2
|
Kotlin
|
0
| 4
|
33abdfcbe04c49902e5f9db82bd7790c62ae677c
| 978
|
aws-cdk-kt
|
Apache License 2.0
|
app/src/main/java/com/example/appstore/ui/search_filter/SearchFilterFragment.kt
|
rezakardan
| 779,591,568
| false
|
{"Kotlin": 353707, "Java": 16027}
|
package com.example.appstore.ui.search_filter
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.appstore.R
import com.example.appstore.databinding.FragmentSearchFilterBinding
import com.example.appstore.viewmodels.SearchViewModel
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class SearchFilterFragment : BottomSheetDialogFragment() {
lateinit var binding: FragmentSearchFilterBinding
override fun getTheme() = R.style.RemoveBottomSheetBackground
@Inject
lateinit var searchFilterAdapter: SearchFilterAdapter
private val searchFilterViewMode: SearchViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSearchFilterBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.closeImg.setOnClickListener { this@SearchFilterFragment.dismiss()}
searchFilterViewMode.filterSearch()
loadSearchFilter()
}
private fun loadSearchFilter() {
searchFilterViewMode.filterSearchLiveData.observe(viewLifecycleOwner) {
searchFilterAdapter.setData(it)
initFilterSearchRecycler()
}
}
private fun initFilterSearchRecycler(){
binding.filtersList.adapter = searchFilterAdapter
binding.filtersList.layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
searchFilterAdapter.setOnSearchFilter {
this@SearchFilterFragment.dismiss()
searchFilterViewMode.sendSearchFilter(it)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c64368f08faae5b50d158dadb79a8a1a3cd3e140
| 2,235
|
AppStore__Git
|
MIT License
|
modules/wasm-binary/src/commonMain/kotlin/validator/ValidatorException.kt
|
wasmium
| 761,480,110
| false
|
{"Kotlin": 597834, "JavaScript": 203}
|
package org.wasmium.wasm.binary.validator
import org.wasmium.wasm.binary.WasmBinaryException
public class ValidatorException(public override val message: String) : WasmBinaryException()
| 0
|
Kotlin
|
0
| 3
|
9664a7c5c9bf1652ee4e8dab1bbceffebd0869ca
| 188
|
wasmium-wasm-binary
|
Apache License 2.0
|
ui/ui-text/src/test/java/androidx/ui/input/FinishComposingTextEditOpTest.kt
|
FYI-Google
| 258,765,297
| false
| null |
/*
* Copyright 2019 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.compose.ui.text.input
import androidx.compose.ui.text.TextRange
import androidx.test.filters.SmallTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@SmallTest
@RunWith(JUnit4::class)
class FinishComposingTextEditOpTest {
@Test
fun test_set() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
eb.setComposition(1, 4)
FinishComposingTextEditOp().process(eb)
assertEquals("ABCDE", eb.toString())
assertEquals(0, eb.cursor)
assertFalse(eb.hasComposition())
}
@Test
fun test_preserve_selection() {
val eb = EditingBuffer("ABCDE", TextRange(1, 4))
eb.setComposition(2, 5)
FinishComposingTextEditOp().process(eb)
assertEquals("ABCDE", eb.toString())
assertEquals(1, eb.selectionStart)
assertEquals(4, eb.selectionEnd)
assertFalse(eb.hasComposition())
}
}
| 11
| null |
1
| 6
|
b9cd83371e928380610719dfbf97c87c58e80916
| 1,631
|
platform_frameworks_support
|
Apache License 2.0
|
kafkistry-kafka-connector/src/main/kotlin/com/infobip/kafkistry/kafka/ops/ConfigOps.kt
|
infobip
| 456,885,171
| false
| null |
package com.infobip.kafkistry.kafka.ops
import com.infobip.kafkistry.kafka.BrokerId
import com.infobip.kafkistry.kafka.TOPIC_CONFIG_PROPERTIES
import com.infobip.kafkistry.kafka.ThrottleRate
import com.infobip.kafkistry.model.TopicConfigMap
import com.infobip.kafkistry.model.TopicName
import com.infobip.kafkistry.service.KafkaClusterManagementException
import kafka.server.DynamicConfig
import org.apache.kafka.clients.admin.*
import org.apache.kafka.common.config.ConfigResource
import java.util.concurrent.CompletableFuture
class ConfigOps(
clientCtx: ClientCtx,
): BaseOps(clientCtx) {
fun partialUpdateTopicConfig(
topicName: TopicName,
config: TopicConfigMap,
) : CompletableFuture<Unit> {
val configResource = ConfigResource(ConfigResource.Type.TOPIC, topicName)
return updateConfig(
configResource = configResource,
alterConfigs = {
val resourceConfigs = adminClient
.describeConfigs(listOf(configResource), DescribeConfigsOptions().withReadTimeout())
.all()
.asCompletableFuture("partial topic update config read current")
.get()
val currentConfig = resourceConfigs[configResource]
?: throw KafkaClusterManagementException("Did not get response for config of topic $topicName")
val fullConfig = currentConfig.entries().associate { it.name() to it.value() }.plus(config)
fullConfig.toKafkaConfig()
},
alterConfigOps = { config.toToAlterSetOps() },
)
}
@SuppressWarnings("kotlin:S1874") //sonar: deprecation usage
private fun updateConfig(
configResource: ConfigResource,
alterConfigs: () -> Config,
alterConfigOps: () -> Collection<AlterConfigOp>,
): CompletableFuture<Unit> {
val alterConfigsResult = if (clusterVersion < VERSION_2_3) {
if (configResource.type() == ConfigResource.Type.BROKER) {
runOperation("alter broker config") {
val adminZkClient = newZKAdminClient()
val brokerConfigs = adminZkClient.fetchEntityConfig("brokers", configResource.name())
alterConfigOps().forEach { alterOp ->
when (alterOp.opType()) {
AlterConfigOp.OpType.SET -> brokerConfigs[alterOp.configEntry().name()] = alterOp.configEntry().value()
AlterConfigOp.OpType.DELETE -> brokerConfigs.remove(alterOp.configEntry().name())
else -> throw UnsupportedOperationException("Unsupported operation type ${alterOp.opType()}")
}
}
adminZkClient.changeConfigs("brokers", configResource.name(), brokerConfigs, true)
}
return CompletableFuture.completedFuture(Unit)
} else {
//suppressing since it's deprecated for version 2.3.0 but, it's the only way for older broker versions
@Suppress("DEPRECATION")
adminClient.alterConfigs(
mapOf(configResource to alterConfigs()), AlterConfigsOptions().withWriteTimeout()
)
}
} else {
adminClient.incrementalAlterConfigs(
mapOf(configResource to alterConfigOps()), AlterConfigsOptions().withWriteTimeout()
)
}
return alterConfigsResult
.all()
.asCompletableFuture("alter configs")
.thenApply { }
}
fun updateTopicConfig(topicName: TopicName, updatingConfig: TopicConfigMap): CompletableFuture<Unit> {
return updateConfig(
configResource = ConfigResource(ConfigResource.Type.TOPIC, topicName),
alterConfigs = { updatingConfig.toKafkaConfig() },
alterConfigOps = { updatingConfig.toToTopicAlterOps() },
)
}
fun setBrokerConfig(brokerId: BrokerId, config: Map<String, String>): CompletableFuture<Unit> {
return updateConfig(
configResource = ConfigResource(ConfigResource.Type.BROKER, brokerId.toString()),
alterConfigs = { config.toKafkaConfig() },
alterConfigOps = { config.toToAlterSetOps() },
)
}
fun unsetBrokerConfig(brokerId: BrokerId, configKeys: Set<String>): CompletableFuture<Unit> {
return updateConfig(
configResource = ConfigResource(ConfigResource.Type.BROKER, brokerId.toString()),
alterConfigs = { configKeys.associateWith { null }.toKafkaConfig() },
alterConfigOps = { configKeys.toToAlterUnsetOps() },
)
}
fun updateThrottleRate(brokerId: BrokerId, throttleRate: ThrottleRate): CompletableFuture<Unit> {
val dynamicConf = DynamicConfig.`Broker$`.`MODULE$`
val configs = with(dynamicConf) {
mapOf(
LeaderReplicationThrottledRateProp() to throttleRate.leaderRate?.takeIf { it > 0 }?.toString(),
FollowerReplicationThrottledRateProp() to throttleRate.followerRate?.takeIf { it > 0 }?.toString(),
ReplicaAlterLogDirsIoMaxBytesPerSecondProp() to throttleRate.alterDirIoRate?.takeIf { it > 0 }?.toString(),
)
}
return updateConfig(ConfigResource(ConfigResource.Type.BROKER, brokerId.toString()),
alterConfigs = { Config(configs.map { ConfigEntry(it.key, it.value) }) },
alterConfigOps = {
configs.map {
AlterConfigOp(
ConfigEntry(it.key, it.value),
if (it.value != null) AlterConfigOp.OpType.SET else AlterConfigOp.OpType.DELETE
)
}
}
)
}
private fun TopicConfigMap.toKafkaConfig(): Config = this
.mapNotNull { e -> ConfigEntry(e.key, e.value).takeIf { it.value() != null } }
.let { Config(it) }
private fun TopicConfigMap.toToAlterSetOps(): Collection<AlterConfigOp> = this
.map { e -> ConfigEntry(e.key, e.value.takeIf { it != null }) }
.map { AlterConfigOp(it, if (it.value() != null) AlterConfigOp.OpType.SET else AlterConfigOp.OpType.DELETE) }
private fun Set<String>.toToAlterUnsetOps(): Collection<AlterConfigOp> = this
.map { ConfigEntry(it, null) }
.map { AlterConfigOp(it, AlterConfigOp.OpType.DELETE) }
private fun TopicConfigMap.toToTopicAlterOps(): Collection<AlterConfigOp> = this
.toToAlterSetOps()
.plus(
TOPIC_CONFIG_PROPERTIES
.filter { it !in this.keys }
.map { AlterConfigOp(ConfigEntry(it, null), AlterConfigOp.OpType.DELETE) }
)
}
| 2
| null |
6
| 42
|
bbd06186aff2fd73fc2b42f0b282cfbef271ed75
| 6,795
|
kafkistry
|
Apache License 2.0
|
app/src/main/java/com/kirillemets/flashcards/ui/home/HomeFragment.kt
|
KirillEmets
| 291,228,411
| false
| null |
package com.kirillemets.flashcards.ui.home
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.kirillemets.flashcards.R
import com.kirillemets.flashcards.databinding.FragmentHomeBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class HomeFragment : Fragment() {
private val viewModel: HomeFragmentViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
super.onCreate(savedInstanceState)
val binding = FragmentHomeBinding.inflate(inflater)
binding.buttonStartReview.setOnClickListener {
navigateToReviewFragment()
}
viewModel.loadCardCount()
lifecycleScope.launchWhenStarted {
viewModel.homeUIState.collect { homeUIState ->
binding.countOfCardsTextView.text =
resources.getString(R.string.countOfWordsToReview, homeUIState.reviewWordCount)
binding.uiState = homeUIState
}
}
binding.lifecycleOwner = this
return binding.root
}
private fun navigateToReviewFragment() {
findNavController().navigate(R.id.action_reviewStarterFragment_to_reviewFragment)
}
}
| 3
|
Kotlin
|
0
| 1
|
fbdee70812ee4514ba94c8453500a30c7c7a38da
| 1,479
|
japaneseflashcards
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/incentivesapi/health/HealthPingCheck.kt
|
ministryofjustice
| 445,553,088
| false
|
{"Kotlin": 616953, "Python": 4467, "Dockerfile": 1357}
|
package uk.gov.justice.digital.hmpps.incentivesapi.health
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.client.WebClient
import uk.gov.justice.hmpps.kotlin.health.ReactiveHealthPingCheck
@Component("hmppsAuth")
class AuthHealthPing(@Qualifier("authWebClient") webClient: WebClient) : ReactiveHealthPingCheck(webClient)
@Component("prisonApi")
class PrisonHealthPing(@Qualifier("prisonHealthWebClient") webClient: WebClient) : ReactiveHealthPingCheck(webClient)
@Component("offenderSearch")
class OffenderSearchHealthPing(@Qualifier("offenderSearchHealthWebClient") webClient: WebClient) : ReactiveHealthPingCheck(webClient)
| 3
|
Kotlin
|
1
| 2
|
e5c28a76c609de01706c6bc692c4a599e10461bd
| 741
|
hmpps-incentives-api
|
MIT License
|
OffchainPaymentSample/src/main/java/com/example/payment/PreferencesUtil.kt
|
kiddingDream
| 166,622,891
| false
| null |
package com.example.payment
import android.content.Context
import android.content.SharedPreferences
object PreferencesUtil {
private val name = "APP_Config"
private val prefs: SharedPreferences by lazy { OffChainPaymentActivity.instance.applicationContext.getSharedPreferences(name, Context.MODE_PRIVATE) }
/**
* 获取存放数据
* @return 值
*/
@Suppress("UNCHECKED_CAST")
fun getValue(key: String, default: Any): Any = with(prefs) {
return when (default) {
is Int -> getInt(key, default)
is String -> getString(key, default)
is Long -> getLong(key, default)
is Float -> getFloat(key, default)
is Boolean -> getBoolean(key, default)
else -> throw IllegalArgumentException("SharedPreferences 类型错误")
}
}
fun getString(key: String, default: String = ""): String {
return getValue(key, default) as String
}
fun getInt(key: String, default: Int = 0): Int {
return getValue(key, default) as Int
}
fun getLong(key: String, default: Long = 0): Long {
return getValue(key, default) as Long
}
fun getBoolean(key: String, default: Boolean = false): Boolean {
return getValue(key, default) as Boolean
}
fun getFloat(key: String, default: Float = 0f): Float {
return getValue(key, default) as Float
}
/**
* 存放SharedPreferences
* @param key 键
* @param value 值
*/
fun saveValue(key: String, value: Any) = with(prefs.edit()) {
when (value) {
is Long -> putLong(key, value)
is Int -> putInt(key, value)
is String -> putString(key, value)
is Float -> putFloat(key, value)
is Boolean -> putBoolean(key, value)
else -> throw IllegalArgumentException("SharedPreferences 类型错误")
}.apply()
}
/**
* 清除
*/
fun clear() {
prefs.edit().clear().apply()
}
/**
* 删除某Key的值
*/
fun remove(key: String) {
prefs.edit().remove(key).apply()
}
}
| 0
|
Kotlin
|
0
| 0
|
3c8f2c678acf954ea5b98a1bf13ee1462c572f58
| 2,093
|
firstCelerSDKDapp
|
MIT License
|
tmp/arrays/youTrackTests/367.kt
|
DaniilStepanov
| 228,623,440
| false
| null |
// Original bug: KT-12734
class A {
fun make(param: I) {
param.t()
}
}
fun main(args: Array<String>) {
val k: A? = A()
val a = ""
k?.let {
k.make(object: I {
override fun t() {
println(a) // breakpoint
}
})
}
}
interface I {
fun t()
}
| 1
| null |
8
| 1
|
602285ec60b01eee473dcb0b08ce497b1c254983
| 329
|
bbfgradle
|
Apache License 2.0
|
payments-core/src/main/java/com/stripe/android/view/i18n/TranslatorManager.kt
|
stripe
| 6,926,049
| false
| null |
package com.stripe.android.view.i18n
import android.app.Application
import com.stripe.android.StripeError
import com.stripe.android.view.i18n.TranslatorManager.setErrorMessageTranslator
/**
* A class that provides a [ErrorMessageTranslator] for translating server-provided error
* messages, as defined in [Stripe API Errors Reference](https://stripe.com/docs/api/errors).
*
* See [com.stripe.android.view.PaymentMethodsActivity] for example usage.
*
* To use a custom [ErrorMessageTranslator] in your app, override [Application.onCreate] in
* your app's Application subclass and call [setErrorMessageTranslator].
*
* <pre>
* public class MyApp extends Application {
* public void onCreate() {
* super.onCreate();
* TranslatorManager.setErrorMessageTranslator(new MyErrorMessageTranslator());
* }
* }
* </pre>
*/
object TranslatorManager {
private val DEFAULT_ERROR_MESSAGE_TRANSLATOR = Default()
private var errorMessageTranslator: ErrorMessageTranslator? = null
fun getErrorMessageTranslator(): ErrorMessageTranslator {
return errorMessageTranslator ?: DEFAULT_ERROR_MESSAGE_TRANSLATOR
}
fun setErrorMessageTranslator(errorMessageTranslator: ErrorMessageTranslator?) {
this.errorMessageTranslator = errorMessageTranslator
}
private class Default : ErrorMessageTranslator {
override fun translate(
httpCode: Int,
errorMessage: String?,
stripeError: StripeError?
): String {
return errorMessage.orEmpty()
}
}
}
| 64
| null |
522
| 935
|
bec4fc5f45b5401a98a310f7ebe5d383693936ea
| 1,565
|
stripe-android
|
MIT License
|
src/main/kotlin/ua/pp/lumivoid/redstonehelper/network/SendPacket.kt
|
Bumer-32
| 779,465,671
| false
|
{"Kotlin": 169782, "Java": 12032, "Groovy": 7051}
|
package ua.pp.lumivoid.redstonehelper.network
import net.minecraft.server.network.ServerPlayerEntity
import ua.pp.lumivoid.redstonehelper.Constants
object SendPacket {
private val logger = Constants.LOGGER
fun sendPacket(sendingClass: Record) {
logger.debug("Sending packet to server")
Constants.NET_CHANNEL.clientHandle().send(sendingClass)
}
fun sendToPlayer(player: ServerPlayerEntity, sendingClass: Record) {
logger.debug("Sending packet to player")
Constants.NET_CHANNEL.serverHandle(player).send(sendingClass)
}
}
| 0
|
Kotlin
|
1
| 3
|
67b58d6da2397b85498d09c19bfa7e59b2f4671f
| 578
|
Redstone-Helper
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonersearch/services/CanonicalPnc.kt
|
ministryofjustice
| 256,501,813
| false
| null |
package uk.gov.justice.digital.hmpps.prisonersearch.common.model
fun String.canonicalPNCNumber(): String = if (isPNCNumber()) combinePNC(splitPNC()) else this
fun String.canonicalPNCNumberShort(): String? =
when {
isPNCNumberShort() -> combinePNC(splitPNC())
isPNCNumberLong() -> with(splitPNC()) { combinePNC(Pnc(year.substring(2, 4), serialNumber, checksum)) }
else -> null
}
fun String.canonicalPNCNumberLong(): String? =
when {
isPNCNumberLong() -> combinePNC(splitPNC())
isPNCNumberShort() -> with(splitPNC()) { combinePNC(Pnc(addCenturyToYear(year), serialNumber, checksum)) }
else -> null
}
private fun combinePNC(pnc: Pnc) = with(pnc) { "$year/$serialNumber$checksum".uppercase() }
private fun String.splitPNC(): Pnc {
val (year, serial) = split("/")
val serialNumber = serial.substring(0, serial.length - 1).toInt()
val checksum = last()
return Pnc(year, serialNumber, checksum)
}
data class Pnc(val year: String, val serialNumber: Int, val checksum: Char)
private fun String.isPNCNumber() = matches("^([0-9]{2}|[0-9]{4})/[0-9]+[a-zA-Z]".toRegex())
private fun String.isPNCNumberShort() = matches("^([0-9]{2})/[0-9]+[a-zA-Z]".toRegex())
private fun String.isPNCNumberLong() = matches("^([0-9]{4})/[0-9]+[a-zA-Z]".toRegex())
private fun addCenturyToYear(year: String): String = if (year.toInt() in 39..99) "19$year" else "20$year"
| 1
| null |
3
| 5
|
d00ec5d967d436f275ec87db28d350b584763e3a
| 1,389
|
prisoner-offender-search
|
MIT License
|
app/src/main/kotlin/com/cesarvaliente/kunidirectional/ItemsApplication.kt
|
CesarValiente
| 88,026,476
| false
| null |
/**
* Copyright (C) 2017 Cesar Valiente & Corey Shaw
*
* https://github.com/CesarValiente
* https://github.com/coshaw
*
* 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.cesarvaliente.kunidirectional
import android.app.Application
import android.preference.PreferenceManager
import com.cesarvaliente.kunidirectional.persistence.setupPersistence
class ItemsApplication : Application() {
override fun onCreate() {
super.onCreate()
storeInitialization()
}
private fun storeInitialization() {
if (isPersistenceEnabled()) {
AppStore.enablePersistence()
setupPersistence(context = this)
}
}
private fun isPersistenceEnabled(): Boolean {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
return sharedPreferences.getBoolean(getString(R.string.pref_persistence_key), true)
}
}
| 2
| null |
30
| 313
|
81706091f1700165a63eba310a12cedc136ded1f
| 1,424
|
KUnidirectional
|
Apache License 2.0
|
android/src/main/kotlin/com/mesosfer/flimer/FlimerPlugin.kt
|
alann-maulana
| 391,268,108
| false
|
{"C++": 21296, "CMake": 15223, "Dart": 10012, "Ruby": 4456, "Swift": 2249, "HTML": 1537, "C": 1404, "Kotlin": 1368, "Objective-C": 659}
|
package com.mesosfer.flimer
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
/** FlimerPlugin */
class FlimerPlugin: FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flimer")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
result.notImplemented()
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
| 1
|
C++
|
0
| 2
|
a354ef2d39bb8d4ecfca2babda4d04b7d58dd84b
| 1,236
|
flimer
|
MIT License
|
permission-api/src/main/kotlin/com/github/b1412/security/custom/CustomUserDetailsAuthenticationProvider.kt
|
b1412
| 206,295,390
| false
| null |
package com.github.b1412.security.custom
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.InternalAuthenticationServiceException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.util.Assert
class CustomUserDetailsAuthenticationProvider(
private val passwordEncoder: PasswordEncoder,
private val userDetailsService: CustomUserDetailsService
) : AbstractUserDetailsAuthenticationProvider() {
private var userNotFoundEncodedPassword: String? = null
@Throws(AuthenticationException::class)
override fun additionalAuthenticationChecks(
userDetails: UserDetails,
authentication: UsernamePasswordAuthenticationToken
) {
if (authentication.credentials == null) {
logger.debug("Authentication failed: no credentials provided")
throw BadCredentialsException(
messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")
)
}
val presentedPassword = authentication.credentials
.toString()
if (!passwordEncoder.matches(presentedPassword, userDetails.password)) {
logger.debug("Authentication failed: password does not match stored value")
throw BadCredentialsException(
messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")
)
}
}
@Throws(Exception::class)
override fun doAfterPropertiesSet() {
Assert.notNull(this.userDetailsService, "A UserDetailsService must be set")
this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD)
}
override fun retrieveUser(username: String, authentication: UsernamePasswordAuthenticationToken): UserDetails {
val auth = authentication as CustomAuthenticationToken
val loadedUser: UserDetails?
try {
loadedUser = this.userDetailsService.loadUserByUsernameAndClientId(auth.principal.toString(), auth.domain!!)
} catch (notFound: UsernameNotFoundException) {
if (authentication.getCredentials() != null) {
val presentedPassword = authentication.getCredentials().toString()
passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword)
}
throw notFound
} catch (repositoryProblem: Exception) {
throw InternalAuthenticationServiceException(repositoryProblem.message, repositoryProblem)
}
return loadedUser
}
companion object {
private const val USER_NOT_FOUND_PASSWORD = "<PASSWORD>"
}
}
| 1
| null |
1
| 1
|
ee02bf12022ad23b334cb90b3f314be048c3d8eb
| 3,154
|
permission-api
|
Apache License 2.0
|
src/commonMain/kotlin/kotools/types/result/Operations.kt
|
kotools
| 581,475,148
| false
| null |
package kotools.types.result
import kotools.types.ExperimentalSinceKotoolsTypes
import kotools.types.experimental.ExperimentalResultApi
/**
* Transforms the encapsulated value from [T] to [R] if this result is a
* [success][Result.isSuccess], or returns the original exception if this result
* or the one returned by the [transform] function is a
* [failure][Result.isFailure].
*/
@ExperimentalResultApi
@ExperimentalSinceKotoolsTypes("4.2")
public inline fun <T, R> Result<T>.flatMap(
transform: (T) -> Result<R>
): Result<R> = exceptionOrNull()
?.let(Result.Companion::failure)
?: transform(getOrThrow())
| 27
| null |
2
| 4
|
5c889bf9d48d84b751905b4fed7833a0349a8685
| 626
|
types
|
MIT License
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Eyeslash.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup
public val BoldGroup.Eyeslash: ImageVector
get() {
if (_eyeslash != null) {
return _eyeslash!!
}
_eyeslash = Builder(name = "Eyeslash", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.2714f, 9.1783f)
curveTo(20.9814f, 8.7183f, 20.6714f, 8.2883f, 20.3514f, 7.8883f)
curveTo(19.9814f, 7.4183f, 19.2814f, 7.3783f, 18.8614f, 7.7983f)
lineTo(15.8614f, 10.7983f)
curveTo(16.0814f, 11.4583f, 16.1214f, 12.2183f, 15.9214f, 13.0083f)
curveTo(15.5714f, 14.4183f, 14.4314f, 15.5583f, 13.0214f, 15.9083f)
curveTo(12.2314f, 16.1083f, 11.4714f, 16.0683f, 10.8114f, 15.8483f)
curveTo(10.8114f, 15.8483f, 9.3814f, 17.2783f, 8.3514f, 18.3083f)
curveTo(7.8514f, 18.8083f, 8.0114f, 19.6883f, 8.6814f, 19.9483f)
curveTo(9.7514f, 20.3583f, 10.8614f, 20.5683f, 12.0014f, 20.5683f)
curveTo(13.7814f, 20.5683f, 15.5114f, 20.0483f, 17.0914f, 19.0783f)
curveTo(18.7014f, 18.0783f, 20.1514f, 16.6083f, 21.3214f, 14.7383f)
curveTo(22.2714f, 13.2283f, 22.2214f, 10.6883f, 21.2714f, 9.1783f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(14.0206f, 9.9806f)
lineTo(9.9806f, 14.0206f)
curveTo(9.4706f, 13.5006f, 9.1406f, 12.7806f, 9.1406f, 12.0006f)
curveTo(9.1406f, 10.4306f, 10.4206f, 9.1406f, 12.0006f, 9.1406f)
curveTo(12.7806f, 9.1406f, 13.5006f, 9.4706f, 14.0206f, 9.9806f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.25f, 5.7497f)
lineTo(14.86f, 9.1397f)
curveTo(14.13f, 8.3997f, 13.12f, 7.9597f, 12.0f, 7.9597f)
curveTo(9.76f, 7.9597f, 7.96f, 9.7697f, 7.96f, 11.9997f)
curveTo(7.96f, 13.1197f, 8.41f, 14.1297f, 9.14f, 14.8597f)
lineTo(5.76f, 18.2497f)
horizontalLineTo(5.75f)
curveTo(4.64f, 17.3497f, 3.62f, 16.1997f, 2.75f, 14.8397f)
curveTo(1.75f, 13.2697f, 1.75f, 10.7197f, 2.75f, 9.1497f)
curveTo(3.91f, 7.3297f, 5.33f, 5.8997f, 6.91f, 4.9197f)
curveTo(8.49f, 3.9597f, 10.22f, 3.4297f, 12.0f, 3.4297f)
curveTo(14.23f, 3.4297f, 16.39f, 4.2497f, 18.25f, 5.7497f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(14.8581f, 11.9981f)
curveTo(14.8581f, 13.5681f, 13.5781f, 14.8581f, 11.9981f, 14.8581f)
curveTo(11.9381f, 14.8581f, 11.8881f, 14.8581f, 11.8281f, 14.8381f)
lineTo(14.8381f, 11.8281f)
curveTo(14.8581f, 11.8881f, 14.8581f, 11.9381f, 14.8581f, 11.9981f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.7689f, 2.2289f)
curveTo(21.4689f, 1.9289f, 20.9789f, 1.9289f, 20.6789f, 2.2289f)
lineTo(2.2289f, 20.6889f)
curveTo(1.9289f, 20.9889f, 1.9289f, 21.4789f, 2.2289f, 21.7789f)
curveTo(2.3789f, 21.9189f, 2.5689f, 21.9989f, 2.7689f, 21.9989f)
curveTo(2.9689f, 21.9989f, 3.1589f, 21.9189f, 3.3089f, 21.7689f)
lineTo(21.7689f, 3.3089f)
curveTo(22.0789f, 3.0089f, 22.0789f, 2.5289f, 21.7689f, 2.2289f)
close()
}
}
.build()
return _eyeslash!!
}
private var _eyeslash: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 5,412
|
VuesaxIcons
|
MIT License
|
app/src/main/java/com/xquare/xquare_android/component/Header.kt
|
team-xquare
| 478,925,648
| false
|
{"Kotlin": 447887}
|
package com.xquare.xquare_android.component
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.semicolon.design.Body1
import com.semicolon.design.Body3
import com.semicolon.design.color.primary.gray.gray800
import com.xquare.xquare_android.R
@Composable
fun Header(
painter: Painter? = null,
title: String,
btnText: String? = null,
btnEnabled: Boolean = false,
backgroundColor: Color = Color.Unspecified,
onIconClick: () -> Unit = {},
onBtnClick: () -> Unit = {},
) {
val btnColor = if (btnEnabled) gray800 else Color(0xFF9E9E9E)
Box(
modifier = Modifier
.height(56.dp)
.fillMaxWidth()
.background(backgroundColor),
contentAlignment = Alignment.Center,
) {
Body1(text = title)
Row(
modifier = Modifier
.fillMaxSize()
.padding(end = 15.88.dp),
verticalAlignment = Alignment.CenterVertically
) {
Spacer(Modifier.size(16.dp))
painter?.let {
Image(
modifier = Modifier
.clickable(
interactionSource = MutableInteractionSource(),
indication = null,
enabled = true
) { onIconClick() },
painter = it,
contentDescription = null
)
}
btnText?.let { text ->
Body3(
text = text,
color = btnColor,
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(align = Alignment.End)
.clickable(
interactionSource = MutableInteractionSource(),
indication = null,
enabled = btnEnabled,
) {
onBtnClick()
},
)
}
}
}
}
@Composable
@Preview(showBackground = true)
fun ShowHeader() {
Header(
painter = painterResource(id = R.drawable.ic_back),
title = "일정 수정",
btnText = "등록"
)
}
| 20
|
Kotlin
|
1
| 25
|
f9bc5d0bc3ed2957705dc6db53d0139f62827649
| 3,241
|
xquare-android
|
MIT License
|
tools/gradle-plugins/extensions/markdown/src/main/kotlin/com/varabyte/kobwebx/gradle/markdown/tasks/MarkdownTask.kt
|
varabyte
| 389,223,226
| false
|
{"Kotlin": 1677550}
|
package com.varabyte.kobwebx.gradle.markdown.tasks
import com.varabyte.kobweb.common.lang.packageConcat
import com.varabyte.kobweb.common.lang.toPackageName
import com.varabyte.kobweb.gradle.core.tasks.KobwebTask
import com.varabyte.kobweb.gradle.core.util.prefixQualifiedPackage
import com.varabyte.kobwebx.gradle.markdown.MarkdownBlock
import org.gradle.api.file.FileTree
import org.gradle.api.file.RelativePath
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import java.io.File
import java.nio.file.Path
import javax.inject.Inject
import kotlin.io.path.Path
import kotlin.io.path.invariantSeparatorsPathString
abstract class MarkdownTask @Inject constructor(
@get:Internal protected val markdownBlock: MarkdownBlock,
desc: String
) :
KobwebTask(desc) {
@get:Input
abstract val pagesPackage: Property<String>
private val rootPath get() = Path(markdownBlock.markdownPath.get())
@get:Internal
abstract val resources: Property<SourceDirectorySet>
@InputFiles
fun getMarkdownRoots(): Provider<List<File>> = resources.map {
it.srcDirs.map { root -> root.resolve(markdownBlock.markdownPath.get()) }
}
@InputFiles
fun getMarkdownResources(): Provider<FileTree> {
return resources.zip(markdownBlock.markdownPath) { fileTree, path ->
fileTree.matching { include("$path/**/*.md") }
}
}
protected fun funNameFor(mdFile: File): String {
// The suggested replacement for "capitalize" is awful
@Suppress("DEPRECATION")
return "${mdFile.nameWithoutExtension.capitalize()}Page"
}
protected fun RelativePath.toPath(): Path {
return rootPath.relativize(Path(this.pathString))
}
protected fun packagePartsFor(mdFile: RelativePath): List<String> {
val mdPathRel = mdFile.toPath().invariantSeparatorsPathString
val parts = mdPathRel.split('/')
val dirParts = parts.subList(0, parts.lastIndex)
return dirParts.map { it.toPackageName() }
}
protected fun absolutePackageFor(packageParts: List<String>): String {
return project.prefixQualifiedPackage(
pagesPackage.get().packageConcat(packageParts.joinToString("."))
)
}
protected fun absolutePackageFor(mdFile: RelativePath): String {
return absolutePackageFor(packagePartsFor(mdFile))
}
}
| 100
|
Kotlin
|
65
| 1,440
|
8f0afe18fa10c5868b2f9f9fab89efbe569d6743
| 2,552
|
kobweb
|
Apache License 2.0
|
library/src/main/java/com/chuckerteam/chucker/internal/ui/error/ErrorAdapter.kt
|
foursquare
| 219,050,867
| false
| null |
package com.chatbooks.chatter.internal.ui.error
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.chatbooks.chatter.R
import com.chatbooks.chatter.internal.data.entity.RecordedThrowableTuple
import java.text.DateFormat
internal class ErrorAdapter(
val listener: ErrorClickListListener
) : RecyclerView.Adapter<ErrorAdapter.ErrorViewHolder>() {
private var data: List<RecordedThrowableTuple> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ErrorViewHolder {
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.chatter_list_item_error, parent, false)
return ErrorViewHolder(view)
}
override fun onBindViewHolder(holder: ErrorViewHolder, position: Int) {
val throwable = data[position]
holder.bind(throwable)
}
override fun getItemCount(): Int {
return data.size
}
fun setData(data: List<RecordedThrowableTuple>) {
this.data = data
notifyDataSetChanged()
}
inner class ErrorViewHolder(
itemView: View
) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val tagView: TextView = itemView.findViewById(R.id.tag)
private val clazzView: TextView = itemView.findViewById(R.id.clazz)
private val messageView: TextView = itemView.findViewById(R.id.message)
private val dateView: TextView = itemView.findViewById(R.id.date)
private var throwableId: Long? = null
init {
itemView.setOnClickListener(this)
}
internal fun bind(throwable: RecordedThrowableTuple) = with(throwable) {
throwableId = id
tagView.text = tag
clazzView.text = clazz
messageView.text = message
dateView.text = formattedDate
}
override fun onClick(v: View) {
throwableId?.let {
listener.onErrorClick(it, adapterPosition)
}
}
}
private val RecordedThrowableTuple.formattedDate: String
get() {
return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM)
.format(this.date)
}
interface ErrorClickListListener {
fun onErrorClick(throwableId: Long, position: Int)
}
}
| 0
| null |
1
| 1
|
2e34e4f871fea7b59b5d970548fd7d8d147f79c4
| 2,449
|
chucker
|
Apache License 2.0
|
app/src/main/java/ch/admin/foitt/pilotwallet/app/presentation/NavigationHost.kt
|
e-id-admin
| 775,912,525
| false
|
{"Kotlin": 1521284}
|
package ch.admin.foitt.pilotwallet.app.presentation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import ch.admin.foitt.pilotwallet.feature.changeLogin.presentation.ConfirmNewPinScreen
import ch.admin.foitt.pilotwallet.feature.changeLogin.presentation.ConfirmNewPinViewModel
import ch.admin.foitt.pilotwallet.feature.changeLogin.presentation.EnterCurrentPinScreen
import ch.admin.foitt.pilotwallet.feature.changeLogin.presentation.EnterCurrentPinViewModel
import ch.admin.foitt.pilotwallet.feature.changeLogin.presentation.EnterNewPinScreen
import ch.admin.foitt.pilotwallet.feature.changeLogin.presentation.EnterNewPinViewModel
import ch.admin.foitt.pilotwallet.feature.credentialDelete.presentation.CredentialDeleteScreen
import ch.admin.foitt.pilotwallet.feature.credentialDelete.presentation.CredentialDeleteViewModel
import ch.admin.foitt.pilotwallet.feature.credentialDetail.presentation.CredentialDetailScreen
import ch.admin.foitt.pilotwallet.feature.credentialDetail.presentation.CredentialDetailViewModel
import ch.admin.foitt.pilotwallet.feature.credentialOffer.presentation.CredentialOfferErrorScreen
import ch.admin.foitt.pilotwallet.feature.credentialOffer.presentation.CredentialOfferErrorViewModel
import ch.admin.foitt.pilotwallet.feature.credentialOffer.presentation.CredentialOfferScreen
import ch.admin.foitt.pilotwallet.feature.credentialOffer.presentation.CredentialOfferViewModel
import ch.admin.foitt.pilotwallet.feature.credentialOffer.presentation.DeclineCredentialOfferScreen
import ch.admin.foitt.pilotwallet.feature.credentialOffer.presentation.DeclineCredentialOfferViewModel
import ch.admin.foitt.pilotwallet.feature.home.presentation.HomeScreen
import ch.admin.foitt.pilotwallet.feature.home.presentation.HomeViewModel
import ch.admin.foitt.pilotwallet.feature.login.presentation.BiometricLoginScreen
import ch.admin.foitt.pilotwallet.feature.login.presentation.BiometricLoginViewModel
import ch.admin.foitt.pilotwallet.feature.login.presentation.LockScreen
import ch.admin.foitt.pilotwallet.feature.login.presentation.LockViewModel
import ch.admin.foitt.pilotwallet.feature.login.presentation.NoDevicePinSetScreen
import ch.admin.foitt.pilotwallet.feature.login.presentation.NoDevicePinSetViewModel
import ch.admin.foitt.pilotwallet.feature.login.presentation.PinLoginScreen
import ch.admin.foitt.pilotwallet.feature.login.presentation.PinLoginViewModel
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.ConfirmPinScreen
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.ConfirmPinViewModel
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.EnterPinScreen
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.EnterPinViewModel
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.OnboardingIntroScreen
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.OnboardingIntroViewModel
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.OnboardingQRScreen
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.OnboardingQRViewModel
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.RegisterBiometricsScreen
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.RegisterBiometricsViewModel
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.UserPrivacyPolicyScreen
import ch.admin.foitt.pilotwallet.feature.onboarding.presentation.UserPrivacyPolicyViewModel
import ch.admin.foitt.pilotwallet.feature.policeQrCode.presentation.PoliceQrCodeScreen
import ch.admin.foitt.pilotwallet.feature.policeQrCode.presentation.PoliceQrCodeViewModel
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationCredentialListScreen
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationCredentialListViewModel
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationDeclinedScreen
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationDeclinedViewModel
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationEmptyWalletScreen
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationEmptyWalletViewModel
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationFailureScreen
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationFailureViewModel
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationNoMatchScreen
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationNoMatchViewModel
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationRequestScreen
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationRequestViewModel
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationSuccessScreen
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationSuccessViewModel
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationValidationErrorScreen
import ch.admin.foitt.pilotwallet.feature.presentationRequest.presentation.PresentationValidationErrorViewModel
import ch.admin.foitt.pilotwallet.feature.qrscan.presentation.QrScanPermissionScreen
import ch.admin.foitt.pilotwallet.feature.qrscan.presentation.QrScanPermissionViewModel
import ch.admin.foitt.pilotwallet.feature.qrscan.presentation.QrScannerScreen
import ch.admin.foitt.pilotwallet.feature.qrscan.presentation.QrScannerViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.SettingsScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.SettingsViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.biometrics.AuthWithPinScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.biometrics.AuthWithPinViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.biometrics.EnableBiometricsErrorScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.biometrics.EnableBiometricsErrorViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.biometrics.EnableBiometricsLockoutScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.biometrics.EnableBiometricsLockoutViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.biometrics.EnableBiometricsScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.biometrics.EnableBiometricsViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.impressum.ImpressumScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.impressum.ImpressumViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.language.LanguageScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.language.LanguageViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.licences.LicencesScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.licences.LicencesViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.security.DataAnalysisScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.security.DataAnalysisViewModel
import ch.admin.foitt.pilotwallet.feature.settings.presentation.security.SecuritySettingsScreen
import ch.admin.foitt.pilotwallet.feature.settings.presentation.security.SecuritySettingsViewModel
import ch.admin.foitt.pilotwallet.platform.invitation.presentation.InvalidCredentialErrorScreen
import ch.admin.foitt.pilotwallet.platform.invitation.presentation.InvalidCredentialErrorViewModel
import ch.admin.foitt.pilotwallet.platform.invitation.presentation.InvitationFailureScreen
import ch.admin.foitt.pilotwallet.platform.invitation.presentation.InvitationFailureViewModel
import ch.admin.foitt.pilotwallet.platform.invitation.presentation.UnknownIssuerErrorScreen
import ch.admin.foitt.pilotwallet.platform.invitation.presentation.UnknownIssuerErrorViewModel
import ch.admin.foitt.pilotwallet.platform.invitation.presentation.UnknownVerifierErrorScreen
import ch.admin.foitt.pilotwallet.platform.invitation.presentation.UnknownVerifierErrorViewModel
import ch.admin.foitt.pilotwallet.platform.nointernet.presentation.NoInternetConnectionScreen
import ch.admin.foitt.pilotwallet.platform.nointernet.presentation.NoInternetConnectionViewModel
import ch.admin.foitt.pilotwallet.platform.scaffold.extension.screenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.NavGraphs
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.AuthWithPinScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.BiometricLoginScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.ConfirmNewPinScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.ConfirmPinScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.CredentialDeleteScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.CredentialDetailScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.CredentialOfferErrorScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.CredentialOfferScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.DataAnalysisScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.DeclineCredentialOfferScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.EnableBiometricsErrorScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.EnableBiometricsLockoutScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.EnableBiometricsScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.EnterCurrentPinScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.EnterNewPinScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.EnterPinScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.HomeScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.ImpressumScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.InvalidCredentialErrorScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.InvitationFailureScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.LanguageScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.LicencesScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.LockScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.NoDevicePinSetScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.NoInternetConnectionScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.OnboardingIntroScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.OnboardingQRScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PinLoginScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PoliceQrCodeScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PresentationCredentialListScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PresentationDeclinedScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PresentationEmptyWalletScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PresentationFailureScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PresentationNoMatchScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PresentationRequestScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PresentationSuccessScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.PresentationValidationErrorScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.QrScanPermissionScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.QrScannerScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.RegisterBiometricsScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.SecuritySettingsScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.SettingsScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.StartScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.UnknownIssuerErrorScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.UnknownVerifierErrorScreenDestination
import ch.admin.foitt.pilotwalletcomposedestinations.destinations.UserPrivacyPolicyScreenDestination
import com.ramcosta.composedestinations.DestinationsNavHost
import com.ramcosta.composedestinations.spec.NavHostEngine
@Composable
fun NavigationHost(
engine: NavHostEngine,
navController: NavHostController,
) {
DestinationsNavHost(
navGraph = NavGraphs.root,
engine = engine,
navController = navController,
) {
screenDestination(StartScreenDestination) { viewModel: StartViewModel ->
StartScreen(viewModel)
}
screenDestination(LockScreenDestination) { viewModel: LockViewModel ->
LockScreen(viewModel)
}
screenDestination(NoDevicePinSetScreenDestination) { viewModel: NoDevicePinSetViewModel ->
NoDevicePinSetScreen(viewModel)
}
screenDestination(OnboardingIntroScreenDestination) { viewModel: OnboardingIntroViewModel ->
OnboardingIntroScreen(viewModel)
}
screenDestination(OnboardingQRScreenDestination) { viewModel: OnboardingQRViewModel ->
OnboardingQRScreen(viewModel)
}
screenDestination(UserPrivacyPolicyScreenDestination) { viewModel: UserPrivacyPolicyViewModel ->
UserPrivacyPolicyScreen(viewModel)
}
screenDestination(EnterPinScreenDestination) { viewModel: EnterPinViewModel ->
EnterPinScreen(viewModel)
}
screenDestination(ConfirmPinScreenDestination) { viewModel: ConfirmPinViewModel ->
ConfirmPinScreen(viewModel)
}
screenDestination(RegisterBiometricsScreenDestination) { viewModel: RegisterBiometricsViewModel ->
RegisterBiometricsScreen(viewModel)
}
screenDestination(EnableBiometricsLockoutScreenDestination) { viewModel: EnableBiometricsLockoutViewModel ->
EnableBiometricsLockoutScreen(viewModel)
}
screenDestination(EnableBiometricsScreenDestination) { viewModel: EnableBiometricsViewModel ->
EnableBiometricsScreen(viewModel)
}
screenDestination(EnableBiometricsErrorScreenDestination) { viewModel: EnableBiometricsErrorViewModel ->
EnableBiometricsErrorScreen(viewModel)
}
screenDestination(PinLoginScreenDestination) { viewModel: PinLoginViewModel ->
PinLoginScreen(viewModel)
}
screenDestination(BiometricLoginScreenDestination) { viewModel: BiometricLoginViewModel ->
BiometricLoginScreen(viewModel)
}
screenDestination(SettingsScreenDestination) { viewModel: SettingsViewModel ->
SettingsScreen(viewModel)
}
screenDestination(SecuritySettingsScreenDestination) { viewModel: SecuritySettingsViewModel ->
SecuritySettingsScreen(viewModel)
}
screenDestination(DataAnalysisScreenDestination) { _: DataAnalysisViewModel ->
DataAnalysisScreen()
}
screenDestination(LanguageScreenDestination) { viewModel: LanguageViewModel ->
LanguageScreen(viewModel)
}
screenDestination(ImpressumScreenDestination) { viewModel: ImpressumViewModel ->
ImpressumScreen(viewModel)
}
screenDestination(LicencesScreenDestination) { viewModel: LicencesViewModel ->
LicencesScreen(viewModel)
}
screenDestination(QrScanPermissionScreenDestination) { viewModel: QrScanPermissionViewModel ->
QrScanPermissionScreen(viewModel)
}
screenDestination(QrScannerScreenDestination) { viewModel: QrScannerViewModel ->
QrScannerScreen(viewModel)
}
screenDestination(InvitationFailureScreenDestination) { viewModel: InvitationFailureViewModel ->
InvitationFailureScreen(viewModel)
}
screenDestination(CredentialOfferScreenDestination) { viewModel: CredentialOfferViewModel ->
CredentialOfferScreen(viewModel)
}
screenDestination(DeclineCredentialOfferScreenDestination) { viewModel: DeclineCredentialOfferViewModel ->
DeclineCredentialOfferScreen(viewModel)
}
screenDestination(CredentialOfferErrorScreenDestination) { viewModel: CredentialOfferErrorViewModel ->
CredentialOfferErrorScreen(viewModel)
}
screenDestination(UnknownIssuerErrorScreenDestination) { viewModel: UnknownIssuerErrorViewModel ->
UnknownIssuerErrorScreen(viewModel)
}
screenDestination(UnknownVerifierErrorScreenDestination) { viewModel: UnknownVerifierErrorViewModel ->
UnknownVerifierErrorScreen(viewModel)
}
screenDestination(NoInternetConnectionScreenDestination) { viewModel: NoInternetConnectionViewModel ->
NoInternetConnectionScreen(viewModel)
}
screenDestination(PresentationRequestScreenDestination) { viewModel: PresentationRequestViewModel ->
PresentationRequestScreen(viewModel)
}
screenDestination(PresentationSuccessScreenDestination) { viewModel: PresentationSuccessViewModel ->
PresentationSuccessScreen(viewModel)
}
screenDestination(PresentationFailureScreenDestination) { viewModel: PresentationFailureViewModel ->
PresentationFailureScreen(viewModel)
}
screenDestination(PresentationValidationErrorScreenDestination) { viewModel: PresentationValidationErrorViewModel ->
PresentationValidationErrorScreen(viewModel)
}
screenDestination(PresentationCredentialListScreenDestination) { viewModel: PresentationCredentialListViewModel ->
PresentationCredentialListScreen(viewModel)
}
screenDestination(PresentationEmptyWalletScreenDestination) { viewModel: PresentationEmptyWalletViewModel ->
PresentationEmptyWalletScreen(viewModel)
}
screenDestination(PresentationNoMatchScreenDestination) { viewModel: PresentationNoMatchViewModel ->
PresentationNoMatchScreen(viewModel)
}
screenDestination(PresentationDeclinedScreenDestination) { viewModel: PresentationDeclinedViewModel ->
PresentationDeclinedScreen(viewModel)
}
screenDestination(HomeScreenDestination) { viewModel: HomeViewModel ->
HomeScreen(viewModel)
}
screenDestination(PoliceQrCodeScreenDestination) { viewModel: PoliceQrCodeViewModel ->
PoliceQrCodeScreen(viewModel)
}
screenDestination(CredentialDetailScreenDestination) { viewModel: CredentialDetailViewModel ->
CredentialDetailScreen(viewModel)
}
screenDestination(CredentialDeleteScreenDestination) { viewModel: CredentialDeleteViewModel ->
CredentialDeleteScreen(viewModel)
}
screenDestination(AuthWithPinScreenDestination) { viewModel: AuthWithPinViewModel ->
AuthWithPinScreen(viewModel)
}
screenDestination(EnterCurrentPinScreenDestination) { viewModel: EnterCurrentPinViewModel ->
EnterCurrentPinScreen(viewModel)
}
screenDestination(ConfirmNewPinScreenDestination) { viewModel: ConfirmNewPinViewModel ->
ConfirmNewPinScreen(viewModel)
}
screenDestination(EnterNewPinScreenDestination) { viewModel: EnterNewPinViewModel ->
EnterNewPinScreen(viewModel)
}
screenDestination(InvalidCredentialErrorScreenDestination) { viewModel: InvalidCredentialErrorViewModel ->
InvalidCredentialErrorScreen(viewModel)
}
}
}
| 1
|
Kotlin
|
1
| 4
|
6572b418ec5abc5d94b18510ffa87a1e433a5c82
| 20,798
|
eidch-pilot-android-wallet
|
MIT License
|
src/jvmTest/kotlin/eu/vendeli/rethis/tests/commands/generic/TypeCommandTest.kt
|
vendelieu
| 861,014,428
| false
|
{"Kotlin": 213441, "Shell": 1248}
|
package eu.vendeli.rethis.tests.commands.generic
import eu.vendeli.rethis.commands.set
import eu.vendeli.rethis.commands.type
import eu.vendeli.rethis.ReThisTestCtx
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
class TypeCommandTest : ReThisTestCtx() {
@Test
suspend fun `test TYPE command`() {
client.set("testKey", "testVal").shouldNotBeNull()
client.type("testKey") shouldBe "string"
}
@Test
suspend fun `test TYPE command with non-existent key`() {
client.type("nonExistentKey") shouldBe "none"
}
}
| 5
|
Kotlin
|
0
| 7
|
8ae609b5430e9ca9255c5a1cba2bdfc70e316020
| 591
|
re.this
|
Apache License 2.0
|
scripts/src/main/java/io/github/fate_grand_automata/scripts/modules/Refill.kt
|
Fate-Grand-Automata
| 245,391,245
| false
| null |
package com.mathewsachin.fategrandautomata.scripts.modules
import com.mathewsachin.fategrandautomata.scripts.IFgoAutomataApi
import com.mathewsachin.fategrandautomata.scripts.Images
import com.mathewsachin.fategrandautomata.scripts.ScriptNotify
import com.mathewsachin.fategrandautomata.scripts.entrypoints.AutoBattle
import com.mathewsachin.libautomata.dagger.ScriptScope
import javax.inject.Inject
import kotlin.time.Duration
@ScriptScope
class Refill @Inject constructor(
api: IFgoAutomataApi
) : IFgoAutomataApi by api {
var timesRefilled = 0
private set
/**
* Refills the AP with apples depending on preferences.
* If needed, loops and wait for AP regeneration
*/
private fun refillOnce() {
val refill = prefs.refill
if (refill.resources.isNotEmpty()
&& timesRefilled < refill.repetitions
) {
refill.resources
.map { locations.locate(it) }
.forEach { it.click() }
Duration.seconds(1).wait()
locations.staminaOkClick.click()
++timesRefilled
Duration.seconds(3).wait()
} else if (prefs.waitAPRegen) {
locations.staminaCloseClick.click()
messages.notify(ScriptNotify.WaitForAPRegen())
Duration.seconds(60).wait()
} else throw AutoBattle.BattleExitException(AutoBattle.ExitReason.APRanOut)
}
fun refill() {
while (images[Images.Stamina] in locations.staminaScreenRegion) {
refillOnce()
}
}
fun autoDecrement() {
val refill = prefs.refill
// Auto-decrement apples
refill.repetitions -= timesRefilled
}
}
| 84
|
Kotlin
|
187
| 993
|
eb630b8efcdb56782f796de2e17b36fdf9e19f3b
| 1,705
|
FGA
|
MIT License
|
app/src/main/kotlin/io/github/importre/popular/DetailsActivity.kt
|
importre
| 33,769,779
| false
| null |
package io.github.importre.popular
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.text.format.DateUtils
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.VideoView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import io.github.importre.popular.api.Item
import kotlinx.android.anko.*
import kotlin.properties.Delegates
public class DetailsActivity : BaseActivity(), AnkoLogger {
private var item: Item = Item()
private var imageSize: Int = matchParent
val toolbar: Toolbar by Delegates.lazy {
find<Toolbar>(R.id.toolbar)
}
val image: ImageView by Delegates.lazy {
find<ImageView>(R.id.image)
}
val video: VideoView by Delegates.lazy {
find<VideoView>(R.id.video)
}
val commentList: LinearLayout by Delegates.lazy {
find<LinearLayout>(R.id.comment_list)
}
override fun onCreate(savedInstanceState: Bundle?) {
super<BaseActivity>.onCreate(savedInstanceState)
initData()
verticalLayout {
toolbar {
id = R.id.toolbar
backgroundColor = primaryColor
setTitleTextColor(Color.WHITE)
setSubtitleTextColor(Color.WHITE)
setSubtitleTextAppearance(ctx, R.style.TextAppearance_AppCompat_Small)
setContentInsetsAbsolute(insetStart, 0)
setNavigationIcon(R.drawable.ic_arrow_back_white_24dp)
if (Build.VERSION.SDK_INT >= 21) {
setElevation(dip(4).toFloat())
}
}.layoutParams(width = matchParent, height = toolbarSize.toInt())
scrollView {
setFillViewport(true)
verticalLayout {
gravity = Gravity.CENTER
imageView {
id = R.id.image
}.layoutParams(width = matchParent, height = dip(imageSize))
relativeLayout {
videoView {
id = R.id.video
}.layoutParams(width = matchParent, height = dip(imageSize))
}
verticalLayout {
id = R.id.comment_list
}
}
}
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super<BaseActivity>.onPostCreate(savedInstanceState)
setSupportActionBar(toolbar)
updateUi()
}
override fun onPause() {
super<BaseActivity>.onPause()
video.stopPlayback()
}
private fun initData() {
imageSize = configuration.smallestScreenWidthDp
val data = getIntent()?.getStringExtra("data")
if (data != null) {
item = Gson().fromJson(data, javaClass<Item>())
} else {
longToast(R.string.error_failure)
finish()
}
}
private fun updateUi() {
toolbar.setTitle(item.user.username)
var time = DateUtils.getRelativeTimeSpanString(
item.created_time * 1000, System.currentTimeMillis(), 0,
DateUtils.FORMAT_ABBREV_RELATIVE).toString();
toolbar.setSubtitle(time)
if ("video".equals(item.type)) {
video.setVideoURI(Uri.parse(item.videos.low_resolution.url))
video.requestFocus()
video.setOnPreparedListener {
video.start()
}
image.visibility = View.GONE
} else {
Glide.with(this)
.load(item.images.standard_resolution.url)
.fitCenter()
.crossFade()
.into(image);
video.visibility = View.GONE
}
for (comment in item.comments.data) {
val v = layoutInflater.inflate(
R.layout.layout_comment, commentList, false)
Glide.with(this)
.load(comment.from.profile_picture)
.fitCenter()
.crossFade()
.into(v.find<ImageView>(R.id.profile))
v.find<TextView>(R.id.name).setText(comment.from.username)
v.find<TextView>(R.id.comment).setText(comment.text)
time = DateUtils.getRelativeTimeSpanString(
comment.created_time * 1000, System.currentTimeMillis(), 0,
DateUtils.FORMAT_ABBREV_RELATIVE).toString();
v.find<TextView>(R.id.time).setText(time)
commentList.addView(v)
}
}
}
| 1
| null |
4
| 26
|
68f4ea931f3b15df9be002798fe347930039f176
| 4,796
|
popular
|
MIT License
|
src/main/kotlin/dev/mbo/rs256/util/KeyPair.kt
|
mbogner
| 498,129,280
| false
| null |
/*
* Copyright 2022 mbo.dev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.mbo.rs256.util
import java.security.PrivateKey
import java.security.PublicKey
data class KeyPair(
val privateKey: PrivateKey,
val publicKey: PublicKey,
)
| 1
|
Kotlin
|
0
| 0
|
2fa4fd05e3cee4fafd091aad59b7e041158ed074
| 764
|
rs256jwt-web
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.