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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bloc-redux/src/commonMain/kotlin/com/onegravity/bloc/redux/select/SelectorBuilder.kt
|
1gravity
| 470,411,711
| false
| null |
package org.reduxkotlin.select
/**
* Wrapper class for Selector factory methods, that basically is used only to capture type
* information for the state parameter
*/
class SelectorBuilder<S : Any> {
/**
* Special single input selector that should be used when you just want to retrieve a single field:
* Warning: Don't use this with primitive type fields, use [withSingleFieldByValue] instead!!!
*/
fun <I : Any> withSingleField(fn: S.() -> I) = object : AbstractSelector<S, I>() {
@Suppress("UNCHECKED_CAST")
private val inputField = InputField(fn, byRefEqualityCheck) as SelectorInput<Any, Any>
override val computeAndCount = fun(i: Array<out Any>): I {
++_recomputations
@Suppress("UNCHECKED_CAST")
return i[0] as I
}
override operator fun invoke(state: S): I {
return memoizer.memoize(state, inputField)
}
override val equalityCheck: EqualityCheckFn
get() = byRefEqualityCheck
override val memoizer: Memoizer<I> by lazy {
singleInputMemoizer(computeAndCount)
}
}
/**
* Special single input selector that should be used when you just want to retrieve a single
* field that is a primitive type like Int, Float, Double, etc..., because it compares memoized
* values, instead of references
*/
fun <I : Any> withSingleFieldByValue(fn: S.() -> I) = object : AbstractSelector<S, I>() {
@Suppress("UNCHECKED_CAST")
private val inputField = InputField(fn, byValEqualityCheck) as SelectorInput<Any, Any>
override val computeAndCount = fun(i: Array<out Any>): I {
++_recomputations
@Suppress("UNCHECKED_CAST")
return i[0] as I
}
override operator fun invoke(state: S): I {
return memoizer.memoize(state, inputField)
}
override val equalityCheck: EqualityCheckFn
get() = byValEqualityCheck
override val memoizer: Memoizer<I> by lazy {
singleInputMemoizer(computeAndCount)
}
operator fun <I : Any> invoke(fn: S.() -> I): AbstractSelector<S, I> {
return withSingleField(fn)
}
}
}
| 0
| null |
3
| 34
|
a911759197a447baca7acbb88a9cbe5b3f5f010d
| 2,255
|
Kotlin-Bloc
|
Apache License 2.0
|
glance/glance-appwidget/integration-tests/demos/src/main/java/androidx/glance/appwidget/demos/ProgressIndicatorAppWidget.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 101448370, "Java": 64375670, "C++": 9133578, "AIDL": 605967, "Python": 310682, "Shell": 187759, "TypeScript": 40586, "HTML": 32277, "Groovy": 25622, "Svelte": 20307, "ANTLR": 19860, "CMake": 18003, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.glance.appwidget.demos
import android.content.Context
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.GlanceTheme
import androidx.glance.appwidget.CircularProgressIndicator
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.LinearProgressIndicator
import androidx.glance.appwidget.provideContent
import androidx.glance.background
import androidx.glance.color.ColorProvider
import androidx.glance.layout.Alignment
import androidx.glance.layout.Column
import androidx.glance.layout.Row
import androidx.glance.layout.Spacer
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.padding
import androidx.glance.layout.size
import androidx.glance.layout.width
import androidx.glance.material3.ColorProviders
import androidx.glance.unit.ColorProvider
class ProgressIndicatorAppWidget : GlanceAppWidget() {
override suspend fun provideGlance(
context: Context,
id: GlanceId
) = provideContent {
GlanceTheme(ProgressIndicatorDemoColorScheme.colors) {
Column(
modifier = GlanceModifier.fillMaxSize()
.background(R.color.default_widget_background),
verticalAlignment = Alignment.CenterVertically,
horizontalAlignment = Alignment.CenterHorizontally
) {
Row {
LinearProgressIndicatorsDemo(modifier = GlanceModifier.defaultWeight())
Spacer(modifier = GlanceModifier.width(10.dp))
CircularProgressIndicatorsDemo()
}
}
}
}
@Composable
private fun CircularProgressIndicatorsDemo(modifier: GlanceModifier = GlanceModifier) {
Column(modifier) {
CircularProgressIndicator()
Spacer(GlanceModifier.size(8.dp))
CircularProgressIndicator(
color = GlanceTheme.colors.primary
)
Spacer(GlanceModifier.size(8.dp))
CircularProgressIndicator(
color = ColorProvider(day = Color.White, night = Color.Red)
)
Spacer(GlanceModifier.size(8.dp))
CircularProgressIndicator(
color = ColorProvider(androidx.glance.R.color.glance_colorSecondary)
)
Spacer(GlanceModifier.size(8.dp))
CircularProgressIndicator(
color = ColorProvider(Color.Red)
)
}
}
@Composable
private fun LinearProgressIndicatorsDemo(modifier: GlanceModifier) {
Column(modifier) {
LinearProgressIndicator()
Spacer(GlanceModifier.size(8.dp))
LinearProgressIndicator(
progress = 0.5f,
color = GlanceTheme.colors.primary,
backgroundColor = GlanceTheme.colors.onBackground
)
Spacer(GlanceModifier.size(8.dp))
LinearProgressIndicator(
progress = .66f,
modifier = GlanceModifier.padding(bottom = 8.dp),
color = ColorProvider(androidx.glance.R.color.glance_colorError),
backgroundColor = ColorProvider(
resId = androidx.glance.R.color.glance_colorSecondary
)
)
Spacer(GlanceModifier.size(8.dp))
LinearProgressIndicator(
progress = .66f,
modifier = GlanceModifier.padding(bottom = 8.dp),
color = ColorProvider(day = Color.White, night = Color.Red),
backgroundColor = ColorProvider(day = Color.Red, night = Color.White)
)
Spacer(GlanceModifier.size(8.dp))
LinearProgressIndicator(progress = 0.8f, color = ColorProvider(Color.White))
}
}
}
class ProgressIndicatorAppWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = ProgressIndicatorAppWidget()
}
internal object ProgressIndicatorDemoColorScheme {
private val md_theme_light_primary = Color(0xFF026E00)
private val md_theme_light_onBackground = Color(0xFF1E1C00)
private val md_theme_dark_primary = Color(0xFF02E600)
private val md_theme_dark_onBackground = Color(0xFFF2E720)
private val LightColors = lightColorScheme(
primary = md_theme_light_primary,
onBackground = md_theme_light_onBackground,
)
private val DarkColors = darkColorScheme(
primary = md_theme_dark_primary,
onBackground = md_theme_dark_onBackground,
)
val colors = ColorProviders(light = LightColors, dark = DarkColors)
}
| 25
|
Kotlin
|
918
| 5,019
|
063c6938121b19f73d04517b1e7fdcb9e3309403
| 5,559
|
androidx
|
Apache License 2.0
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/utilities/VariableStuff.kt
|
notnotnerds
| 581,631,890
| false
|
{"Java": 195204, "Kotlin": 97441}
|
package org.firstinspires.ftc.teamcode.support
object VariableStuff {
const val clawOpenPos=.65
const val clawClosePos=.95
const val lowerArm=.7
const val levelArm=.55
const val raiseArm=0.0
const val liftHigh=4700
const val liftMid=2200
}
| 1
| null |
1
| 1
|
df51a7a3a495398a43977e575da77c6f43871b99
| 268
|
FtcRobotController
|
BSD 3-Clause Clear License
|
src/main/kotlin/com/ort/howlingwolf/api/controller/DebugController.kt
|
h-orito
| 176,481,255
| false
|
{"Kotlin": 820146, "HTML": 245777, "Batchfile": 522, "Shell": 454}
|
package com.ort.howlingwolf.api.controller
import com.ort.dbflute.exbhv.CharaBhv
import com.ort.dbflute.exbhv.PlayerBhv
import com.ort.dbflute.exbhv.VillageDayBhv
import com.ort.dbflute.exbhv.VillageSettingBhv
import com.ort.dbflute.exentity.Player
import com.ort.dbflute.exentity.VillageSetting
import com.ort.howlingwolf.api.body.AdminDummyLoginBody
import com.ort.howlingwolf.api.body.AdminParticipateBody
import com.ort.howlingwolf.api.view.debug.DebugVillageView
import com.ort.howlingwolf.application.coordinator.VillageCoordinator
import com.ort.howlingwolf.application.service.CharachipService
import com.ort.howlingwolf.application.service.PlayerService
import com.ort.howlingwolf.application.service.VillageService
import com.ort.howlingwolf.domain.model.charachip.Charas
import com.ort.howlingwolf.domain.model.player.Players
import com.ort.howlingwolf.domain.model.village.Village
import com.ort.howlingwolf.domain.model.village.participant.AccessInfo
import com.ort.howlingwolf.fw.HowlingWolfDateUtil
import com.ort.howlingwolf.fw.exception.HowlingWolfBusinessException
import com.ort.howlingwolf.fw.security.HowlingWolfUser
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
/**
* デバッグ用なのでDDDに拘らない
*/
@RestController
class DebugController(
val charaBhv: CharaBhv,
val playerBhv: PlayerBhv,
val villageDayBhv: VillageDayBhv,
val villageSettingBhv: VillageSettingBhv,
val villageCoordinator: VillageCoordinator,
val villageService: VillageService,
val charachipService: CharachipService,
val playerService: PlayerService
) {
// ===================================================================================
// Attribute
// =========
@Value("\${env: null}")
private var env: String? = null
// ===================================================================================
// Execute
// =========
/**
* 人数指定で参加させる
* @param villageId villageId
* @param user user
* @param body body
*/
@PostMapping("/admin/village/{villageId}/participate")
fun participateVillage(
@PathVariable("villageId") villageId: Int,
@AuthenticationPrincipal user: HowlingWolfUser,
@RequestBody @Validated body: AdminParticipateBody
) {
if ("local" != env) throw HowlingWolfBusinessException("この環境では使用できません")
val village = villageService.findVillage(villageId)
// 参戦していないキャラを人数分探す
val charaList = charaBhv.selectList { cb ->
cb.query().setCharaGroupId_Equal(village.setting.charachip.charachipId)
cb.query().notExistsVillagePlayer { villagePlayerCB ->
villagePlayerCB.query().setVillageId_Equal(villageId)
villagePlayerCB.query().setIsGone_Equal(false)
}
cb.fetchFirst(body.participateCount!!)
}
var playerId = 2
for (chara in charaList) {
// 希望役職をランダムに取得
val randomSkill = village.setting.organizations.allRequestableSkillList().shuffled().first()
val randomSkill2 = village.setting.organizations.allRequestableSkillList().shuffled().first()
// 入村
villageCoordinator.participate(
villageId = villageId,
playerId = playerId,
charaId = chara.charaId,
message = "テストアカウント入村 playerId: ${playerId}",
isSpectate = false,
firstRequestSkill = randomSkill.toCdef(),
secondRequestSkill = randomSkill2.toCdef(),
accessInfo = AccessInfo("test account $playerId", "test account $playerId")
)
playerId++
}
}
/**
* 指定村参加者IDでログインする
* @param villageId villageId
* @param user user
* @param body body
*/
@PostMapping("/admin/village/{villageId}/dummy-login")
fun dummyLogin(
@PathVariable("villageId") villageId: Int,
@AuthenticationPrincipal user: HowlingWolfUser,
@RequestBody @Validated body: AdminDummyLoginBody
) {
if ("local" != env) throw HowlingWolfBusinessException("この環境では使用できません")
// 現在接続しているユーザのuidと、指定されたプレイヤーのuidを入れ替える
val currentPlayer = playerBhv.selectEntityWithDeletedCheck {
it.query().setUid_Equal(user.uid)
}
val toPlayer = playerBhv.selectEntityWithDeletedCheck {
it.query().setPlayerId_Equal(body.targetId!!)
}
val current = currentPlayer.uid
val to = toPlayer.uid
updatePlayerUid(currentPlayer.playerId, "dummy_uid")
updatePlayerUid(toPlayer.playerId, current)
updatePlayerUid(currentPlayer.playerId, to)
}
/**
* 次の日へ
* @param villageId villageId
* @param user user
*/
@PostMapping("/admin/village/{villageId}/change-day")
fun changeDay(
@PathVariable("villageId") villageId: Int,
@AuthenticationPrincipal user: HowlingWolfUser
) {
if ("local" != env) throw HowlingWolfBusinessException("この環境では使用できません")
val latestDay = villageDayBhv.selectEntityWithDeletedCheck {
it.query().setVillageId_Equal(villageId)
it.query().addOrderBy_Day_Desc()
it.query().queryNoonnight().addOrderBy_DispOrder_Desc()
it.fetchFirst(1)
}
latestDay.daychangeDatetime = HowlingWolfDateUtil.currentLocalDateTime().minusSeconds(1L)
villageDayBhv.update(latestDay)
}
/**
* 村情報取得(役職やプレーヤーが全て見える状態)
* @param villageId villageId
*/
@GetMapping("/admin/village/{villageId}")
fun village(@PathVariable("villageId") villageId: Int): DebugVillageView {
if ("local" != env) throw HowlingWolfBusinessException("この環境では使用できません")
val village: Village = villageService.findVillage(villageId)
val charas: Charas = charachipService.findCharas(village.setting.charachip.charachipId)
val players: Players = playerService.findPlayers(villageId)
val createPlayer: com.ort.howlingwolf.domain.model.player.Player = playerService.findPlayer(village.creatorPlayerId)
return DebugVillageView(
village = village,
charas = charas,
players = players,
createPlayer = createPlayer
)
}
/**
* 突然死なしにする
* @param villageId villageId
* @param user user
*/
@PostMapping("/admin/village/{villageId}/no-suddenly-death")
fun setNoSuddenlyDeath(
@PathVariable("villageId") villageId: Int,
@AuthenticationPrincipal user: HowlingWolfUser
) {
if ("local" != env) throw HowlingWolfBusinessException("この環境では使用できません")
val setting = VillageSetting()
setting.villageId = villageId
setting.setVillageSettingItemCode_突然死ありか()
setting.villageSettingText = "0"
villageSettingBhv.update(setting)
}
@PostMapping("/admin/village/{villageId}/multiple-say")
fun multiSay(
@PathVariable("villageId") villageId: Int,
@AuthenticationPrincipal user: HowlingWolfUser
) {
if ("local" != env) throw HowlingWolfBusinessException("この環境では使用できません")
repeat(100) {
villageCoordinator.say(villageId, user, "${it}回目の発言", "NORMAL_SAY", "NORMAL")
}
}
// ===================================================================================
// Assist Logic
// ============
private fun updatePlayerUid(playerId: Int?, uid: String?) {
val p = Player()
p.playerId = playerId
p.uid = uid
playerBhv.update(p)
}
}
| 1
|
Kotlin
|
1
| 3
|
ec5db8e5323ea79f4a23648a33f8e81a71df96dc
| 8,476
|
wolf4busy-api
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/NoteAltTwoTone.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/NoteAltTwoTone")
package mui.icons.material
@JsName("default")
external val NoteAltTwoTone: SvgIconComponent
| 10
| null |
5
| 983
|
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
| 192
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/example/movieproject/ui/fragment/login/LoginFragment.kt
|
MehmetAkifUrgen
| 599,776,429
| false
| null |
@file:Suppress("DEPRECATION")
package com.example.movieproject.ui.fragment.login
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.movieproject.R
import com.example.movieproject.databinding.FragmentLoginBinding
import com.google.android.flexbox.*
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class LoginFragment : Fragment() {
private lateinit var binding: FragmentLoginBinding
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var auth: FirebaseAuth
private val RC_SIGN_IN = 9001
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
auth = Firebase.auth
Log.d("data", auth.currentUser?.displayName.toString())
if (auth.currentUser?.uid != null) {
findNavController().navigate(LoginFragmentDirections.actionLoginFragmentToHomeFragment())
} else {
}
binding = FragmentLoginBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
firebase()
onClick()
}
private fun onClick() {
binding.googleSignInButton.setOnClickListener {
signInWithGoogle()
}
}
private fun firebase() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(requireContext(), gso)
// Firebase Authentication nesnesini initialize et
auth = Firebase.auth
}
private fun signInWithGoogle() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Google hesabından dönen sonucu işle
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google hesabı doğrulandı, Firebase Authentication'a aktar
val account = task.getResult(ApiException::class.java)!!
firebaseAuthWithGoogle(account.idToken!!)
findNavController().navigate(LoginFragmentDirections.actionLoginFragmentToHomeFragment())
} catch (e: ApiException) {
// Google hesabı doğrulanamadı
Log.w("error", "Google sign in failed", e)
Toast.makeText(requireContext(), "Google sign in failed", Toast.LENGTH_SHORT).show()
}
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
// Giriş başarılı
val user = auth.currentUser
// TODO: Uygulama içinde kullanıcı verilerini kaydet
} else {
// Giriş hatası
Log.w("hata", "signInWithCredential:failure", task.exception)
// TODO: Kullanıcıya bir hata mesajı göster
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
21aef4a728dd55be96d10e7925bc97b2047aa9cb
| 4,219
|
MovieProject-Clean-Architecture-MVVM-Hilt-Flow-Tmdb-Paging3
|
MIT License
|
app/src/main/java/com/seeleo/mikuweather/viewmodel/WeatherViewModelFactory.kt
|
lzcapp
| 798,234,078
| false
|
{"Kotlin": 59595}
|
package com.seeleo.mikuweather.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.seeleo.mikuweather.repository.WeatherRepository
class WeatherViewModelFactory(private val weatherRepository: WeatherRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return if (modelClass.isAssignableFrom(WeatherViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
WeatherViewModel(this.weatherRepository) as T
} else {
throw IllegalArgumentException("ViewModel Not Found")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1ff9c869c4049cc067fedb7a60f9e124c3bd7196
| 637
|
MikuWeather_Android_CN
|
MIT License
|
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/requests/send/abstracts/SendMessageRequest.kt
|
InsanusMokrassar
| 163,152,024
| false
| null |
package dev.inmo.tgbotapi.requests.send.abstracts
import dev.inmo.tgbotapi.CommonAbstracts.types.*
interface SendMessageRequest<T: Any> : SendChatMessageRequest<T>, ReplyMessageId, DisableNotification, ProtectContent
| 18
|
Kotlin
|
9
| 126
|
007112e67a2e24076e3f5fb9db1e9cef5e5cdb46
| 219
|
TelegramBotAPI
|
Apache License 2.0
|
src/main/kotlin/bridgegame/api/Suit.kt
|
rajmahendra
| 800,019,948
| false
|
{"Kotlin": 5440}
|
package bridgegame.api
enum class Suit(private val symbol: String, val shortName: String) {
SPADE("♠\uFE0F","S"),
HEART("❤\uFE0F","H"),
DIAMOND("♦\uFE0F","D"),
CLUB("♣\uFE0F","C");
override fun toString(): String {
return shortName
}
companion object {
val values = enumValues<Suit>()
}
}
| 0
|
Kotlin
|
0
| 0
|
562f5ea39e189a0026e4520282f7a0537a849b7d
| 339
|
bridge-game
|
Apache License 2.0
|
source-code/starter-project/BookHaven/app/src/main/java/com/droidcon/bookhaven/ui/book/detail/BookDetailScreen.kt
|
droidcon-academy
| 840,180,197
| false
|
{"Kotlin": 130227}
|
package com.droidcon.bookhaven.ui.book.detail
import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.droidcon.bookhaven.R
import kotlinx.coroutines.launch
@Composable
fun BookDetailScreen(
bookId: Int,
viewmodel: BookDetailViewmodel,
navigateBack: () -> Unit,
modifier: Modifier = Modifier,
) {
val coroutineScope = rememberCoroutineScope()
val state by viewmodel.state.collectAsStateWithLifecycle()
val effect by viewmodel.effect.collectAsStateWithLifecycle(initialValue = BookDetailEffect.None)
val context = LocalContext.current
LaunchedEffect(effect) {
when (effect) {
BookDetailEffect.NavigateBack -> {
navigateBack()
viewmodel.onEffectHandled()
}
BookDetailEffect.ShowInvalidBookToast -> {
Toast
.makeText(
context,
R.string.invalid_book_prompt,
Toast.LENGTH_SHORT,
).show()
viewmodel.onEffectHandled()
}
BookDetailEffect.None -> Unit
}
}
BookDetailContent(
bookId = bookId,
state = state,
modifier = modifier,
) { action ->
coroutineScope.launch { viewmodel.userActions.send(action) }
}
}
| 0
|
Kotlin
|
0
| 1
|
982e1ef98477674ed47409a0ef49ce63a4ab96f1
| 1,654
|
android-mc-testing-fundamentals
|
Apache License 2.0
|
ktor-backend/daily-attendance/src/main/kotlin/com/steiner/workbench/daily_attendance/model/KeepDays.kt
|
nesteiner
| 693,014,583
| false
|
{"Kotlin": 366481, "Dart": 247737, "C++": 24228, "CMake": 19460, "HTML": 1843, "C": 1425}
|
package com.steiner.workbench.daily_attendance.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
sealed class KeepDays {
@Serializable
@SerialName("forever")
object Forever: KeepDays()
@Serializable
@SerialName("manual")
class Manual(val days: Int): KeepDays()
}
| 1
|
Kotlin
|
0
| 0
|
e0fe7a0f9aca965bc74736f1364153a695597bfe
| 342
|
Workbench
|
MIT License
|
src/main/java/org/github/otanikotani/workflow/ui/GitHubWorkflowRunLogConsole.kt
|
Otanikotani
| 235,634,673
| false
| null |
package org.github.otanikotani.workflow.ui
import com.intellij.execution.impl.ConsoleViewImpl
import com.intellij.execution.process.AnsiEscapeDecoder
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import org.jetbrains.plugins.github.ui.util.SingleValueModel
class GitHubWorkflowRunLogConsole(project: Project,
logModel: SingleValueModel<String?>,
disposable: Disposable) : ConsoleViewImpl(project, true), AnsiEscapeDecoder.ColoredTextAcceptor {
init {
val myTextAnsiEscapeDecoder = AnsiEscapeDecoder()
logModel.addValueChangedListener {
this.clear()
if (!logModel.value.isNullOrBlank()) {
myTextAnsiEscapeDecoder.escapeText(logModel.value!!, ProcessOutputTypes.STDOUT, this)
}
}
Disposer.register(disposable, Disposable {
Disposer.dispose(this)
})
}
override fun coloredTextAvailable(text: String, attributes: Key<*>) {
this.print(text, ConsoleViewContentType.getConsoleViewType(attributes))
}
}
| 13
| null |
9
| 25
|
70401ba7eda37a9fc3bc58b1ede8dec9ce5de52e
| 1,325
|
view-github-actions-idea-plugin
|
MIT License
|
app/src/main/java/com/kylecorry/trail_sense/shared/views/chart/label/HourChartLabelFormatter.kt
|
kylecorry31
| 215,154,276
| false
| null |
package com.kylecorry.trail_sense.shared.views.chart.label
import android.content.Context
import com.kylecorry.ceres.chart.label.ChartLabelFormatter
import com.kylecorry.sol.time.Time
import com.kylecorry.sol.time.Time.toZonedDateTime
import com.kylecorry.trail_sense.shared.FormatService
import java.time.Instant
import java.time.LocalTime
class HourChartLabelFormatter(
context: Context,
private val getStartTime: () -> Instant
) : ChartLabelFormatter {
private val formatter = FormatService.getInstance(context)
override fun format(value: Float): String {
val duration = Time.hours(value.toDouble())
val time = getStartTime().plus(duration)
val local = time.toZonedDateTime().toLocalTime()
val hour = if (local.minute >= 30) {
local.hour + 1
} else {
local.hour
}
return formatter.formatTime(
LocalTime.of(hour % 24, 0),
includeSeconds = false,
includeMinutes = false
)
}
}
| 456
| null |
66
| 989
|
41176d17b498b2dcecbbe808fbe2ac638e90d104
| 1,025
|
Trail-Sense
|
MIT License
|
coil-base/src/test/java/coil/intercept/EngineInterceptorTest.kt
|
ianhanniballake
| 384,854,300
| false
| null |
package coil.interceptor
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import androidx.test.core.app.ApplicationProvider
import coil.ComponentRegistry
import coil.EventListener
import coil.ImageLoader
import coil.RealImageLoader
import coil.annotation.ExperimentalCoilApi
import coil.bitmappool.BitmapPool
import coil.decode.DataSource
import coil.decode.DrawableDecoderService
import coil.decode.Options
import coil.fetch.DrawableResult
import coil.fetch.Fetcher
import coil.memory.BitmapReferenceCounter
import coil.memory.MemoryCache.Key
import coil.memory.RealMemoryCache
import coil.memory.RealWeakMemoryCache
import coil.memory.RequestService
import coil.memory.StrongMemoryCache
import coil.request.ImageRequest
import coil.request.Parameters
import coil.size.OriginalSize
import coil.size.PixelSize
import coil.size.Precision
import coil.size.Scale
import coil.size.Size
import coil.transform.CircleCropTransformation
import coil.transform.Transformation
import coil.util.SystemCallbacks
import coil.util.createBitmap
import coil.util.createOptions
import coil.util.createRequest
import coil.util.invoke
import coil.util.size
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlin.test.fail
@RunWith(RobolectricTestRunner::class)
@OptIn(ExperimentalCoilApi::class)
class EngineInterceptorTest {
private lateinit var context: Context
private lateinit var strongMemoryCache: StrongMemoryCache
private lateinit var interceptor: EngineInterceptor
@Before
fun before() {
context = ApplicationProvider.getApplicationContext()
val bitmapPool = BitmapPool(Int.MAX_VALUE)
val weakMemoryCache = RealWeakMemoryCache(null)
val referenceCounter = BitmapReferenceCounter(weakMemoryCache, bitmapPool, null)
strongMemoryCache = StrongMemoryCache(weakMemoryCache, referenceCounter, Int.MAX_VALUE, null)
interceptor = EngineInterceptor(
registry = ComponentRegistry(),
bitmapPool = bitmapPool,
strongMemoryCache = strongMemoryCache,
weakMemoryCache = weakMemoryCache,
requestService = RequestService(null),
systemCallbacks = SystemCallbacks(ImageLoader(context) as RealImageLoader, context),
drawableDecoder = DrawableDecoderService(bitmapPool),
logger = null
)
}
@Test
fun `computeKey - null key`() {
val request = createRequest(context)
val fetcher = createFakeFetcher(key = null)
val size = OriginalSize
val key = runBlocking {
interceptor.computeKey(request, Unit, fetcher, size)
}
assertNull(key)
}
@Test
fun `computeKey - simple key`() {
val request = createRequest(context)
val fetcher = createFakeFetcher()
val size = OriginalSize
val result = runBlocking {
interceptor.computeKey(request, Unit, fetcher, size)
}
assertEquals(Key("base_key", Parameters.EMPTY), result)
}
@Test
fun `computeKey - params only`() {
val parameters = createFakeParameters()
val request = createRequest(context) {
parameters(parameters)
}
val fetcher = createFakeFetcher()
val size = OriginalSize
val result = runBlocking {
interceptor.computeKey(request, Unit, fetcher, size)
}
assertEquals(Key("base_key", parameters), result)
}
@Test
fun `computeKey - transformations only`() {
val transformations = createFakeTransformations()
val request = createRequest(context) {
transformations(transformations)
}
val fetcher = createFakeFetcher()
val size = PixelSize(123, 332)
val result = runBlocking {
interceptor.computeKey(request, Unit, fetcher, size)
}
assertEquals(Key("base_key", transformations, size, Parameters.EMPTY), result)
}
@Test
fun `computeKey - complex key`() {
val parameters = createFakeParameters()
val transformations = createFakeTransformations()
val request = createRequest(context) {
parameters(parameters)
transformations(transformations)
}
val fetcher = createFakeFetcher()
val size = OriginalSize
val result = runBlocking {
interceptor.computeKey(request, Unit, fetcher, size)
}
assertEquals(Key("base_key", transformations, size, parameters), result)
}
@Test
fun `isCachedValueValid - fill`() {
val request = createRequest(context) {
size(100, 100)
precision(Precision.INEXACT)
scale(Scale.FILL)
}
val cached = createBitmap()
assertFalse(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(200, 200)
))
assertFalse(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(150, 50)
))
assertTrue(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(100, 100)
))
assertTrue(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(50, 100)
))
assertTrue(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(50, 50)
))
assertTrue(interceptor.isCachedValueValid(
cached = createBitmap(width = 400, height = 200),
isSampled = true,
request = request,
size = PixelSize(400, 200)
))
}
@Test
fun `isCachedValueValid - fit`() {
val request = createRequest(context) {
size(100, 100)
precision(Precision.INEXACT)
scale(Scale.FIT)
}
val cached = createBitmap()
assertFalse(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(200, 200)
))
assertTrue(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(150, 50)
))
assertTrue(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(100, 100)
))
assertTrue(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(50, 100)
))
assertTrue(interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = request,
size = PixelSize(50, 50)
))
assertFalse(interceptor.isCachedValueValid(
cached = createBitmap(width = 200, height = 400),
isSampled = true,
request = request,
size = PixelSize(400, 800)
))
}
@Test
fun `isCachedValueValid - small not sampled cached drawable is valid`() {
val cached = createBitmap()
val isValid = interceptor.isCachedValueValid(
cached = cached,
isSampled = false,
request = createRequest(context) {
precision(Precision.INEXACT)
scale(Scale.FILL)
},
size = PixelSize(200, 200)
)
assertTrue(isValid)
}
@Test
fun `isCachedValueValid - allowHardware=false prevents using cached hardware bitmap`() {
fun isBitmapConfigValid(config: Bitmap.Config): Boolean {
val cached = createBitmap(config = config)
return interceptor.isCachedValueValid(
cached = cached,
isSampled = true,
request = createRequest(context) {
allowHardware(false)
scale(Scale.FILL)
},
size = PixelSize(100, 100)
)
}
assertFalse(isBitmapConfigValid(Bitmap.Config.HARDWARE))
assertTrue(isBitmapConfigValid(Bitmap.Config.RGBA_F16))
assertTrue(isBitmapConfigValid(Bitmap.Config.ARGB_8888))
assertTrue(isBitmapConfigValid(Bitmap.Config.RGB_565))
}
@Test
fun `isCachedValueValid - exact precision`() {
assertFalse(interceptor.isCachedValueValid(
cached = createBitmap(width = 100, height = 100),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FILL)
},
size = PixelSize(50, 50)
))
assertFalse(interceptor.isCachedValueValid(
cached = createBitmap(width = 100, height = 100),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FIT)
},
size = PixelSize(50, 50)
))
assertTrue(interceptor.isCachedValueValid(
cached = createBitmap(width = 100, height = 100),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FILL)
},
size = PixelSize(100, 50)
))
assertFalse(interceptor.isCachedValueValid(
cached = createBitmap(width = 100, height = 100),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FIT)
},
size = PixelSize(100, 50)
))
assertTrue(interceptor.isCachedValueValid(
cached = createBitmap(width = 100, height = 100),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FILL)
},
size = PixelSize(100, 100)
))
assertTrue(interceptor.isCachedValueValid(
cached = createBitmap(width = 100, height = 100),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FIT)
},
size = PixelSize(100, 100)
))
assertTrue(interceptor.isCachedValueValid(
cached = createBitmap(width = 400, height = 200),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FILL)
},
size = PixelSize(400, 200)
))
assertFalse(interceptor.isCachedValueValid(
cached = createBitmap(width = 200, height = 400),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FIT)
},
size = PixelSize(400, 800)
))
}
@Test
fun `isCachedValueValid - one pixel off`() {
assertTrue(interceptor.isCachedValueValid(
cached = createBitmap(width = 244, height = 600),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FIT)
},
size = PixelSize(245, 600)
))
assertTrue(interceptor.isCachedValueValid(
cached = createBitmap(width = 244, height = 600),
isSampled = true,
request = createRequest(context) {
precision(Precision.INEXACT)
scale(Scale.FIT)
},
size = PixelSize(245, 600)
))
assertFalse(interceptor.isCachedValueValid(
cached = createBitmap(width = 243, height = 599),
isSampled = true,
request = createRequest(context) {
precision(Precision.EXACT)
scale(Scale.FIT)
},
size = PixelSize(245, 600)
))
assertFalse(interceptor.isCachedValueValid(
cached = createBitmap(width = 243, height = 599),
isSampled = true,
request = createRequest(context) {
precision(Precision.INEXACT)
scale(Scale.FIT)
},
size = PixelSize(245, 600)
))
}
@Test
fun `isCachedValueValid - transformation that reduces size of output bitmap`() {
val transformations = listOf(CircleCropTransformation())
val cachedSize = PixelSize(1000, 500) // The size of the previous request.
val key = Key("key", transformations, cachedSize, Parameters.EMPTY)
val value = object : RealMemoryCache.Value {
override val bitmap = createBitmap(width = 200, height = 200) // The small cached bitmap.
override val isSampled = true
}
val request = createRequest(context)
assertTrue(interceptor.isCachedValueValid(
cacheKey = key,
cacheValue = value,
request = request.newBuilder().precision(Precision.INEXACT).scale(Scale.FIT).build(),
size = PixelSize(650, 400)
))
assertTrue(interceptor.isCachedValueValid(
cacheKey = key,
cacheValue = value,
request = request.newBuilder().precision(Precision.EXACT).scale(Scale.FIT).build(),
size = PixelSize(1000, 500)
))
assertFalse(interceptor.isCachedValueValid(
cacheKey = key,
cacheValue = value,
request = request.newBuilder().precision(Precision.INEXACT).scale(Scale.FIT).build(),
size = PixelSize(1500, 1000)
))
assertFalse(interceptor.isCachedValueValid(
cacheKey = key,
cacheValue = value,
request = request.newBuilder().precision(Precision.EXACT).scale(Scale.FIT).build(),
size = PixelSize(800, 500)
))
}
private fun EngineInterceptor.isCachedValueValid(
cached: Bitmap,
isSampled: Boolean,
request: ImageRequest,
size: Size
): Boolean {
val key = Key("key")
val value = object : RealMemoryCache.Value {
override val bitmap = cached
override val isSampled = isSampled
}
return isCachedValueValid(key, value, request, size)
}
@Test
fun `applyTransformations - transformations convert drawable to bitmap`() {
val drawable = ColorDrawable(Color.BLACK)
val size = PixelSize(100, 100)
val result = runBlocking {
interceptor.applyTransformations(
result = DrawableResult(
drawable = drawable,
isSampled = false,
dataSource = DataSource.MEMORY
),
request = createRequest(context) { transformations(CircleCropTransformation()) },
size = size,
options = createOptions(),
eventListener = EventListener.NONE
)
}
val resultDrawable = result.drawable
assertTrue(resultDrawable is BitmapDrawable)
assertEquals(resultDrawable.bitmap.size, size)
}
@Test
fun `applyTransformations - empty transformations does not convert drawable to bitmap`() {
val drawable = ColorDrawable(Color.BLACK)
val size = PixelSize(100, 100)
val result = runBlocking {
interceptor.applyTransformations(
result = DrawableResult(
drawable = drawable,
isSampled = false,
dataSource = DataSource.MEMORY
),
request = createRequest(context) { transformations(emptyList()) },
size = size,
options = createOptions(),
eventListener = EventListener.NONE
)
}
assertSame(drawable, result.drawable)
}
private fun createFakeTransformations(): List<Transformation> {
return listOf(
object : Transformation {
override fun key() = "key1"
override suspend fun transform(pool: BitmapPool, input: Bitmap, size: Size) = fail()
},
object : Transformation {
override fun key() = "key2"
override suspend fun transform(pool: BitmapPool, input: Bitmap, size: Size) = fail()
}
)
}
private fun createFakeParameters(): Parameters {
return Parameters.Builder()
.set("key1", "no_cache", cacheKey = null)
.set("key2", "cached2")
.set("key3", "cached3")
.build()
}
private fun createFakeFetcher(key: String? = "base_key"): Fetcher<Any> {
return object : Fetcher<Any> {
override fun key(data: Any) = key
override suspend fun fetch(
pool: BitmapPool,
data: Any,
size: Size,
options: Options
) = fail()
}
}
}
| 0
| null |
0
| 1
|
f152e172dbfe6b9c231967242f16dc63fda422e8
| 17,927
|
coil
|
Apache License 2.0
|
app/src/main/java/org/tokend/template/fragments/BaseFragment.kt
|
tokend
| 192,905,357
| false
| null |
package org.tokend.template.fragments
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import io.reactivex.disposables.CompositeDisposable
import org.tokend.template.App
import org.tokend.template.activities.OnBackPressedListener
import org.tokend.template.di.providers.*
import org.tokend.template.features.assets.model.Asset
import org.tokend.template.features.balances.model.BalanceRecord
import org.tokend.template.features.kyc.storage.ActiveKycPersistence
import org.tokend.template.features.signin.logic.PostSignInManagerFactory
import org.tokend.template.features.tfa.logic.AppTfaCallback
import org.tokend.template.logic.Session
import org.tokend.template.logic.credentials.persistence.CredentialsPersistence
import org.tokend.template.logic.credentials.persistence.WalletInfoPersistence
import org.tokend.template.logic.persistence.BackgroundLockManager
import org.tokend.template.util.errorhandler.ErrorHandlerFactory
import org.tokend.template.util.navigation.ActivityRequest
import org.tokend.template.view.ToastManager
import org.tokend.template.view.util.formatter.AmountFormatter
import javax.inject.Inject
abstract class BaseFragment : Fragment(), OnBackPressedListener {
@Inject
lateinit var appTfaCallback: AppTfaCallback
@Inject
lateinit var accountProvider: AccountProvider
@Inject
lateinit var apiProvider: ApiProvider
@Inject
lateinit var walletInfoProvider: WalletInfoProvider
@Inject
lateinit var repositoryProvider: RepositoryProvider
@Inject
lateinit var urlConfigProvider: UrlConfigProvider
@Inject
lateinit var errorHandlerFactory: ErrorHandlerFactory
@Inject
lateinit var toastManager: ToastManager
@Inject
lateinit var assetCodeComparator: Comparator<String>
@Inject
lateinit var assetComparator: Comparator<Asset>
@Inject
lateinit var balanceComparator: Comparator<BalanceRecord>
@Inject
lateinit var amountFormatter: AmountFormatter
@Inject
lateinit var session: Session
@Inject
lateinit var credentialsPersistence: CredentialsPersistence
@Inject
lateinit var walletInfoPersistence: WalletInfoPersistence
@Inject
lateinit var activeKycPersistence: ActiveKycPersistence
@Inject
lateinit var backgroundLockManager: BackgroundLockManager
@Inject
lateinit var postSignInManagerFactory: PostSignInManagerFactory
override fun onBackPressed() = true
/**
* Disposable holder which will be disposed on fragment destroy
*/
protected lateinit var compositeDisposable: CompositeDisposable
protected val activityRequestsBag: MutableCollection<ActivityRequest<*>> = mutableSetOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity?.application as? App)?.stateComponent?.inject(this)
compositeDisposable = CompositeDisposable()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (savedInstanceState == null) {
onInitAllowed()
}
}
override fun onDestroyView() {
super.onDestroyView()
compositeDisposable.dispose()
compositeDisposable = CompositeDisposable()
}
/**
* You must implement your fragment initialization here
*/
abstract fun onInitAllowed()
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
activityRequestsBag.forEach { request ->
request.handleActivityResult(requestCode, resultCode, data)
}
activityRequestsBag.iterator().also { iterator ->
while (iterator.hasNext()) {
val request = iterator.next()
if (request.isCompleted) {
iterator.remove()
}
}
}
}
}
| 1
| null |
1
| 6
|
05bb971859713830a9c229206dc9f525ce80f754
| 4,016
|
conto-android-client
|
Apache License 2.0
|
emoji/src/main/java/chat/rocket/android/emoji/EmojiParser.kt
|
RocketChat
| 48,179,404
| false
| null |
package chat.rocket.android.emoji
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ImageSpan
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.RequestOptions
import timber.log.Timber
class EmojiParser {
companion object {
private val regex = ":[\\w]+:".toRegex()
/**
* Parses a text string containing unicode characters and/or shortnames to a rendered
* Spannable.
*
* @param text The text to parse
* @param factory Optional. A [Spannable.Factory] instance to reuse when creating [Spannable].
* @return A rendered Spannable containing any supported emoji.
*/
fun parse(
context: Context,
text: CharSequence,
factory: Spannable.Factory? = null
): CharSequence {
val unicodedText = EmojiRepository.shortnameToUnicode(text)
val spannable = factory?.newSpannable(unicodedText)
?: SpannableString.valueOf(unicodedText)
val typeface = try {
EmojiRepository.cachedTypeface
} catch (ex: UninitializedPropertyAccessException) {
// swallow this exception and create typeface now
Typeface.createFromAsset(context.assets, "fonts/emojione-android.ttf")
}
// Look for groups of emojis, set a EmojiTypefaceSpan with the emojione font.
val length = spannable.length
var inEmoji = false
var emojiStart = 0
var offset = 0
while (offset < length) {
val codepoint = unicodedText.codePointAt(offset)
val count = Character.charCount(codepoint)
// Skip control characters.
if (codepoint == 0x2028) {
offset += count
continue
}
if (codepoint >= 0x200) {
if (!inEmoji) {
emojiStart = offset
}
inEmoji = true
} else {
if (inEmoji) {
spannable.setSpan(
EmojiTypefaceSpan("sans-serif", typeface),
emojiStart, offset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
inEmoji = false
}
offset += count
if (offset >= length && inEmoji) {
spannable.setSpan(
EmojiTypefaceSpan("sans-serif", typeface),
emojiStart, offset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
val customEmojis = EmojiRepository.getCustomEmojis()
val px = context.resources.getDimensionPixelSize(R.dimen.custom_emoji_small)
return spannable.also { sp ->
regex.findAll(spannable).iterator().forEach { match ->
customEmojis.find { matchEmoji(it, match.value) }?.let { emoji ->
emoji.url?.let { url ->
try {
val glideRequest = if (url.endsWith("gif", true)) {
Glide.with(context).asGif()
} else {
Glide.with(context).asBitmap()
}
val futureTarget = glideRequest
.load(url)
.apply(RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL))
.submit(px, px)
val range = match.range
futureTarget.get()?.let { image ->
if (image is Bitmap) {
spannable.setSpan(
ImageSpan(context, image), range.start,
range.endInclusive + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
} else if (image is GifDrawable) {
image.setBounds(
0,
0,
image.intrinsicWidth,
image.intrinsicHeight
)
spannable.setSpan(
ImageSpan(image), range.start,
range.endInclusive + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
} catch (ex: Throwable) {
Timber.e(ex)
}
}
}
}
}
}
private fun matchEmoji(it: Emoji, text: String): Boolean {
if (it.shortname == text) {
return true
} else {
it.shortnameAlternates.forEach {
if (":$it:" == text) {
return true
}
}
return false
}
}
}
}
| 283
|
Kotlin
|
585
| 877
|
f832d59cb2130e5c058f5d9e9de5ff961d5d3380
| 5,827
|
Rocket.Chat.Android
|
MIT License
|
src/test/kotlin/rocks/frieler/android/release/gradle/PrepareNextDevelopmentVersionTest.kt
|
christopherfrieler
| 347,635,688
| false
| null |
package rocks.frieler.android.release.gradle
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.gradle.api.internal.GradleInternal
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.internal.project.taskfactory.TaskIdentity
import org.gradle.api.model.ObjectFactory
import org.gradle.internal.service.ServiceRegistry
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.io.File
import java.nio.file.Files
internal class PrepareNextDevelopmentVersionTest {
private val project: ProjectInternal = mock()
private lateinit var prepareNextDevelopmentVersionTask: PrepareNextDevelopmentVersion
@BeforeEach
fun initTaskWithMockedProject() {
val mockGradleInvocation = mock<GradleInternal>()
val mockServiceregistry = mock<ServiceRegistry>()
whenever(project.services).thenReturn(mockServiceregistry)
whenever(project.gradle).thenReturn(mockGradleInvocation)
val mockObjectFactory = mock<ObjectFactory>()
whenever(project.objects).thenReturn(mockObjectFactory)
@Suppress("DEPRECATION")
prepareNextDevelopmentVersionTask = org.gradle.api.internal.AbstractTask.injectIntoNewInstance(
project,
TaskIdentity.create("prepareNextDevelopmentVersion", PrepareNextDevelopmentVersion::class.java, project)
) {
PrepareNextDevelopmentVersion()
}
prepareNextDevelopmentVersionTask.scmRepository = mock()
}
@Test
internal fun `prepareNextDevelopmentVersion prepares next minor SNAPSHOT version and versioncode, clears the changelog and commits it all`() {
whenever(prepareNextDevelopmentVersionTask.scmRepository.getCurrentBranch()).thenReturn("master")
whenever(prepareNextDevelopmentVersionTask.scmRepository.hasLocalChanges()).thenReturn(false)
val testRootBuildFile = prepareTestBuildFile("1.0.0_build.gradle.kts")
whenever(project.file("./build.gradle.kts")).thenReturn(testRootBuildFile)
val testAppBuildFile = prepareTestBuildFile("versionCode_1_android_build.gradle.kts")
whenever(project.file("app/build.gradle.kts")).thenReturn(testAppBuildFile)
val testChangelogFile = Files.createTempFile("changelog", "txt").toFile().apply {
writeText("There was a change.${System.lineSeparator()}")
}
whenever(project.file("app/src/main/play/release-notes/de-DE/default.txt")).thenReturn(testChangelogFile)
prepareNextDevelopmentVersionTask.prepareNextDevelopmentVersion()
assert(testRootBuildFile.readText().contains("version = \"1.1.0-SNAPSHOT\"${System.lineSeparator()}"))
assert(testAppBuildFile.readText().contains("versionCode = 2${System.lineSeparator()}"))
assert(testChangelogFile.readText() == "")
verify(prepareNextDevelopmentVersionTask.scmRepository).commitAllChanges("prepare 1.1.0-SNAPSHOT")
}
@Test
internal fun `prepareNextDevelopmentVersionTask fails when executed on another branch than master`() {
whenever(prepareNextDevelopmentVersionTask.scmRepository.getCurrentBranch()).thenReturn("not-master")
assertThrows<IllegalStateException> {
prepareNextDevelopmentVersionTask.prepareNextDevelopmentVersion()
}
}
@Test
internal fun `prepareNextDevelopmentVersionTask fails when there are local changes`() {
whenever(prepareNextDevelopmentVersionTask.scmRepository.getCurrentBranch()).thenReturn("master")
whenever(prepareNextDevelopmentVersionTask.scmRepository.hasLocalChanges()).thenReturn(true)
assertThrows<IllegalStateException> {
prepareNextDevelopmentVersionTask.prepareNextDevelopmentVersion()
}
}
@Test
fun `prepareNextDevelopmentVersion fails when current version is already a SNAPSHOT`() {
whenever(prepareNextDevelopmentVersionTask.scmRepository.getCurrentBranch()).thenReturn("master")
whenever(prepareNextDevelopmentVersionTask.scmRepository.hasLocalChanges()).thenReturn(false)
val testBuildFile = prepareTestBuildFile("1.0.0-SNAPSHOT_build.gradle.kts")
whenever(project.file("./build.gradle.kts")).thenReturn(testBuildFile)
val illegalStateException = assertThrows<java.lang.IllegalStateException> {
prepareNextDevelopmentVersionTask.prepareNextDevelopmentVersion()
}
assert(illegalStateException.message == "current version '1.0.0-SNAPSHOT' does not match pattern <major>.<minor>.<fix>!")
}
@Test
fun `prepareNextDevelopmentVersion fails when there is no version specification`() {
whenever(prepareNextDevelopmentVersionTask.scmRepository.getCurrentBranch()).thenReturn("master")
whenever(prepareNextDevelopmentVersionTask.scmRepository.hasLocalChanges()).thenReturn(false)
val testBuildFile = prepareTestBuildFile("no_version_build.gradle.kts")
whenever(project.file("./build.gradle.kts")).thenReturn(testBuildFile)
val illegalStateException = assertThrows<java.lang.IllegalStateException> {
prepareNextDevelopmentVersionTask.prepareNextDevelopmentVersion()
}
assert(illegalStateException.message == "no version specification found!")
}
private fun prepareTestBuildFile(buildFile: String): File {
return Files.createTempFile("build", "gradle.kts").toFile().apply {
val testBuildFile = File(this@PrepareNextDevelopmentVersionTest.javaClass.getResource("/test-gradle-files/$buildFile").toURI())
testBuildFile.copyTo(this, overwrite = true)
}
}
}
| 0
|
Kotlin
|
0
| 2
|
fe914bac032f8fc0bb39f65b424f11e5d67238ff
| 5,747
|
android-release-gradle-plugin
|
MIT License
|
src/main/java/com/dzen/campfire/api/requests/rubrics/RRubricsModerChangeName.kt
|
ZeonXX
| 381,983,751
| false
|
{"Kotlin": 1087578}
|
package com.dzen.campfire.api.requests.rubrics
import com.dzen.campfire.api.tools.client.Request
import com.sup.dev.java.libs.json.Json
open class RRubricsModerChangeName(
var rubricId: Long,
var newName: String,
var comment: String
) : Request<RRubricsModerChangeName.Response>() {
override fun jsonSub(inp: Boolean, json: Json) {
rubricId = json.m(inp, "rubricId", rubricId)
newName = json.m(inp, "newName", newName)
comment = json.m(inp, "comment", comment)
}
override fun instanceResponse(json: Json): Response {
return Response(json)
}
class Response : Request.Response {
constructor(json: Json) {
json(false, json)
}
constructor() {
}
override fun json(inp: Boolean, json: Json) {
}
}
}
| 0
|
Kotlin
|
2
| 5
|
6f3b371624fb66a065bcbaa6302830c574c55e9f
| 842
|
CampfireApi
|
Apache License 2.0
|
src/commonMain/kotlin/net/kyori/adventure/webui/websocket/Packet.kt
|
KyoriPowered
| 390,772,083
| false
| null |
package net.kyori.adventure.webui.websocket
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
/** The client -> server call. */
public sealed interface Packet
@Serializable
@SerialName("call")
public data class Call(public val miniMessage: String? = null) : Packet
@Serializable
@SerialName("placeholders")
public data class Placeholders(
public val stringPlaceholders: Map<String, String>? = null,
public val componentPlaceholders: Map<String, JsonObject>? = null,
public val miniMessagePlaceholders: Map<String, String>? = null
) : Packet
@Serializable
public data class Combined(
public val miniMessage: String? = null,
public val placeholders: Placeholders? = null
)
| 22
|
Kotlin
|
4
| 8
|
96e161a8975f506dfa6c60e65114e2810d813a05
| 773
|
adventure-webui
|
MIT License
|
oldAndroidProjects/untracked/Pratice3/PraticeProjects/Khaata/app/src/main/java/com/shivathapa/khaata/KhaataApplication.kt
|
shivathapaa
| 800,628,391
| false
|
{"Kotlin": 3353288, "Shell": 2341}
|
package com.shivathapa.khaata
import android.app.Application
import com.shivathapa.khaata.data.AppContainer
import com.shivathapa.khaata.data.AppDataContainer
class KhaataApplication : Application() {
lateinit var container: AppContainer
override fun onCreate() {
super.onCreate()
container = AppDataContainer(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
442ac0be8d0d619e9abf6abb62249a06c1cd4320
| 350
|
Android-Practice-Projects
|
The Unlicense
|
integration-tests/kotlin-dsl/src/main/resources/routes/routes-with-error-handler.kts
|
apache
| 193,065,376
| false
|
{"Java": 9211773, "Groovy": 57009, "Mustache": 48429, "XSLT": 25367, "Kotlin": 16697, "JavaScript": 14832, "Shell": 11110, "Tcl": 5013, "Rust": 3839, "FreeMarker": 2706, "PLpgSQL": 2094, "HTML": 909, "XQuery": 271, "Ruby": 88}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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 zipkin2.server.internal.cassandra3
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
import org.springframework.context.annotation.AnnotationConfigApplicationContext
/** opens package access for testing */
object Access {
fun registerCassandra3(context: AnnotationConfigApplicationContext) = context.register(
PropertyPlaceholderAutoConfiguration::class.java,
ZipkinCassandra3StorageConfiguration::class.java)
}
| 349
|
Java
|
188
| 254
|
13f2b16ab81ae58ebcb34a0ba17120f73b57ff59
| 1,276
|
camel-quarkus
|
Apache License 2.0
|
CleanArchitectureExample/presentation/src/main/java/com/binhnk/clean/architecture/util/Utils.kt
|
binhnk-1899
| 189,147,136
| false
| null |
package com.binhnk.clean.architecture.util
import android.content.Context
import android.widget.Toast
class Utils {
companion object {
fun shortToast(mContext: Context, message:String) {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show()
}
}
}
| 1
| null |
1
| 1
|
d0205e1f3c7aa7ec92c0ee9aa8bb31fb2ae21ca4
| 292
|
CleanArchitectureExample
|
Apache License 2.0
|
model-client/src/jvmMain/kotlin/org/modelix/model/client/ReplicatedRepository.kt
|
modelix
| 533,211,353
| false
| null |
/*
* 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.modelix.model.client
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import org.apache.commons.lang3.mutable.MutableObject
import org.modelix.model.VersionMerger
import org.modelix.model.api.*
import org.modelix.model.client.SharedExecutors.fixDelay
import org.modelix.model.lazy.BranchReference
import org.modelix.model.lazy.CLTree
import org.modelix.model.lazy.CLVersion
import org.modelix.model.lazy.CLVersion.Companion.loadFromHash
import org.modelix.model.lazy.RepositoryId
import org.modelix.model.metameta.MetaModelBranch
import org.modelix.model.operations.IAppliedOperation
import org.modelix.model.operations.IOperation
import org.modelix.model.operations.OTBranch
import java.time.LocalDateTime
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Supplier
/**
* Dispose should be called on this, as otherwise a regular polling will go on.
*/
actual open class ReplicatedRepository actual constructor(
private val client: IModelClient,
private val branchReference: BranchReference,
private val user: () -> String
) {
private val localBranch: IBranch
private val localOTBranch: OTBranch
@Deprecated("MetaModelBranch is deprecated")
private val localMMBranch: IBranch
private val mergeLock = Any()
private val merger: VersionMerger
private val coroutineScope = CoroutineScope(Dispatchers.Default)
actual constructor(client: IModelClient, repositoryId: RepositoryId, branchName: String, user: () -> String) :
this(client, repositoryId.getBranchReference(branchName), user)
@Volatile
actual var localVersion: CLVersion?
private set
@Volatile
private var remoteVersion: CLVersion?
private val versionChangeDetector: VersionChangeDetector
private val isEditing = AtomicBoolean(false)
private var disposed = false
private var divergenceTime = 0
private val convergenceWatchdog: ScheduledFuture<*>
actual val branch: IBranch
get() {
checkDisposed()
return localMMBranch
}
/**
* Call this at the beginning of an edit operation in the editor
*/
fun startEdit() {
isEditing.set(true)
}
/**
* Call this at the end of an edit operation in the editor
*/
fun endEdit(): CLVersion? {
if (disposed) return null
try {
synchronized(mergeLock) {
deleteDetachedNodes()
return createAndMergeLocalVersion()
}
} finally {
isEditing.set(false)
}
}
protected fun deleteDetachedNodes() {
val hasDetachedNodes = localOTBranch.computeRead {
localOTBranch.transaction
.getChildren(ITree.ROOT_ID, ITree.DETACHED_NODES_ROLE).iterator().hasNext()
}
// avoid unnecessary write
if (hasDetachedNodes) {
localOTBranch.runWrite {
// clear detached nodes
val t: IWriteTransaction = localOTBranch.writeTransaction
t.getChildren(ITree.ROOT_ID, ITree.DETACHED_NODES_ROLE).forEach { nodeId: Long -> t.deleteNode(nodeId) }
}
}
}
protected fun createAndMergeLocalVersion(): CLVersion? {
checkDisposed()
var opsAndTree: Pair<List<IAppliedOperation>, ITree>
var localBase: CLVersion?
var remoteBase: CLVersion?
var newLocalVersion: CLVersion
synchronized(mergeLock) {
opsAndTree = localOTBranch.operationsAndTree
localBase = localVersion
remoteBase = remoteVersion
val ops: Array<IOperation> = opsAndTree.first.map { it.getOriginalOp() }.toTypedArray()
if (ops.isEmpty()) {
return null
}
newLocalVersion = createVersion(opsAndTree.second as CLTree, ops, localBase)
localVersion = newLocalVersion
divergenceTime = 0
}
SharedExecutors.FIXED.execute(object : Runnable {
override fun run() {
val doMerge: Supplier<Boolean> = object : Supplier<Boolean> {
override fun get(): Boolean {
var mergedVersion: CLVersion
try {
mergedVersion = merger.mergeChange(remoteBase!!, newLocalVersion)
LOG.debug {
String.format(
"Merged local %s with remote %s -> %s",
newLocalVersion.hash,
remoteBase!!.hash,
mergedVersion.hash
)
}
} catch (ex: Exception) {
LOG.error(ex) { "" }
mergedVersion = newLocalVersion
}
synchronized(mergeLock) {
writeLocalVersion(localVersion)
if (remoteVersion == remoteBase) {
writeRemoteVersion(mergedVersion)
return true
} else {
remoteBase = remoteVersion
return false
}
}
}
}
// Avoid locking during the merge as it may require communication with the model server
for (mergeAttempt in 0..2) {
if (doMerge.get()) {
return
}
}
synchronized(mergeLock) {
remoteBase = remoteVersion
doMerge.get()
}
}
})
return newLocalVersion
}
protected fun writeRemoteVersion(newVersion: CLVersion) {
synchronized(mergeLock) {
if (remoteVersion!!.hash != newVersion.hash) {
remoteVersion = newVersion
client.asyncStore!!.put(branchReference.getKey(), newVersion.hash)
}
}
}
protected fun writeLocalVersion(newVersion: CLVersion?) {
synchronized(mergeLock) {
if (newVersion!!.hash != this.localVersion!!.hash) {
this.localVersion = newVersion
divergenceTime = 0
localBranch.runWrite {
val newTree = newVersion.tree
val currentTree = localBranch.transaction.tree as CLTree?
if (getHash(newTree) != getHash(currentTree)) {
localBranch.writeTransaction.tree = newTree
}
}
}
}
}
fun createVersion(tree: CLTree, operations: Array<IOperation>, previousVersion: CLVersion?): CLVersion {
checkDisposed()
val time = LocalDateTime.now().toString()
return CLVersion.createRegularVersion(
id = client.idGenerator.generate(),
time = time,
author = user(),
tree = tree,
baseVersion = previousVersion,
operations = operations
)
}
actual fun isDisposed() = disposed
actual open fun dispose() {
checkDisposed()
disposed = true
try {
versionChangeDetector.dispose()
} catch (ex: Exception) {
LOG.error(ex) { "" }
}
convergenceWatchdog.cancel(false)
coroutineScope.cancel("ReplicatedRepository disposed")
}
fun checkDisposed() {
if (disposed) {
throw RuntimeException("Already disposed, replicated client $client, branch: $branchReference, author: ${user()}")
}
}
companion object {
private val LOG = mu.KotlinLogging.logger {}
private fun getHash(v: CLVersion?): String? {
return v?.hash
}
private fun getHash(v: CLTree?): String? {
return v?.hash
}
}
init {
val versionHash = client[branchReference.getKey()]
val store = client.storeCache!!
var initialVersion = if (versionHash.isNullOrEmpty()) null else loadFromHash(versionHash, store)
val initialTree = MutableObject<CLTree>()
if (initialVersion == null) {
initialTree.setValue(CLTree.builder(store).repositoryId(branchReference.repositoryId).build())
initialVersion = createVersion(initialTree.value, arrayOf(), null)
client.asyncStore!!.put(branchReference.getKey(), initialVersion.hash)
} else {
initialTree.setValue(CLTree(initialVersion.treeHash?.getValue(store), store))
}
// prefetch to avoid HTTP request in command listener
SharedExecutors.FIXED.execute { initialTree.value.getChildren(ITree.ROOT_ID, ITree.DETACHED_NODES_ROLE) }
localVersion = initialVersion
remoteVersion = initialVersion
localBranch = PBranch(initialTree.value, client.idGenerator)
localOTBranch = OTBranch(localBranch, client.idGenerator, store)
localMMBranch = MetaModelBranch(localOTBranch)
merger = VersionMerger(store, client.idGenerator)
versionChangeDetector = object : VersionChangeDetector(client, branchReference.getKey(), coroutineScope) {
override fun processVersionChange(oldVersionHash: String?, newVersionHash: String?) {
if (disposed) {
return
}
if (newVersionHash == null || newVersionHash.length == 0) {
return
}
if (newVersionHash == getHash(remoteVersion)) {
return
}
val newRemoteVersion = loadFromHash(newVersionHash, store)
val localBase = MutableObject<CLVersion?>()
synchronized(mergeLock) {
localBase.setValue(localVersion)
remoteVersion = newRemoteVersion
}
val doMerge = object : Supplier<Boolean> {
override fun get(): Boolean {
var mergedVersion: CLVersion
try {
mergedVersion = merger.mergeChange(localBase.value!!, newRemoteVersion)
if (LOG.isDebugEnabled) {
LOG.debug(
String.format(
"Merged remote %s with local %s -> %s",
newRemoteVersion.hash,
localBase.value!!.hash,
mergedVersion.hash
)
)
}
} catch (ex: Exception) {
LOG.error(ex) { "" }
mergedVersion = newRemoteVersion
}
val mergedTree = mergedVersion.tree
synchronized(mergeLock) {
remoteVersion = mergedVersion
if (localVersion == localBase.value) {
writeLocalVersion(mergedVersion)
writeRemoteVersion(mergedVersion)
return true
} else {
localBase.setValue(localVersion)
return false
}
}
}
}
// Avoid locking during the merge as it may require communication with the model server
for (mergeAttempt in 0..2) {
if (doMerge.get()) {
return
}
}
synchronized(mergeLock) {
localBase.setValue(localVersion)
doMerge.get()
}
}
}
localOTBranch.addListener(object : IBranchListener {
override fun treeChanged(oldTree: ITree?, newTree: ITree) {
if (disposed) {
return
}
if (isEditing.get()) {
return
}
SharedExecutors.FIXED.execute {
if (isEditing.get()) {
return@execute
}
createAndMergeLocalVersion()
}
}
})
convergenceWatchdog = fixDelay(
1000,
Runnable {
val localHash = if (localVersion == null) null else localVersion!!.hash
val remoteHash = if (remoteVersion == null) null else remoteVersion!!.hash
if (localHash == remoteHash) {
divergenceTime = 0
} else {
divergenceTime++
}
if (divergenceTime > 5) {
synchronized(mergeLock) { divergenceTime = 0 }
}
}
)
}
}
| 49
| null |
9
| 6
|
b132ea54e33ab8dab19fa716b292352755ff375e
| 14,013
|
modelix.core
|
Apache License 2.0
|
app/src/main/java/com/hackathon/security/Assessment.kt
|
rajarajank96
| 731,995,359
| false
|
{"Kotlin": 26614}
|
package com.hackathon.security
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceSettings
import com.google.recaptchaenterprise.v1.Assessment
import com.google.recaptchaenterprise.v1.CreateAssessmentRequest
import com.google.recaptchaenterprise.v1.Event
import com.google.recaptchaenterprise.v1.ProjectName
import com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason
import java.io.IOException
val lowRiskKey = "<KEY>"
val highRiskKey = "<KEY>"
object ZIntegrityAssessment
{
/**
* Create an assessment to analyze the risk of an UI action. Assessment approach is the same for
* both 'score' and 'checkbox' type recaptcha site keys.
*
* @param projectID : GCloud Project ID
* @param recaptchaSiteKey : Site key obtained by registering a domain/app to use recaptcha
* services. (score/ checkbox type)
* @param token : The token obtained from the client on passing the recaptchaSiteKey.
* @param recaptchaAction : Action name corresponding to the token.
*/
@Throws(IOException::class)
fun create(token: String)
{
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the `client.close()` method on the client to safely
// clean up any remaining background resources.
println("<<< 1: ${RecaptchaEnterpriseServiceSettings.getDefaultEndpoint()}")
RecaptchaEnterpriseServiceClient.create().use { client ->
println("<<< In: $client")
// Set the properties of the event to be tracked.
val event: Event = Event.newBuilder().setSiteKey("<KEY>").setToken(token).build()
// Build the assessment request.
val createAssessmentRequest: CreateAssessmentRequest =
CreateAssessmentRequest.newBuilder()
.setParent(ProjectName.of("simpleapi-206310").toString())
.setAssessment(Assessment.newBuilder().setEvent(event).build())
.build()
val response: Assessment = client.createAssessment(createAssessmentRequest)
// Check if the token is valid.
if (!response.tokenProperties.valid)
{
println("<<< The CreateAssessment call failed because the token was: " + response.tokenProperties.invalidReason.name)
return
}
// Check if the expected action was executed.
// (If the key is checkbox type and 'action' attribute wasn't set, skip this check.)
if (!response.tokenProperties.action.equals("login"))
{
println("<<< The action attribute in reCAPTCHA tag is: " + response.tokenProperties.action)
println(
("<<< The action attribute in the reCAPTCHA tag "
+ "does not match the action ("
+ "login"
+ ") you are expecting to score")
)
return
}
// Get the reason(s) and the risk score.
// For more information on interpreting the assessment,
// see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
for (reason: ClassificationReason? in response.riskAnalysis.reasonsList)
{
println("<<< $reason")
}
val recaptchaScore: Float = response.riskAnalysis.score
println("<<< The reCAPTCHA score is: $recaptchaScore")
// Get the assessment name (id). Use this to annotate the assessment.
val assessmentName: String = response.name
println("<<< Assessment name: " + assessmentName.substring(assessmentName.lastIndexOf("/") + 1))
client.close()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
34498164f418bbf13b1653f6fcff926fd21a8edf
| 4,030
|
android-security
|
MIT License
|
matisse/src/main/java/com/matisse/utils/UIUtils.kt
|
zhenian
| 192,932,387
| true
|
{"Gradle": 4, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 60, "XML": 40, "Java": 2}
|
package com.matisse.utils
import android.app.Activity
import android.content.Context
import android.content.res.Resources
import android.graphics.PorterDuff
import android.os.Build
import androidx.fragment.app.FragmentActivity
import android.util.DisplayMetrics
import android.util.TypedValue
import android.util.TypedValue.applyDimension
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import com.matisse.R
import com.matisse.entity.IncapableCause
import com.matisse.widget.IncapableDialog
object UIUtils {
fun handleCause(context: Context, cause: IncapableCause?) {
if (cause == null)
return
when (cause.mForm) {
IncapableCause.NONE -> {
// do nothing.
}
IncapableCause.DIALOG -> {
// Show description with dialog
val incapableDialog = IncapableDialog.newInstance(cause.mTitle, cause.mMessage)
incapableDialog.show((context as FragmentActivity).supportFragmentManager,
IncapableDialog::class.java.name)
}
// default is TOAST
IncapableCause.TOAST -> Toast.makeText(context, cause.mMessage, Toast.LENGTH_SHORT).show()
}
}
fun spanCount(context: Context, gridExpectedSize: Int): Int {
val screenWidth = context.resources.displayMetrics.widthPixels
val expected = screenWidth / gridExpectedSize
var spanCount = Math.round(expected.toFloat())
if (spanCount == 0) {
spanCount = 1
}
return spanCount
}
fun setTextDrawable(context: Context, textView: TextView?, attr: Int) {
if (textView == null) {
return
}
val drawables = textView.compoundDrawables
val ta = context.theme.obtainStyledAttributes(intArrayOf(attr))
val color = ta.getColor(0, 0)
ta.recycle()
for (i in drawables.indices) {
val drawable = drawables[i]
if (drawable != null) {
val state = drawable.constantState ?: continue
val newDrawable = state.newDrawable().mutate()
newDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN)
newDrawable.bounds = drawable.bounds
drawables[i] = newDrawable
}
}
textView.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3])
}
/**
* 设置控件显示隐藏
* 避免控件重复设置,统一提前添加判断
*
* @param isVisible true visible
* @param view targetview
*/
fun setViewVisible(isVisible: Boolean, view: View?) {
if (view == null) {
return
}
val visibleFlag = if (isVisible) View.VISIBLE else View.GONE
if (view.visibility != visibleFlag) {
view.visibility = visibleFlag
}
}
fun dp2px(context: Context, dipValue: Float): Float {
val mDisplayMetrics = getDisplayMetrics(context)
return applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, mDisplayMetrics)
}
/**
* 获取屏幕尺寸与密度.
* @param context the context
* @return mDisplayMetrics
*/
private fun getDisplayMetrics(context: Context?): DisplayMetrics {
val mResources: Resources = if (context == null) {
Resources.getSystem()
} else {
context.resources
}
return mResources.displayMetrics
}
/**
* 获取屏幕的宽度px
*
* @param context 上下文
* @return 屏幕宽px
*/
fun getScreenWidth(context: Context): Int {
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val outMetrics = DisplayMetrics()// 创建了一张白纸
windowManager.defaultDisplay.getMetrics(outMetrics)// 给白纸设置宽高
return outMetrics.widthPixels
}
/**
* 获取屏幕的高度px
* @param context 上下文
* @return 屏幕高px
*/
fun getScreenHeight(context: Context): Int {
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val outMetrics = DisplayMetrics()// 创建了一张白纸
windowManager.defaultDisplay.getMetrics(outMetrics)// 给白纸设置宽高
return outMetrics.heightPixels
}
/**
* 设置状态栏字体颜色
* @param activity activity
* @param isDark isdark
*/
fun setTextColorStatusBar(activity: Activity, isDark: Boolean) {
FlymeSetStatusBarLightMode(activity.window, isDark)
MIUISetStatusBarLightMode(activity.window, isDark)
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isDark) {//6.0
// if (isDark) {
// activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
// } else {
// activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
// }
// }
}
/**
* 设置状态栏图标为深色和魅族特定的文字风格
* 可以用来判断是否为Flyme用户
* @param window 需要设置的窗口
* @param dark 是否把状态栏字体及图标颜色设置为深色
* @return boolean 成功执行返回true
*/
private fun FlymeSetStatusBarLightMode(window: Window?, dark: Boolean): Boolean {
var result = false
if (window != null) {
try {
val lp = window.attributes
val darkFlag = WindowManager.LayoutParams::class.java
.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
val meizuFlags = WindowManager.LayoutParams::class.java
.getDeclaredField("meizuFlags")
darkFlag.isAccessible = true
meizuFlags.isAccessible = true
val bit = darkFlag.getInt(null)
var value = meizuFlags.getInt(lp)
value = if (dark) {
value or bit
} else {
value and bit.inv()
}
meizuFlags.setInt(lp, value)
window.attributes = lp
result = true
} catch (e: Exception) {
}
}
return result
}
/**
* 设置状态栏字体图标为深色,需要MIUIV6以上
* @param window 需要设置的窗口
* @param dark 是否把状态栏字体及图标颜色设置为深色
* @return boolean 成功执行返回true
*/
private fun MIUISetStatusBarLightMode(window: Window?, dark: Boolean): Boolean {
var result = false
if (window != null) {
val clazz = window.javaClass
try {
val darkModeFlag: Int
val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams")
val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
darkModeFlag = field.getInt(layoutParams)
val extraFlagField = clazz.getMethod("setExtraFlags", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType)
if (dark) {
extraFlagField.invoke(window, darkModeFlag, darkModeFlag)//状态栏透明且黑色字体
} else {
extraFlagField.invoke(window, 0, darkModeFlag)//清除黑色字体
}
result = true
} catch (e: Exception) {
}
}
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
7d72a6c703b6e83f4a4f5933f68c2049f2a07b81
| 7,323
|
Matisse-Kotlin
|
Apache License 2.0
|
notary-commons/src/main/kotlin/com/d3/commons/sidechain/iroha/IrohaChainHandler.kt
|
d3ledger
| 129,921,969
| false
| null |
/*
* Copyright D3 Ledger, Inc. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.d3.commons.sidechain.iroha
import com.d3.commons.sidechain.ChainHandler
import com.d3.commons.sidechain.SideChainEvent
import com.d3.commons.util.hex
import jp.co.soramitsu.iroha.java.Utils
import mu.KLogging
/**
* Implementation of [ChainHandler] to convert from Iroha protocol to [SideChainEvent.IrohaEvent]
*/
class IrohaChainHandler : ChainHandler<iroha.protocol.BlockOuterClass.Block> {
/**
* Parse Iroha block for interesting commands
*/
override fun parseBlock(block: iroha.protocol.BlockOuterClass.Block): List<SideChainEvent.IrohaEvent> {
logger.info { "Iroha chain handler for block ${block.blockV1.payload.height}" }
var hash = ""
return block.blockV1.payload.transactionsList
.map { tx ->
hash = String.hex(Utils.hash(tx))
tx
}
.flatMap { tx -> tx.payload.reducedPayload.commandsList }
.map { command ->
when {
//TODO: create separate ChainHandler impl for withdrawal proof events
command.hasAddPeer() -> listOf(
SideChainEvent.IrohaEvent.AddPeer.fromProto(
command.addPeer
)
)
command.hasTransferAsset() -> {
logger.info { "transfer iroha event (from: ${command.transferAsset.srcAccountId}, to ${command.transferAsset.destAccountId}, amount: ${command.transferAsset.amount}, asset: ${command.transferAsset.assetId}" }
listOf(
SideChainEvent.IrohaEvent.SideChainTransfer.fromProto(
command.transferAsset,
hash
)
)
}
else -> listOf()
}
}
.flatten()
}
/**
* Logger
*/
companion object : KLogging()
}
| 2
| null |
5
| 15
|
0e719a1a8fcdce23933df68749028befe40cbc50
| 2,114
|
notary
|
Apache License 2.0
|
src/main/kotlin/dev/deepslate/fallacy/rule/item/VanillaExtendedFoodPropertiesRule.kt
|
Mottle
| 841,231,519
| false
|
{"Kotlin": 289220, "Java": 21036}
|
package dev.deepslate.fallacy.rule.item
import dev.deepslate.fallacy.common.item.component.NutritionData
import dev.deepslate.fallacy.common.item.data.ExtendedFoodProperties
import dev.deepslate.fallacy.common.item.data.ExtendedProperties
import dev.deepslate.fallacy.util.internalExtendedProperties
import net.minecraft.world.item.Items
object VanillaExtendedFoodPropertiesRule {
private val defaultNutrition = mapOf(
Items.ENCHANTED_GOLDEN_APPLE to NutritionData(
carbohydrate = 5f,
fat = 5f,
protein = 5f,
fiber = 5f,
electrolyte = 5f
),
Items.GOLDEN_APPLE to NutritionData(
carbohydrate = 1f,
fat = 1f,
protein = 1f,
fiber = 1f,
electrolyte = 1f
),
Items.GOLDEN_CARROT to NutritionData(carbohydrate = 0.4f, fiber = 0.8f),
Items.COOKED_BEEF to NutritionData(fat = 0.4f, protein = 1.5f),
Items.COOKED_PORKCHOP to NutritionData(fat = 1f, protein = 0.8f),
Items.COOKED_MUTTON to NutritionData(fat = 0.8f, protein = 0.8f),
Items.COOKED_SALMON to NutritionData(fat = 0.1f, protein = 0.5f),
Items.BAKED_POTATO to NutritionData(carbohydrate = 1.5f, fat = 0.1f),
Items.BEETROOT to NutritionData(carbohydrate = 1.5f, fiber = 0.3f),
Items.BEETROOT_SOUP to NutritionData(carbohydrate = 1.5f),
Items.BREAD to NutritionData(carbohydrate = 0.8f, fiber = 0.1f),
Items.CARROT to NutritionData(carbohydrate = 0.4f, fiber = 0.8f),
Items.COOKED_CHICKEN to NutritionData(fat = 0.7f, protein = 0.8f),
Items.COOKED_COD to NutritionData(protein = 1f),
Items.COOKED_RABBIT to NutritionData(protein = 1f),
Items.RABBIT_STEW to NutritionData(protein = 0.8f),
Items.APPLE to NutritionData(carbohydrate = 0.6f, fiber = 0.8f, electrolyte = 0.1f),
Items.CHORUS_FRUIT to NutritionData(electrolyte = 0.6f, fiber = 1f),
Items.DRIED_KELP to NutritionData(carbohydrate = 0.4f, fiber = 0.4f, electrolyte = 1f),
Items.MELON_SLICE to NutritionData(carbohydrate = 0.8f, electrolyte = 0.8f),
Items.POTATO to NutritionData(carbohydrate = 1.2f, fat = 0.1f),
Items.PUMPKIN_PIE to NutritionData(carbohydrate = 0.6f, fat = 0.3f),
Items.BEEF to NutritionData(fat = 0.4f, protein = 1f),
Items.CHICKEN to NutritionData(fat = 0.5f, protein = 0.8f),
Items.MUTTON to NutritionData(fat = 0.8f, protein = 0.6f),
Items.PORKCHOP to NutritionData(fat = 0.8f, protein = 0.8f),
Items.RABBIT to NutritionData(protein = 0.8f),
Items.SWEET_BERRIES to NutritionData(carbohydrate = 0.2f, electrolyte = 0.2f),
Items.GLOW_BERRIES to NutritionData(carbohydrate = 0.1f, electrolyte = 0.5f),
Items.CAKE to NutritionData(carbohydrate = 1f, fat = 0.5f),
Items.HONEY_BOTTLE to NutritionData(carbohydrate = 2f),
Items.PUFFERFISH to NutritionData(protein = 2f),
Items.COD to NutritionData(protein = 1f),
Items.SALMON to NutritionData(fat = 0.1f, protein = 0.5f),
Items.TROPICAL_FISH to NutritionData(protein = 1f),
Items.COOKIE to NutritionData(carbohydrate = 1.2f, fat = 1f),
Items.MUSHROOM_STEW to NutritionData(carbohydrate = 1f, fat = 0.4f, fiber = 0.5f)
)
private val defaultFullLevel = mapOf(
Items.PUMPKIN_PIE to 1,
Items.GLOW_BERRIES to 1,
Items.SWEET_BERRIES to 1,
Items.COOKIE to 1,
Items.GOLDEN_APPLE to 3,
Items.ENCHANTED_GOLDEN_APPLE to 4,
Items.DRIED_KELP to 1
)
fun rule() {
(defaultNutrition.keys + defaultFullLevel.keys).map { item ->
val nutrition = defaultNutrition[item]
val fullLevel = defaultFullLevel[item]
val foodData = ExtendedFoodProperties.Builder()
if (nutrition != null) {
foodData.withNutrition(nutrition)
}
if (fullLevel != null) {
foodData.withFullLevel(fullLevel)
}
item.internalExtendedProperties = ExtendedProperties.Builder().withFoodProperties(foodData.build()).build()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6858960a6c7021660159a04b8656215efe74cb6e
| 4,208
|
Fallacy
|
MIT License
|
sample/src/main/java/eu/kevin/sample/samples/payment/card/CardPaymentActivity.kt
|
getkevin
| 375,151,388
| false
| null |
package eu.kevin.sample.samples.payment.card
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle.State
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.snackbar.Snackbar
import eu.kevin.inapppayments.paymentsession.PaymentSessionContract
import eu.kevin.inapppayments.paymentsession.entities.PaymentSessionConfiguration
import eu.kevin.inapppayments.paymentsession.enums.PaymentType
import eu.kevin.sample.R
import eu.kevin.sample.databinding.KevinActivityPaymentsCardBinding
import kotlinx.coroutines.launch
import java.util.UUID
internal class CardPaymentActivity : AppCompatActivity() {
private lateinit var binding: KevinActivityPaymentsCardBinding
private val viewModel: CardPaymentViewModel by viewModels()
/**
* ActivityResult callback used to obtain payment initiation session result.
*
* More info: https://developer.kevin.eu/home/mobile-sdk/android/payment-initiation
*/
private val paymentInitiationSession =
registerForActivityResult(PaymentSessionContract()) { result ->
viewModel.handlePaymentInitiationResult(result)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = KevinActivityPaymentsCardBinding.inflate(layoutInflater)
setContentView(binding.root)
lifecycleScope.launch {
repeatOnLifecycle(State.STARTED) {
viewModel.uiState.collect {
updateUiState(it)
}
}
}
binding.initiatePaymentButton.setOnClickListener {
viewModel.initiateCardPayment()
}
}
private fun updateUiState(uiState: CardPaymentUiState) {
with(binding) {
initiatePaymentButton.visibility = if (uiState.isLoading) GONE else VISIBLE
paymentText.visibility = if (uiState.isLoading) GONE else VISIBLE
creditorText.visibility = if (uiState.isLoading) GONE else VISIBLE
paymentWarningText.visibility = if (uiState.isLoading) GONE else VISIBLE
progressBar.visibility = if (uiState.isLoading) VISIBLE else GONE
uiState.paymentId?.let { paymentId ->
initiateCardPayment(
paymentId = paymentId
)
}
uiState.paymentCreditor?.let { creditor ->
val account = creditor.accounts.first()
creditorText.text = getString(R.string.text_creditor_info, creditor.name, account.currencyCode)
}
uiState.userMessage?.let { message -> showSnackbar(message) }
}
}
/**
* Initiate card payment process.
*
* More info: https://developer.kevin.eu/home/mobile-sdk/android/payment-initiation
*/
private fun initiateCardPayment(paymentId: UUID) {
// Payment session must be initiated with paymentId obtained via kevin. API
val configuration = PaymentSessionConfiguration.Builder(paymentId.toString())
.setPaymentType(PaymentType.CARD)
.build()
paymentInitiationSession.launch(configuration)
viewModel.onPaymentInitiated()
}
private fun showSnackbar(message: String) {
Snackbar.make(binding.rootLayout, message, Snackbar.LENGTH_SHORT).show()
viewModel.onUserMessageShown()
}
}
| 1
|
Kotlin
|
2
| 6
|
e6f4c7e1687595274fb99afd2ceef298610a2043
| 3,568
|
kevin-android
|
MIT License
|
src/main/kotlin/com/c5inco/modifiers/plugin/intellij/SwingColors.kt
|
c5inco
| 349,346,768
| false
| null |
package com.c5inco.modifiers.plugin.intellij
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import com.intellij.ide.ui.LafManagerListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.ui.JBColor
import javax.swing.UIManager
import java.awt.Color as AWTColor
interface SwingColors {
val background: Color
val onBackground: Color
val surface: Color
val onSurface: Color
}
@Composable
fun SwingColors(): SwingColors {
val swingColor = remember { SwingColorsImpl() }
val messageBus = remember {
ApplicationManager.getApplication().messageBus.connect()
}
remember(messageBus) {
messageBus.subscribe(
LafManagerListener.TOPIC,
ThemeChangeListener(swingColor::updateCurrentColors)
)
}
DisposableEffect(messageBus) {
onDispose {
messageBus.disconnect()
}
}
return swingColor
}
private class SwingColorsImpl : SwingColors {
private val _backgroundState: MutableState<Color> = mutableStateOf(getBackgroundColor)
private val _onBackgroundState: MutableState<Color> = mutableStateOf(getOnBackgroundColor)
private val _surfaceState: MutableState<Color> = mutableStateOf(getSurfaceColor)
private val _onSurfaceState: MutableState<Color> = mutableStateOf(getOnSurfaceColor)
override val background: Color get() = _backgroundState.value
override val onBackground: Color get() = _onBackgroundState.value
override val surface: Color get() = _surfaceState.value
override val onSurface: Color get() = _onSurfaceState.value
private val getBackgroundColor get() = getEditorBackground()
private val getOnBackgroundColor get() = getColor(ON_SURFACE_KEY)
private val getSurfaceColor get() = getColor(SURFACE_KEY)
private val getOnSurfaceColor get() = getColor(ON_SURFACE_KEY)
init {
updateCurrentColors()
}
fun updateCurrentColors() {
if (!JBColor.isBright()) {
_backgroundState.value = getBackgroundColor
_surfaceState.value = getBackgroundColor
} else {
_backgroundState.value = getSurfaceColor
_surfaceState.value = getBackgroundColor
}
_onBackgroundState.value = getOnBackgroundColor
_onSurfaceState.value = getOnSurfaceColor
}
private val AWTColor.asComposeColor: Color get() = Color(red, green, blue, alpha)
private fun getColor(key: String): Color = UIManager.getColor(key).asComposeColor
private fun getEditorBackground(): Color {
val currentScheme = EditorColorsManager.getInstance().schemeForCurrentUITheme
return currentScheme.defaultBackground.asComposeColor
}
companion object {
private const val SURFACE_KEY = "Panel.background"
private const val ON_SURFACE_KEY = "Panel.foreground"
}
}
| 3
|
Kotlin
|
3
| 98
|
28757a8ac22dc724c55e4fa5c2568e4fcdf5afcc
| 2,953
|
Compose-Modifiers-Playground
|
MIT License
|
src/commonMain/kotlin/io/skerna/commons/sreaction/Handler.kt
|
skerna
| 181,100,389
| false
| null |
/*
* Copyright (c) 2019 SKERNA
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.skerna.commons.sreaction
import kotlin.js.JsName
@JsName("Handler")
interface Handler<E> {
@JsName("handle")
fun handle(value:E)
companion object {
/**
* Util Handler, permite crear un Handler con una lambda como handler paramter
* permite aprovechar la utilidad de las interfaces + la simplicidad de las lambdas
* @param lambda
* @param E
*
*/
@JsName("create")
fun<E> create(lambda: (asyncResult:E)->Unit): Handler<E> {
return object: Handler<E> {
override fun handle(value: E) {
lambda(value)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
79e82b699c7b3995d991daa5b461402f92afab08
| 1,814
|
commons-sreaction
|
MIT License
|
packages/react-native-bpk-component-calendar/src/android/src/main/java/net/skyscanner/backpack/reactnative/calendar/CalendarViewManager.kt
|
felixarpa
| 187,169,476
| true
|
{"JavaScript": 398336, "Objective-C": 25042, "Kotlin": 16336, "Ruby": 4111, "Shell": 2442, "Python": 1748}
|
/*
* Backpack - Skyscanner's Design System
*
* Copyright 2016-2019 Skyscanner Ltd
*
* 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 net.skyscanner.backpack.reactnative.calendar
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.UIManagerModule
import com.facebook.react.uimanager.ViewGroupManager
import com.facebook.react.uimanager.annotations.ReactProp
import net.skyscanner.backpack.calendar.model.CalendarRange
import net.skyscanner.backpack.calendar.model.SingleDay
import net.skyscanner.backpack.calendar.presenter.SelectionType
import net.skyscanner.backpack.reactnative.calendar.events.CalendarChangeEvent
import org.threeten.bp.Instant
import org.threeten.bp.LocalDate
import org.threeten.bp.ZoneId
import java.lang.IllegalArgumentException
class CalendarViewManager : ViewGroupManager<RNCalendarView>() {
companion object {
const val VIEW_NAME = "AndroidBPKCalendarView"
internal val ZONE_ID_UTC = ZoneId.of("UTC")
}
// This means we are not relying on RN's css to layout children and doing it ourselves.
// see RNCalendarView.requestLayout
override fun needsCustomLayoutForChildren() = true
override fun getName() = VIEW_NAME
override fun createViewInstance(reactContext: ThemedReactContext): RNCalendarView {
return RNCalendarView(reactContext)
}
@ReactProp(name = "selectedDates")
fun setSelectedDates(view: RNCalendarView, dates: ReadableArray) {
view.selectedDates = (0..(dates.size() - 1)).map {
unixToCalendarDay(dates.getInt(it))
}.toTypedArray()
}
@ReactProp(name = "selectionType")
fun setSelectionType(view: RNCalendarView, selectionType: String) {
view.selectionType = when (selectionType) {
"range" -> SelectionType.RANGE
"single" -> SelectionType.SINGLE
"multiple" -> SelectionType.RANGE // TODO: support multiple selection
else -> throw IllegalArgumentException("Selection type $selectionType is not supported")
}
}
@ReactProp(name = "locale")
fun setLocale(view: RNCalendarView, locale: String) {
view.locale = locale
}
@ReactProp(name = "minDate")
fun setMinDate(view: RNCalendarView, minDate: Int?) {
minDate?.let {
view.minDate = unixToCalendarDay(it)
}
}
@ReactProp(name = "maxDate")
fun setMaxDate(view: RNCalendarView, maxDate: Int?) {
maxDate?.let {
view.maxDate = unixToCalendarDay(it)
}
}
override fun addEventEmitters(reactContext: ThemedReactContext, view: RNCalendarView) {
val dispatcher = reactContext.getNativeModule(UIManagerModule::class.java).eventDispatcher
view.onDatesChange = { selection ->
val dates = mutableListOf<LocalDate>()
when (selection) {
is CalendarRange -> {
selection.start?.let { dates.add(it) }
selection.end?.let { dates.add(it) }
}
is SingleDay -> {
dates.add(selection.selectedDay)
}
}
dispatcher.dispatchEvent(CalendarChangeEvent(view.id, dates.toTypedArray()))
}
}
override fun onAfterUpdateTransaction(view: RNCalendarView) {
super.onAfterUpdateTransaction(view)
view.render()
}
private fun unixToCalendarDay(unixTime: Int): LocalDate {
// TODO: Explore sending a "dummy" date here (01-01-2019) to avoid having to deal with timezones
return Instant.ofEpochMilli(unixTime * 1000L).atZone(ZONE_ID_UTC).toLocalDate()
}
}
| 0
|
JavaScript
|
0
| 0
|
0b710aa8143b3fe25d0de914c9482d156e7da55d
| 3,973
|
backpack-react-native
|
Apache License 2.0
|
app/src/main/kotlin/io/armcha/ribble/domain/fetcher/Fetcher.kt
|
armcha
| 98,714,221
| false
| null |
package io.armcha.ribble.domain.fetcher
import io.armcha.ribble.data.cache.MemoryCache
import io.armcha.ribble.domain.fetcher.result_listener.RequestType
import io.armcha.ribble.domain.fetcher.result_listener.ResultListener
import io.reactivex.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by Chatikyan on 04.08.2017.
*/
@Singleton
class Fetcher @Inject constructor(private val disposable: CompositeDisposable,
private val memoryCache: MemoryCache) {
private val requestMap = ConcurrentHashMap<RequestType, Status>()
private fun <T> getIOToMainTransformer(): SingleTransformer<T, T> {
return SingleTransformer {
it.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
}
fun <T> fetch(flowable: Flowable<T>, requestType: RequestType,
resultListener: ResultListener, success: (T) -> Unit) {
disposable.add(flowable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { resultListener startAndAdd requestType }
.subscribe(onSuccess<T>(requestType, success),
resultListener.onError(requestType)))
}
fun <T> fetch(observable: Observable<T>, requestType: RequestType,
resultListener: ResultListener, success: (T) -> Unit) {
disposable.add(observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { resultListener startAndAdd requestType }
.subscribe(onSuccess<T>(requestType, success),
resultListener.onError(requestType)))
}
fun <T> fetch(single: Single<T>, requestType: RequestType,
resultListener: ResultListener, success: (T) -> Unit) {
disposable.add(single
.compose(getIOToMainTransformer())
.doOnSubscribe { resultListener startAndAdd requestType }
.subscribe(onSuccess<T>(requestType, success),
resultListener.onError(requestType)))
}
fun complete(completable: Completable, requestType: RequestType,
resultListener: ResultListener, success: () -> Unit) {
disposable.add(completable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { resultListener startAndAdd requestType }
.subscribe({
requestMap.replace(requestType, Status.SUCCESS)
success()
}, resultListener.onError(requestType)))
}
private infix fun ResultListener.startAndAdd(requestType: RequestType) {
onRequestStart(requestType)
if (requestType != RequestType.TYPE_NONE)
requestMap.put(requestType, Status.LOADING)
}
private fun ResultListener.onError(requestType: RequestType): (Throwable) -> Unit {
return {
requestMap.replace(requestType, Status.ERROR)
onRequestError(requestType, it.message)
}
}
private fun <T> onSuccess(requestType: RequestType, success: (T) -> Unit): (T) -> Unit {
return {
val status = if (it is List<*> && it.isEmpty()) {
Status.EMPTY_SUCCESS
} else {
memoryCache.put(requestType, it)
Status.SUCCESS
}
requestMap.replace(requestType, status)
success(it)
}
}
fun hasActiveRequest(): Boolean = requestMap.isNotEmpty()
fun getRequestStatus(requestType: RequestType) = requestMap.getOrElse(requestType, { Status.IDLE })
fun removeRequest(requestType: RequestType) {
requestMap.remove(requestType)
}
fun clear() {
disposable.clear()
}
}
| 6
| null |
120
| 879
|
815beaeb7c6c3f5d7d5c32aa60172372b2e5a844
| 4,151
|
Ribble
|
Apache License 2.0
|
src/main/kotlin/es/jtp/kterm/utils/Extensions.kt
|
juliotpaez
| 182,441,916
| false
| null |
package es.jtp.kterm.utils
/**
* Returns a string representation with some characters escaped to be represented as the content of a quoted string, i.e. "...".
*/
fun String.stringify() =
this.replace("\\", "\\\\").replace("\t", "\\t").replace("\r", "\\r").replace("\n", "\\n").replace("\"", "\\\"")
| 0
|
Kotlin
|
0
| 0
|
e839fc72accb21b5a70894705b89983456abe278
| 310
|
kterm
|
MIT License
|
Tests/01-FirstUnitTest/app/src/main/java/com/example/firsttest/homework/Fibonacci.kt
|
PierreVieira
| 314,919,628
| false
| null |
package com.example.firsttest.homework
object Fibonacci {
/**
* Returns the n-th fibonacci number
* They are defined like this:
* fib(0) = 0
* fib(1) = 1
* fib(n) = fib(n - 2) + fib(n - 1)
* */
fun fib(n: Int): Long {
if (n == 0) {
return 0
}
if (n == 1) {
return 1
}
var a = 0L
var b = 1L
var c = 1L
repeat(n - 1) {
c = a + b
a = b
b = c
}
return c
}
}
| 0
|
Kotlin
|
0
| 0
|
089c1c1e18a353c325e6cd51bfd02f0477ae53bf
| 537
|
AndroidApps
|
MIT License
|
shared/feature/geminio-sdk/src/main/kotlin/ru/hh/plugins/geminio/sdk/recipe/models/widgets/RecipeParameter.kt
|
hhru
| 159,637,875
| false
| null |
package ru.hh.plugins.geminio.sdk.recipe.models.widgets
import ru.hh.plugins.geminio.sdk.recipe.models.expressions.RecipeExpression
sealed class RecipeParameter {
abstract val id: String
abstract val name: String
abstract val help: String?
abstract val visibilityExpression: RecipeExpression?
abstract val availabilityExpression: RecipeExpression?
data class StringParameter(
override val id: String,
override val name: String,
override val help: String?,
override val visibilityExpression: RecipeExpression?,
override val availabilityExpression: RecipeExpression?,
val default: String?,
val suggestExpression: RecipeExpression?,
val constraints: List<StringParameterConstraint>,
) : RecipeParameter()
data class BooleanParameter(
override val id: String,
override val name: String,
override val help: String?,
override val visibilityExpression: RecipeExpression?,
override val availabilityExpression: RecipeExpression?,
val default: Boolean?
) : RecipeParameter()
}
| 17
| null |
18
| 97
|
2d6c02fc814eff3934c17de77ef7ade91d3116f5
| 1,120
|
android-multimodule-plugin
|
MIT License
|
core/src/main/java/com/aidventory/core/common/designsystem/component/EmptyContent.kt
|
yuriikonovalov
| 615,443,609
| false
| null |
package com.aidventory.core.common.designsystem.component
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
@Composable
fun EmptyContent(
text: String,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = text,
textAlign = TextAlign.Center
)
}
}
| 0
|
Kotlin
|
0
| 0
|
f6605489ce47b35b75e0628e6be64372eb5518e6
| 708
|
aidventory
|
MIT License
|
protocol/push/src/main/kotlin/com/walletconnect/push/engine/calls/SubscribeToDappUseCase.kt
|
WalletConnect
| 435,951,419
| false
| null |
@file:JvmSynthetic
package com.walletconnect.notify.engine.calls
import android.net.Uri
import android.util.Base64
import com.walletconnect.android.internal.common.crypto.kmr.KeyManagementRepository
import com.walletconnect.android.internal.common.crypto.sha256
import com.walletconnect.android.internal.common.explorer.ExplorerRepository
import com.walletconnect.android.internal.common.explorer.data.model.Listing
import com.walletconnect.android.internal.common.json_rpc.data.JsonRpcSerializer
import com.walletconnect.android.internal.common.model.AccountId
import com.walletconnect.android.internal.common.model.AppMetaData
import com.walletconnect.android.internal.common.model.AppMetaDataType
import com.walletconnect.android.internal.common.model.DidJwt
import com.walletconnect.android.internal.common.model.EnvelopeType
import com.walletconnect.android.internal.common.model.IrnParams
import com.walletconnect.android.internal.common.model.Participants
import com.walletconnect.android.internal.common.model.Redirect
import com.walletconnect.android.internal.common.model.Tags
import com.walletconnect.android.internal.common.model.params.NotifyParams
import com.walletconnect.android.internal.common.model.type.JsonRpcInteractorInterface
import com.walletconnect.android.internal.common.signing.cacao.Cacao
import com.walletconnect.android.internal.common.storage.MetadataStorageRepositoryInterface
import com.walletconnect.android.internal.utils.DAY_IN_SECONDS
import com.walletconnect.foundation.common.model.PublicKey
import com.walletconnect.foundation.common.model.Topic
import com.walletconnect.foundation.common.model.Ttl
import com.walletconnect.foundation.util.Logger
import com.walletconnect.notify.common.calcExpiry
import com.walletconnect.notify.common.model.NotificationScope
import com.walletconnect.notify.common.model.NotifyRpc
import com.walletconnect.notify.data.storage.SubscriptionRepository
import com.walletconnect.notify.data.wellknown.did.DidJsonDTO
import com.walletconnect.notify.engine.domain.ExtractNotifyConfigUseCase
import com.walletconnect.notify.engine.domain.RegisterIdentityAndReturnDidJwtUseCaseInterface
import com.walletconnect.util.bytesToHex
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.withContext
import java.net.URL
internal class SubscribeToDappUseCase(
private val serializer: JsonRpcSerializer,
private val jsonRpcInteractor: JsonRpcInteractorInterface,
private val extractNotifyConfigUseCase: ExtractNotifyConfigUseCase,
private val subscriptionRepository: SubscriptionRepository,
private val crypto: KeyManagementRepository,
private val explorerRepository: ExplorerRepository,
private val metadataStorageRepository: MetadataStorageRepositoryInterface,
private val registerIdentityAndReturnDidJwt: RegisterIdentityAndReturnDidJwtUseCaseInterface,
private val logger: Logger,
) : SubscribeToDappUseCaseInterface {
override suspend fun subscribeToDapp(dappUri: Uri, account: String, onSign: (String) -> Cacao.Signature?, onSuccess: (Long, DidJwt) -> Unit, onFailure: (Throwable) -> Unit) = supervisorScope {
val dappWellKnownProperties: Result<Pair<PublicKey, List<NotificationScope.Remote>>> = runCatching {
extractDidJson(dappUri).getOrThrow() to extractNotifyConfigUseCase(dappUri).getOrThrow()
}
dappWellKnownProperties.fold(
onSuccess = { (dappPublicKey, dappScopes) ->
val subscribeTopic = Topic(sha256(dappPublicKey.keyAsBytes))
if (subscriptionRepository.isAlreadyRequested(account, subscribeTopic.value)) return@fold onFailure(IllegalStateException("Account: $account is already subscribed to dapp: $dappUri"))
val selfPublicKey = crypto.generateAndStoreX25519KeyPair()
val responseTopic = crypto.generateTopicFromKeyAgreement(selfPublicKey, dappPublicKey)
val dappMetaData: AppMetaData = getDappMetaData(dappUri).getOrElse {
return@fold onFailure(it)
}
val didJwt = registerIdentityAndReturnDidJwt(AccountId(account), dappUri.toString(), dappScopes.map { it.name }, onSign, onFailure).getOrElse { error ->
return@fold onFailure(error)
}
val params = NotifyParams.SubscribeParams(didJwt.value)
val request = NotifyRpc.NotifySubscribe(params = params)
val irnParams = IrnParams(Tags.NOTIFY_SUBSCRIBE, Ttl(DAY_IN_SECONDS))
runCatching<Unit> {
subscriptionRepository.insertOrAbortRequestedSubscription(
requestId = request.id,
subscribeTopic = subscribeTopic.value,
responseTopic = responseTopic.value,
account = account,
mapOfScope = dappScopes.associate { scope -> scope.name to Pair(scope.description, true) },
expiry = calcExpiry().seconds,
)
}.mapCatching {
metadataStorageRepository.insertOrAbortMetadata(
topic = responseTopic,
appMetaData = dappMetaData,
appMetaDataType = AppMetaDataType.PEER,
)
}.onFailure { error ->
logger.error("Cannot insert: ${error.message}")
return@fold onFailure(error)
}
jsonRpcInteractor.subscribe(responseTopic) { error ->
return@subscribe onFailure(error)
}
jsonRpcInteractor.publishJsonRpcRequest(
topic = subscribeTopic,
params = irnParams,
payload = request,
envelopeType = EnvelopeType.ONE,
participants = Participants(selfPublicKey, dappPublicKey),
onSuccess = {
onSuccess(request.id, didJwt)
},
onFailure = { error ->
onFailure(error)
}
)
},
onFailure = { error -> return@supervisorScope onFailure(error) }
)
}
private suspend fun extractDidJson(dappUri: Uri): Result<PublicKey> = withContext(Dispatchers.IO) {
val didJsonDappUri = dappUri.run {
if (this.path?.contains(DID_JSON) == false) {
this.buildUpon().appendPath(DID_JSON).build()
} else {
this
}
}
val wellKnownDidJsonString = URL(didJsonDappUri.toString()).openStream().bufferedReader().use { it.readText() }
val didJson = serializer.tryDeserialize<DidJsonDTO>(wellKnownDidJsonString) ?: return@withContext Result.failure(Exception("Failed to parse $DID_JSON"))
val verificationKey = didJson.keyAgreement.first()
val jwkPublicKey = didJson.verificationMethod.first { it.id == verificationKey }.publicKeyJwk.x
val replacedJwk = jwkPublicKey.replace("-", "+").replace("_", "/")
val publicKey = Base64.decode(replacedJwk, Base64.DEFAULT).bytesToHex()
Result.success(PublicKey(publicKey))
}
private suspend fun getDappMetaData(dappUri: Uri) = withContext(Dispatchers.IO) {
val listOfDappHomepages = runCatching {
explorerRepository.getAllDapps().listings.associateBy { listing -> listing.homepage }
}.getOrElse { error ->
return@withContext Result.failure(error)
}
val (dappHomepageUri: Uri, dappListing: Listing) = listOfDappHomepages.entries.filter { (_, dappListing) ->
dappListing.description != null
}.firstOrNull { (dappHomepageUri, _) ->
dappHomepageUri.host != null && dappHomepageUri.host!!.contains(dappUri.host!!)
} ?: return@withContext Result.failure<AppMetaData>(IllegalArgumentException("Unable to find dapp listing for $dappUri"))
return@withContext Result.success(
AppMetaData(
name = dappListing.name,
description = dappListing.description!!,
icons = listOf(dappListing.imageUrl.sm, dappListing.imageUrl.md, dappListing.imageUrl.lg),
url = dappHomepageUri.toString(),
redirect = Redirect(dappListing.app.android)
)
)
}
private companion object {
const val DID_JSON = ".well-known/did.json"
}
}
internal interface SubscribeToDappUseCaseInterface {
suspend fun subscribeToDapp(
dappUri: Uri,
account: String,
onSign: (String) -> Cacao.Signature?,
onSuccess: (Long, DidJwt) -> Unit,
onFailure: (Throwable) -> Unit,
)
}
| 147
|
Kotlin
|
59
| 157
|
e34c0e716ca68021602463773403d8d7fd558b34
| 8,864
|
WalletConnectKotlinV2
|
Apache License 2.0
|
booster-transform-br-inline/src/main/kotlin/com/didiglobal/booster/transform/br/inline/BRInlineTransformer.kt
|
didi
| 182,968,735
| false
| null |
package com.didiglobal.booster.transform.br.inline
import com.didiglobal.booster.kotlinx.asIterable
import com.didiglobal.booster.kotlinx.search
import com.didiglobal.booster.kotlinx.touch
import com.didiglobal.booster.transform.ArtifactManager.Companion.ALL_CLASSES
import com.didiglobal.booster.transform.ArtifactManager.Companion.DATA_BINDING_DEPENDENCY_ARTIFACTS
import com.didiglobal.booster.transform.TransformContext
import com.didiglobal.booster.transform.asm.ClassTransformer
import com.google.auto.service.AutoService
import org.gradle.api.logging.Logging
import org.objectweb.asm.Opcodes.GETSTATIC
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.FieldInsnNode
import org.objectweb.asm.tree.LdcInsnNode
import java.io.File
import java.io.PrintWriter
internal const val BR_FILE_EXT = "-br.bin"
/**
* Represents a class node transformer for constants shrinking
*
* @author linjiang
*/
@AutoService(ClassTransformer::class)
class BRInlineTransformer : ClassTransformer {
private lateinit var symbols: SymbolList
private lateinit var logger: PrintWriter
private lateinit var validClasses: Set<String>
override val name: String = Build.ARTIFACT
override fun onPreTransform(context: TransformContext) {
logger = getReport(context, "report.txt").touch().printWriter()
validClasses = context.findValidClasses()
val allBR = context.findAllBR()
symbols = allBR.find { it.second == context.appBR }?.first?.let {
SymbolList.from(it)
} ?: SymbolList.Builder().build()
if (symbols.isEmpty()) {
"Inline BR symbols failed: BR.class doesn't exist or blank".apply {
logger_.error(this)
logger.println(this)
}
return
}
// Remove all BR class files
allBR.also { pairs ->
val totalSize = allBR.map { it.first.length() }.sum()
val maxWidth = allBR.map { it.second.length }.max()?.plus(10) ?: 10
logger.println("Delete files:")
pairs.forEach {
if (it.first.delete()) {
logger.println(" - `${it.second}`")
}
}
logger.println("-".repeat(maxWidth))
logger.println("Total: $totalSize bytes")
logger.println()
}
}
override fun transform(context: TransformContext, klass: ClassNode): ClassNode {
if (symbols.isEmpty()) {
return klass
}
klass.replaceSymbolReferenceWithConstant()
return klass
}
override fun onPostTransform(context: TransformContext) {
this.logger.close()
}
private val TransformContext.appBR
get() = "${originalApplicationId.replace('.', '/')}/BR.class"
private fun TransformContext.findValidClasses(): Set<String> {
return if (isDataBindingEnabled) {
artifacts.get(DATA_BINDING_DEPENDENCY_ARTIFACTS)
.filter { it.name.endsWith(BR_FILE_EXT) }
.map { "${it.name.substringBefore("-").replace('.', '/')}/BR.class" }
.plus(appBR)
.toSet()
} else {
emptySet()
}
}
private fun TransformContext.findAllBR(): List<Pair<File, String>> {
return artifacts.get(ALL_CLASSES).map { classes ->
val base = classes.toURI()
classes.search { r ->
base.relativize(r.toURI()).path in validClasses
}.map { r ->
r to base.relativize(r.toURI()).path
}
}.flatten()
}
private fun ClassNode.replaceSymbolReferenceWithConstant() {
methods.forEach { method ->
method.instructions.iterator().asIterable().filter {
it.opcode == GETSTATIC
}.map {
it as FieldInsnNode
}.filter {
"I" == it.desc && "${it.owner}.class" in validClasses
}.forEach { field ->
// Replace int field with constant
try {
method.instructions.insertBefore(field, LdcInsnNode(symbols.getInt(field.name)))
method.instructions.remove(field)
logger.println(" * ${field.owner}.${field.name} => ${symbols.getInt(field.name)}: ${name}.${method.name}${method.desc}")
} catch (e: NullPointerException) {
logger.println(" ! Unresolvable symbol `${field.owner}.${field.name}` : $name.${method.name}${method.desc}")
}
}
}
}
}
private val logger_ = Logging.getLogger(BRInlineTransformer::class.java)
| 47
| null |
554
| 4,625
|
8d3bf8e8cb6aa1194feb4f1d8024a6b6ab1ebda9
| 4,696
|
booster
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/twilio/passkeys/PasskeyPayloadMapper.kt
|
twilio
| 755,169,665
| false
|
{"Kotlin": 159946, "Swift": 21348, "Ruby": 18931, "Shell": 5990}
|
/*
* Copyright © 2024 Twilio Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twilio.passkeys
import com.twilio.passkeys.exception.INVALID_JSON_PAYLOAD_ERROR
import com.twilio.passkeys.exception.TwilioException
import com.twilio.passkeys.exception.UNKNOWN_ERROR
import com.twilio.passkeys.extensions.b64Decode
import com.twilio.passkeys.extensions.b64Encode
import com.twilio.passkeys.models.AuthenticatePasskeyDto
import com.twilio.passkeys.models.AuthenticatePasskeyRequest
import com.twilio.passkeys.models.AuthenticatePasskeyResponse
import com.twilio.passkeys.models.CreatePasskeyDto
import com.twilio.passkeys.models.CreatePasskeyRequest
import com.twilio.passkeys.models.CreatePasskeyResponse
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
/**
* Object responsible for mapping passkey-related payloads and responses.
* This object provides methods for mapping passkey creation and authentication payloads,
* as well as mapping creation and authentication responses.
*/
internal object PasskeyPayloadMapper {
/**
* JSON parser configured for passkey-related operations.
*/
@OptIn(ExperimentalSerializationApi::class)
private val json =
Json {
ignoreUnknownKeys = true
explicitNulls = false
}
/**
* Maps a create payload JSON to a [CreatePasskeyRequest].
*
* @param createPayload The payload containing the create passkey information.
* @return The passkey creation request mapped from the provided payload.
*/
fun mapToCreatePasskeyRequest(createPayload: String): CreatePasskeyRequest {
val createPasskeyRequest = json.decodeFromString<CreatePasskeyRequest>(createPayload)
createPasskeyRequest.apply {
challenge = challenge.b64Decode().b64Encode()
user.id = user.id.b64Decode().b64Encode()
}
return createPasskeyRequest
}
/**
* Maps a authenticate payload JSON to a [AuthenticatePasskeyRequest].
*
* @param authenticatePayload The payload containing the authenticate passkey information.
* @return The passkey authentication request mapped from the provided payload.
*/
fun mapToAuthenticatePasskeyRequest(authenticatePayload: String): AuthenticatePasskeyRequest {
val authenticatePasskeyRequest =
json.decodeFromString<AuthenticatePasskeyRequest>(authenticatePayload)
authenticatePasskeyRequest.publicKey.apply {
challenge = challenge.b64Decode().b64Encode()
}
return authenticatePasskeyRequest
}
/**
* Maps a registration result JSON to a [CreatePasskeyResponse].
*
* @param registrationResultJson The JSON string containing registration result information.
* @return The passkey creation response mapped from the provided JSON.
*/
fun mapToCreatePasskeyResponse(registrationResultJson: String): CreatePasskeyResponse {
val createPasskeyDto = json.decodeFromString<CreatePasskeyDto>(registrationResultJson)
return CreatePasskeyResponse(
id = createPasskeyDto.id,
rawId = createPasskeyDto.rawId,
authenticatorAttachment = createPasskeyDto.authenticatorAttachment,
type = createPasskeyDto.type,
attestationObject = createPasskeyDto.response.attestationObject,
clientDataJSON = createPasskeyDto.response.clientDataJSON,
transports = createPasskeyDto.response.transports,
)
}
/**
* Maps an authentication result JSON to a [AuthenticatePasskeyResponse].
*
* @param authenticatePasskeyResultJson The JSON string containing authentication result information.
* @return The passkey authentication response mapped from the provided JSON.
*/
fun mapToAuthenticatePasskeyResponse(authenticatePasskeyResultJson: String): AuthenticatePasskeyResponse {
val authenticatePasskeyDto =
json.decodeFromString<AuthenticatePasskeyDto>(authenticatePasskeyResultJson)
return AuthenticatePasskeyResponse(
id = authenticatePasskeyDto.id,
rawId = authenticatePasskeyDto.rawId,
authenticatorAttachment = authenticatePasskeyDto.authenticatorAttachment,
type = authenticatePasskeyDto.type,
clientDataJSON = authenticatePasskeyDto.response.clientDataJSON,
authenticatorData = authenticatePasskeyDto.response.authenticatorData,
signature = authenticatePasskeyDto.response.signature,
userHandle = authenticatePasskeyDto.response.userHandle,
)
}
/**
* Maps an exception to a [TwilioException] with appropriate error messages.
*
* @param e The exception to be mapped.
* @return The TwilioException mapped from the provided exception.
*/
fun mapException(e: Exception): TwilioException {
return when (e) {
is SerializationException, is IllegalArgumentException, is IndexOutOfBoundsException ->
TwilioException(
INVALID_JSON_PAYLOAD_ERROR,
e.message.toString(),
)
else -> TwilioException(UNKNOWN_ERROR, e.message.toString())
}
}
}
| 5
|
Kotlin
|
0
| 4
|
244a4da6ae7579426cb3fa8b4bf948154084a18d
| 5,517
|
twilio-verify-passkeys
|
Apache License 2.0
|
kotlinx-coroutines-core/jvm/test/examples/example-delay-01.kt
|
hltj
| 151,721,407
| true
| null |
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
// This file was automatically generated from Delay.kt by Knit tool. Do not edit.
package kotlinx.coroutines.examples.exampleDelay01
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
flow {
emit(1)
delay(90)
emit(2)
delay(90)
emit(3)
delay(1010)
emit(4)
delay(1010)
emit(5)
}.debounce(1000)
.toList().joinToString().let { println(it) } }
| 1
|
Kotlin
|
99
| 255
|
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
| 526
|
kotlinx.coroutines-cn
|
Apache License 2.0
|
cache/cache-symbol-processor/src/test/kotlin/ru/tinkoff/kora/cache/symbol/processor/testdata/CacheableTargetArgumentWrongType.kt
|
Tinkoff
| 568,800,636
| false
| null |
package ru.tinkoff.kora.cache.symbol.processor.testdata
import ru.tinkoff.kora.cache.annotation.CachePut
import ru.tinkoff.kora.cache.annotation.Cacheable
import ru.tinkoff.kora.cache.symbol.processor.testcache.DummyCacheManager
import java.math.BigDecimal
class CacheableTargetArgumentMissing {
var value = "1"
@Cacheable(name = "sync_cache", tags = [DummyCacheManager::class])
fun getValue(arg1: String?, arg2: BigDecimal?): String {
return value
}
@CachePut(name = "sync_cache", tags = [DummyCacheManager::class], parameters = ["arg1", "arg4"])
fun putValue(arg2: BigDecimal?, arg3: String?, arg1: String?): String {
return value
}
}
| 19
| null |
21
| 145
|
d73219324d1875dab225ee52106dc43c8c4dcaa5
| 685
|
kora
|
Apache License 2.0
|
examples/ejectionHandler/src/main/kotlin/ejectionHandler/EjectionHandler.kt
|
ebrown17
| 191,096,960
| false
| null |
package ejectionHandler
import pinpak.core.*
fun main(){
val pipeline = PinPak.create("EjectionHandlerExample") { config ->
config.addEjectionHandler(EjectionHandler { name, data,error ->
println("$name ejected [$data] with $error")
})
config.addDeliveryHandler(DeliveryHandler { name, data ->
println("$name delivered $data")
})
config.addInterceptorLast("zero", PassThroughStringInterceptor())
config.addInterceptorLast("one", PassThroughIntegerInterceptor())
config.addInterceptorLast("two", PassThroughIntegerInterceptor())
}
pipeline.injectData("Will cause Exception")
}
| 0
|
Kotlin
|
0
| 1
|
dcd765d96c7e5dde06b0cf04c7e461f077748043
| 677
|
pinpak
|
Apache License 2.0
|
common-ui-view/src/main/java/app/tivi/TiviFragment.kt
|
grvgoel81
| 272,160,037
| false
| null |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi
import android.content.Context
import com.airbnb.mvrx.BaseMvRxFragment
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
abstract class DaggerMvRxFragment : BaseMvRxFragment(), HasAndroidInjector {
@Inject
lateinit var androidInjector: DispatchingAndroidInjector<Any>
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun androidInjector(): AndroidInjector<Any> {
return androidInjector
}
}
| 1
| null |
1
| 1
|
f9a8bed638a448afdb272b8a20b9cc6d365bd627
| 1,278
|
tivi
|
Apache License 2.0
|
app/src/main/java/com/techchallange/app/util/DateUtils.kt
|
hasankucuk
| 209,618,765
| false
| null |
package com.techchallange.app.util
import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.util.*
import android.widget.TextView
import androidx.databinding.BindingAdapter
import io.reactivex.annotations.NonNull
/**
* This function returns integer month name to string month name.
*
* return long month name exp Haziran, Temmuz
*
* @author hasankucuk
* @since 1.0
*/
class DateUtils {
companion object{
@SuppressLint("SimpleDateFormat")
@JvmStatic
fun toSimpleString(date: String): String {
val calendar = Calendar.getInstance()
calendar.set(Calendar.MONTH, date.toInt())
val format = SimpleDateFormat("MMMM")
return format.format(calendar.time)
}
@JvmStatic
@BindingAdapter("bindServerDate")
fun bindServerDate(@NonNull textView: TextView, date: String) {
textView.text = toSimpleString(date)
}
}
}
| 0
|
Kotlin
|
1
| 6
|
8204cc8ce3e2cae24da7056a94ecd1dbb31a562f
| 919
|
Android-Developer-Tech-Challenge
|
Apache License 2.0
|
src/main/kotlin/io/vlang/lang/psi/types/VlangBaseTypeEx.kt
|
vlang
| 754,996,747
| false
|
{"Kotlin": 1646396, "V": 250415, "Java": 68641, "Lex": 20424, "HTML": 6275}
|
package org.vlang.lang.psi.types
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.psi.PsiElement
import org.vlang.ide.codeInsight.VlangCodeInsightUtil
import org.vlang.lang.psi.*
import org.vlang.lang.psi.impl.VlangLangUtil
import org.vlang.lang.psi.impl.VlangLightType.VlangGenericType
@Suppress("PropertyName")
abstract class VlangBaseTypeEx(protected val anchor: PsiElement? = null) : UserDataHolderBase(), VlangTypeEx {
protected val UNKNOWN_TYPE = "unknown"
protected val ANON = "anon"
protected val containingFile = anchor?.containingFile as? VlangFile
protected open val moduleName = containingFile?.getModuleQualifiedName() ?: ""
override fun anchor() = anchor
override fun module() = moduleName
override fun name(): String {
return qualifiedName().removePrefix(moduleName).removePrefix(".")
}
override fun isBuiltin() = moduleName == VlangCodeInsightUtil.BUILTIN_MODULE || moduleName == VlangCodeInsightUtil.STUBS_MODULE
protected fun String?.safeAppend(str: String?): String {
if (str == null) return this ?: ""
return if (this == null) str else this + str
}
protected fun String?.safeAppend(type: VlangTypeEx?): String {
return this.safeAppend(type?.toString())
}
protected fun VlangTypeEx?.safeAppend(str: String): String {
return this?.toString().safeAppend(str)
}
protected fun prioritize(context: PsiElement?, variants: Collection<VlangNamedElement>): VlangNamedElement? {
val containingFile = context?.containingFile?.originalFile
val containingDir = containingFile?.containingDirectory
val priorityMap = mutableMapOf<Int, VlangNamedElement>()
variants.forEach { variant ->
val variantContainingFile = variant.containingFile?.originalFile as? VlangFile ?: return@forEach
val variantContainingDir = variantContainingFile.containingDirectory
val priority = when {
variantContainingFile == containingFile -> 1000 // local variant has the highest priority
variantContainingDir == containingDir -> 100 // same directory variant has the second highest priority
variantContainingFile.virtualFile.path.contains("examples") -> 10
variantContainingFile.isTestFile() -> 1 // test variant has the lowest priority
else -> 0 // other variants have the lowest priority
}
priorityMap[priority] = variant
}
// find the highest priority
val maxPriority = priorityMap.keys.maxOrNull() ?: 0
return priorityMap[maxPriority]
}
override fun methodsList(project: Project, visited: MutableSet<VlangTypeEx>): List<VlangMethodDeclaration> {
if (this in visited) return emptyList()
val ownMethods = VlangLangUtil.getMethodList(project, this)
val unwrapped = unwrapPointer().unwrapAlias()
val inheritedMethods = if (unwrapped != this) unwrapped.methodsList(project, visited) else emptyList()
val embeddedMethods = if (unwrapped is VlangStructTypeEx) {
val toExVisited = mutableMapOf<VlangType, VlangTypeEx>()
val embeddedStructs = (unwrapped.anchor() as? VlangStructType)?.embeddedStructs ?: emptyList()
embeddedStructs.mapNotNull { it.toEx(toExVisited).methodsList(project, visited) }.flatten()
} else {
emptyList()
}
visited.add(this)
return ownMethods + inheritedMethods + embeddedMethods
}
override fun findMethod(project: Project, name: String): VlangMethodDeclaration? {
return methodsList(project).find { it.name == name }
}
companion object {
protected val primitivesMap = VlangPrimitiveTypes.values().associateBy { it.value }
val VlangTypeEx?.isAny: Boolean
get() = when (this) {
is VlangAnyTypeEx -> true
is VlangUnknownTypeEx -> true
is VlangVoidPtrTypeEx -> true
else -> false
}
fun VlangTypeEx?.isNullableEqual(other: VlangTypeEx?): Boolean {
if (this == null && other == null) return true
if (this == null || other == null) return false
return this.isEqual(other)
}
fun VlangTypeEx.isGeneric(): Boolean {
var isGeneric = false
accept(object : VlangTypeVisitor {
override fun enter(type: VlangTypeEx): Boolean {
if (type is VlangGenericTypeEx) {
isGeneric = true
return false
}
return true
}
})
return isGeneric
}
fun VlangTypeEx.getGenericTs(): Set<String> {
val genericTs = mutableSetOf<String>()
accept(object : VlangTypeVisitor {
override fun enter(type: VlangTypeEx): Boolean {
if (type is VlangGenericTypeEx) {
genericTs.add(type.name())
return false
}
return true
}
})
return genericTs
}
fun VlangTypeEx.unwrapPointer(): VlangTypeEx {
if (this is VlangPointerTypeEx) {
return this.inner
}
return this
}
fun VlangTypeEx.unwrapArray(): VlangTypeEx {
if (this is VlangArrayTypeEx) {
return this.inner
}
return this
}
fun VlangTypeEx.unwrapGenericInstantiation(): VlangTypeEx {
if (this is VlangGenericInstantiationEx) {
return this.inner
}
return this
}
fun VlangTypeEx.unwrapAlias(): VlangTypeEx {
if (this is VlangAliasTypeEx) {
return this.inner
}
return this
}
fun VlangTypeEx.unwrapFunction(): VlangTypeEx? {
if (this is VlangFunctionTypeEx) {
return this.result
}
return this
}
fun VlangType?.toEx(visited: MutableMap<VlangType, VlangTypeEx> = mutableMapOf()): VlangTypeEx {
if (this == null) {
return VlangUnknownTypeEx.INSTANCE
}
if (this in visited) {
return visited[this]!!
}
val type = toExInner(visited)
if (genericArguments != null) {
val genericArguments = genericArguments!!.typeArguments.map { it.toEx() }
val instantiationType = VlangGenericInstantiationEx(type, genericArguments, this)
visited[this] = instantiationType
return instantiationType
}
visited[this] = type
return type
}
private fun VlangType.toExInner(visited: MutableMap<VlangType, VlangTypeEx>): VlangTypeEx {
val type = resolveType()
if (type is VlangStructType && type.parent is VlangStructDeclaration) {
return when ((type.parent as VlangStructDeclaration).getQualifiedName()) {
"builtin.array" -> VlangBuiltinArrayTypeEx.INSTANCE
"builtin.map" -> VlangBuiltinMapTypeEx.INSTANCE
"builtin.string" -> VlangStringTypeEx.INSTANCE
"stub.UnknownCDeclaration" -> VlangStructTypeEx.UnknownCDeclarationStruct
else -> {
if (type.isUnion) VlangUnionTypeEx(parentName(type), type)
else VlangStructTypeEx(parentName(type), type)
}
}
}
return when (type) {
is VlangEnumType -> VlangEnumTypeEx(parentName(type), type)
is VlangInterfaceType -> VlangInterfaceTypeEx(parentName(type), type)
is VlangOptionType -> VlangOptionTypeEx(type.type?.toEx(visited), type)
is VlangResultType -> VlangResultTypeEx(type.type?.toEx(visited), type)
is VlangThreadType -> VlangThreadTypeEx(type.type?.toEx(visited) ?: VlangVoidTypeEx.INSTANCE, type)
is VlangSharedType -> VlangSharedTypeEx(type.type.toEx(visited), type)
is VlangPointerType -> VlangPointerTypeEx(type.type.toEx(visited), type)
is VlangArrayType -> VlangArrayTypeEx(type.type.toEx(visited), type)
is VlangFixedSizeArrayType -> VlangFixedSizeArrayTypeEx(type.type.toEx(visited), type.size, type)
is VlangChannelType -> VlangChannelTypeEx(type.type.toEx(visited), type)
is VlangMapType -> VlangMapTypeEx(type.keyType.toEx(visited), type.valueType.toEx(visited), type)
is VlangTupleType -> VlangTupleTypeEx(type.typeListNoPin.typeList.map { it.toEx(visited) }, type)
is VlangGenericType -> VlangGenericTypeEx(type.name, type)
is VlangAnonymousStructType -> VlangAnonStructTypeEx(type)
is VlangFunctionType -> VlangFunctionTypeEx.from(type) ?: VlangUnknownTypeEx.INSTANCE
is VlangAliasType -> {
val typeName = parentName(type)
val declaration = type.parent as VlangNamedElement
// special type from stubs
if (declaration.getQualifiedName() == "stubs.Any") {
return VlangAliasTypeEx.anyType(type)
}
if (type.typeUnionList != null && type.typeUnionList!!.typeList.size > 1) {
visited[this] = VlangSumTypeEx("<temp>", emptyList(), type)
val types = type.typeUnionList!!.typeList.map { it.toEx(visited) }
return VlangSumTypeEx(typeName, types, type)
}
if (typeName == "any") {
return VlangAnyTypeEx.INSTANCE
}
if (typeName == "voidptr") {
return VlangVoidPtrTypeEx.INSTANCE
}
val primitive = primitivesMap[typeName]
if (primitive != null) {
return VlangPrimitiveTypeEx(primitive)
}
val firstType = type.typeUnionList?.typeList?.firstOrNull()
if (firstType?.text == typeName) {
// stubs case:
// type i32 = i32
return VlangAliasTypeEx(typeName, VlangUnknownTypeEx.INSTANCE, type)
}
VlangAliasTypeEx(typeName, firstType.toEx(visited), type)
}
else -> {
if (type.text == "void") {
return VlangVoidTypeEx.INSTANCE
}
// only for tests
// TODO: remove
if (type.text == "string") {
return VlangStringTypeEx.INSTANCE
}
if (type.text == "array") {
return VlangBuiltinArrayTypeEx.INSTANCE
}
if (type.text == "map") {
return VlangBuiltinMapTypeEx.INSTANCE
}
VlangUnknownTypeEx.INSTANCE
}
}
}
private fun parentName(type: PsiElement) = (type.parent as VlangNamedElement).name!!
}
}
| 5
|
Kotlin
|
5
| 33
|
a0d2cbfa63b995d93aaca3c80676f0c2f9bef117
| 12,039
|
intellij-v
|
MIT License
|
app/src/main/java/ru/dimon6018/metrolauncher/content/settings/activities/ThemeSettingsActivity.kt
|
queuejw
| 659,118,377
| false
|
{"Kotlin": 358288, "Java": 81331}
|
package ru.dimon6018.metrolauncher.content.settings.activities
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.WindowCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.google.android.material.button.MaterialButton
import com.google.android.material.card.MaterialCardView
import com.google.android.material.color.DynamicColors
import com.google.android.material.materialswitch.MaterialSwitch
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textview.MaterialTextView
import ru.dimon6018.metrolauncher.Application
import ru.dimon6018.metrolauncher.Application.Companion.PREFS
import ru.dimon6018.metrolauncher.R
import ru.dimon6018.metrolauncher.content.data.Prefs
import ru.dimon6018.metrolauncher.helpers.utils.Utils.Companion.accentName
import ru.dimon6018.metrolauncher.helpers.utils.Utils.Companion.applyWindowInsets
import ru.dimon6018.metrolauncher.helpers.utils.Utils.Companion.launcherAccentColor
import ru.dimon6018.metrolauncher.helpers.utils.Utils.Companion.launcherAccentTheme
class ThemeSettingsActivity : AppCompatActivity() {
private var themeMenu: MaterialCardView? = null
private var chooseThemeBtn: MaterialButton? = null
private var chooseAccentBtn: MaterialCardView? = null
private var accentNameTextView: MaterialTextView? = null
private var light: MaterialTextView? = null
private var dark: MaterialTextView? = null
private var accentTip: MaterialTextView? = null
private var context: Context? = null
private var tileImg: ImageView? = null
private var wallpaperSwitch: MaterialSwitch? = null
private var wallpaperTransparentTilesSwitch: MaterialSwitch? = null
private var main: CoordinatorLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(launcherAccentTheme())
super.onCreate(savedInstanceState)
setContentView(R.layout.launcher_settings_theme)
WindowCompat.setDecorFitsSystemWindows(window, false)
context = this
chooseThemeBtn = findViewById(R.id.chooseTheme)
accentTip = findViewById(R.id.accentTip)
chooseAccentBtn = findViewById(R.id.chooseAccent)
accentNameTextView = findViewById(R.id.choosedAccentName)
themeMenu = findViewById(R.id.chooseThemeMenu)
light = findViewById(R.id.chooseLight)
dark = findViewById(R.id.chooseDark)
tileImg = findViewById(R.id.moreTilesImage)
accentTip = findViewById(R.id.accentTip)
val textFinal = getString(R.string.settings_theme_accent_title_part2) + " " + getString(R.string.settings_theme_accent_title_part1) + " " + getString(R.string.settings_theme_accent_title_part3)
val spannable: Spannable = SpannableString(textFinal)
spannable.setSpan(ForegroundColorSpan(launcherAccentColor(theme)), textFinal.indexOf(getString(R.string.settings_theme_accent_title_part1)),textFinal.indexOf(getString(R.string.settings_theme_accent_title_part1)) + getString(R.string.settings_theme_accent_title_part1).length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
accentTip?.setText(spannable, TextView.BufferType.SPANNABLE)
val moreTilesSwitch: MaterialSwitch = findViewById(R.id.moreTilesSwitch)
wallpaperSwitch = findViewById(R.id.wallpaperShowSwtich)
val pinAppsToStartSwitch: MaterialSwitch = findViewById(R.id.newAppsToStartSwitch)
accentNameTextView!!.text = accentName(this)
val themeButtonLabel: String = if (PREFS!!.isLightThemeUsed) {
getString(R.string.light)
} else {
getString(R.string.dark)
}
chooseThemeBtn!!.text = themeButtonLabel
chooseThemeBtn!!.setOnClickListener {
chooseThemeBtn!!.visibility = View.GONE
themeMenu!!.visibility = View.VISIBLE
}
light!!.setOnClickListener {
PREFS!!.useLightTheme(true)
PREFS!!.setPrefsChanged(true)
restoreThemeButtonsAndApplyChanges()
}
dark!!.setOnClickListener {
PREFS!!.useLightTheme(false)
PREFS!!.setPrefsChanged(true)
restoreThemeButtonsAndApplyChanges()
}
chooseAccentBtn!!.setOnClickListener { AccentDialog.display(supportFragmentManager) }
moreTilesSwitch.isChecked = PREFS!!.isMoreTilesEnabled
moreTilesSwitch.text = if(PREFS!!.isMoreTilesEnabled) getString(R.string.on) else getString(R.string.off)
pinAppsToStartSwitch.isChecked = PREFS!!.pinNewApps
pinAppsToStartSwitch.text = if(PREFS!!.pinNewApps) getString(R.string.on) else getString(R.string.off)
wallpaperTransparentTilesSwitch = findViewById(R.id.wallpaperTransparentTilesSwtich)
//wallpaper switches
wallpaperSwitch?.setOnCheckedChangeListener { _, check ->
PREFS!!.setWallpaper(check)
PREFS!!.setPrefsChanged(true)
refreshWallpaperSwitches()
}
wallpaperTransparentTilesSwitch?.setOnCheckedChangeListener { _, check ->
PREFS!!.setTransparentTiles(check)
PREFS!!.setPrefsChanged(true)
refreshWallpaperSwitches()
}
//wallpaper switches end
moreTilesSwitch.setOnCheckedChangeListener { _, isChecked ->
PREFS!!.setMoreTilesPref(isChecked)
moreTilesSwitch.text = if(isChecked) getString(R.string.on) else getString(R.string.off)
moreTilesSwitch.setChecked(isChecked)
PREFS!!.setPrefsChanged(true)
setImg()
}
pinAppsToStartSwitch.setOnCheckedChangeListener { _, isChecked ->
PREFS!!.setPinNewApps(isChecked)
pinAppsToStartSwitch.text = if(isChecked) getString(R.string.on) else getString(R.string.off)
pinAppsToStartSwitch.setChecked(isChecked)
}
val dynamicColorSwitch: MaterialSwitch = findViewById(R.id.dynamicColorSwtich)
dynamicColorSwitch.setChecked(PREFS!!.accentColor == 20)
dynamicColorSwitch.text = if(PREFS!!.accentColor == 20) getString(R.string.on) else getString(R.string.off)
dynamicColorSwitch.setOnCheckedChangeListener { _, isChecked ->
if(DynamicColors.isDynamicColorAvailable()) {
if (isChecked) {
PREFS!!.accentColor = 20
} else {
PREFS!!.accentColor = PREFS!!.pref.getInt("previous_accent_color", 5)
}
dynamicColorSwitch.text =
if (isChecked) getString(R.string.on) else getString(R.string.off)
dynamicColorSwitch.setChecked(isChecked)
recreate()
} else {
Snackbar.make(dynamicColorSwitch, getString(R.string.dynamicColor_error), Snackbar.LENGTH_LONG).show()
}
}
val lockDesktopSwitch: MaterialSwitch = findViewById(R.id.blockStartSwitch)
lockDesktopSwitch.isChecked = PREFS!!.isStartBlocked
lockDesktopSwitch.text = if(PREFS!!.isStartBlocked) getString(R.string.on) else getString(R.string.off)
lockDesktopSwitch.setOnCheckedChangeListener { _, isChecked ->
PREFS!!.blockStartScreen(isChecked)
lockDesktopSwitch.text = if(isChecked) getString(R.string.on) else getString(R.string.off)
}
setImg()
main = findViewById(R.id.coordinator)
main?.apply { applyWindowInsets(this) }
}
private fun enterAnimation(exit: Boolean) {
if(main == null) {
return
}
val animatorSet = AnimatorSet()
if(exit) {
animatorSet.playTogether(
ObjectAnimator.ofFloat(main!!, "translationX", 0f, 300f),
ObjectAnimator.ofFloat(main!!, "rotationY", 0f, 90f),
ObjectAnimator.ofFloat(main!!, "alpha", 1f, 0f),
ObjectAnimator.ofFloat(main!!, "scaleX", 1f, 0.5f),
ObjectAnimator.ofFloat(main!!, "scaleY", 1f, 0.5f),
)
} else {
animatorSet.playTogether(
ObjectAnimator.ofFloat(main!!, "translationX", 300f, 0f),
ObjectAnimator.ofFloat(main!!, "rotationY", 90f, 0f),
ObjectAnimator.ofFloat(main!!, "alpha", 0f, 1f),
ObjectAnimator.ofFloat(main!!, "scaleX", 0.5f, 1f),
ObjectAnimator.ofFloat(main!!, "scaleY", 0.5f, 1f)
)
}
animatorSet.setDuration(400)
animatorSet.start()
}
override fun onPause() {
enterAnimation(true)
super.onPause()
}
override fun onResume() {
super.onResume()
enterAnimation(false)
refreshWallpaperSwitches()
}
private fun refreshWallpaperSwitches() {
wallpaperSwitch?.isChecked = PREFS!!.isWallpaperUsed
wallpaperSwitch?.text = if(PREFS!!.isWallpaperUsed) getString(R.string.on) else getString(R.string.off)
wallpaperTransparentTilesSwitch?.isChecked = PREFS!!.isTilesTransparent
wallpaperTransparentTilesSwitch?.text = if(PREFS!!.isTilesTransparent) getString(R.string.on) else getString(R.string.off)
}
private fun setImg() {
tileImg?.setImageResource(if(PREFS!!.isMoreTilesEnabled) R.mipmap.tiles_small else R.mipmap.tiles_default)
}
private fun restoreThemeButtonsAndApplyChanges() {
chooseThemeBtn!!.visibility = View.VISIBLE
themeMenu!!.visibility = View.GONE
setAppTheme()
}
private fun setAppTheme() {
if (Prefs(this).isLightThemeUsed) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
(application as Application).setNightMode()
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
(application as Application).setNightMode()
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
}
}
class AccentDialog : DialogFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.AppTheme_FullScreenDialog)
}
override fun onStart() {
super.onStart()
val dialog = dialog
val width = ViewGroup.LayoutParams.MATCH_PARENT
val height = ViewGroup.LayoutParams.MATCH_PARENT
dialog?.setTitle("ACCENT")
dialog?.window!!.setLayout(width, height)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
PREFS!!.setPrefsChanged(true)
return inflater.inflate(R.layout.accent_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val prefs = Prefs(requireContext())
val lime = view.findViewById<ImageView>(R.id.choose_color_lime)
val back = view.findViewById<FrameLayout>(R.id.back_accent_menu)
back.setOnClickListener { dismiss() }
lime.setOnClickListener {
prefs.accentColor = 0
dismiss()
requireActivity().recreate()
}
val green = view.findViewById<ImageView>(R.id.choose_color_green)
green.setOnClickListener {
prefs.accentColor = 1
dismiss()
requireActivity().recreate()
}
val emerald = view.findViewById<ImageView>(R.id.choose_color_emerald)
emerald.setOnClickListener {
prefs.accentColor = 2
dismiss()
requireActivity().recreate()
}
val cyan = view.findViewById<ImageView>(R.id.choose_color_cyan)
cyan.setOnClickListener {
prefs.accentColor = 3
dismiss()
requireActivity().recreate()
}
val teal = view.findViewById<ImageView>(R.id.choose_color_teal)
teal.setOnClickListener {
prefs.accentColor = 4
dismiss()
requireActivity().recreate()
}
val cobalt = view.findViewById<ImageView>(R.id.choose_color_cobalt)
cobalt.setOnClickListener {
prefs.accentColor = 5
dismiss()
requireActivity().recreate()
}
val indigo = view.findViewById<ImageView>(R.id.choose_color_indigo)
indigo.setOnClickListener {
prefs.accentColor = 6
dismiss()
requireActivity().recreate()
}
val violet = view.findViewById<ImageView>(R.id.choose_color_violet)
violet.setOnClickListener {
prefs.accentColor = 7
dismiss()
requireActivity().recreate()
}
val pink = view.findViewById<ImageView>(R.id.choose_color_pink)
pink.setOnClickListener {
prefs.accentColor = 8
dismiss()
requireActivity().recreate()
}
val magenta = view.findViewById<ImageView>(R.id.choose_color_magenta)
magenta.setOnClickListener {
prefs.accentColor = 9
dismiss()
requireActivity().recreate()
}
val crimson = view.findViewById<ImageView>(R.id.choose_color_crimson)
crimson.setOnClickListener {
prefs.accentColor = 10
dismiss()
requireActivity().recreate()
}
val red = view.findViewById<ImageView>(R.id.choose_color_red)
red.setOnClickListener {
prefs.accentColor = 11
dismiss()
requireActivity().recreate()
}
val orange = view.findViewById<ImageView>(R.id.choose_color_orange)
orange.setOnClickListener {
prefs.accentColor = 12
dismiss()
requireActivity().recreate()
}
val amber = view.findViewById<ImageView>(R.id.choose_color_amber)
amber.setOnClickListener {
prefs.accentColor = 13
dismiss()
requireActivity().recreate()
}
val yellow = view.findViewById<ImageView>(R.id.choose_color_yellow)
yellow.setOnClickListener {
prefs.accentColor = 14
dismiss()
requireActivity().recreate()
}
val brown = view.findViewById<ImageView>(R.id.choose_color_brown)
brown.setOnClickListener {
prefs.accentColor = 15
dismiss()
requireActivity().recreate()
}
val olive = view.findViewById<ImageView>(R.id.choose_color_olive)
olive.setOnClickListener {
prefs.accentColor = 16
dismiss()
requireActivity().recreate()
}
val steel = view.findViewById<ImageView>(R.id.choose_color_steel)
steel.setOnClickListener {
prefs.accentColor = 17
dismiss()
requireActivity().recreate()
}
val mauve = view.findViewById<ImageView>(R.id.choose_color_mauve)
mauve.setOnClickListener {
prefs.accentColor = 18
dismiss()
requireActivity().recreate()
}
val taupe = view.findViewById<ImageView>(R.id.choose_color_taupe)
taupe.setOnClickListener {
prefs.accentColor = 19
dismiss()
requireActivity().recreate()
}
}
companion object {
private const val TAG = "accentD"
fun display(fragmentManager: FragmentManager?): AccentDialog {
val accentDialog = AccentDialog()
accentDialog.show(fragmentManager!!, TAG)
return accentDialog
}
}
}
}
| 1
|
Kotlin
|
1
| 28
|
9f3e2e04378f3ac16e526f18c02a19631ed9e181
| 17,018
|
MetroPhoneLauncher
|
MIT License
|
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/design/PaintLine.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.remix.remix.design
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 com.woowla.compose.icon.collections.remix.remix.DesignGroup
public val DesignGroup.PaintFill: ImageVector
get() {
if (_paintFill != null) {
return _paintFill!!
}
_paintFill = Builder(name = "PaintFill", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.228f, 18.732f)
lineTo(20.996f, 16.965f)
lineTo(22.763f, 18.732f)
curveTo(23.74f, 19.709f, 23.74f, 21.292f, 22.763f, 22.268f)
curveTo(21.787f, 23.244f, 20.204f, 23.244f, 19.228f, 22.268f)
curveTo(18.251f, 21.292f, 18.251f, 19.709f, 19.228f, 18.732f)
close()
moveTo(8.879f, 1.08f)
lineTo(20.192f, 12.393f)
curveTo(20.583f, 12.784f, 20.583f, 13.417f, 20.192f, 13.808f)
lineTo(11.707f, 22.293f)
curveTo(11.316f, 22.683f, 10.683f, 22.683f, 10.293f, 22.293f)
lineTo(1.808f, 13.808f)
curveTo(1.417f, 13.417f, 1.417f, 12.784f, 1.808f, 12.393f)
lineTo(9.586f, 4.615f)
lineTo(7.464f, 2.494f)
lineTo(8.879f, 1.08f)
close()
moveTo(11.0f, 6.029f)
lineTo(3.929f, 13.101f)
horizontalLineTo(18.071f)
lineTo(11.0f, 6.029f)
close()
}
}
.build()
return _paintFill!!
}
private var _paintFill: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 2,358
|
compose-icon-collections
|
MIT License
|
app/src/main/java/com/example/composemvvm/datasource/networking/NetworkingService.kt
|
AnastasiaRainMaker
| 425,563,066
| false
|
{"Kotlin": 18543}
|
package com.example.compose_mvvm_weather_app.networking
import com.example.compose_mvvm_weather_app.model.WeatherApiResponse
import com.example.compose_mvvm_weather_app.utils.Constants
import retrofit2.http.GET
import retrofit2.http.Query
interface NetworkingService {
@GET("data/2.5/onecall?exclude=minutely,hourly,alerts&lang=en&units=imperial")
suspend fun fetchWeather(
@Query("lat") lat: String,
@Query("lon") lon: String,
@Query("appid") appid: String = Constants.APP_ID
): WeatherApiResponse
}
| 0
|
Kotlin
|
10
| 52
|
1736c9897d6fbc024ac8a4e56e0a941dce0af662
| 540
|
Compose-MVVM-app-sample
|
Apache License 2.0
|
frogorecyclerview/src/main/java/com/frogobox/recycler/core/FrogoBuilderRvBase.kt
|
amirisback
| 229,149,549
| false
| null |
package com.frogobox.recycler.core
import androidx.recyclerview.widget.RecyclerView
import com.frogobox.recycler.R
/**
* Created by faisalamir on 24/07/21
* FrogoRecyclerView
* -----------------------------------------
* Name : <NAME>
* E-mail : <EMAIL>
* Github : github.com/amirisback
* -----------------------------------------
* Copyright (C) 2021 FrogoBox Inc.
* All rights reserved
*
*/
abstract class FrogoBuilderRvBase<T> {
protected lateinit var frogoRecyclerView: RecyclerView
protected var emptyViewId: Int = R.layout.frogo_rv_container_empty_view
protected var optionAdapter = ""
protected val listDataFH = mutableListOf<FrogoHolder<T>>()
protected val listData = mutableListOf<T>()
protected fun init(frogoRecyclerView: RecyclerView) {
this.frogoRecyclerView = frogoRecyclerView
}
}
| 1
| null |
16
| 99
|
0554af5591bb2a812b44e6df1faeedcccf2c50ce
| 859
|
frogo-recycler-view
|
Apache License 2.0
|
term-2/block-4/task-7/lib/meteo-storm-glass/src/main/kotlin/meteo/stormglass/data/model/StormGlassErrorModel.kt
|
AzimMuradov
| 626,118,027
| false
| null |
package meteo.stormglass.data.model
import kotlinx.serialization.Serializable
@Serializable
internal data class StormGlassErrorModel(val errors: Map<String, String>)
| 0
|
Kotlin
|
0
| 0
|
20d712d69d19a399072ce997fe11f3066dc01354
| 168
|
computer-workshop-spbu
|
Apache License 2.0
|
app/src/main/java/br/com/hearthisat/service/config/Error.kt
|
danielsadoliveira
| 205,500,215
| false
| null |
package br.com.hearthisat.service.config
import br.com.hearthisat.extensions.caseNotNull
import br.com.hearthisat.extensions.caseNull
import com.google.gson.JsonParseException
import com.google.gson.JsonSyntaxException
import okhttp3.Request
import okhttp3.ResponseBody
import retrofit2.Response
/**
* Created by danielsdo on 15/08/17.
*/
data class Error(val errorType: ErrorType, val statusCode: HttpStatusCode = HttpStatusCode(0), val responseBody: ResponseBody? = null, val errorBody: String? = null, val request: Request? = null) {
object Factory {
/**
* Make an Error instance from a Throwable instance.
*
* @return Error instance from request and throwable instances.
*/
fun from(request: Request, throwable: Throwable): Error {
when(throwable) {
is java.net.SocketTimeoutException -> {
return Error(ErrorType.ClientTimeOut(), request = request)
}
is java.net.ConnectException,
is java.net.UnknownHostException,
is java.io.EOFException -> {
return Error(ErrorType.CannotReachServer(), request = request)
}
is JsonParseException,
is JsonSyntaxException,
is IllegalAccessException -> {
return Error(ErrorType.MarshalingFailed(throwable), request = request)
}
else -> {
var error: Error? = null
throwable.cause.caseNotNull { cause ->
if (cause != throwable) {
error = from(request, throwable = cause)
}
}.caseNull {
error = Error(ErrorType.Unknown(throwable = throwable), request = request)
}
return error!!
}
}
}
/**
* Make an Error instance from a retrofit2.Response instance.
*
* @return Error instance from request and response instances.
*/
fun <T> from(request: Request, resp: Response<T>): Error {
val raw = resp.raw()
val code = HttpStatusCode(raw?.code() ?: 0)
val errorType = when (code.description) {
HttpStatusCode.Status.InternalServerError -> ErrorType.InternalServerError()
HttpStatusCode.Status.NetworkConnectTimeoutError -> ErrorType.ServerTimeOut()
HttpStatusCode.Status.Unauthorized -> ErrorType.Unauthorized()
HttpStatusCode.Status.BadRequest -> ErrorType.BadRequest(request, resp)
else -> ErrorType.Unknown()
}
return Error(errorType, code, raw?.body(), resp.errorBody()?.string(), request = request)
}
}
sealed class ErrorType {
class Unknown(val throwable: Throwable? = null) : ErrorType()
class CannotReachServer : ErrorType()
class MarshalingFailed(val throwable: Throwable? = null) : ErrorType()
class InternalServerError : ErrorType()
open class TimeOut : ErrorType()
class ServerTimeOut : TimeOut()
class ClientTimeOut : TimeOut()
class Unauthorized : ErrorType()
class BadRequest<T>(val request: Request, val response: Response<T>) : ErrorType()
}
}
| 0
|
Kotlin
|
1
| 4
|
720e4a29587289c1a7ae28d554a487def1e200b0
| 3,422
|
hearthisat
|
The Unlicense
|
src/main/kotlin/no/nav/familie/ba/sak/integrasjoner/pdl/PdlUtil.kt
|
navikt
| 224,639,942
| false
| null |
package no.nav.familie.ef.sak.opplysninger.personopplysninger
import no.nav.familie.ef.sak.infrastruktur.exception.PdlNotFoundException
import no.nav.familie.ef.sak.infrastruktur.exception.PdlRequestException
import no.nav.familie.ef.sak.opplysninger.personopplysninger.pdl.PdlBolkResponse
import no.nav.familie.ef.sak.opplysninger.personopplysninger.pdl.PdlResponse
import org.slf4j.Logger
import org.slf4j.LoggerFactory
val secureLogger: Logger = LoggerFactory.getLogger("secureLogger")
inline fun <reified DATA : Any, reified T : Any> feilsjekkOgReturnerData(ident: String?,
pdlResponse: PdlResponse<DATA>,
dataMapper: (DATA) -> T?): T {
if (pdlResponse.harFeil()) {
if (pdlResponse.errors?.any { it.extensions?.notFound() == true } == true) {
throw PdlNotFoundException()
}
secureLogger.error("Feil ved henting av ${T::class} fra PDL: ${pdlResponse.errorMessages()}")
throw PdlRequestException("Feil ved henting av ${T::class} fra PDL. Se secure logg for detaljer.")
}
val data = dataMapper.invoke(pdlResponse.data)
if (data == null) {
val errorMelding = if (ident != null) "Feil ved oppslag på ident $ident. " else "Feil ved oppslag på person."
secureLogger.error(errorMelding +
"PDL rapporterte ingen feil men returnerte tomt datafelt")
throw PdlRequestException("Manglende ${T::class} ved feilfri respons fra PDL. Se secure logg for detaljer.")
}
return data
}
inline fun <reified T : Any> feilsjekkOgReturnerData(pdlResponse: PdlBolkResponse<T>): Map<String, T> {
if (pdlResponse.data == null) {
secureLogger.error("Data fra pdl er null ved bolkoppslag av ${T::class} fra PDL: ${pdlResponse.errorMessages()}")
throw PdlRequestException("Data er null fra PDL - ${T::class}. Se secure logg for detaljer.")
}
val feil = pdlResponse.data.personBolk.filter { it.code != "ok" }.associate { it.ident to it.code }
if (feil.isNotEmpty()) {
secureLogger.error("Feil ved henting av ${T::class} fra PDL: $feil")
throw PdlRequestException("Feil ved henting av ${T::class} fra PDL. Se secure logg for detaljer.")
}
return pdlResponse.data.personBolk.associateBy({ it.ident }, { it.person!! })
}
| 8
| null |
2
| 9
|
ce534f2feb45a66b0b01ddda7edbd6646bae306b
| 2,417
|
familie-ba-sak
|
MIT License
|
module_test/src/main/java/com/ndhzs/module/test/page/TestViewModel.kt
|
VegetableChicken-Group
| 497,243,579
| false
|
{"Kotlin": 315359, "Shell": 8775}
|
package com.ndhzs.module.test.page
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.ndhzs.lib.base.ui.BaseViewModel
import com.ndhzs.lib.utils.extensions.defaultHandler
import com.ndhzs.lib.utils.extensions.postDelay
import kotlin.random.Random
/**
* ...
* @author 985892345 (<NAME>)
* @email <EMAIL>
* @date 2022/7/25 18:41
*/
class TestViewModel : BaseViewModel() {
private val _data = MutableLiveData<Int>()
val data: LiveData<Int>
get() = _data
fun refresh() {
// 模拟网络请求
defaultHandler.postDelay(100) {
// 发送数据给 _data
_data.value = Random.nextInt()
}
}
}
| 0
|
Kotlin
|
14
| 30
|
3455309ef00ecbe61dbc2c80b8871f8981b412e2
| 647
|
WanAndroid_Multi
|
MIT License
|
app/src/main/java/com/example/covidmapper/MainActivity.kt
|
rishabh115
| 249,815,342
| false
| null |
package com.example.covidmapper
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity(), DataListener {
private lateinit var covidAdapter: CovidAdapter
private lateinit var progress: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val covidList = findViewById<RecyclerView>(R.id.rv_main)
progress = findViewById(R.id.progress)
covidAdapter = CovidAdapter()
covidList.adapter = covidAdapter
covidList.layoutManager = LinearLayoutManager(this)
progress.visibility = View.VISIBLE
DataParser(this).getCountriesData()
}
override fun onDataReceived(response: Response) {
when(response){
is Success -> {
progress.visibility = View.GONE
covidAdapter.setData(response.data)
}
is Failure -> {
progress.visibility = View.GONE
Toast.makeText(applicationContext, "Failed to fetch data!", Toast.LENGTH_SHORT).show()
}
}.exhaustiveCall
}
}
| 0
|
Kotlin
|
1
| 3
|
ebef2341b815360b04ef3e0e0ecd359e617328ff
| 1,396
|
CovidMapper
|
MIT License
|
src/main/kotlin/pistonlang/compiler/util/lists/NonEmptyList.kt
|
PistonLang
| 594,852,711
| false
| null |
package pistonlang.compiler.util.lists
@JvmInline
value class NonEmptyList<out T> internal constructor(private val nested: List<T>) : List<T> by nested {
override fun isEmpty(): Boolean = false
}
fun <T> List<T>.assertNonEmpty(): NonEmptyList<T> =
if (isEmpty()) error("The list should not be empty")
else NonEmptyList(this)
fun <T> nonEmptyListOf(first: T) = NonEmptyList(listOf(first))
| 0
|
Kotlin
|
0
| 0
|
296b4894becc0e0597930dbc230e7af80eeb6e7d
| 403
|
compiler
|
MIT License
|
KotlinTest/src/main/java/com/zcf/app2/Urls.kt
|
liang979zhang
| 134,248,607
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 56, "XML": 90, "Java": 1}
|
package com.zcf.app2
/**
* Created by Administrator on 2018/5/21.
*/
object Urls {
val url: String = "http://www.wanandroid.com/"
}
| 1
| null |
1
| 1
|
d08245f76642e5280073f879b727796a7f04f8ed
| 139
|
kotlinStudy-master
|
Apache License 2.0
|
jvm-debugger/test/testData/sequence/streams/sequence/misc/ZipWithNextSingle.kt
|
JetBrains
| 278,369,660
| false
| null |
package misc
fun main(args: Array<String>) {
// Breakpoint!
sequenceOf(1).zipWithNext().count()
}
| 0
| null |
30
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 102
|
intellij-kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/myapplication/activity/RegistroExitoso2Activity.kt
|
Francuster
| 788,721,638
| false
|
{"Kotlin": 392562, "Java": 3238}
|
package com.example.myapplication.activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.R
class RegistroExitoso2Activity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.ingreso_exitoso)
// --- Actualizar TextViews estado
val textoNombreUsuario = findViewById<TextView>(R.id.ingreso_denegado)
textoNombreUsuario.text = "REGISTRO EXITOSO"
}
fun Siguiente(view : View){
val intent = Intent(applicationContext, InicioRrHhActivity::class.java)
startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
f229fd95d9a3de9b0d78d7b535eb89da20bb8ea6
| 776
|
PPI_RF
|
Apache License 2.0
|
src/main/kotlin/com/kneelawk/transpositioners/client/screen/TPBackgroundPainters.kt
|
Kneelawk
| 332,850,862
| false
| null |
package com.kneelawk.transpositioners.client.screen
import com.kneelawk.transpositioners.client.screen.icon.IconRenderingUtils
import io.github.cottonmc.cotton.gui.client.BackgroundPainter
import io.github.cottonmc.cotton.gui.widget.WItemSlot
import io.github.cottonmc.cotton.gui.widget.data.HorizontalAlignment
import io.github.cottonmc.cotton.gui.widget.data.VerticalAlignment
import io.github.cottonmc.cotton.gui.widget.icon.Icon
object TPBackgroundPainters {
fun moduleSlot(moduleIdentifier: Icon): BackgroundPainter {
return BackgroundPainter { matrices, left, top, panel ->
BackgroundPainter.SLOT.paintBackground(matrices, left, top, panel)
if (panel is WItemSlot && !panel.isBigSlot) {
val slotsWide = panel.width / 18
val slotsTall = panel.height / 18
for (y in 0 until slotsTall) {
for (x in 0 until slotsWide) {
IconRenderingUtils.paint(
moduleIdentifier, matrices, left + x * 18 + 1, top + y * 18 + 1, 16, 16,
HorizontalAlignment.CENTER, VerticalAlignment.CENTER
)
}
}
} else {
IconRenderingUtils.paint(
moduleIdentifier, matrices, left + 1, top + 1, panel.width - 2, panel.height - 2,
HorizontalAlignment.CENTER, VerticalAlignment.CENTER
)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fc85e9c93dc93a81353004a08d18ab5d836437a8
| 1,515
|
Transpositioners
|
MIT License
|
Extensions/Economy/src/main/kotlin/net/sourcebot/module/economy/Economy.kt
|
TheSourceCodeLLC
| 271,902,483
| false
| null |
package net.sourcebot.module.economy
import net.dv8tion.jda.api.entities.Member
import net.sourcebot.Source
import net.sourcebot.api.configuration.ConfigurationInfo
import net.sourcebot.api.module.SourceModule
import net.sourcebot.module.economy.command.*
import net.sourcebot.module.economy.data.EconomyData
import net.sourcebot.module.economy.listener.BoosterListener
import net.sourcebot.module.economy.listener.EconomyListener
import net.sourcebot.module.profiles.Profiles
class Economy : SourceModule() {
override val configurationInfo = ConfigurationInfo("economy") {
node("nickname-cost", "The amount of coins a nickname change costs")
}
override fun enable() {
registerCommands(
BalanceCommand(),
GambleCommand(),
DailyCommand(),
CoinLeaderboardCommand(),
PayCommand()
)
subscribeEvents(EconomyListener())
if (Source.MODULE_HANDLER.moduleExists("Boosters")) {
subscribeEvents(BoosterListener())
}
}
companion object {
@JvmStatic operator fun get(member: Member) = Profiles.proxyObject(member, "economy") {
EconomyData(it, member)
}
}
}
| 5
|
Kotlin
|
8
| 9
|
2bd6a869343a50cf6c9104c4afec092d827ffe5d
| 1,220
|
Source
|
MIT License
|
app/src/main/java/com/yury/lebowski/ui/operations/OperationTabListAdapter.kt
|
iliailemkov
| 143,139,061
| true
|
{"Kotlin": 112583}
|
package com.yury.lebowski.ui.operations
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import com.yury.lebowski.data.local.models.enums.OperationState
class OperationTabListAdapter(fm: FragmentManager, tabTitle: Array<String>, accountId: Long) : FragmentStatePagerAdapter(fm) {
private val tabTitles = tabTitle
private val accountId = accountId
override fun getPageTitle(position: Int): CharSequence? {
return tabTitles[position]
}
override fun getItem(position: Int): Fragment? {
when (position) {
0 -> return OperationTabFragment.newInstance(OperationState.Normal, accountId)
1 -> return OperationTabFragment.newInstance(OperationState.Periodical, accountId)
2 -> return OperationTabFragment.newInstance(OperationState.Draft, accountId)
else -> return null
}
}
override fun getCount(): Int {
return 3
}
}
| 0
|
Kotlin
|
0
| 0
|
aec038962531c5c1945ce4df71f3f93c15ebd4c1
| 1,016
|
Lebowski
|
Creative Commons Attribution 3.0 Unported
|
src/main/kotlin/com/dannbrown/braziliandelight/content/block/FallingCoconutBlock.kt
|
danbrown
| 768,934,002
| false
|
{"Kotlin": 370306, "Java": 3856}
|
package com.dannbrown.braziliandelight.content.block
import com.dannbrown.braziliandelight.init.AddonBlocks
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.world.damagesource.DamageSource
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.item.FallingBlockEntity
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.context.BlockPlaceContext
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.ItemLike
import net.minecraft.world.level.Level
import net.minecraft.world.level.LevelReader
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.FaceAttachedHorizontalDirectionalBlock
import net.minecraft.world.level.block.FallingBlock
import net.minecraft.world.level.block.HorizontalDirectionalBlock
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.level.block.state.properties.AttachFace
import net.minecraft.world.level.block.state.properties.BlockStateProperties
import net.minecraft.world.level.block.state.properties.DirectionProperty
import net.minecraft.world.level.pathfinder.PathComputationType
import net.minecraft.world.phys.HitResult
import net.minecraft.world.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.VoxelShape
import java.util.function.Supplier
class FallingCoconutBlock(props: Properties, private val item: Supplier<ItemLike>): FallingBlock(props) {
companion object{
val SHAPE: VoxelShape = box(4.0, 0.0, 4.0, 12.0, 8.0, 12.0)
const val FALL_DAMAGE_PER_DISTANCE = 2.0f
const val FALL_DAMAGE_MAX = 20
val FACING: DirectionProperty = BlockStateProperties.HORIZONTAL_FACING
}
init {
registerDefaultState(defaultBlockState().setValue(FACING, Direction.NORTH))
}
override fun createBlockStateDefinition(pBuilder: StateDefinition.Builder<Block, BlockState>) {
pBuilder.add(FACING)
}
override fun getCloneItemStack(state: BlockState?, target: HitResult?, level: BlockGetter?, pos: BlockPos?, player: Player?): ItemStack {
return ItemStack(item.get())
}
override fun getShape(pState: BlockState, pLevel: BlockGetter, pPos: BlockPos, pContext: CollisionContext): VoxelShape {
return SHAPE
}
override fun getStateForPlacement(pContext: BlockPlaceContext): BlockState? {
return defaultBlockState().setValue(FACING, pContext.horizontalDirection.opposite)
}
override fun falling(pFallingEntity: FallingBlockEntity) {
pFallingEntity.setHurtsEntities(FALL_DAMAGE_PER_DISTANCE, FALL_DAMAGE_MAX)
}
override fun getFallDamageSource(pEntity: Entity): DamageSource {
return pEntity.damageSources().fallingBlock(pEntity)
}
override fun isPathfindable(pState: BlockState, pLevel: BlockGetter, pPos: BlockPos, pType: PathComputationType): Boolean {
return false
}
override fun canSurvive(pState: BlockState, pLevel: LevelReader, pPos: BlockPos): Boolean {
// if bellow is face sturdy
val blockPos = pPos.below()
val blockState = pLevel.getBlockState(blockPos)
return blockState.isFaceSturdy(pLevel, blockPos, Direction.UP)
}
override fun onLand(pLevel: Level, pPos: BlockPos, pState: BlockState, pReplaceableState: BlockState, pFallingBlock: FallingBlockEntity) {
pLevel.setBlockAndUpdate(pPos, AddonBlocks.COCONUT.get().defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, pState.getValue(FACING)).setValue(FaceAttachedHorizontalDirectionalBlock.FACE, AttachFace.FLOOR))
}
override fun onBrokenAfterFall(pLevel: Level, pPos: BlockPos, pFallingBlock: FallingBlockEntity) {
if (!pFallingBlock.isSilent) {
Block.popResource(pLevel, pPos, ItemStack(item.get()))
}
}
}
| 0
|
Kotlin
|
0
| 1
|
c69fbc2a58d23c4048eca870714d681b9697970b
| 3,825
|
braziliandelight
|
MIT License
|
core/src/main/java/com/zyhang/startup/utils/ProcessUtils.kt
|
EvilMouth
| 306,280,273
| false
|
{"Gradle": 13, "Java Properties": 2, "YAML": 3, "Shell": 1, "Ignore List": 11, "Batchfile": 1, "Markdown": 1, "INI": 7, "Proguard": 9, "Kotlin": 56, "XML": 24, "Java": 7}
|
package com.zyhang.startup.utils
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Process
class ProcessUtils {
companion object {
private var currentProcessName: String? = null
fun getCurrentProcessName(context: Context): String? {
if (currentProcessName == null) {
currentProcessName = getCurrentProcessNameIn(context)
}
return currentProcessName
}
@SuppressLint("DiscouragedPrivateApi", "PrivateApi")
@JvmStatic
private fun getCurrentProcessNameIn(context: Context): String? {
// 1.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
val name = Application.getProcessName()
if (!name.isNullOrEmpty()) {
return name
}
}
// 2.
runCatching {
val method = Class.forName(
"android.app.ActivityThread",
false,
Application::class.java.classLoader
).getDeclaredMethod("currentProcessName")
method.isAccessible = true
val invoke = method.invoke(null)
if (invoke is String && invoke.isNotEmpty()) {
return invoke
}
}
// 3.
val pid = Process.myPid()
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
am.runningAppProcesses.forEach { processInfo ->
if (processInfo.pid == pid) {
return processInfo.processName
}
}
// 4.
return null
}
}
}
| 0
|
Kotlin
|
0
| 12
|
3bb85cbcc918d2819422c1dd800b5dbb74ecae9a
| 1,859
|
Startup
|
Apache License 2.0
|
core/src/main/java/com/zyhang/startup/utils/ProcessUtils.kt
|
EvilMouth
| 306,280,273
| false
|
{"Gradle": 13, "Java Properties": 2, "YAML": 3, "Shell": 1, "Ignore List": 11, "Batchfile": 1, "Markdown": 1, "INI": 7, "Proguard": 9, "Kotlin": 56, "XML": 24, "Java": 7}
|
package com.zyhang.startup.utils
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Process
class ProcessUtils {
companion object {
private var currentProcessName: String? = null
fun getCurrentProcessName(context: Context): String? {
if (currentProcessName == null) {
currentProcessName = getCurrentProcessNameIn(context)
}
return currentProcessName
}
@SuppressLint("DiscouragedPrivateApi", "PrivateApi")
@JvmStatic
private fun getCurrentProcessNameIn(context: Context): String? {
// 1.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
val name = Application.getProcessName()
if (!name.isNullOrEmpty()) {
return name
}
}
// 2.
runCatching {
val method = Class.forName(
"android.app.ActivityThread",
false,
Application::class.java.classLoader
).getDeclaredMethod("currentProcessName")
method.isAccessible = true
val invoke = method.invoke(null)
if (invoke is String && invoke.isNotEmpty()) {
return invoke
}
}
// 3.
val pid = Process.myPid()
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
am.runningAppProcesses.forEach { processInfo ->
if (processInfo.pid == pid) {
return processInfo.processName
}
}
// 4.
return null
}
}
}
| 0
|
Kotlin
|
0
| 12
|
3bb85cbcc918d2819422c1dd800b5dbb74ecae9a
| 1,859
|
Startup
|
Apache License 2.0
|
app/src/main/java/com/batdemir/template/data/entities/db/ListModel.kt
|
batdemir
| 332,569,012
| false
| null |
package com.batdemir.template.data.entities.db
import android.os.Parcel
import android.os.Parcelable
data class ListModel(
val dt: Long,
val main: MainModel,
val weather: List<WeatherModel>,
val clouds: CloudsModel,
val wind: WindModel,
val visibility: Long,
val pop: Double,
val sys: SysModel,
val dt_txt: String
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readLong(),
parcel.readParcelable(MainModel::class.java.classLoader)!!,
parcel.createTypedArrayList(WeatherModel)!!,
parcel.readParcelable(CloudsModel::class.java.classLoader)!!,
parcel.readParcelable(WindModel::class.java.classLoader)!!,
parcel.readLong(),
parcel.readDouble(),
parcel.readParcelable(SysModel::class.java.classLoader)!!,
parcel.readString()!!
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(dt)
parcel.writeParcelable(main, flags)
parcel.writeTypedList(weather)
parcel.writeParcelable(clouds, flags)
parcel.writeParcelable(wind, flags)
parcel.writeLong(visibility)
parcel.writeDouble(pop)
parcel.writeParcelable(sys, flags)
parcel.writeString(dt_txt)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<ListModel> {
override fun createFromParcel(parcel: Parcel): ListModel {
return ListModel(parcel)
}
override fun newArray(size: Int): Array<ListModel?> {
return arrayOfNulls(size)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2721e6369ac5e828f8b4c78e2dc619a5743ba096
| 1,642
|
weather.example.public
|
Apache License 2.0
|
src/test/kotlin/com/hbk619/intellisay/files/FileNameListenerTest.kt
|
hbk619
| 762,230,623
| false
|
{"Kotlin": 90904}
|
package com.hbk619.intellisay.files
import com.hbk619.intellisay.BaseTestCase
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.testFramework.UsefulTestCase
class FileNameListenerTest: BaseTestCase() {
override fun getTestDataPath(): String {
return "src/test/testdata/java-play"
}
fun testSayFileNameWhenFileOpened() {
myFixture.configureByFile("src/Main.java")
myFixture.performEditorAction("IntelliSay.SayFileName")
val queue = getAudibleQueue()
UsefulTestCase.assertSize(1, queue.calls)
val call = queue.calls[0]
UsefulTestCase.assertEquals(listOf(project, "Main.java", "Saying file name"), call.args)
}
fun testWarnsWhenFileNotOpen() {
myFixture.configureByFile("src/Main.java")
FileEditorManagerEx.getInstanceEx(project).closeAllFiles()
myFixture.performEditorAction("IntelliSay.SayFileName")
val queue = getAudibleQueue()
UsefulTestCase.assertSize(1, queue.calls)
val call = queue.calls[0]
UsefulTestCase.assertEquals(listOf(project, "Editor not focused. Press escape", "Saying file name"), call.args)
}
}
| 0
|
Kotlin
|
0
| 0
|
c166a75bd838e9eff16713e779c377de7e62880e
| 1,190
|
intellisay
|
MIT License
|
src/main/kotlin/g1001_1100/s1051_height_checker/Solution.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
|
package g1001_1100.s1051_height_checker
// #Easy #Array #Sorting #Counting_Sort #2023_05_29_Time_140_ms_(94.37%)_Space_35.3_MB_(77.46%)
class Solution {
fun heightChecker(heights: IntArray): Int {
var heightDiff = 0
val count = IntArray(101)
val actualLine = IntArray(heights.size)
for (height in heights) {
count[height]++
}
var heightLength = 0
for (i in count.indices) {
if (count[i] > 0) {
for (j in 0 until count[i]) {
actualLine[heightLength] = i
heightLength++
}
count[i] = 0
}
}
for (i in heights.indices) {
if (actualLine[i] != heights[i]) {
heightDiff++
}
}
return heightDiff
}
}
| 0
|
Kotlin
|
20
| 43
|
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
| 852
|
LeetCode-in-Kotlin
|
MIT License
|
app/src/main/java/ru/fredboy/toxoid/clean/domain/usecase/tox/GetLatestSelfConnectionStatusUseCase.kt
|
fredboy
| 549,930,628
| false
| null |
package ru.fredboy.toxoid.clean.domain.usecase.tox
import im.tox.tox4j.core.enums.ToxConnection
import ru.fredboy.toxoid.clean.data.repository.ToxSelfConnectionRepository
import javax.inject.Inject
class GetLatestSelfConnectionStatusUseCase @Inject constructor(
private val toxSelfConnectionRepository: ToxSelfConnectionRepository
) {
fun execute(): ToxConnection {
return toxSelfConnectionRepository.getLatestSelfConnectionStatus()
}
}
| 0
|
Kotlin
|
0
| 1
|
01bb244970635a8e3e01d418e3c64b71d99010a3
| 460
|
toxoid
|
MIT License
|
src/main/kotlin/de/flapdoodle/tab/observable/KObservables.kt
|
flapdoodle-oss
| 237,231,857
| false
| null |
package de.flapdoodle.tab.observable
import de.flapdoodle.fx.bindings.Bindings
import javafx.beans.binding.ObjectBinding
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import org.fxmisc.easybind.monadic.MonadicBinding
fun <S : Any, D : Any> AObservable<S>.mapNonNull(map: (S) -> D?): AObservable<D> {
return KObservables.mapNonNull(this, map)
}
fun <S : Any, D : Any> AObservable<S>.map(map: (S) -> D): AObservable<D> {
return KObservables.map(this, map)
}
fun <S : Any, D : Any> AObservable<List<S>>.mapList(map: (S) -> D): AObservable<List<D>> {
return KObservables.map(this) {
it.map(map)
}
}
fun <S : Any, D : Any> AObservable<S>.mapToList(map: (S) -> List<D>): AObservable<List<D>> {
return KObservables.map(this) {
map(it)
}
}
fun <A : Any, B : Any, D : Any> AObservable<A>.merge(other: AObservable<B>, map: (A, B) -> D): AObservable<D> {
return KObservables.merge(this, other, map)
}
fun <T : Any> AObservable<T>.asBinding(): MonadicBinding<T> {
return KObservables.AObservableAsBinding(this)
}
fun <T : Any> AObservable<List<T>>.asListBinding(): ObservableList<T> {
return KObservables.asListBinding(this)
}
object KObservables {
fun <S : Any, D : Any> map(src: AObservable<S>, map: (S) -> D): AObservable<D> {
val ret = ChangeableObservable(map(src.value()))
val changeListener = ChangeListener<S> { _, old, new ->
if (old != new) {
ret.value(map(new))
}
}
src.addListener(WeakChangeListenerDelegate(changeListener))
return AObservable.Wrapper(ret, listOf(src, changeListener))
}
fun <S : Any, D : Any> mapNonNull(src: AObservable<S>, map: (S) -> D?): AObservable<D> {
val initialValue = map(src.value())
require(initialValue!=null) {"initial value is null"}
val ret = ChangeableObservable(initialValue)
val changeListener = ChangeListener<S> { _, old, new ->
if (old != new) {
val mapped = map(new)
if (mapped!=null) {
ret.value(mapped)
}
}
}
src.addListener(WeakChangeListenerDelegate(changeListener))
return AObservable.Wrapper(ret, listOf(src, changeListener))
}
fun <A : Any, B : Any, D : Any> merge(a: AObservable<A>, b: AObservable<B>, map: (A, B) -> D): AObservable<D> {
val ret = ChangeableObservable(map(a.value(), b.value()))
val changeListenerA = ChangeListener<A> { _, _, newA ->
ret.value(map(newA, b.value()))
}
val changeListenerB = ChangeListener<B> { _, _, newB ->
ret.value(map(a.value(), newB))
}
a.addListener(WeakChangeListenerDelegate(changeListenerA))
b.addListener(WeakChangeListenerDelegate(changeListenerB))
return AObservable.Wrapper(ret, listOf(a, b, changeListenerA, changeListenerB))
}
fun <T: Any> asListBinding(src: AObservable<List<T>>) : ObservableList<T> {
val ret = FXCollections.observableArrayList<T>()
val listener = ChangeListener<List<T>> { _, _, list ->
ret.setAll(list)
}
ret.setAll(src.value())
src.addListener(WeakChangeListenerDelegate(listener))
return Wrapper(
delegate = ret,
listener = listener,
source = src
)
}
class AObservableAsBinding<T : Any>(
private val src: AObservable<T>
) : ObjectBinding<T>(), MonadicBinding<T> {
val listener = ChangeListener<T> { _, _, _ ->
invalidate()
}
init {
src.addListener(WeakChangeListenerDelegate(listener))
}
override fun computeValue(): T {
return src.value()
}
}
class Wrapper<T>(
delegate: ObservableList<T>,
private val listener: ChangeListener<out Any>,
private val source: AObservable<out Any>
) : Bindings.ObservableListWrapper<T>(delegate)
}
| 0
|
Kotlin
|
1
| 0
|
8fbeeba0df11af2c780d48a505b826c9196c6158
| 3,737
|
tab
|
Apache License 2.0
|
android-lang/src/com/android/tools/idea/lang/agsl/AgslParserDefinition.kt
|
JetBrains
| 60,701,247
| false
|
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
|
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.tools.idea.lang.agsl
import com.android.tools.idea.lang.agsl.parser.AgslParser
import com.android.tools.idea.lang.agsl.psi.AgslFile
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.fileTypes.PlainTextParserDefinition
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
/**
* Temporary delegate to either the [ActualAgslParserDefinition] or the [PlainTextParserDefinition] based on whether AGSL support is
* enabled.
*/
class AgslParserDefinition :
ParserDefinition by ActualAgslParserDefinition() {
fun createLexer(): Lexer = AgslLexer()
}
private class ActualAgslParserDefinition : ParserDefinition {
fun createLexer(): Lexer = AgslLexer()
override fun createLexer(project: Project): Lexer = createLexer()
override fun createParser(project: Project): PsiParser = AgslParser()
override fun getFileNodeType(): IFileElementType = AGSL_FILE_ELEMENT_TYPE
override fun getWhitespaceTokens(): TokenSet = AgslTokenTypeSets.WHITESPACES
override fun getCommentTokens(): TokenSet = AgslTokenTypeSets.COMMENTS
override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY
override fun createElement(node: ASTNode): PsiElement = AgslTokenTypes.Factory.createElement(node)
override fun createFile(viewProvider: FileViewProvider): PsiFile = AgslFile(viewProvider)
override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode): ParserDefinition.SpaceRequirements =
ParserDefinition.SpaceRequirements.MAY
}
private val AGSL_FILE_ELEMENT_TYPE = IFileElementType(AgslLanguage.INSTANCE)
| 5
|
Kotlin
|
230
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 2,467
|
android
|
Apache License 2.0
|
app/src/main/kotlin/com/ojhdtapp/parabox/ui/common/ChangeLogBottomSheet.kt
|
Parabox-App
| 482,740,446
| false
|
{"Kotlin": 1527632, "Java": 316}
|
package com.ojhdtapp.parabox.ui.common
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.ModalBottomSheetProperties
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.halilibo.richtext.commonmark.Markdown
import com.halilibo.richtext.ui.BasicRichText
import com.ojhdtapp.parabox.core.util.LoadState
import com.ojhdtapp.parabox.domain.model.ChangeLog
import com.ojhdtapp.parabox.ui.MainSharedEvent
import com.ojhdtapp.parabox.ui.MainSharedState
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChangeLogBottomSheet(
modifier: Modifier = Modifier,
changeLogBottomSheetState: MainSharedState.ChangeLogBottomSheetState,
onEvent: (MainSharedEvent) -> Unit,
) {
val sheetState = rememberModalBottomSheetState()
if (changeLogBottomSheetState.showBottomSheet) {
ModalBottomSheet(
sheetState = sheetState,
onDismissRequest = {
onEvent(MainSharedEvent.ShowChangeLog(false))
},
modifier = modifier
) {
when (changeLogBottomSheetState.loadState) {
LoadState.LOADING -> {
Box(
modifier = Modifier
.fillMaxWidth()
.height(176.dp),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
LoadState.ERROR -> {
Box(
modifier = Modifier
.fillMaxWidth()
.height(176.dp),
contentAlignment = Alignment.Center
) {
androidx.compose.material3.Text(text = "发生错误")
}
}
LoadState.SUCCESS -> {
LazyColumn {
items(items = changeLogBottomSheetState.data) {
Column(
modifier = Modifier.padding(horizontal = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Surface(shape = RoundedCornerShape(24.dp), color = MaterialTheme.colorScheme.primaryContainer) {
Box(
modifier = Modifier
.height(48.dp)
.padding(horizontal = 16.dp),
contentAlignment = Alignment.Center
) {
Text(
text = it.version,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary
)
}
}
Spacer(modifier = Modifier.height(16.dp))
BasicRichText(modifier = Modifier.fillMaxWidth()) {
Markdown(
content = (AppCompatDelegate.getApplicationLocales()[0]?.toLanguageTag() ?: Locale.getDefault().language).let { tag ->
if (tag.contains("zh")) {
it.contentMdCn
} else {
it.contentMdEn
}
}
)
}
Spacer(modifier = Modifier.height(32.dp))
}
}
}
}
}
}
}
}
| 2
|
Kotlin
|
8
| 128
|
ff3c8605d40e73ce90a86e816b21bb6d30f8d084
| 5,082
|
Parabox
|
MIT License
|
testing/src/test/kotlin/cz/vutbr/fit/knot/enticing/testing/performance/EnticingTestFixture.kt
|
d-kozak
| 180,137,313
| false
|
{"Kotlin": 1104829, "TypeScript": 477922, "Python": 23617, "Shell": 19609, "HTML": 8510, "ANTLR": 2005, "CSS": 1432}
|
package cz.vutbr.fit.knot.enticing.testing.performance
import cz.vutbr.fit.knot.enticing.dto.SearchQuery
import cz.vutbr.fit.knot.enticing.dto.config.dsl.EnticingConfiguration
import cz.vutbr.fit.knot.enticing.dto.config.dsl.validateOrFail
import cz.vutbr.fit.knot.enticing.dto.config.executeScript
import cz.vutbr.fit.knot.enticing.index.client.WebserverApi
import cz.vutbr.fit.knot.enticing.index.client.webserverLogin
import cz.vutbr.fit.knot.enticing.log.SimpleStdoutLoggerFactory
import cz.vutbr.fit.knot.enticing.management.ManagementService
import cz.vutbr.fit.knot.enticing.management.command.concrete.*
import kotlinx.coroutines.runBlocking
import java.io.File
interface FixtureConfiguration {
val scriptPath: String
val corpusName: String
val searchSettingsPath: String
}
object SmallWiki2018Config : FixtureConfiguration {
override val scriptPath = "../deploy/small-wiki/testConfig.kts"
override val corpusName: String = "wiki-2018"
override val searchSettingsPath = "../deploy/small-wiki/small-wiki.search.settings.json"
}
object FullWiki2018Config : FixtureConfiguration {
override val scriptPath = "../deploy/big-wiki/config.kts"
override val corpusName: String = "wiki-2018"
override val searchSettingsPath = "../deploy/big-wiki/webserver-search-settings.json"
}
class EnticingTestFixture(private val fixtureConfig: FixtureConfiguration, rebootComponents: Boolean) : AutoCloseable {
private val config = executeScript<EnticingConfiguration>(fixtureConfig.scriptPath).validateOrFail()
private val webserverApi: WebserverApi
private val managementService = ManagementService(config, SimpleStdoutLoggerFactory)
init {
if (rebootComponents) {
buildLocally()
killTestSetup()
startTestSetup()
}
webserverApi = webserverLogin(config.webserverConfiguration.fullAddress, "admin", "knot12")
if (rebootComponents)
webserverApi.importSearchSettings(File(fixtureConfig.searchSettingsPath).readText())
println(webserverApi.userInfo())
}
fun sendQuery(query: SearchQuery) = webserverApi.sendQuery(query)
fun sendQuery(query: String) = sendQuery(SearchQuery(query))
fun getMore() = webserverApi.getMore()
fun buildLocally() {
// todo fix local build
// managementService.executeCommand(LocalBuildCommand)
runBlocking {
managementService.executeCommand(CopyJarsCommand(config.localHome, config.deploymentConfiguration, SimpleStdoutLoggerFactory))
}
}
fun startTestSetup() {
runBlocking {
managementService.executeCommand(StartManagementServiceCommand(config.managementServiceConfiguration.fullAddress, config.deploymentConfiguration))
managementService.executeCommand(StartIndexServersCommand(config.corpuses.getValue(fixtureConfig.corpusName), config.deploymentConfiguration))
managementService.executeCommand(StartWebserverCommand(config.webserverConfiguration.fullAddress, config.deploymentConfiguration))
}
}
fun killTestSetup() {
runBlocking {
managementService.executeCommand(KillManagementServiceCommand(config.managementServiceConfiguration.address))
managementService.executeCommand(KillIndexServersCommand(config.corpuses.getValue(fixtureConfig.corpusName)))
managementService.executeCommand(KillWebserverCommand(config.webserverConfiguration.address))
}
}
override fun close() {
managementService.close()
}
}
| 0
|
Kotlin
|
0
| 0
|
1ea9f874c6d2e4ea158e20bbf672fc45bcb4a561
| 3,580
|
enticing
|
MIT License
|
subprojects/delivery/cd/src/main/kotlin/com/avito/ci/steps/TestSummaryPluginBuildStep.kt
|
avito-tech
| 230,265,582
| false
| null |
package com.avito.ci.steps
import com.android.build.gradle.internal.tasks.factory.dependsOn
import com.avito.android.stats.statsdConfig
import com.avito.impact.configuration.internalModule
import com.avito.instrumentation.extractReportCoordinates
import com.avito.instrumentation.instrumentationTaskDefaultEnvironment
import com.avito.logger.GradleLoggerPlugin
import com.avito.reportviewer.model.ReportCoordinates
import com.avito.test.summary.TestSummaryExtension
import com.avito.test.summary.TestSummaryFactory
import com.avito.test.summary.testSummaryPluginId
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.getByType
public abstract class TestSummaryPluginBuildStep(context: String, name: String) :
BuildStep(context, name),
ImpactAnalysisAwareBuildStep by ImpactAnalysisAwareBuildStep.Impl() {
public var configuration: String = ""
protected abstract val stepName: String
protected abstract fun getOrCreateTask(
rootTasksContainer: TaskContainer,
extension: TestSummaryExtension,
reportCoordinates: ReportCoordinates,
testSummaryFactory: TestSummaryFactory,
): TaskProvider<out Task>
override fun registerTask(project: Project, rootTask: TaskProvider<out Task>) {
require(project.rootProject.pluginManager.hasPlugin(testSummaryPluginId)) {
"$stepName step can't be initialized without $testSummaryPluginId plugin applied to root project"
}
require(configuration.isNotBlank()) {
"$stepName step can't be initialized without provided instrumentation configuration"
}
if (useImpactAnalysis && !project.internalModule.isModified()) return
// flavors not supported here
val instrumentationTask = project.tasks.instrumentationTaskDefaultEnvironment(configuration, null)
val reportCoordinates = instrumentationTask.extractReportCoordinates()
val task = getOrCreateTask(
rootTasksContainer = project.rootProject.tasks,
extension = project.rootProject.extensions.getByType(),
reportCoordinates = reportCoordinates.get(),
testSummaryFactory = TestSummaryFactory(
loggerFactory = GradleLoggerPlugin.getLoggerFactory(project).get(),
statsDConfig = project.statsdConfig,
)
)
task.configure {
it.dependsOn(instrumentationTask)
}
rootTask.dependsOn(task)
}
}
| 6
| null |
36
| 327
|
b8d12a06a169ae60d89d24f66978a7dc23833282
| 2,581
|
avito-android
|
MIT License
|
java/src/test/java/trinsic/KotlinTestKt.kt
|
trinsic-id
| 361,889,702
| false
|
{"Dart": 1230446, "TypeScript": 932951, "Java": 476366, "Rust": 305144, "Kotlin": 187564, "Python": 107506, "C#": 93194, "Go": 92301, "PowerShell": 6207, "JavaScript": 4802}
|
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
class KotlinTestKt {
@Test
fun ecosystemDemo() {
runBlocking { runEcosystemsDemo() }
}
@Test
fun trustRegistryDemo() {
runBlocking { runTrustRegistryDemo() }
}
@Test
fun vaccineDemo() {
runBlocking { runVaccineDemo() }
}
}
| 10
|
Dart
|
16
| 28
|
8174f1266566ff1396fa344c212e19b2dcca6623
| 326
|
sdk
|
Apache License 2.0
|
_pending/WeatherApp_v8/app/src/main/java/com/weatherapp/models/Clouds.kt
|
sosimpson1
| 371,359,679
| false
| null |
package com.blissvine.weatherapp.models
import java.io.Serializable
data class Clouds(
val all: Int,
): Serializable
| 1
| null |
3
| 1
|
fc0bfc3b717a681f504c7a438460798d4c7620d5
| 123
|
my-android-journey
|
MIT License
|
src/main/kotlin/org/opensearch/commons/notifications/model/EventSource.kt
|
opensearch-project
| 354,136,133
| false
| null |
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.commons.notifications.model
import org.opensearch.common.Strings
import org.opensearch.common.io.stream.StreamInput
import org.opensearch.common.io.stream.StreamOutput
import org.opensearch.common.io.stream.Writeable
import org.opensearch.common.xcontent.ToXContent
import org.opensearch.common.xcontent.XContentBuilder
import org.opensearch.common.xcontent.XContentParser
import org.opensearch.common.xcontent.XContentParserUtils
import org.opensearch.commons.notifications.NotificationConstants.FEATURE_TAG
import org.opensearch.commons.notifications.NotificationConstants.REFERENCE_ID_TAG
import org.opensearch.commons.notifications.NotificationConstants.SEVERITY_TAG
import org.opensearch.commons.notifications.NotificationConstants.TAGS_TAG
import org.opensearch.commons.notifications.NotificationConstants.TITLE_TAG
import org.opensearch.commons.utils.logger
import org.opensearch.commons.utils.stringList
import java.io.IOException
/**
* Data class representing Notification event source.
*/
data class EventSource(
val title: String,
val referenceId: String,
val feature: String,
val severity: SeverityType = SeverityType.INFO,
val tags: List<String> = listOf()
) : BaseModel {
init {
require(!Strings.isNullOrEmpty(title)) { "name is null or empty" }
}
companion object {
private val log by logger(EventSource::class.java)
/**
* reader to create instance of class from writable.
*/
val reader = Writeable.Reader { EventSource(it) }
/**
* Creator used in REST communication.
* @param parser XContentParser to deserialize data from.
*/
@JvmStatic
@Throws(IOException::class)
fun parse(parser: XContentParser): EventSource {
var title: String? = null
var referenceId: String? = null
var feature: String? = null
var severity: SeverityType = SeverityType.INFO
var tags: List<String> = emptyList()
XContentParserUtils.ensureExpectedToken(
XContentParser.Token.START_OBJECT,
parser.currentToken(),
parser
)
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
val fieldName = parser.currentName()
parser.nextToken()
when (fieldName) {
TITLE_TAG -> title = parser.text()
REFERENCE_ID_TAG -> referenceId = parser.text()
FEATURE_TAG -> feature = parser.text()
SEVERITY_TAG -> severity = SeverityType.fromTagOrDefault(parser.text())
TAGS_TAG -> tags = parser.stringList()
else -> {
parser.skipChildren()
log.info("Unexpected field: $fieldName, while parsing EventSource")
}
}
}
title ?: throw IllegalArgumentException("$TITLE_TAG field absent")
referenceId ?: throw IllegalArgumentException("$REFERENCE_ID_TAG field absent")
feature ?: throw IllegalArgumentException("$FEATURE_TAG field absent")
return EventSource(
title,
referenceId,
feature,
severity,
tags
)
}
}
/**
* {@inheritDoc}
*/
override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder {
builder!!
return builder.startObject()
.field(TITLE_TAG, title)
.field(REFERENCE_ID_TAG, referenceId)
.field(FEATURE_TAG, feature)
.field(SEVERITY_TAG, severity.tag)
.field(TAGS_TAG, tags)
.endObject()
}
/**
* Constructor used in transport action communication.
* @param input StreamInput stream to deserialize data from.
*/
constructor(input: StreamInput) : this(
title = input.readString(),
referenceId = input.readString(),
feature = input.readString(),
severity = input.readEnum(SeverityType::class.java),
tags = input.readStringList()
)
/**
* {@inheritDoc}
*/
override fun writeTo(output: StreamOutput) {
output.writeString(title)
output.writeString(referenceId)
output.writeString(feature)
output.writeEnum(severity)
output.writeStringCollection(tags)
}
}
| 28
| null |
93
| 7
|
d221aa35182c323a191144cdb3668f08df45d964
| 4,617
|
common-utils
|
Apache License 2.0
|
src/main/kotlin/org/opensearch/commons/notifications/model/EventSource.kt
|
opensearch-project
| 354,136,133
| false
| null |
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.commons.notifications.model
import org.opensearch.common.Strings
import org.opensearch.common.io.stream.StreamInput
import org.opensearch.common.io.stream.StreamOutput
import org.opensearch.common.io.stream.Writeable
import org.opensearch.common.xcontent.ToXContent
import org.opensearch.common.xcontent.XContentBuilder
import org.opensearch.common.xcontent.XContentParser
import org.opensearch.common.xcontent.XContentParserUtils
import org.opensearch.commons.notifications.NotificationConstants.FEATURE_TAG
import org.opensearch.commons.notifications.NotificationConstants.REFERENCE_ID_TAG
import org.opensearch.commons.notifications.NotificationConstants.SEVERITY_TAG
import org.opensearch.commons.notifications.NotificationConstants.TAGS_TAG
import org.opensearch.commons.notifications.NotificationConstants.TITLE_TAG
import org.opensearch.commons.utils.logger
import org.opensearch.commons.utils.stringList
import java.io.IOException
/**
* Data class representing Notification event source.
*/
data class EventSource(
val title: String,
val referenceId: String,
val feature: String,
val severity: SeverityType = SeverityType.INFO,
val tags: List<String> = listOf()
) : BaseModel {
init {
require(!Strings.isNullOrEmpty(title)) { "name is null or empty" }
}
companion object {
private val log by logger(EventSource::class.java)
/**
* reader to create instance of class from writable.
*/
val reader = Writeable.Reader { EventSource(it) }
/**
* Creator used in REST communication.
* @param parser XContentParser to deserialize data from.
*/
@JvmStatic
@Throws(IOException::class)
fun parse(parser: XContentParser): EventSource {
var title: String? = null
var referenceId: String? = null
var feature: String? = null
var severity: SeverityType = SeverityType.INFO
var tags: List<String> = emptyList()
XContentParserUtils.ensureExpectedToken(
XContentParser.Token.START_OBJECT,
parser.currentToken(),
parser
)
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
val fieldName = parser.currentName()
parser.nextToken()
when (fieldName) {
TITLE_TAG -> title = parser.text()
REFERENCE_ID_TAG -> referenceId = parser.text()
FEATURE_TAG -> feature = parser.text()
SEVERITY_TAG -> severity = SeverityType.fromTagOrDefault(parser.text())
TAGS_TAG -> tags = parser.stringList()
else -> {
parser.skipChildren()
log.info("Unexpected field: $fieldName, while parsing EventSource")
}
}
}
title ?: throw IllegalArgumentException("$TITLE_TAG field absent")
referenceId ?: throw IllegalArgumentException("$REFERENCE_ID_TAG field absent")
feature ?: throw IllegalArgumentException("$FEATURE_TAG field absent")
return EventSource(
title,
referenceId,
feature,
severity,
tags
)
}
}
/**
* {@inheritDoc}
*/
override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder {
builder!!
return builder.startObject()
.field(TITLE_TAG, title)
.field(REFERENCE_ID_TAG, referenceId)
.field(FEATURE_TAG, feature)
.field(SEVERITY_TAG, severity.tag)
.field(TAGS_TAG, tags)
.endObject()
}
/**
* Constructor used in transport action communication.
* @param input StreamInput stream to deserialize data from.
*/
constructor(input: StreamInput) : this(
title = input.readString(),
referenceId = input.readString(),
feature = input.readString(),
severity = input.readEnum(SeverityType::class.java),
tags = input.readStringList()
)
/**
* {@inheritDoc}
*/
override fun writeTo(output: StreamOutput) {
output.writeString(title)
output.writeString(referenceId)
output.writeString(feature)
output.writeEnum(severity)
output.writeStringCollection(tags)
}
}
| 28
| null |
93
| 7
|
d221aa35182c323a191144cdb3668f08df45d964
| 4,617
|
common-utils
|
Apache License 2.0
|
spesialist-selve/src/test/kotlin/no/nav/helse/mediator/api/OppgaveApiTest.kt
|
navikt
| 244,907,980
| false
| null |
package no.nav.helse.mediator.api
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.client.*
import io.ktor.client.features.*
import io.ktor.client.features.json.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.features.*
import io.ktor.http.*
import io.ktor.jackson.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import no.nav.helse.AzureAdAppConfig
import no.nav.helse.azureAdAppAuthentication
import no.nav.helse.mediator.api.AbstractApiTest.Companion.authentication
import no.nav.helse.mediator.api.AbstractApiTest.Companion.clientId
import no.nav.helse.mediator.api.AbstractApiTest.Companion.issuer
import no.nav.helse.mediator.api.AbstractApiTest.Companion.jwtStub
import no.nav.helse.objectMapper
import no.nav.helse.oppgave.OppgaveDto
import no.nav.helse.oppgave.OppgaveMediator
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.TestInstance.Lifecycle
import org.junit.jupiter.api.assertThrows
import java.net.ServerSocket
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@TestInstance(Lifecycle.PER_CLASS)
internal class OppgaveApiTest {
private val httpPort = ServerSocket(0).use { it.localPort }
private val oppgaveMediator = mockk<OppgaveMediator>(relaxed = true)
private val KODE7_SAKSBEHANDLER_GROUP = "c21e58b6-d838-4cb0-919a-398cd40117e3"
@BeforeAll
fun setup() {
embeddedServer(Netty, port = httpPort) {
install(ContentNegotiation) { register(ContentType.Application.Json, JacksonConverter(objectMapper)) }
val jwkProvider = jwtStub.getJwkProviderMock()
val azureConfig = AzureAdAppConfig(
clientId = clientId,
issuer = issuer,
jwkProvider = jwkProvider
)
azureAdAppAuthentication(azureConfig)
routing {
authenticate("oidc") {
oppgaveApi(
oppgaveMediator = oppgaveMediator,
riskSupersaksbehandlergruppe = UUID.randomUUID(),
kode7Saksbehandlergruppe = UUID.randomUUID()
)
}
}
}.also {
it.start(wait = false)
}
}
private val client = HttpClient {
defaultRequest {
host = "localhost"
port = httpPort
}
install(JsonFeature) {
serializer = JacksonSerializer(jackson = objectMapper)
}
}
@Test
fun `returnerer 400 bad request hvis fødselsnummer ikke er satt eller er null`() {
assertThrows<ClientRequestException> {
runBlocking {
client.get<HttpStatement>("/api/v1/oppgave") { header("fodselsnummer", null) }.execute()
}
}
}
@Test
fun `får 404 not found hvis oppgaven ikke finnes`() {
every { oppgaveMediator.hentOppgaveId(any()) } returns null
assertThrows<ClientRequestException> {
runBlocking {
client.get<HttpStatement>("/api/v1/oppgave") { header("fodselsnummer", "42069") }.execute()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a2f919f15447aaed116878d29ea3f42a76a921cc
| 3,371
|
helse-spesialist
|
MIT License
|
src/main/kotlin/days/aoc2023/Day18.kt
|
bjdupuis
| 435,570,912
| false
|
{"Kotlin": 537037}
|
package days.aoc2023
import days.Day
import util.Point2d
import util.Point2dl
import util.isOdd
import util.toward
import kotlin.math.max
import kotlin.math.min
class Day18 : Day(2023, 18) {
override fun partOne(): Any {
return calculatePartOneShoelace(inputList)
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
fun calculatePartOne(input: List<String>): Int {
var cursor = Point2d(0,0)
val instructions = input.mapNotNull {
Regex("(\\w) (\\d+) \\(#(\\w+)\\)").matchEntire(it)?.destructured?.let { (direction, length, color) ->
DigInstruction(direction, length.toInt(), color)
}
}
instructions.fold(cursor) { cursor, instruction ->
instruction.calculateRangesFrom(cursor)
}
var lowerRight = Point2d(Int.MIN_VALUE, Int.MIN_VALUE)
var upperLeft = Point2d(Int.MAX_VALUE, Int.MAX_VALUE)
instructions.forEach { instruction ->
upperLeft = Point2d(
min(upperLeft.x, min(instruction.xRange.first, instruction.xRange.last)),
min(upperLeft.y, min(instruction.yRange.first, instruction.yRange.last)))
lowerRight = Point2d(
max(lowerRight.x, max(instruction.xRange.first, instruction.xRange.last)),
max(lowerRight.y, max(instruction.yRange.first, instruction.yRange.last)))
}
fun pointIsOnBoundary(point: Point2d): Boolean {
for (instruction in instructions) {
if (point.y in instruction.yRange && point.x in instruction.xRange) {
return true
}
}
return false
}
fun pointIsInside(point: Point2d): Boolean {
var crossed = 0
var horizontalsTraversed = mutableSetOf<DigInstruction>()
for (x in point.x toward upperLeft.x) {
for (instruction in instructions) {
if (point.y in instruction.yRange && x in instruction.xRange) {
if (instruction.isVertical()) {
crossed++
} else if (instruction.isHorizontal() && !horizontalsTraversed.contains(instruction)) {
horizontalsTraversed.add(instruction)
}
}
}
}
return (crossed + horizontalsTraversed.size).isOdd()
}
var startingPoint = Point2d(0, 0)
outer@for (x in upperLeft.x toward lowerRight.x) {
for (y in upperLeft.y toward lowerRight.y) {
startingPoint = Point2d(x, y)
if (!pointIsOnBoundary(startingPoint) && pointIsInside(startingPoint)) {
break@outer
}
}
}
val frontier = mutableListOf(startingPoint)
val seen = mutableListOf<Point2d>()
val inside = mutableSetOf(startingPoint)
while (frontier.isNotEmpty()) {
val current = frontier.removeFirst()
seen.add(current)
current.allNeighbors().filter { !seen.contains(it) && !frontier.contains(it) }.forEach {
if (!pointIsOnBoundary(it)) {
frontier.add(it)
}
inside.add(it)
}
}
return inside.count()
}
data class DigInstruction(val direction: String, val length: Int, val color: String) {
lateinit var xRange: IntProgression;
lateinit var yRange: IntProgression;
fun calculateRangesFrom(origin: Point2d): Point2d {
when (direction) {
"U" -> {
xRange = origin.x .. origin.x
yRange = origin.y toward origin.y - length
}
"D" -> {
xRange = origin.x .. origin.x
yRange = origin.y toward origin.y + length
}
"R" -> {
xRange = origin.x toward origin.x + length
yRange = origin.y .. origin.y
}
"L" -> {
xRange = origin.x toward origin.x - length
yRange = origin.y .. origin.y
}
}
return Point2d(xRange.last, yRange.last)
}
fun isHorizontal(): Boolean = xRange.first != xRange.last
fun isVertical(): Boolean = yRange.first != yRange.last
lateinit var start: Point2dl
lateinit var end: Point2dl
fun calculateExtrema(origin: Point2dl): Point2dl {
start = origin
when (direction) {
"U" -> {
end = start.copy(y = start.y - length)
}
"D" -> {
end = start.copy(y = start.y + length)
}
"R" -> {
end = start.copy(x = start.x + length)
}
"L" -> {
end = start.copy(x = start.x - length)
}
}
return end
}
}
data class RealDigInstruction(val encoded: String) {
val length = encoded.take(5).toInt(16)
val direction = when (encoded.last()) {
'0' -> 'R'
'1' -> 'D'
'2' -> 'L'
'3' -> 'U'
else -> throw IllegalStateException("Oops")
}.toString()
lateinit var start: Point2dl
fun calculateExtrema(origin: Point2dl): Point2dl {
start = origin
return when (direction) {
"U" -> {
start.copy(y = start.y - length)
}
"D" -> {
start.copy(y = start.y + length)
}
"R" -> {
start.copy(x = start.x + length)
}
"L" -> {
start.copy(x = start.x - length)
}
else -> throw IllegalStateException("oh dear")
}
}
}
fun calculatePartOneShoelace(input: List<String>): Long {
var cursor = Point2dl(0,0)
val instructions = input.mapNotNull {
Regex("(\\w) (\\d+) \\(#(\\w+)\\)").matchEntire(it)?.destructured?.let { (direction, length, color) ->
DigInstruction(direction, length.toInt(), color)
}
}
instructions.fold(cursor) { cursor, instruction ->
instruction.calculateExtrema(cursor)
}
var area = 0L
instructions.zipWithNext { a, b ->
area += (a.start.x * b.start.y) - (a.start.y * b.start.x)
}
val last = instructions.last()
val first = instructions.first()
//area += (last.start.x * first.start.y) - (last.start.y * first.start.x)
return (area / 2) + (instructions.sumOf { it.length } / 2) + 1
}
fun calculatePartTwo(input: List<String>): Long {
var cursor = Point2dl(0,0)
val instructions = input.mapNotNull {
Regex("(\\w) (\\d+) \\(#(\\w+)\\)").matchEntire(it)?.destructured?.let { (_, _, encoded) ->
RealDigInstruction(encoded)
}
}
instructions.fold(cursor) { cursor, instruction ->
instruction.calculateExtrema(cursor)
}
var area = 0L
instructions.zipWithNext { a, b ->
area += (a.start.x * b.start.y) - (a.start.y * b.start.x)
}
val last = instructions.last()
val first = instructions.first()
area += (last.start.x * first.start.y) - (last.start.y * first.start.x)
return return (area / 2) + (instructions.sumOf { it.length } / 2) + 1
}
}
| 0
|
Kotlin
|
0
| 1
|
c692fb71811055c79d53f9b510fe58a6153a1397
| 7,821
|
Advent-Of-Code
|
Creative Commons Zero v1.0 Universal
|
libdatabase2/src/main/java/ru/relation/onetomany/AlbumEntity.kt
|
elronsmith
| 317,674,896
| false
| null |
package ru.relation.onetomany
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = AlbumEntity.TABLE_NAME)
data class AlbumEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Long = 0,
@ColumnInfo(name = "name")
val name: String
) {
companion object {
const val TABLE_NAME = "albums"
}
}
| 0
|
Kotlin
|
0
| 0
|
1d5eff3afb6123727db0ff28547f7365c79caf9b
| 406
|
ExampleRoom
|
Apache License 2.0
|
mock/src/main/kotlin/MockMachineMonitor.kt
|
neilellis
| 15,782,049
| false
| null |
/*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* 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 kontrol.mock
import kontrol.api.Monitor
import kontrol.api.StateMachine
import kontrol.api.Machine
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kontrol.api.MachineState
import kontrol.api.MonitorRule
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis"><NAME></a>
*/
public class MockMachineMonitor() : Monitor<MachineState, Machine> {
override fun target(): Machine? {
throw UnsupportedOperationException()
}
val timer: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
override fun start(target: Machine, stateMachine: StateMachine<MachineState>, rules: Set<MonitorRule<MachineState, Machine>>) {
timer.scheduleWithFixedDelay({
println("Random Transition")
try {
stateMachine.transition(MachineState.values()[(Math.random() * MachineState.values().size).toInt()])
} catch (e: Exception) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
}
override fun stop() {
timer.shutdown();
}
}
| 0
|
Kotlin
|
0
| 0
|
38d115785e33b1383d389815e039f5f09f6ccec1
| 1,803
|
kontrol
|
Apache License 2.0
|
idea/tests/testData/multiModuleQuickFix/createExpect/enumComplex/jvm/jvm.kt
|
JetBrains
| 278,369,660
| false
| null |
// "Create expected enum class in common module testModule_Common" "true"
// DISABLE-ERRORS
actual enum class <caret>Complex {
FIRST {
override fun foo() {}
};
actual abstract fun foo()
}
| 0
| null |
30
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 209
|
intellij-kotlin
|
Apache License 2.0
|
app/src/main/java/at/ac/fhcampuswien/bookapplication/widgets/AppBar.kt
|
sytungan
| 555,676,870
| false
|
{"Kotlin": 43876}
|
package at.ac.fhcampuswien.bookapplication.widgets
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
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.tooling.preview.Preview
import at.ac.fhcampuswien.bookapplication.ui.theme.AppColors
import at.ac.fhcampuswien.bookapplication.ui.theme.AppTypography
@Composable
fun AppBar(title: String) {
TopAppBar(
backgroundColor = AppColors.Blue1F63DA,
contentColor = Color.White
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = title, style = AppTypography.h4)
}
}
}
@Preview
@Composable
fun AppBarPreview() {
AppBar("Book template")
}
| 0
|
Kotlin
|
0
| 0
|
ad2aa3652a110c52855ce5752c6f0d7ac7e385f9
| 1,154
|
simple-book-app
|
MIT License
|
src/test/kotlin/no/nav/familie/ef/sak/cucumber/steps/BeregningBarnetilsynEnPeriodeStepDefinitions.kt
|
navikt
| 206,805,010
| false
| null |
package no.nav.familie.ef.sak.cucumber.steps
import io.cucumber.datatable.DataTable
import io.cucumber.java.no.Gitt
import io.cucumber.java.no.Når
import io.cucumber.java.no.Så
import no.nav.familie.ef.sak.beregning.barnetilsyn.BeregningBarnetilsynUtil
import no.nav.familie.ef.sak.cucumber.domeneparser.parseBigDecimal
import no.nav.familie.ef.sak.cucumber.domeneparser.parseInt
import no.nav.familie.ef.sak.cucumber.domeneparser.parseÅrMåned
import no.nav.familie.ef.sak.no.nav.familie.ef.sak.cucumber.domeneparser.BeregningBarnetilsynDomenebegrep.ANTALL_BARN
import no.nav.familie.ef.sak.no.nav.familie.ef.sak.cucumber.domeneparser.BeregningBarnetilsynDomenebegrep.KONTANTSTØTTEBELØP
import no.nav.familie.ef.sak.no.nav.familie.ef.sak.cucumber.domeneparser.BeregningBarnetilsynDomenebegrep.PERIODEDATO
import no.nav.familie.ef.sak.no.nav.familie.ef.sak.cucumber.domeneparser.BeregningBarnetilsynDomenebegrep.PERIODEUTGIFT
import no.nav.familie.ef.sak.no.nav.familie.ef.sak.cucumber.domeneparser.BeregningBarnetilsynDomenebegrep.TILLEGSSTØNADBELØP
import org.assertj.core.api.Assertions.assertThat
import java.math.BigDecimal
import java.time.YearMonth
class BeregningBarnetilsynEnPeriodeStepDefinitions {
lateinit var resultat: BigDecimal
lateinit var inputData: PeriodeDataDto
@Gitt("følgende data")
fun data(dataTable: DataTable) {
inputData = dataTable.asMaps().map {
PeriodeDataDto(
periodeutgift = parseBigDecimal(PERIODEUTGIFT, it),
kontantstøtteBeløp = parseBigDecimal(KONTANTSTØTTEBELØP, it),
tillegstønadbeløp = parseBigDecimal(TILLEGSSTØNADBELØP, it),
antallBarn = parseInt(ANTALL_BARN, it),
årMåned = parseÅrMåned(PERIODEDATO, it)
)
}.first()
}
@Når("vi beregner barnetilsyn beløp")
fun `vi beregner barnetilsyn beløp`() {
resultat = beregnPeriodebeløp(inputData).utbetaltBeløp
}
private fun beregnPeriodebeløp(periodeDataDto: PeriodeDataDto) =
BeregningBarnetilsynUtil.beregnPeriodeBeløp(
periodeutgift = periodeDataDto.periodeutgift,
kontantstøtteBeløp = periodeDataDto.kontantstøtteBeløp,
tilleggsstønadBeløp = periodeDataDto.tillegstønadbeløp,
antallBarn = periodeDataDto.antallBarn,
årMåned = periodeDataDto.årMåned,
false
)
@Så("forventer vi barnetilsyn periodebeløp")
fun `forventer vi barnetilsyn periodebeløp`(dataTable: DataTable) {
val forventetBeløp = dataTable.asMaps().map { it["Beløp"]!!.toBigDecimal() }.first()
assertThat(resultat).isEqualByComparingTo(forventetBeløp)
}
}
data class PeriodeDataDto(
val periodeutgift: BigDecimal,
val kontantstøtteBeløp: BigDecimal,
val tillegstønadbeløp: BigDecimal,
val antallBarn: Int,
val årMåned: YearMonth
)
| 8
|
Kotlin
|
2
| 0
|
d1d8385ead500c4d24739b970940af854fa5fe2c
| 2,887
|
familie-ef-sak
|
MIT License
|
shared/ui/src/androidMain/kotlin/com/moviearchive/ui/android/widget/Actions.kt
|
Adnan9011
| 742,366,441
| false
|
{"Kotlin": 131984, "Swift": 574}
|
package com.moviearchive.ui.android.widget
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.moviearchive.ui.widget.LikeAction
@Preview
@Composable
private fun LikeActionPreview() {
LikeAction(
isLiked = true,
onFavoriteClicked = {}
)
}
| 0
|
Kotlin
|
1
| 12
|
71895140edd28ee13691a0fbe1fd49baf262a6cc
| 317
|
movie_archive_kmp
|
MIT License
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/vpclattice/CfnServiceProps.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 142794926}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.vpclattice
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
/**
* Properties for defining a `CfnService`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.vpclattice.*;
* CfnServiceProps cfnServiceProps = CfnServiceProps.builder()
* .authType("authType")
* .certificateArn("certificateArn")
* .customDomainName("customDomainName")
* .dnsEntry(DnsEntryProperty.builder()
* .domainName("domainName")
* .hostedZoneId("hostedZoneId")
* .build())
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html)
*/
public interface CfnServiceProps {
/**
* The type of IAM policy.
*
* * `NONE` : The resource does not use an IAM policy. This is the default.
* * `AWS_IAM` : The resource uses an IAM policy. When this type is used, auth is enabled and an
* auth policy is required.
*
* Default: - "NONE"
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-authtype)
*/
public fun authType(): String? = unwrap(this).getAuthType()
/**
* The Amazon Resource Name (ARN) of the certificate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-certificatearn)
*/
public fun certificateArn(): String? = unwrap(this).getCertificateArn()
/**
* The custom domain name of the service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-customdomainname)
*/
public fun customDomainName(): String? = unwrap(this).getCustomDomainName()
/**
* The DNS information of the service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-dnsentry)
*/
public fun dnsEntry(): Any? = unwrap(this).getDnsEntry()
/**
* The name of the service.
*
* The name must be unique within the account. The valid characters are a-z, 0-9, and hyphens (-).
* You can't use a hyphen as the first or last character, or immediately after another hyphen.
*
* If you don't specify a name, CloudFormation generates one. However, if you specify a name, and
* later want to replace the resource, you must specify a new name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-name)
*/
public fun name(): String? = unwrap(this).getName()
/**
* The tags for the service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [CfnServiceProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param authType The type of IAM policy.
* * `NONE` : The resource does not use an IAM policy. This is the default.
* * `AWS_IAM` : The resource uses an IAM policy. When this type is used, auth is enabled and an
* auth policy is required.
*/
public fun authType(authType: String)
/**
* @param certificateArn The Amazon Resource Name (ARN) of the certificate.
*/
public fun certificateArn(certificateArn: String)
/**
* @param customDomainName The custom domain name of the service.
*/
public fun customDomainName(customDomainName: String)
/**
* @param dnsEntry The DNS information of the service.
*/
public fun dnsEntry(dnsEntry: IResolvable)
/**
* @param dnsEntry The DNS information of the service.
*/
public fun dnsEntry(dnsEntry: CfnService.DnsEntryProperty)
/**
* @param dnsEntry The DNS information of the service.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("3efe9b948caff662dde3459e0c0997e86b85201c4c333d14d68fcc0d3a5e07fa")
public fun dnsEntry(dnsEntry: CfnService.DnsEntryProperty.Builder.() -> Unit)
/**
* @param name The name of the service.
* The name must be unique within the account. The valid characters are a-z, 0-9, and hyphens
* (-). You can't use a hyphen as the first or last character, or immediately after another hyphen.
*
* If you don't specify a name, CloudFormation generates one. However, if you specify a name,
* and later want to replace the resource, you must specify a new name.
*/
public fun name(name: String)
/**
* @param tags The tags for the service.
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags The tags for the service.
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder: software.amazon.awscdk.services.vpclattice.CfnServiceProps.Builder =
software.amazon.awscdk.services.vpclattice.CfnServiceProps.builder()
/**
* @param authType The type of IAM policy.
* * `NONE` : The resource does not use an IAM policy. This is the default.
* * `AWS_IAM` : The resource uses an IAM policy. When this type is used, auth is enabled and an
* auth policy is required.
*/
override fun authType(authType: String) {
cdkBuilder.authType(authType)
}
/**
* @param certificateArn The Amazon Resource Name (ARN) of the certificate.
*/
override fun certificateArn(certificateArn: String) {
cdkBuilder.certificateArn(certificateArn)
}
/**
* @param customDomainName The custom domain name of the service.
*/
override fun customDomainName(customDomainName: String) {
cdkBuilder.customDomainName(customDomainName)
}
/**
* @param dnsEntry The DNS information of the service.
*/
override fun dnsEntry(dnsEntry: IResolvable) {
cdkBuilder.dnsEntry(dnsEntry.let(IResolvable.Companion::unwrap))
}
/**
* @param dnsEntry The DNS information of the service.
*/
override fun dnsEntry(dnsEntry: CfnService.DnsEntryProperty) {
cdkBuilder.dnsEntry(dnsEntry.let(CfnService.DnsEntryProperty.Companion::unwrap))
}
/**
* @param dnsEntry The DNS information of the service.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("3efe9b948caff662dde3459e0c0997e86b85201c4c333d14d68fcc0d3a5e07fa")
override fun dnsEntry(dnsEntry: CfnService.DnsEntryProperty.Builder.() -> Unit): Unit =
dnsEntry(CfnService.DnsEntryProperty(dnsEntry))
/**
* @param name The name of the service.
* The name must be unique within the account. The valid characters are a-z, 0-9, and hyphens
* (-). You can't use a hyphen as the first or last character, or immediately after another hyphen.
*
* If you don't specify a name, CloudFormation generates one. However, if you specify a name,
* and later want to replace the resource, you must specify a new name.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param tags The tags for the service.
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags The tags for the service.
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.vpclattice.CfnServiceProps =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.vpclattice.CfnServiceProps,
) : CdkObject(cdkObject), CfnServiceProps {
/**
* The type of IAM policy.
*
* * `NONE` : The resource does not use an IAM policy. This is the default.
* * `AWS_IAM` : The resource uses an IAM policy. When this type is used, auth is enabled and an
* auth policy is required.
*
* Default: - "NONE"
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-authtype)
*/
override fun authType(): String? = unwrap(this).getAuthType()
/**
* The Amazon Resource Name (ARN) of the certificate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-certificatearn)
*/
override fun certificateArn(): String? = unwrap(this).getCertificateArn()
/**
* The custom domain name of the service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-customdomainname)
*/
override fun customDomainName(): String? = unwrap(this).getCustomDomainName()
/**
* The DNS information of the service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-dnsentry)
*/
override fun dnsEntry(): Any? = unwrap(this).getDnsEntry()
/**
* The name of the service.
*
* The name must be unique within the account. The valid characters are a-z, 0-9, and hyphens
* (-). You can't use a hyphen as the first or last character, or immediately after another hyphen.
*
* If you don't specify a name, CloudFormation generates one. However, if you specify a name,
* and later want to replace the resource, you must specify a new name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-name)
*/
override fun name(): String? = unwrap(this).getName()
/**
* The tags for the service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-vpclattice-service.html#cfn-vpclattice-service-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnServiceProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.vpclattice.CfnServiceProps):
CfnServiceProps = CdkObjectWrappers.wrap(cdkObject) as? CfnServiceProps ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnServiceProps):
software.amazon.awscdk.services.vpclattice.CfnServiceProps = (wrapped as
CdkObject).cdkObject as software.amazon.awscdk.services.vpclattice.CfnServiceProps
}
}
| 1
|
Kotlin
|
0
| 4
|
eb3eef728b34da593a3e55dc423d4f5fa3668e9c
| 11,566
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
common/ui/compose/src/main/java/com/afterroot/ui/common/compose/components/MediaCard.kt
|
thesandipv
| 255,834,235
| false
|
{"Kotlin": 565099, "Shell": 1180}
|
/*
* Copyright (C) 2020-2022 Sandip Vaghela
* 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.afterroot.ui.common.compose.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import app.tivi.common.compose.Layout
import app.tivi.common.compose.ui.AutoSizedCircularProgressIndicator
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.afterroot.watchdone.data.model.Media
import com.afterroot.watchdone.data.model.Movie
import com.afterroot.watchdone.data.model.TV
import info.movito.themoviedbapi.model.Multi
@Composable
fun <T : Multi> PosterCard(
media: T,
modifier: Modifier = Modifier,
type: Multi.MediaType = media.mediaType ?: Multi.MediaType.MOVIE,
onClick: (() -> Unit)? = null,
) {
var title: String? = null
var posterPath: String? = null
when (type) {
Multi.MediaType.MOVIE -> {
media as Movie
title = media.title
posterPath = media.posterPath
}
Multi.MediaType.TV_SERIES -> {
media as TV
title = media.name
posterPath = media.posterPath
}
else -> {}
}
BasePosterCard(title = title, posterPath = posterPath, modifier = modifier, onClick = onClick)
}
@Composable
fun MovieCard(movie: Movie, modifier: Modifier = Modifier, onClick: (() -> Unit)? = null) {
BasePosterCard(
title = movie.title,
posterPath = movie.posterPath,
modifier = modifier,
onClick = onClick,
)
}
@Composable
fun MovieCard(movie: Media, modifier: Modifier = Modifier, onClick: (() -> Unit)? = null) {
BasePosterCard(
title = movie.title,
posterPath = movie.posterPath,
modifier = modifier,
onClick = onClick,
)
}
@Composable
fun TVCard(tv: TV, modifier: Modifier = Modifier, onClick: (() -> Unit)? = null) {
BasePosterCard(
title = tv.name,
posterPath = tv.posterPath,
modifier = modifier,
onClick = onClick,
)
}
@Composable
fun BasePosterCard(
modifier: Modifier = Modifier,
title: String? = null,
posterPath: String? = null,
onClick: (() -> Unit)? = null,
) {
Card(modifier = modifier) {
Box(
modifier = Modifier
.fillMaxSize()
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier),
) {
Text(
text = title ?: "",
style = MaterialTheme.typography.labelSmall,
modifier = Modifier
.padding(4.dp)
.align(Alignment.Center),
)
if (posterPath != null) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(
LocalTMDbBaseUrl.current + LocalPosterSize.current + posterPath,
).crossfade(true).build(),
contentDescription = title,
modifier = Modifier.matchParentSize(),
contentScale = ContentScale.Crop,
)
}
}
}
}
@Composable
fun Backdrop(
backdropPath: String?,
modifier: Modifier = Modifier,
shape: Shape = MaterialTheme.shapes.medium,
title: String? = null,
onClick: (() -> Unit)? = null,
) {
Surface(
color = MaterialTheme.colorScheme.onSurface
.copy(alpha = 0.2f)
.compositeOver(MaterialTheme.colorScheme.surface),
shape = shape,
modifier = modifier,
) {
Box(
modifier = Modifier
.fillMaxSize()
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier),
) {
if (backdropPath != null) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(
LocalTMDbBaseUrl.current + LocalBackdropSize.current + backdropPath,
).crossfade(true).build(),
contentDescription = title,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
}
if (title != null) {
Text(
text = title,
style = MaterialTheme.typography.labelSmall,
modifier = Modifier
.padding(Layout.gutter * 2)
.align(Alignment.BottomStart),
)
}
}
}
}
@Composable
fun Header(
title: String,
modifier: Modifier = Modifier,
loading: Boolean = false,
content: @Composable RowScope.() -> Unit = {},
) {
Row(modifier, verticalAlignment = Alignment.CenterVertically) {
Spacer(Modifier.width(16.dp))
Text(
text = title,
color = contentColorFor(MaterialTheme.colorScheme.surface),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.align(Alignment.CenterVertically)
.padding(vertical = 8.dp),
)
Spacer(Modifier.weight(1f))
AnimatedVisibility(visible = loading) {
AutoSizedCircularProgressIndicator(
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.padding(8.dp)
.size(16.dp),
)
}
content()
Spacer(Modifier.width(16.dp))
}
}
| 9
|
Kotlin
|
1
| 5
|
b52a8c406045372408f45575f281e1920f57a87f
| 7,107
|
watchdone
|
Apache License 2.0
|
ledger/src/main/kotlin/org/knowledger/ledger/data/HumidityData.kt
|
fakecoinbase
| 282,563,487
| false
| null |
@file:UseSerializers(BigDecimalSerializer::class)
package org.knowledger.ledger.data
import kotlinx.serialization.BinaryFormat
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import org.knowledger.ledger.config.GlobalLedgerConfiguration.GLOBALCONTEXT
import org.knowledger.ledger.core.serial.BigDecimalSerializer
import java.io.InvalidClassException
import java.math.BigDecimal
/**
* Humidity value can be expressed in Absolute/Volumetric
* or Relative humidity. As such possible measurements
* can be in g/Kg ([HumidityUnit.GramsByKilograms]), Kg/Kg ([HumidityUnit.KilogramsByKilograms])
* or percentage ([HumidityUnit.Relative]) expressed by the [unit].
*/
@Serializable
@SerialName("HumidityData")
data class HumidityData(
val humidity: BigDecimal,
val unit: HumidityUnit
) : LedgerData {
override fun clone(): HumidityData =
copy()
override fun serialize(encoder: BinaryFormat): ByteArray =
encoder.dump(serializer(), this)
override fun calculateDiff(previous: SelfInterval): BigDecimal =
when (previous) {
is HumidityData -> calculateDiffHum(previous)
else -> throw InvalidClassException(
"""SelfInterval supplied is:
| ${previous.javaClass.name},
| not ${this::class.java.name}
""".trimMargin()
)
}
private fun calculateDiffHum(previous: HumidityData): BigDecimal {
val newH: BigDecimal
val oldH: BigDecimal
if (unit == HumidityUnit.Relative) {
newH = humidity
oldH = previous.humidity
} else {
newH = unit.convertTo(humidity, HumidityUnit.KilogramsByKilograms)
oldH = previous.unit.convertTo(humidity, HumidityUnit.KilogramsByKilograms)
}
return newH.subtract(oldH)
.divide(oldH, GLOBALCONTEXT)
}
override fun toString(): String {
return "HumidityData(hum=$humidity, unit=$unit)"
}
}
| 0
|
Kotlin
|
0
| 0
|
8bc64987e1ab4d26663064da06393de6befc30ae
| 2,077
|
SeriyinslashKnowLedger
|
MIT License
|
libs/canvas-api-2/src/main/java/com/instructure/canvasapi2/models/DiscussionTopicHeader.kt
|
instructure
| 179,290,947
| false
| null |
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.instructure.canvasapi2.models
import com.google.gson.annotations.SerializedName
import com.instructure.canvasapi2.utils.toApiString
import kotlinx.parcelize.Parcelize
import java.util.*
@Parcelize
data class DiscussionTopicHeader(
override var id: Long = 0, // Discussion Topic Id;
@SerializedName("discussion_type")
var discussionType: String? = null, // Type of discussion (side_comment or threaded).
var title: String? = null,
var message: String? = null, // HTML content
@SerializedName("html_url")
var htmlUrl: String? = null, // URL to the topic on canvas.
// Only one of the following two will be filled out. the other will be null.
// If posted_at isn't null, it represents when the discussion WAS posted.
// If delayed_post_at isn't null, it represents when the discussion WILL be posted.
@SerializedName("posted_at")
var postedDate: Date? = null,
@SerializedName("delayed_post_at")
var delayedPostDate: Date? = null,
@SerializedName("last_reply_at")
var lastReplyDate: Date? = null, // Last response to the thread.
@SerializedName("require_initial_post")
var requireInitialPost: Boolean = false, // Whether or not users are required to post before they can respond to comments.
@SerializedName("discussion_subentry_count")
var discussionSubentryCount: Int = 0, // The count of entries in the topic.
@SerializedName("read_state")
var readState: String? = null, // Whether or not the topic has been read yet.
@SerializedName("unread_count")
var unreadCount: Int = 0, // Number of unread messages.
var position: Int = 0, // If topic is pinned it'll have a position
@SerializedName("assignment_id")
var assignmentId: Long = 0, // The unique identifier of the assignment if the topic is for grading, otherwise null.
@SerializedName("locked")
var locked: Boolean = false, // Whether or not the discussion is 'closed for comments'.
@SerializedName("locked_for_user")
var lockedForUser: Boolean = false, // whether or not this is Locked for students to see.
@SerializedName("lock_explanation")
var lockExplanation: String? = null, // (Optional) An explanation of why this is Locked for the user. Present when locked_for_user is true.
var pinned: Boolean = false, // whether or not the discussion has been "pinned" by an instructor
var author: DiscussionParticipant? = null, // The user that Started the thread.
@SerializedName("podcast_url")
var podcastUrl: String? = null, // If the topic is a podcast topic this is the feed url for the current user.
@SerializedName("group_category_id")
var groupCategoryId: String? = null,
// If true, this topic is an announcement. This requires announcement-posting permissions.
@SerializedName("is_announcement")
var announcement: Boolean = false,
// If the topic is for grading and a group assignment this will
// point to the original topic in the course.
// String maybe?
// NOT USED in our code
//@SerializedName("root_topic_id")
//var rootTopicId: Long = 0,
// A list of topic_ids for the group discussions the user is a part of.
// NOT USED in our code
//@SerializedName("topic_children")
//var topicChildren: List<Long> = ArrayList(),
// Used primarily to determine whether a discussion is a group discussion
@SerializedName("group_topic_children")
var groupTopicChildren: List<GroupTopicChild> = ArrayList(),
// List of file attachments
var attachments: MutableList<RemoteFile> = ArrayList(),
// NOT USED in our code
//var unauthorized: Boolean = false,
var permissions: DiscussionTopicPermission? = null,
var assignment: Assignment? = null,
@SerializedName("lock_info")
var lockInfo: LockInfo? = null,
var published: Boolean = false, // Whether this discussion topic is published (true) or draft state (false)
@SerializedName("allow_rating")
var allowRating: Boolean = false, // Whether or not users can rate entries in this topic.
@SerializedName("only_graders_can_rate")
var onlyGradersCanRate: Boolean = false, // Whether or not grade permissions are required to rate entries.
@SerializedName("sort_by_rating")
var sortByRating: Boolean = false, // Whether or not entries should be sorted by rating.
// Context code. This is only set when getting DiscussionTopicHeaders from the announcements API
// NOT USED in our code
//@SerializedName("context_code")
//var contextCode: String? = null,
var subscribed: Boolean = false,
@SerializedName("lock_at")
var lockAt: Date? = null,
@SerializedName("user_can_see_posts")
var userCanSeePosts: Boolean = true,
@SerializedName("specific_sections")
var specificSections: String? = null, // For when we're submitting the sections
var sections: List<Section>? = null, // Comes back from the server
@SerializedName("anonymous_state")
var anonymousState: String? = null,
// Used to check if this discussion was converted from an offline entity so the details screen could fetch the whole discussion.
// We might not need this if we implement offline mode on the discussion details screen.
val offline: Boolean = false
) : CanvasModel<DiscussionTopicHeader>() {
override val comparisonDate: Date?
get() = if (lastReplyDate != null)
lastReplyDate
else
postedDate
val shouldShowReplies get() = !lockedForUser || lockInfo?.unlockDate?.after(Date()) != true
var type: DiscussionType
get() {
if ("side_comment" == this.discussionType) {
return DiscussionType.SIDE_COMMENT
} else if ("threaded" == this.discussionType) {
return DiscussionType.THREADED
}
return DiscussionType.UNKNOWN
}
set(type) = when (type) {
DiscussionType.SIDE_COMMENT -> this.discussionType = "side_comment"
DiscussionType.THREADED -> this.discussionType = "threaded"
else -> this.discussionType = "unknown"
}
var status: ReadState
get() = when (readState) {
"read" -> ReadState.READ
"unread" -> ReadState.UNREAD
else -> ReadState.UNREAD
}
set(status) = if (status == ReadState.READ) {
this.readState = "read"
} else {
this.readState = "unread"
}
enum class ReadState {
READ, UNREAD
}
enum class DiscussionType(val apiString: String) {
UNKNOWN("unknown"),
SIDE_COMMENT("side_comment"),
THREADED("threaded")
}
fun convertToDiscussionEntry(localizedGradedDiscussion: String, localizedPointsPossible: String): DiscussionEntry {
val discussionEntry = DiscussionEntry()
discussionEntry.message = this.message
discussionEntry.parent = null
discussionEntry.parentId = -1L
discussionEntry.replies = ArrayList()
var description = ""
if (assignment != null) {
description = localizedGradedDiscussion
if (assignment!!.pointsPossible > 0)
description += "<br>" + java.lang.Double.toString(assignment!!.pointsPossible) + " " + localizedPointsPossible
}
discussionEntry.description = description
discussionEntry.message = this.message
when {
this.lastReplyDate != null -> discussionEntry.updatedAt = this.lastReplyDate.toApiString()
this.postedDate != null -> discussionEntry.updatedAt = this.postedDate.toApiString()
else -> discussionEntry.updatedAt = this.delayedPostDate.toApiString()
}
discussionEntry.author = author
discussionEntry.attachments = this.attachments
discussionEntry.unread = this.status == ReadState.UNREAD
return discussionEntry
}
fun incrementDiscussionSubentryCount() {
discussionSubentryCount += 1
}
fun decrementDiscussionSubentryCount() {
discussionSubentryCount -= 1
if (discussionSubentryCount < 0) {
discussionSubentryCount = 0
}
}
}
| 7
| null |
90
| 99
|
1bac9958504306c03960bdce7fbb87cc63bc6845
| 9,210
|
canvas-android
|
Apache License 2.0
|
client_end_user/shared/src/commonMain/kotlin/presentation/chatSupport/ChatSupportInteractionListener.kt
|
TheChance101
| 671,967,732
| false
|
{"Kotlin": 2473455, "Ruby": 8872, "HTML": 6083, "Swift": 4726, "JavaScript": 3082, "CSS": 1436, "Dockerfile": 1407, "Shell": 1140}
|
package presentation.chatSupport
import presentation.base.BaseInteractionListener
interface ChatSupportInteractionListener: BaseInteractionListener {
fun onMessageChanged(message: String)
fun onClickSendMessage(message: String, userId: String)
fun onClickBack()
}
| 4
|
Kotlin
|
55
| 572
|
1d2e72ba7def605529213ac771cd85cbab832241
| 277
|
beep-beep
|
Apache License 2.0
|
compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/AnimatedVisibilityDemo.kt
|
RikkaW
| 389,105,112
| false
| null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.layoutanimation
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.demos.gesture.pastelColors
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.samples.AnimatedFloatingActionButton
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.shrinkVertically
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.Button
import androidx.compose.material.Checkbox
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlin.math.max
import kotlin.math.min
@Preview
@Composable
fun AnimatedVisibilityDemo() {
val animateContentSize = remember { mutableStateOf(false) }
Column {
AnimatedItems(animateContentSize.value)
AnimateContentSizeOption(animateContentSize)
AnimatedFloatingActionButton()
}
}
@Composable
fun AnimatedItems(animateContentSize: Boolean) {
var itemNum by remember { mutableIntStateOf(0) }
Column {
Row(
Modifier.fillMaxWidth().padding(20.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Button(onClick = { itemNum = min((itemNum + 1), 6) }) { Text("Add") }
Button(onClick = { itemNum = max((itemNum - 1), 0) }) { Text("Remove") }
}
Box(Modifier.padding(bottom = 20.dp)) {
val modifier = if (animateContentSize) Modifier.animateContentSize() else Modifier
Column(Modifier.background(Color.LightGray).fillMaxWidth().then(modifier)) {
Column(Modifier.background(Color.LightGray).fillMaxWidth().then(modifier)) {
AnimatedVisibility(visible = itemNum > 0) {
Item(
pastelColors[0],
"Expand Vertically + Fade In\nShrink " +
"Vertically + Fade Out\n(Column Default)"
)
}
HorizontalTransition(visible = itemNum > 1) {
Item(pastelColors[1], "Expand Horizontally\nShrink Horizontally")
}
SlideTransition(visible = itemNum > 2) {
Item(
pastelColors[2],
"Slide In Horizontally + Fade In\nSlide Out Horizontally + " +
"Fade Out"
)
}
AnimatedVisibility(
visible = itemNum > 3,
enter = expandVertically(),
exit = shrinkVertically()
) {
Item(pastelColors[3], "Expand Vertically\nShrink Vertically")
}
FadeTransition(visible = itemNum > 4) {
Item(pastelColors[4], "Fade In\nFade Out")
}
FullyLoadedTransition(visible = itemNum > 5) {
Item(
pastelColors[0],
"Expand Vertically + Fade In + Slide In Vertically\n" +
"Shrink Vertically + Fade Out + Slide Out Vertically"
)
}
}
}
}
}
}
@Composable
fun Item(color: Color, text: String = "") {
Box(Modifier.requiredHeight(80.dp).fillMaxWidth().background(color)) {
Text(text, modifier = Modifier.align(Alignment.CenterStart).padding(start = 10.dp))
}
}
@Composable
fun AnimateContentSizeOption(state: MutableState<Boolean>) {
Row(
Modifier.selectable(selected = state.value, onClick = { state.value = !state.value })
.padding(10.dp)
) {
Checkbox(state.value, { state.value = it })
Text("AnimateContentSize", modifier = Modifier.align(Alignment.CenterVertically))
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun HorizontalTransition(visible: Boolean, content: @Composable () -> Unit) {
AnimatedVisibility(
visible = visible,
enter =
expandHorizontally(
// Set the start width to 20 (pixels), 0 by default
initialWidth = { 20 }
),
exit =
shrinkHorizontally(
// Shrink towards the end (i.e. right edge for LTR, left edge for RTL). The default
// direction for the shrink is towards [Alignment.Start]
shrinkTowards = Alignment.End,
// Set the end width for the shrink animation to a quarter of the full width.
targetWidth = { fullWidth -> fullWidth / 10 },
// Overwrites the default animation with tween for this shrink animation.
animationSpec = tween(durationMillis = 400)
) + fadeOut()
) {
content()
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun SlideTransition(visible: Boolean, content: @Composable () -> Unit) {
AnimatedVisibility(
visible = visible,
enter =
slideInHorizontally(
// Offsets the content by 1/3 of its width to the left, and slide towards right
initialOffsetX = { fullWidth -> -fullWidth / 3 },
// Overwrites the default animation with tween for this slide animation.
animationSpec = tween(durationMillis = 200)
) +
fadeIn(
// Overwrites the default animation with tween
animationSpec = tween(durationMillis = 200)
),
exit =
slideOutHorizontally(
// Overwrites the ending position of the slide-out to 200 (pixels) to the right
targetOffsetX = { 200 },
animationSpec = spring(stiffness = Spring.StiffnessHigh)
) + fadeOut()
) {
content()
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun FadeTransition(visible: Boolean, content: @Composable () -> Unit) {
AnimatedVisibility(
visible = visible,
enter =
fadeIn(
// Overwrites the initial value of alpha to 0.4f for fade in, 0 by default
initialAlpha = 0.4f
),
exit =
fadeOut(
// Overwrites the default animation with tween
animationSpec = tween(durationMillis = 250)
)
) {
content()
}
}
@Composable
fun FullyLoadedTransition(visible: Boolean, content: @Composable () -> Unit) {
AnimatedVisibility(
visible = visible,
enter =
slideInVertically(
// Start the slide from 40 (pixels) above where the content is supposed to go, to
// produce a parallax effect
initialOffsetY = { -40 }
) + expandVertically(expandFrom = Alignment.Top) + fadeIn(initialAlpha = 0.3f),
exit = slideOutVertically() + shrinkVertically() + fadeOut()
) {
content()
}
}
| 29
| null |
937
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 9,256
|
androidx
|
Apache License 2.0
|
app/src/main/java/com/example/androiddevchallenge/ui/data/entities.kt
|
sol-digital
| 342,192,628
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.data
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.lazy.LazyListState
import com.example.androiddevchallenge.R
val puppiesData = listOf(
PuppyItem(R.drawable.pup_14, "Rex", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_5, "Goldie", "\uD83D\uDC36: n/a | ⚖️: n/a\nPuppy and more text in this description, and more, and more", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_12, "Johnnie", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_6, "Felix", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_10, "Pup", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_8, "Max", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_13, "Molly", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_1, "Grey", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_9, "Snorlax", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
PuppyItem(R.drawable.pup_11, "Flop", "\uD83D\uDC36: n/a | ⚖️: n/a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
)
abstract class ScreenData(
var verticalScrollState: ScrollState? = null,
var horizontalScrollState: ScrollState? = null,
var lazyListState: LazyListState? = null
)
class PuppiesScreen : ScreenData()
class PuppyDetailsScreen(val data: PuppyItem) : ScreenData()
data class LayoutGridParams(
val screenType: String,
val columnsAmount: Int,
val gutter: Int,
val cellSize: Double
)
data class PuppyItem(
val imageId: Int,
val title: String,
val description: String,
val text: String
)
| 0
|
Kotlin
|
0
| 0
|
7c4d583263585ddab590e0cfed5676f3d1161391
| 6,647
|
compose_challenge
|
Apache License 2.0
|
app/src/main/java/com/vitorpamplona/amethyst/model/AntiSpamFilter.kt
|
vitorpamplona
| 587,850,619
| false
| null |
package com.vitorpamplona.amethyst.model
import android.util.Log
import android.util.LruCache
import androidx.lifecycle.LiveData
import com.vitorpamplona.amethyst.service.model.Event
import com.vitorpamplona.amethyst.service.relays.Relay
import com.vitorpamplona.amethyst.ui.components.BundledUpdate
import kotlinx.coroutines.Dispatchers
data class Spammer(val pubkeyHex: HexKey, var duplicatedMessages: Set<HexKey>)
class AntiSpamFilter {
val recentMessages = LruCache<Int, String>(1000)
val spamMessages = LruCache<Int, Spammer>(1000)
@Synchronized
fun isSpam(event: Event, relay: Relay?): Boolean {
val idHex = event.id
// if short message, ok
if (event.content.length < 50) return false
// double list strategy:
// if duplicated, it goes into spam. 1000 spam messages are saved into the spam list.
// Considers tags so that same replies to different people don't count.
val hash = (event.content + event.tags.flatten().joinToString(",")).hashCode()
if ((recentMessages[hash] != null && recentMessages[hash] != idHex) || spamMessages[hash] != null) {
Log.w("Potential SPAM Message", "${event.id} ${recentMessages[hash]} ${spamMessages[hash] != null} ${relay?.url} ${event.content.replace("\n", " | ")}")
// Log down offenders
if (spamMessages.get(hash) == null) {
spamMessages.put(hash, Spammer(event.pubKey, setOf(recentMessages[hash], event.id)))
liveSpam.invalidateData()
} else {
val spammer = spamMessages.get(hash)
spammer.duplicatedMessages = spammer.duplicatedMessages + event.id
liveSpam.invalidateData()
}
return true
}
recentMessages.put(hash, idHex)
return false
}
val liveSpam: AntiSpamLiveData = AntiSpamLiveData(this)
}
class AntiSpamLiveData(val cache: AntiSpamFilter) : LiveData<AntiSpamState>(AntiSpamState(cache)) {
// Refreshes observers in batches.
private val bundler = BundledUpdate(300, Dispatchers.Main) {
if (hasActiveObservers()) {
refresh()
}
}
fun invalidateData() {
bundler.invalidate()
}
private fun refresh() {
postValue(AntiSpamState(cache))
}
}
class AntiSpamState(val cache: AntiSpamFilter)
| 120
| null |
88
| 686
|
24d722cdb72a7b52986e488b66a5540682be18f6
| 2,384
|
amethyst
|
MIT License
|
core/persistence/src/androidMain/kotlin/org/michaelbel/movies/persistence/database/MovieBlockingPersistence.kt
|
michaelbel
| 115,437,864
| false
|
{"Kotlin": 927426, "Swift": 692, "HTML": 606, "Shell": 235}
|
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package org.michaelbel.movies.persistence.database
import androidx.paging.PagingSource
import org.michaelbel.movies.persistence.database.entity.pojo.MoviePojo
import org.michaelbel.movies.persistence.database.typealiases.PagingKey
actual class MovieBlockingPersistence internal constructor(
private val moviesDatabase: MoviesDatabase
) {
fun pagingSource(pagingKey: PagingKey): PagingSource<Int, MoviePojo> {
return moviesDatabase.movieBlockingDao.pagingSource(pagingKey)
}
}
| 7
|
Kotlin
|
36
| 267
|
5d98adfc3b74eb87353870934f4969fc38279b4f
| 563
|
movies
|
Apache License 2.0
|
next/kmp/sys/src/commonMain/kotlin/org/dweb_browser/sys/permission/PermissionManagerRender.kt
|
BioforestChain
| 594,577,896
| false
|
{"Kotlin": 2673868, "TypeScript": 704141, "Swift": 350138, "Vue": 146618, "SCSS": 39016, "Objective-C": 17350, "Shell": 11193, "HTML": 10807, "JavaScript": 3998, "CSS": 818}
|
package org.dweb_browser.sys.permission
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.GppBad
import androidx.compose.material.icons.rounded.GppGood
import androidx.compose.material.icons.rounded.GppMaybe
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import org.dweb_browser.core.std.permission.AuthorizationRecord
import org.dweb_browser.core.std.permission.AuthorizationStatus
import org.dweb_browser.core.std.permission.PermissionTable
import org.dweb_browser.helper.compose.NoDataRender
import org.dweb_browser.sys.window.core.WindowContentRenderScope
import org.dweb_browser.sys.window.render.LocalWindowController
@Composable
fun PermissionManagerRender(
modifier: Modifier,
windowRenderScope: WindowContentRenderScope,
table: PermissionTable
) {
val win = LocalWindowController.current
win.GoBackHandler {
win.hide()
}
Column(windowRenderScope.run {
modifier
.fillMaxSize()
.requiredSize((width / scale).dp, (height / scale).dp) // 原始大小
.scale(scale)
}) {
for (item in table.AllData().also {
if (it.isEmpty()) {
NoDataRender(PermissionI18nResource.no_record())
} else {
ListItem(headlineContent = {
Text(
PermissionI18nResource.record_list_title(),
style = MaterialTheme.typography.titleLarge,
)
})
}
}) {
ListItem(
headlineContent = {
Text(item.applicantMmid)
},
supportingContent = {
Text(item.permissionId)
},
trailingContent = {
var isShowMenu by remember { mutableStateOf(false) }
val authorizationStatus = item.record.safeStatus
IconButton(
{ isShowMenu = true },
colors = IconButtonDefaults.iconButtonColors(
containerColor = if (isShowMenu) {
authorizationStatus.Color().copy(alpha = 0.2f)
} else Color.Transparent
)
) {
Icon(
when (authorizationStatus) {
AuthorizationStatus.GRANTED -> Icons.Rounded.GppGood
AuthorizationStatus.UNKNOWN -> Icons.Rounded.GppMaybe
AuthorizationStatus.DENIED -> Icons.Rounded.GppBad
},
contentDescription = authorizationStatus.name,
tint = authorizationStatus.Color()
)
if (isShowMenu) {
val scope = rememberCoroutineScope()
fun generateAuthorizationRecord(granted: Boolean?) {
scope.launch {
table.addRecord(
AuthorizationRecord.generateAuthorizationRecord(
item.permissionId,
item.applicantMmid,
granted
)
)
isShowMenu = false
}
}
DropdownMenu(isShowMenu, onDismissRequest = { isShowMenu = false }) {
DropdownMenuItem(
onClick = {
generateAuthorizationRecord(true)
},
leadingIcon = {
Icon(
Icons.Rounded.GppGood,
contentDescription = AuthorizationStatus.GRANTED.name
)
},
text = {
Text(PermissionI18nResource.record_state_granted())
},
colors = MenuDefaults.itemColors(leadingIconColor = AuthorizationStatus.GRANTED.Color())
)
DropdownMenuItem(
onClick = {
generateAuthorizationRecord(null)
},
leadingIcon = {
Icon(
Icons.Rounded.GppMaybe,
contentDescription = AuthorizationStatus.UNKNOWN.name
)
},
text = {
Text(PermissionI18nResource.record_state_unknown())
},
colors = MenuDefaults.itemColors(leadingIconColor = AuthorizationStatus.UNKNOWN.Color())
)
DropdownMenuItem(
onClick = {
generateAuthorizationRecord(false)
},
leadingIcon = {
Icon(
Icons.Rounded.GppBad,
contentDescription = AuthorizationStatus.DENIED.name
)
},
text = {
Text(PermissionI18nResource.record_state_denied())
},
colors = MenuDefaults.itemColors(leadingIconColor = AuthorizationStatus.DENIED.Color())
)
Divider()
DropdownMenuItem(
onClick = {
scope.launch {
table.removeRecord(
item.record.providerMmid,
item.permissionId,
item.applicantMmid
)
}
},
leadingIcon = {
Icon(
Icons.Rounded.Delete,
contentDescription = "remove record"
)
},
text = {
Text(PermissionI18nResource.remove_record())
},
)
}// DropdownMenu
}
}// IconButton
}
)
}
}
}
@Composable
fun AuthorizationStatus.Color() = when (this) {
AuthorizationStatus.GRANTED -> MaterialTheme.colorScheme.primary
AuthorizationStatus.UNKNOWN -> MaterialTheme.colorScheme.secondary
AuthorizationStatus.DENIED -> MaterialTheme.colorScheme.error
}
| 47
|
Kotlin
|
4
| 11
|
2a129afdf353564b3dd93ad2ad6dd6528c43413b
| 6,969
|
dweb_browser
|
MIT License
|
app/src/main/java/org/rdtoolkit/util/MediaUtil.kt
|
dimagi
| 262,149,568
| false
| null |
package org.rdtoolkit.util
import android.graphics.BitmapFactory
import android.widget.ImageView
import java.io.InputStream
fun configureImageView(iv: ImageView, stream: InputStream?) : Boolean {
if (stream == null) {
iv.setImageBitmap(null)
return false
}
stream.use {
iv.setImageBitmap(BitmapFactory.decodeStream(it))
return true
}
}
fun setImageBitmapFromFile(imageView: ImageView, currentPhotoPath: String?) {
// Get the dimensions of the View
var targetW = imageView.width
if (targetW == 0) {
targetW = imageView.layoutParams.width
}
if (targetW == 0) {
return
}
// Get the dimensions of the bitmap
val bmOptions = BitmapFactory.Options()
bmOptions.inJustDecodeBounds = true
BitmapFactory.decodeFile(currentPhotoPath, bmOptions)
val photoW = bmOptions.outWidth
// Determine how much to scale down the image
val scaleFactor = Math.max(1, photoW / targetW)
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false
bmOptions.inSampleSize = scaleFactor
bmOptions.inPurgeable = true
val bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions)
imageView.setImageBitmap(bitmap)
}
| 13
| null |
4
| 6
|
f33c44c438c0b14ca7ce9795f558569afb1bdf56
| 1,275
|
rd-toolkit
|
Apache License 2.0
|
gekom-core/src/main/kotlin/fr/cvlaminck/gekom/api/mapper/ValueProvider.kt
|
cyr62110
| 133,463,246
| false
| null |
package fr.cvlaminck.gekom.api.mapper
/**
* Interface providing methods to extract values of properties that will be mapped to the object using a [Mapper].
*/
interface ValueProvider {
/**
* Returns the value and the type of the property with name [propertyName].
*
* @param propertyName Name of the property.
* @return the value and the type of the property or null if the property does not exists.
*/
fun get(propertyName: String): TypedValue<Any>?
}
| 0
|
Kotlin
|
0
| 0
|
4a18ef358ae81cd6724be7790fdf9500693a0fe7
| 490
|
gekom
|
Apache License 2.0
|
platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsDirectoryRenamesProvider.kt
|
ingokegel
| 284,920,751
| false
| null |
// 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 com.intellij.vcs.log.history
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Tag
import com.intellij.util.xmlb.annotations.XCollection
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcsUtil.VcsFileUtil
import com.intellij.vcsUtil.VcsUtil
import java.util.concurrent.atomic.AtomicReference
@State(name = "VcsDirectoryRenames", storages = [Storage(value = "vcs.xml")])
internal class VcsDirectoryRenamesProvider : PersistentStateComponent<Array<RenameRecord>> {
private val renames: AtomicReference<Map<EdgeData<CommitId>, EdgeData<FilePath>>> = AtomicReference(emptyMap())
val renamesMap: Map<EdgeData<CommitId>, EdgeData<FilePath>>
get() = renames.get()
override fun getState(): Array<RenameRecord>? {
return renames.get().entries.groupBy({ it.value }) { it.key }.map { entry ->
val paths = entry.key
val commits = entry.value
val root = commits.first().parent.root
RenameRecord(root.path, VcsFileUtil.relativePath(root, paths.parent), VcsFileUtil.relativePath(root, paths.child),
commits.map { Hashes(it) }.toTypedArray())
}.toTypedArray()
}
override fun loadState(state: Array<RenameRecord>) {
renames.set(state.flatMap { record -> record.getCommitsAndPaths() }.toMap(linkedMapOf()))
}
companion object {
@JvmStatic
fun getInstance(project: Project): VcsDirectoryRenamesProvider = project.service()
}
}
@Tag("hashes")
internal data class Hashes(@Attribute("parentHash") val parentHash: String,
@Attribute("childHash") val childHash: String) {
internal constructor() : this("", "")
internal constructor(edgeData: EdgeData<CommitId>) : this(edgeData.parent.hash.asString(), edgeData.child.hash.asString())
fun getCommitIds(rootFile: VirtualFile): EdgeData<CommitId>? {
if (!VcsLogUtil.HASH_REGEX.matcher(parentHash).matches() || !VcsLogUtil.HASH_REGEX.matcher(childHash).matches()) return null
return EdgeData(CommitId(HashImpl.build(parentHash), rootFile), CommitId(HashImpl.build(childHash), rootFile))
}
}
@Tag("rename")
internal class RenameRecord(@Attribute("root") val root: String,
@Attribute("parentPath") val parentPath: String,
@Attribute("childPath") val childPath: String,
@XCollection(propertyElementName = "hashesList") val hashes: Array<Hashes>) {
internal constructor() : this("", "", "", emptyArray())
private val rootFile by lazy { LocalFileSystem.getInstance().findFileByPath(root) }
private fun getPaths(root: VirtualFile) =
EdgeData(VcsUtil.getFilePath(root, parentPath, true), VcsUtil.getFilePath(root, childPath, true))
private fun getCommits(root: VirtualFile) = hashes.mapNotNull { it.getCommitIds(root) }
fun getCommitsAndPaths(): List<Pair<EdgeData<CommitId>, EdgeData<FilePath>>> {
return rootFile?.let { root ->
val paths = getPaths(root)
getCommits(root).map { Pair(it, paths) }
} ?: emptyList()
}
}
| 284
| null |
5162
| 2
|
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 3,498
|
intellij-community
|
Apache License 2.0
|
feature/weather/src/main/java/com/trifork/feature/weather/presentation/components/animations/AnimationDrawable.kt
|
codeskraps
| 736,729,776
| false
|
{"Kotlin": 198822}
|
package com.trifork.feature.weather.presentation.components.animations
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.runtime.Composable
interface AnimationDrawable {
fun build(): @Composable (BoxScope.() -> Unit)
}
| 0
|
Kotlin
|
0
| 0
|
9870a7358703239f9c46b10823ff562b486b16d5
| 250
|
Weekly-Weather
|
Apache License 2.0
|
app/src/main/java/com/mcmp2023/s/data/db/models/Category.kt
|
S-B-Corporation
| 649,775,096
| false
|
{"Kotlin": 122677}
|
package com.mcmp2023.s.data.db.models
import android.graphics.drawable.Drawable
data class Category(
val id : String,
val name: String,
val icon: Int
)
| 0
|
Kotlin
|
0
| 0
|
2a6ba547eb84bdacc295efdfc93827393d18500b
| 166
|
AplicationSB
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.