path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/test/kotlin/quiz/me/controller/RegistrationControllerTest.kt
|
cthulhuvhudhu
| 784,109,582
| false
|
{"Kotlin": 88464}
|
package quiz.me.controller
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.encodeToJsonElement
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.Mockito.`when`
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.context.annotation.Import
import org.springframework.http.MediaType
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.post
import quiz.me.SecurityConfig
import quiz.me.model.UserTestModels
import quiz.me.model.dto.UserDTO
import quiz.me.service.UserService
import org.springframework.test.web.servlet.MvcResult
import org.springframework.web.bind.MethodArgumentNotValidException
import quiz.me.RegistrationDeniedException
import quiz.me.SpringSecurityWebAuxTestConfig
@WebMvcTest(RegistrationController::class)
@ContextConfiguration(classes = [SpringSecurityWebAuxTestConfig::class, SecurityConfig::class,
RestResponseEntityExceptionHandler::class])
@Import(RegistrationController::class)
class RegistrationControllerTest {
@MockBean
private lateinit var userService: UserService
@Autowired
private lateinit var mockMvc: MockMvc
private val url = "/api/register"
private val mType = MediaType.APPLICATION_JSON
@Test
fun `test POST register valid user dto returns valid ResponseEntity`() {
val testUser = UserTestModels.users.first()
`when`(userService.registerUser(testUser.email, testUser.dto.password))
.thenReturn(testUser.entityOut)
mockMvc.post(url) {
contentType = mType
content = Json.encodeToJsonElement(testUser.dto)
}.andExpect {
status { isOk() }
content { string("") }
}
}
@Test
fun `test POST register invalid email returns client error`() {
val testUser = UserDTO("notemail", "12345")
val response = doTest(Json.encodeToJsonElement(testUser))
assertThat(response.resolvedException).isInstanceOf(MethodArgumentNotValidException::class.java)
assertThat(response.resolvedException?.message).contains("Email is not valid")
}
@Test
fun `test POST register invalid password returns client error`() {
val testUser = UserDTO("a@a.com", "1234")
val response = doTest(Json.encodeToJsonElement(testUser))
assertThat(response.resolvedException).isInstanceOf(MethodArgumentNotValidException::class.java)
assertThat(response.resolvedException?.message).contains("Password must be 5 characters or more")
}
@Test
fun `test POST register user already registered returns client error`() {
val testUser = UserDTO("a@a.com", "12345")
`when`(userService.registerUser(testUser.email, testUser.password))
.thenThrow(RuntimeException())
val response = doTest(Json.encodeToJsonElement(testUser))
assertThat(response.resolvedException).isInstanceOf(RegistrationDeniedException::class.java)
assertThat(response.response.contentAsString).contains("Registration is not permitted at this time")
}
private fun doTest(input: JsonElement): MvcResult {
return mockMvc.post(url) {
contentType = mType
content = input
}.andExpect {
status { isBadRequest() }
}.andReturn()
}
}
| 5
|
Kotlin
|
0
| 0
|
a9c989dee50a7dcd02faec5444012ce73dfdb060
| 3,636
|
quiz-me
|
MIT License
|
stater/src/main/kotlin/ru/alexpanchenko/stater/plugin/visitors/OnSavedInstanceStateVisitor.kt
|
AlexeyPanchenko
| 208,916,702
| false
| null |
package ru.alexpanchenko.stater.plugin.visitors
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import ru.alexpanchenko.stater.plugin.StateFieldStorage
import ru.alexpanchenko.stater.plugin.model.MethodDescriptor
import ru.alexpanchenko.stater.plugin.model.StateType
import ru.alexpanchenko.stater.plugin.utils.*
class OnSavedInstanceStateVisitor(
methodVisitor: MethodVisitor?,
private val fieldStorage: StateFieldStorage,
) : MethodVisitor(Const.ASM_VERSION, methodVisitor) {
override fun visitCode() {
mv.visitCode()
fieldStorage.fields.forEach { field ->
val methodDescriptor: MethodDescriptor = MethodDescriptorUtils.getDescriptorByType(field.type, false)
if (!methodDescriptor.isValid()) {
throw IllegalStateException("StateType for ${field.name} in ${field.owner} is unknown!")
}
mv.visitVarInsn(Opcodes.ALOAD, 1)
mv.visitLdcInsn(field.key)
mv.visitVarInsn(Opcodes.ALOAD, 0)
mv.visitFieldInsn(Opcodes.GETFIELD, field.owner, field.name, field.descriptor)
if (field.type == StateType.CUSTOM) {
addCustomTypeSerialization()
} else if (field.descriptor == Descriptors.LIST) {
// cast List to ArrayList :)
mv.visitTypeInsn(Opcodes.CHECKCAST, Types.ARRAY_LIST)
}
mv.visitMethodInsn(
Opcodes.INVOKEVIRTUAL,
Types.BUNDLE,
methodDescriptor.method,
"(${Descriptors.STRING}${methodDescriptor.descriptor})${Descriptors.VOID}",
false
)
}
}
private fun addCustomTypeSerialization() {
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
Types.SERIALIZER,
Methods.SERIALIZE,
Descriptors.SERIALIZER_SERIALIZE,
false
)
}
}
| 1
| null |
1
| 12
|
fcc62fa6b45273cc47ed7ced79708ab73e03845e
| 1,736
|
stater
|
Apache License 2.0
|
ocr-sdk/src/main/java/ir/ayantech/ocr_sdk/model/GetCardOcrResult.kt
|
AyanTech
| 754,078,135
| false
|
{"Kotlin": 71214}
|
package ir.ayantech.ocr_sdk.model
import android.os.Parcel
import android.os.Parcelable
class GetCardOcrResult {
data class Input(
val FileID: String,
)
data class Output(
val Result: List<Result>,
val CardID: String,
val Status: String,
val NextCallInterval: Long,
)
data class Result(
val Key: String?,
val Value: String?
):Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString()
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(Key)
parcel.writeString(Value)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Result> {
override fun createFromParcel(parcel: Parcel): Result {
return Result(parcel)
}
override fun newArray(size: Int): Array<Result?> {
return arrayOfNulls(size)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f13e6c5f3add745a99ef8b5e1bd97d0a620fcadd
| 1,108
|
OCR-SDK
|
Apache License 2.0
|
app/src/main/java/br/unipar/trucoappkotlin/VictoryActivity.kt
|
DouglasSRM
| 860,155,059
| false
|
{"Kotlin": 7421}
|
package br.unipar.trucoappkotlin
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class VictoryActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Define o layout XML da segunda tela
setContentView(R.layout.activity_victory)
val txtVictoryMessage = findViewById<TextView>(R.id.txtVictoryMessage)
val btnPlayAgain = findViewById<Button>(R.id.btnPlayAgain)
btnPlayAgain.setOnClickListener{
finish()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6e6070f091721c41c7bdb9ea6c777942740fbe82
| 643
|
Projeto-truco-app-kotlin
|
MIT License
|
waltid-wallet-api/src/main/kotlin/id/walt/webwallet/web/controllers/ExchangeController.kt
|
walt-id
| 701,058,624
| false
| null |
package id.walt.webwallet.web.controllers
import id.walt.oid4vc.data.dif.PresentationDefinition
import id.walt.oid4vc.requests.CredentialOfferRequest
import id.walt.webwallet.db.models.WalletCredential
import id.walt.webwallet.db.models.WalletOperationHistory
import id.walt.webwallet.service.SSIKit2WalletService
import id.walt.webwallet.service.WalletServiceManager
import id.walt.webwallet.usecase.exchange.FilterData
import io.github.smiley4.ktorswaggerui.dsl.post
import io.github.smiley4.ktorswaggerui.dsl.route
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.util.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
fun Application.exchange() = walletRoute {
route("exchange", {
tags = listOf("WalletCredential exchange")
}) {
post("useOfferRequest", {
summary = "Claim credential(s) from an issuer"
request {
queryParameter<String>("did") { description = "The DID to issue the credential(s) to" }
queryParameter<Boolean>("requireUserInput") { description = "Whether to claim as pending acceptance" }
body<String> {
description = "The offer request to use"
}
}
response {
HttpStatusCode.OK to {
body<List<WalletCredential>> {
description = "List of credentials"
}
}
}
}) {
val wallet = getWalletService()
val did = call.request.queryParameters["did"] ?: wallet.listDids().firstOrNull()?.did
?: throw IllegalArgumentException("No DID to use supplied")
val requireUserInput = call.request.queryParameters["requireUserInput"].toBoolean()
val offer = call.receiveText()
runCatching {
WalletServiceManager.explicitClaimStrategy.claim(
tenant = wallet.tenant,
account = getUserUUID(),
wallet = wallet.walletId,
did = did,
offer = offer,
pending = requireUserInput
).also {
wallet.addOperationHistory(
WalletOperationHistory.new(
tenant = wallet.tenant,
wallet = wallet,
"useOfferRequest",
mapOf("did" to did, "offer" to offer)
)
)
}
}.onSuccess {
context.respond(HttpStatusCode.OK, it)
}.onFailure { error ->
error.printStackTrace()
context.respond(HttpStatusCode.BadRequest, error.localizedMessage)
}
}
post("matchCredentialsForPresentationDefinition", {
summary = "Returns the credentials stored in the wallet that match the passed presentation definition"
request {
body<PresentationDefinition> { description = "Presentation definition to match credentials against" }
}
response {
HttpStatusCode.OK to {
body<List<JsonObject>> {
description = "Credentials that match the presentation definition"
}
}
}
}) {
val presentationDefinition = PresentationDefinition.fromJSON(context.receive<JsonObject>())
val matchedCredentials = WalletServiceManager.matchPresentationDefinitionCredentialsUseCase.match(
getWalletId(), presentationDefinition
)
context.respond(matchedCredentials)
}
post("unmatchedCredentialsForPresentationDefinition", {
summary =
"Returns the credentials that are required by the presentation definition but not found in the wallet"
request {
body<PresentationDefinition> { description = "Presentation definition" }
}
response {
HttpStatusCode.OK to {
body<List<FilterData>> {
description = "Filters that failed to fulfill the presentation definition"
}
}
}
}) {
val presentationDefinition = PresentationDefinition.fromJSON(context.receive<JsonObject>())
val unmatchedCredentialTypes = WalletServiceManager.unmatchedPresentationDefinitionCredentialsUseCase.find(
getWalletId(), presentationDefinition
)
context.respond(unmatchedCredentialTypes)
}
post("usePresentationRequest", {
summary = "Present credential(s) to a Relying Party"
request {
body<UsePresentationRequest>()
}
response {
HttpStatusCode.OK to {
description = "Successfully claimed credentials"
body<JsonObject> {
description = """{"redirectUri": String}"""
}
}
HttpStatusCode.BadRequest to {
description = "Presentation was not accepted"
body<JsonObject> {
description = """{"redirectUri": String?, "errorMessage": String}"""
}
}
}
}) {
val wallet = getWalletService()
val req = call.receive<UsePresentationRequest>()
println("req: $req")
val request = req.presentationRequest
val did = req.did
?: wallet.listDids().firstOrNull { it.default }?.did
?: throw IllegalArgumentException("No DID to use supplied")
val selectedCredentialIds = req.selectedCredentials
// TODO -> ?: auto matching
val disclosures = req.disclosures
val result = wallet.usePresentationRequest(
PresentationRequestParameter(
did = did,
request = request,
selectedCredentials = selectedCredentialIds,
disclosures = disclosures,
note = req.note,
)
) // TODO add disclosures here
if (result.isSuccess) {
wallet.addOperationHistory(
WalletOperationHistory.new(
tenant = wallet.tenant,
wallet = wallet,
"usePresentationRequest",
mapOf(
"did" to did,
"request" to request,
"selected-credentials" to selectedCredentialIds.joinToString(),
"success" to "true",
"redirect" to result.getOrThrow()
) // change string true to bool
)
)
context.respond(HttpStatusCode.OK, mapOf("redirectUri" to result.getOrThrow()))
} else {
val err = result.exceptionOrNull()
println("Presentation failed: $err")
wallet.addOperationHistory(
WalletOperationHistory.new(
tenant = wallet.tenant,
wallet = wallet,
"usePresentationRequest",
mapOf(
"did" to did,
"request" to request,
"success" to "false",
//"redirect" to ""
) // change string false to bool
)
)
when (err) {
is SSIKit2WalletService.PresentationError -> {
context.respond(
HttpStatusCode.BadRequest, mapOf(
"redirectUri" to err.redirectUri,
"errorMessage" to err.message
)
)
}
else -> context.respond(HttpStatusCode.BadRequest, mapOf("errorMessage" to err?.message))
}
}
}
post("resolvePresentationRequest", {
summary = "Return resolved / parsed presentation request"
request {
body<String> { description = "PresentationRequest to resolve/parse" }
}
response {
HttpStatusCode.OK to {
body<String>()
}
}
}) {
val wallet = getWalletService()
val request = call.receiveText()
val parsedRequest = wallet.resolvePresentationRequest(request)
context.respond(parsedRequest)
}
post("resolveCredentialOffer", {
summary = "Return resolved / parsed credential offer"
request {
body<String> { description = "Credential offer request to resolve/parse" }
}
}) {
val wallet = getWalletService()
val request = call.receiveText()
val reqParams = Url(request).parameters.toMap()
val parsedOffer = wallet.resolveCredentialOffer(CredentialOfferRequest.fromHttpParameters(reqParams))
context.respond(parsedOffer)
}
}
}
@Serializable
data class UsePresentationRequest(
val did: String? = null,
val presentationRequest: String,
val selectedCredentials: List<String>, // todo: automatically choose matching
val disclosures: Map<String, List<String>>? = null,
val note: String? = null,
)
data class PresentationRequestParameter(
val did: String,
val request: String,
val selectedCredentials: List<String>,
val disclosures: Map<String, List<String>>? = null,
val note: String? = null
)
| 8
| null |
6
| 98
|
a86bd0c843d594f6afe6e747d3c4de7d8a4789a8
| 10,211
|
waltid-identity
|
Apache License 2.0
|
NewTabButton/src/main/kotlin/example/CloseTabIcon.kt
|
aterai
| 158,348,575
| false
| null |
package example
import java.awt.*
import javax.swing.*
class CloseTabIcon(
private val color: Color,
) : Icon {
override fun paintIcon(
c: Component,
g: Graphics,
x: Int,
y: Int,
) {
val g2 = g.create() as? Graphics2D ?: return
g2.translate(x, y)
g2.paint = color
g2.drawLine(2, 2, 9, 9)
g2.drawLine(2, 3, 8, 9)
g2.drawLine(3, 2, 9, 8)
g2.drawLine(9, 2, 2, 9)
g2.drawLine(9, 3, 3, 9)
g2.drawLine(8, 2, 2, 8)
g2.dispose()
}
override fun getIconWidth() = 12
override fun getIconHeight() = 12
}
class PlusIcon : Icon {
override fun paintIcon(
c: Component,
g: Graphics,
x: Int,
y: Int,
) {
val g2 = g.create() as? Graphics2D ?: return
g2.translate(x, y)
viewRect.bounds = c.bounds
val r = SwingUtilities.calculateInnerArea(c as? JComponent, viewRect)
OperaTabViewButtonUI.tabPainter(g2, r)
g2.paint = Color.WHITE
var w = viewRect.width
val a = w / 2
val b = w / 3
w -= 2
g2.drawLine(a, b, a, w - b)
g2.drawLine(a - 1, b, a - 1, w - b)
g2.drawLine(b, a, w - b, a)
g2.drawLine(b, a - 1, w - b, a - 1)
g2.dispose()
}
override fun getIconWidth() = 24
override fun getIconHeight() = 24
companion object {
private val viewRect = Rectangle()
}
}
| 0
| null |
5
| 9
|
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
| 1,308
|
kotlin-swing-tips
|
MIT License
|
android/integration/testData/architecture-samples/shared-test/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/network/FakeNetworkDataSource.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.statsig.todoapp.data.source.network
class FakeNetworkDataSource(
var tasks: MutableList<NetworkTask>? = mutableListOf()
) : NetworkDataSource {
override suspend fun loadTasks() = tasks ?: throw Exception("Task list is null")
override suspend fun saveTasks(tasks: List<NetworkTask>) {
this.tasks = tasks.toMutableList()
}
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 978
|
android
|
Apache License 2.0
|
appcues/src/main/java/com/appcues/data/mapper/step/primitives/EmbedPrimitiveMapper.kt
|
appcues
| 413,524,565
| false
|
{"Kotlin": 1101664, "Shell": 17991, "Ruby": 1503}
|
package com.appcues.data.mapper.step.primitives
import com.appcues.data.mapper.styling.mapComponentSize
import com.appcues.data.mapper.styling.mapComponentStyle
import com.appcues.data.model.ExperiencePrimitive.EmbedHtmlPrimitive
import com.appcues.data.remote.response.step.primitive.PrimitiveResponse.EmbedPrimitiveResponse
internal fun EmbedPrimitiveResponse.mapEmbedPrimitive() = EmbedHtmlPrimitive(
id = id,
style = style.mapComponentStyle(),
embed = embed,
intrinsicSize = intrinsicSize.mapComponentSize(),
)
| 5
|
Kotlin
|
2
| 9
|
f89fdadba3e08d161e5d674efa9eb6a46759608b
| 533
|
appcues-android-sdk
|
MIT License
|
CovidTracerApp/app/src/main/java/com/example/covidtracerapp/geofencing/GeofenceBroadcastReceiver.kt
|
akezhanmussa
| 300,800,109
| false
| null |
package com.example.covidtracerapp.geofencing
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.example.covidtracerapp.R
import com.example.covidtracerapp.presentation.MapActivity
import com.example.covidtracerapp.presentation.ShowBeaconsActivity.Companion.ACTION_GEOFENCE_EVENT
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofenceStatusCodes
import com.google.android.gms.location.GeofencingEvent
private val TAG = GeofenceBroadcastReceiver::class.simpleName
private const val NOTIFICATION_ID = 35
private const val NOTIFICATION_CHANNEL_ID = "GeofencingChannel"
class GeofenceBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.i(TAG, "Received")
if (intent.action == ACTION_GEOFENCE_EVENT){
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()){
val errorMessage = GeofenceStatusCodes.getStatusCodeString(geofencingEvent.errorCode)
Log.e(TAG, errorMessage)
return
}
val geofencingTransition = geofencingEvent.geofenceTransition
if (geofencingTransition == Geofence.GEOFENCE_TRANSITION_ENTER){
Log.v(TAG, "Geofence Entered")
val notificationManager = ContextCompat.getSystemService(context, NotificationManager::class.java) as NotificationManager
notificationManager.sendGeofenceEnteredNotification(context)
}
}
}
}
fun createGeofencingNotificationChannel(context: Context){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notificationChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
context.getString(R.string.geofence_notification_channel_name),
NotificationManager.IMPORTANCE_HIGH)
notificationChannel.setShowBadge(false)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.description = context.getString(R.string.geofence_notification_channel_description)
val notificationManager = context.getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(notificationChannel)
}
}
fun NotificationManager.sendGeofenceEnteredNotification(context: Context){
val contentIntent = Intent(context, MapActivity::class.java)
// contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val contentPendingIntent = PendingIntent.getActivity(
context,
NOTIFICATION_ID,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentTitle(context.getString(R.string.geofence_notification_title))
.setContentText(context.getString(R.string.geofence_notification_text))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(contentPendingIntent)
.setSmallIcon(R.mipmap.ic_launcher_round)
notify(NOTIFICATION_ID, builder.build())
}
| 1
|
Kotlin
|
1
| 1
|
1637003262cc32ac5431c71d508339f878513716
| 3,561
|
Coronavirus-tracking-system
|
MIT License
|
src/main/kotlin/ink/ptms/chemdah/core/PlayerProfile.kt
|
TabooLib
| 338,114,548
| false
| null |
package ink.ptms.chemdah.core
import ink.ptms.chemdah.api.ChemdahAPI
import ink.ptms.chemdah.api.event.collect.QuestEvents
import ink.ptms.chemdah.core.database.Database
import ink.ptms.chemdah.core.quest.Quest
import ink.ptms.chemdah.core.quest.QuestDataOperator
import ink.ptms.chemdah.core.quest.Task
import ink.ptms.chemdah.core.quest.Template
import ink.ptms.chemdah.core.quest.objective.Objective
import ink.ptms.chemdah.util.Couple
import ink.ptms.chemdah.util.namespaceQuest
import org.bukkit.Bukkit
import org.bukkit.entity.Player
import taboolib.common.platform.function.adaptCommandSender
import taboolib.common.platform.function.submitAsync
import taboolib.common.util.asList
import taboolib.common5.Coerce
import taboolib.module.kether.KetherShell
import taboolib.module.kether.printKetherErrorMessage
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.function.Consumer
import java.util.function.Function
/**
* Chemdah
* ink.ptms.chemdah.core.PlayerProfile
*
* @author sky
* @since 2021/3/2 12:00 上午
*/
class PlayerProfile(val uniqueId: UUID) {
/**
* 玩家实例
*/
val player: Player
get() = Bukkit.getPlayer(uniqueId)!!
/**
* 玩家是否在线
*/
val isPlayerOnline: Boolean
get() = Bukkit.getPlayer(uniqueId) != null
/**
* 任务或玩家数据是否发生变动
*/
val isDataChanged: Boolean
get() = persistentDataContainer.isChanged || getQuests().any { it.newQuest || it.persistentDataContainer.isChanged }
/**
* 持久化数据储存容器
*/
val persistentDataContainer = DataContainer()
/**
* 任务容器
*/
private val questMap = ConcurrentHashMap<String, Quest>()
/**
* 强制注册新的任务
* 会覆盖原有的相同任务且不会进行任何条件判断和触发事件
*/
fun registerQuest(quest: Quest, newQuest: Boolean = true) {
questMap[quest.id] = quest
if (quest.isValid) {
quest.newQuest = newQuest
QuestEvents.Registered(quest, this).call()
}
}
/**
* 强制注销任务
* 不会进行任何条件判断和触发事件
* @param release 是否从数据库释放数据
*/
fun unregisterQuest(quest: Quest, release: Boolean = true) {
// 删除缓存
questMap.remove(quest.id)
// 释放数据
if (release) {
submitAsync { Database.INSTANCE.releaseQuest(player, this@PlayerProfile, quest) }
}
QuestEvents.Unregistered(quest, this).call()
}
internal fun <T> dataOperator(task: Task, func: QuestDataOperator.() -> T): T {
return func.invoke(QuestDataOperator(this, task))
}
/**
* 获取条目数据控制器
*/
fun <T> dataOperator(task: Task, func: Function<QuestDataOperator, T>): T {
return func.apply(QuestDataOperator(this, task))
}
/**
* 通过序号获取正在进行中的有效任务
* @param openAPI 是否启用开放 API,即允许第三方直接修改这个结果
*/
fun getQuestById(value: String, openAPI: Boolean = true): Quest? {
return if (openAPI) {
getQuests(true).firstOrNull { it.id == value }
} else {
questMap[value]?.takeIf { it.isValid }
}
}
/**
* 获取所有正在进行中的有效任务
* @param openAPI 是否启用开放 API,即允许第三方直接修改这个结果
*/
fun getQuests(openAPI: Boolean = false): List<Quest> {
return if (openAPI) {
ChemdahAPI.eventFactory.callQuestCollect(this, questMap.values.filter { it.isValid })
} else {
questMap.values.filter { it.isValid }
}
}
/**
* 通过序号判断该任务是否已经完成
*/
fun isQuestCompleted(value: String): Boolean {
return getQuestCompletedDate(value) > 0L
}
/**
* 通过模板判断该任务是否已经完成
*/
fun isQuestCompleted(template: Template): Boolean {
return isQuestCompleted(template.id)
}
/**
* 通过序号判断该任务的上次完成时间
*/
fun getQuestCompletedDate(value: String): Long {
return persistentDataContainer["quest.complete.$value", 0L].toLong()
}
/**
* 通过模板判断该任务的上次完成时间
*/
fun getQuestCompletedDate(template: Template): Long {
return getQuestCompletedDate(template.id)
}
/**
* 执行事件脚本代理
*/
fun checkAgent(agent: Any?, quest: Quest? = null, variables: Map<String, Any> = emptyMap()): CompletableFuture<Boolean> {
agent ?: return CompletableFuture.completedFuture(true)
return try {
KetherShell.eval(agent.asList(), sender = adaptCommandSender(player), namespace = namespaceQuest) {
set("@QuestSelected", quest?.template?.node)
set("@QuestContainer", quest)
variables.forEach { (t, u) -> set(t, u) }
}.thenApply {
Coerce.toBoolean(it)
}
} catch (e: Throwable) {
e.printKetherErrorMessage()
CompletableFuture.completedFuture(false)
}
}
/**
* 通过事件获取所有正在进行中的有效条目(有效任务)
*/
fun tasks(event: Any, func: Consumer<Couple<Quest, Task>>) {
getQuests(true).forEach { quest ->
quest.tasks.filter { it.objective.isListener && it.objective.event.isInstance(event) }.forEach { func.accept(Couple(quest, it)) }
}
}
/**
* 通过 Objective 获取所有正在进行中的有效条目(有效任务)
*/
fun tasks(objective: Objective<*>, func: Consumer<Couple<Quest, Task>>) {
getQuests(true).forEach { quest -> quest.tasks.filter { it.objective == objective }.forEach { func.accept(Couple(quest, it)) } }
}
/**
* 检查并更新数据
*/
fun push() {
Database.INSTANCE.update(player, this)
}
}
| 7
|
Kotlin
|
44
| 55
|
b501c2811be1276744af05446d2ca8b8e63c4081
| 5,510
|
chemdah
|
MIT License
|
sykepenger-model/src/main/kotlin/no/nav/helse/tournament/Turneringsnøkkel.kt
|
navikt
| 193,907,367
| false
| null |
package no.nav.helse.tournament
import no.nav.helse.hendelser.Inntektsmelding
import no.nav.helse.hendelser.OverstyrTidslinje
import no.nav.helse.hendelser.Søknad
import no.nav.helse.sykdomstidslinje.Dag
import no.nav.helse.sykdomstidslinje.Dag.Arbeidsdag
import no.nav.helse.sykdomstidslinje.Dag.ArbeidsgiverHelgedag
import no.nav.helse.sykdomstidslinje.Dag.Arbeidsgiverdag
import no.nav.helse.sykdomstidslinje.Dag.Feriedag
import no.nav.helse.sykdomstidslinje.Dag.FriskHelgedag
import no.nav.helse.sykdomstidslinje.Dag.Permisjonsdag
import no.nav.helse.sykdomstidslinje.Dag.ProblemDag
import no.nav.helse.sykdomstidslinje.Dag.SykHelgedag
import no.nav.helse.sykdomstidslinje.Dag.Sykedag
// disse verdiene må være 1-til-1 mellom navnene i dagturnering-csv-filene
internal enum class Turneringsnøkkel {
Arbeidsdag_SØ,
Arbeidsdag_IM,
Sykedag_SØ,
ForeldetSykedag,
Feriedag_SØ,
Feriedag_IM,
FerieUtenSykmeldingdag,
Permisjonsdag_SØ,
SykHelgedag_SØ,
Arbeidsgiverdag_IM,
ArbeidsgiverHelgedag_IM,
Arbeidsgiverdag_SØ,
ArbeidsgiverHelgedag_SØ,
Saksbehandlerdag,
Arbeidsgiverdag_SB,
Arbeidsdag_SB,
SykedagNav_IM,
UkjentDag,
UbestemtDag;
companion object {
fun fraDag(dag: Dag) = when {
dag is Arbeidsgiverdag && dag.kommerFra(OverstyrTidslinje::class) -> Arbeidsgiverdag_SB
dag is Arbeidsdag && dag.kommerFra(OverstyrTidslinje::class) -> Arbeidsdag_SB
dag is Dag.FerieUtenSykmeldingDag -> FerieUtenSykmeldingdag
dag.kommerFra(OverstyrTidslinje::class) -> Saksbehandlerdag
dag is Arbeidsdag && dag.kommerFra(Inntektsmelding::class) -> Arbeidsdag_IM
dag is Arbeidsdag && dag.kommerFra(Søknad::class) -> Arbeidsdag_SØ
dag is Arbeidsgiverdag && dag.kommerFra(Inntektsmelding::class) -> Arbeidsgiverdag_IM
dag is Dag.SykedagNav && dag.kommerFra(Inntektsmelding::class) -> SykedagNav_IM
dag is Arbeidsgiverdag && dag.kommerFra(Søknad::class) -> Arbeidsgiverdag_SØ
dag is ArbeidsgiverHelgedag && dag.kommerFra(Inntektsmelding::class) -> ArbeidsgiverHelgedag_IM
dag is SykHelgedag && dag.kommerFra(Inntektsmelding::class) -> ArbeidsgiverHelgedag_IM
dag is ArbeidsgiverHelgedag && dag.kommerFra(Søknad::class) -> ArbeidsgiverHelgedag_SØ
dag is Feriedag && dag.kommerFra(Inntektsmelding::class) -> Feriedag_IM
dag is Feriedag && dag.kommerFra(Søknad::class) -> Feriedag_SØ
dag is FriskHelgedag && dag.kommerFra(Inntektsmelding::class) -> Feriedag_IM
dag is FriskHelgedag && dag.kommerFra(Søknad::class) -> Feriedag_SØ
dag is Dag.ForeldetSykedag -> ForeldetSykedag
dag is Permisjonsdag -> Permisjonsdag_SØ
dag is ProblemDag -> UbestemtDag
dag is Sykedag && dag.kommerFra(Søknad::class) -> Sykedag_SØ
dag is SykHelgedag && dag.kommerFra(Søknad::class) -> SykHelgedag_SØ
dag is Dag.UkjentDag -> UkjentDag
else -> throw IllegalArgumentException("Ingen turneringsnøkkel definert for ${dag::class.simpleName}")
}
}
}
| 2
| null |
7
| 5
|
2f940cad2bc6a756033a4e19edc5236a0648c971
| 3,171
|
helse-spleis
|
MIT License
|
plugins/full-line/kotlin/src/org/jetbrains/completion/full/line/kotlin/KotlinIconSet.kt
|
xGreat
| 182,651,778
| false
|
{"Text": 7190, "INI": 570, "YAML": 416, "Ant Build System": 10, "Batchfile": 28, "Shell": 616, "Markdown": 680, "Ignore List": 125, "Git Revision List": 1, "Git Attributes": 10, "EditorConfig": 244, "XML": 7188, "SVG": 3739, "Kotlin": 48905, "Java": 80666, "HTML": 3312, "Java Properties": 214, "Gradle": 419, "Maven POM": 82, "JavaScript": 212, "CSS": 69, "JFlex": 32, "JSON": 1374, "Groovy": 3308, "XSLT": 113, "desktop": 1, "Python": 15070, "JAR Manifest": 18, "PHP": 47, "Gradle Kotlin DSL": 477, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Diff": 135, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 1, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 27, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 67, "GraphQL": 60, "OpenStep Property List": 47, "Tcl": 1, "Dockerfile": 5, "fish": 1, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 5, "XML Property List": 81, "Starlark": 2, "E-mail": 18, "Roff": 38, "Roff Manpage": 2, "Swift": 3, "C": 84, "TOML": 153, "Proguard": 2, "PlantUML": 6, "Checksums": 72, "Java Server Pages": 8, "reStructuredText": 68, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "C++": 32, "Handlebars": 1, "Rust": 9, "Makefile": 1, "Go": 34, "Go Checksums": 1, "Go Module": 1, "VBScript": 1, "NSIS": 5, "Thrift": 3, "Cython": 12, "Regular Expression": 3, "JSON5": 4}
|
package org.jetbrains.completion.full.line.kotlin
import com.intellij.ui.IconManager
import org.jetbrains.completion.full.line.language.IconSet
import org.jetbrains.kotlin.idea.KotlinIcons
import javax.swing.Icon
class KotlinIconSet : IconSet {
override val regular: Icon = KotlinIcons.SMALL_LOGO
override val redCode: Icon = IconManager.getInstance().getIcon("/icons/kotlin/redCode.svg", this::class.java)
}
| 1
| null |
1
| 1
|
fb5f23167ce9cc53bfa3ee054b445cf4d8f1ce98
| 415
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/divyansh/tech/wallup/home/browse/screens/popularTags/PopularTagsFragment.kt
|
justdvnsh
| 409,287,171
| false
| null |
package divyansh.tech.wallup.home.browse.screens.popularTags
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.GridLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import divyansh.tech.wallup.common.CommonFragment
import divyansh.tech.wallup.common.CommonViewModel
import divyansh.tech.wallup.databinding.FragmentPopularTagsBinding
import divyansh.tech.wallup.home.browse.screens.popularTags.callbacks.PopularTagsCallback
import divyansh.tech.wallup.home.browse.screens.popularTags.epoxy.EpoxyPopularTagsController
import divyansh.tech.wallup.utils.EventObserver
@AndroidEntryPoint
class PopularTagsFragment : CommonFragment() {
private lateinit var _binding: FragmentPopularTagsBinding
val binding get() = _binding
private val args by navArgs<PopularTagsFragmentArgs>()
private val viewModel by viewModels<PopularTagsViewModel>()
private val controller by lazy {
EpoxyPopularTagsController(PopularTagsCallback(viewModel))
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentPopularTagsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
setupObservers()
}
override fun getCommonViewModel(): CommonViewModel = viewModel
private fun setupRecyclerView() {
binding.popularTagsRv.apply {
layoutManager = GridLayoutManager(requireContext(), 2)
adapter = controller.adapter
}
}
private fun setupObservers() {
viewModel.popularTagsWallpaperLiveData.observe(
viewLifecycleOwner,
Observer {
controller.setData(it)
}
)
viewModel.navigation.observe(
viewLifecycleOwner,
EventObserver {
findNavController().navigate(it)
}
)
}
override fun onResume() {
super.onResume()
viewModel.getWallpapers(args.tag.url)
}
}
| 15
|
Kotlin
|
6
| 7
|
b23f982ae5ff7b21adc3af62f38f639e054fef62
| 2,464
|
WallUP
|
The Unlicense
|
livedata-ktx/src/main/java/com/shopify/livedataktx/Extension.kt
|
Shopify
| 130,487,409
| false
| null |
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Shopify Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.shopify.livedataktx
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.Transformations
object Extension {
fun <IN, OUT> create(
source: LiveDataKtx<IN>,
operator: Operator<IN, OUT>
): MediatorLiveDataKtx<OUT> = toSwitchMap(source) {
PublishLiveDataKtx<OUT>(source).apply {
operator.run(
this,
it
)
}
}
}
/**
* filter
*/
private class FilterOperator<T>(val predicate: (T) -> Boolean) : Operator<T, T> {
override fun run(output: MediatorLiveDataKtx<T>, value: T) {
if (predicate.invoke(value)) {
output.value = value
}
}
}
fun <T> LiveDataKtx<T>.filter(predicate: (T) -> Boolean): LiveDataKtx<T> =
Extension.create(this, FilterOperator(predicate))
fun <T> MutableLiveDataKtx<T>.filter(predicate: (T) -> Boolean): MutableLiveDataKtx<T> =
Extension.create(this, FilterOperator(predicate))
fun <T> MediatorLiveDataKtx<T>.filter(predicate: (T) -> Boolean): MediatorLiveDataKtx<T> =
Extension.create(this, FilterOperator(predicate))
/**
* map
*/
private class MapOperator<T, R>(val mapper: (T) -> R) : Operator<T, R> {
override fun run(output: MediatorLiveDataKtx<R>, value: T) {
output.value = mapper.invoke(value)
}
}
fun <T, R> LiveDataKtx<T>.map(mapper: (T) -> R): LiveDataKtx<R> =
Extension.create(this, MapOperator(mapper))
fun <T, R> MutableLiveDataKtx<T>.map(mapper: (T) -> R): MutableLiveDataKtx<R> =
Extension.create(this, MapOperator(mapper))
fun <T, R> MediatorLiveDataKtx<T>.map(mapper: (T) -> R): MediatorLiveDataKtx<R> =
Extension.create(this, MapOperator(mapper))
/**
* switchMap
*/
private fun <T, R> toSwitchMap(
source: LiveData<T>,
func: (T) -> LiveDataKtx<R>
): MediatorLiveDataKtx<R> = toKtx(Transformations.switchMap(source) { func.invoke(it) })
fun <T, R> LiveDataKtx<T>.switchMap(func: (T) -> LiveDataKtx<R>): LiveDataKtx<R> =
toSwitchMap(this, func)
fun <T, R> MutableLiveDataKtx<T>.switchMap(func: (T) -> LiveDataKtx<R>): MutableLiveDataKtx<R> =
toSwitchMap(this, func)
fun <T, R> MediatorLiveDataKtx<T>.switchMap(func: (T) -> LiveDataKtx<R>): MediatorLiveDataKtx<R> =
toSwitchMap(this, func)
/**
* toKtx
*/
private fun <T> toKtx(source: LiveData<T>): MediatorLiveDataKtx<T> {
val output = MediatorLiveDataKtx<T>()
output.addSource(source, Observer { value -> value?.let { output.value = value } })
return output
}
private fun <T> toNullableKtx(source: LiveData<T>): MediatorLiveDataKtx<T?> {
val output = MediatorLiveDataKtx<T?>()
output.addSource(source, Observer { value -> output.value = value })
return output
}
fun <T> LiveData<T>.toKtx(): LiveDataKtx<T> = toKtx(this)
fun <T> MutableLiveData<T>.toKtx(): MutableLiveDataKtx<T> = toKtx(this)
fun <T> MediatorLiveData<T>.toKtx(): MediatorLiveDataKtx<T> = toKtx(this)
fun <T> LiveData<T>.toNullableKtx(): LiveDataKtx<T?> = toNullableKtx(this)
fun <T> MutableLiveData<T>.toNullableKtx(): MutableLiveDataKtx<T?> = toNullableKtx(this)
fun <T> MediatorLiveData<T>.toNullableKtx(): MediatorLiveDataKtx<T?> = toNullableKtx(this)
| 5
| null |
30
| 466
|
fb45d8b66d8173358017d86d803db141f0533020
| 4,437
|
livedata-ktx
|
MIT License
|
bitcoincore/src/main/kotlin/io/horizontalsystems/bitcoincore/transactions/extractors/MyOutputsCache.kt
|
horizontalsystems
| 147,199,533
| false
| null |
package io.horizontalsystems.bitcoincore.transactions.extractors
import io.horizontalsystems.bitcoincore.core.HashBytes
import io.horizontalsystems.bitcoincore.core.IStorage
import io.horizontalsystems.bitcoincore.models.TransactionInput
import io.horizontalsystems.bitcoincore.models.TransactionOutput
class MyOutputsCache {
private val outputsCache = mutableMapOf<HashBytes, MutableMap<Int, Long>>()
fun add(outputs: List<TransactionOutput>) {
for (output in outputs) {
if (output.publicKeyPath != null) {
if (!outputsCache.containsKey(HashBytes(output.transactionHash))) {
outputsCache[HashBytes(output.transactionHash)] = mutableMapOf()
}
outputsCache[HashBytes(output.transactionHash)]?.set(output.index, output.value)
}
}
}
fun valueSpentBy(input: TransactionInput): Long? {
return outputsCache[HashBytes(input.previousOutputTxHash)]?.get(input.previousOutputIndex.toInt())
}
companion object {
fun create(storage: IStorage): MyOutputsCache {
val outputsCache = MyOutputsCache()
val outputs = storage.getMyOutputs()
outputsCache.add(outputs)
return outputsCache
}
}
}
| 20
| null |
55
| 96
|
110018d54d82bb4e3c2a1d6b0ddd1bb9eeff9167
| 1,290
|
bitcoin-kit-android
|
MIT License
|
src/main/kotlin/net/timafe/letsgo2/config/AsyncConfiguration.kt
|
tillkuhn
| 222,716,226
| false
| null |
package com.bytetrain.prodinv.config
import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor
import java.util.concurrent.Executor
import org.slf4j.LoggerFactory
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.AsyncConfigurer
import org.springframework.scheduling.annotation.EnableAsync
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
@Configuration
@EnableAsync
@EnableScheduling
class AsyncConfiguration(private val taskExecutionProperties: TaskExecutionProperties) : AsyncConfigurer {
private val log = LoggerFactory.getLogger(javaClass)
@Bean(name = ["taskExecutor"])
override fun getAsyncExecutor(): Executor {
log.debug("Creating Async Task Executor")
val executor = ThreadPoolTaskExecutor().apply {
corePoolSize = taskExecutionProperties.pool.coreSize
maxPoolSize = taskExecutionProperties.pool.maxSize
setQueueCapacity(taskExecutionProperties.pool.queueCapacity)
threadNamePrefix = taskExecutionProperties.threadNamePrefix
}
return ExceptionHandlingAsyncTaskExecutor(executor)
}
override fun getAsyncUncaughtExceptionHandler() = SimpleAsyncUncaughtExceptionHandler()
}
| 36
| null |
1
| 1
|
62994d7b25eff595dfa1b4144096d8614b81389a
| 1,548
|
letsgo2
|
Apache License 2.0
|
paho.mqtt.android-kotlin/extendedSample/src/main/java/info/mqtt/android/extsample/StrictApplication.kt
|
emqx
| 297,556,171
| false
|
{"Kotlin": 350308, "Swift": 292033, "JavaScript": 79242, "Java": 78123, "Python": 69119, "C++": 55298, "C": 40179, "TypeScript": 34116, "HTML": 31666, "Go": 23672, "Vue": 22576, "C#": 15739, "Erlang": 10742, "Dart": 6279, "PHP": 4360, "Objective-C++": 3648, "SCSS": 3091, "Shell": 3008, "Objective-C": 2933, "Ruby": 2882, "Elixir": 2467, "Makefile": 1528, "CMake": 1254, "CSS": 1038, "Starlark": 602, "Dockerfile": 269, "QMake": 163}
|
package info.mqtt.android.extsample
import android.os.StrictMode
import info.hannes.logcat.LoggingApplication
class StrictApplication : LoggingApplication() {
override fun onCreate() {
super.onCreate()
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyDialog()
.penaltyLog()
.build()
)
}
}
| 29
|
Kotlin
|
97
| 803
|
d88375ca7e295c2815405420330699feae13963f
| 509
|
MQTT-Client-Examples
|
MIT License
|
apps/etterlatte-vilkaarsvurdering/src/test/kotlin/no/nav/etterlatte/vilkaarsvurdering/AldersovergangRoutesTest.kt
|
navikt
| 417,041,535
| false
|
{"Kotlin": 7239242, "TypeScript": 1782732, "Handlebars": 26265, "Shell": 12680, "PLpgSQL": 1891, "HTML": 1734, "CSS": 598, "Dockerfile": 547}
|
package no.nav.etterlatte.vilkaarsvurdering
import io.kotest.matchers.shouldBe
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.testApplication
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import no.nav.etterlatte.ktor.runServer
import no.nav.etterlatte.ktor.startRandomPort
import no.nav.etterlatte.ktor.token.issueSystembrukerToken
import no.nav.etterlatte.vilkaarsvurdering.klienter.BehandlingKlient
import no.nav.security.mock.oauth2.MockOAuth2Server
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import java.util.UUID
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class AldersovergangRoutesTest {
private val mockOAuth2Server = MockOAuth2Server()
private val behandlingKlient = mockk<BehandlingKlient>()
private val aldersovergangService = mockk<AldersovergangService>()
private val behandlingId = UUID.randomUUID()
private val behandlingDetSkalKopieresFraId = UUID.randomUUID()
@BeforeAll
fun before() {
mockOAuth2Server.startRandomPort()
}
@AfterAll
fun after() {
mockOAuth2Server.shutdown()
}
private val token: String by lazy { mockOAuth2Server.issueSystembrukerToken() }
@Test
fun `skal delegere til aldersovergangservice`() {
testApplication {
runServer(mockOAuth2Server) {
aldersovergang(behandlingKlient, aldersovergangService)
}
val vilkaarsvurdering =
mockk<Vilkaarsvurdering> {
every { id } returns UUID.randomUUID()
}
coEvery {
aldersovergangService.behandleOpphoerAldersovergang(behandlingId, behandlingDetSkalKopieresFraId, any())
} returns vilkaarsvurdering
val response =
client.post("/api/vilkaarsvurdering/aldersovergang/$behandlingId?fra=$behandlingDetSkalKopieresFraId") {
header(HttpHeaders.ContentType, ContentType.Application.Json.toString())
header(HttpHeaders.Authorization, "Bearer $token")
}
response.status shouldBe HttpStatusCode.OK
coVerify { aldersovergangService.behandleOpphoerAldersovergang(behandlingId, behandlingDetSkalKopieresFraId, any()) }
verify { vilkaarsvurdering.id }
}
}
}
| 11
|
Kotlin
|
0
| 6
|
e715675c319d4a0a826855615749573e45ae7a75
| 2,631
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
IBD/app/src/main/java/com/example/mc/model/Markers.kt
|
ancamiha
| 590,185,441
| false
| null |
package com.example.mc.model
data class Markers(
val markers: List<Marker>
)
data class Marker(
val email: String,
val lat: Double,
val lng: Double,
val name: String,
val time: String
)
| 0
|
Kotlin
|
0
| 0
|
42ea3607cc6f79ab3a39c394d510a97fff882211
| 212
|
Introduction-in-Big-Data-Project
|
MIT License
|
compiler/testData/diagnostics/tests/inference/commonSystem/theSameFunctionInArgs.kt
|
mikiyakitahara
| 43,902,391
| true
|
{"Java": 15722183, "Kotlin": 10713329, "JavaScript": 176060, "Protocol Buffer": 43034, "HTML": 25327, "Lex": 17330, "ANTLR": 9689, "CSS": 9358, "Groovy": 5199, "Shell": 4638, "Batchfile": 3703, "IDL": 3251}
|
// !CHECK_TYPE
fun <T> arrayOf(vararg t : T) : Array<T> = t as Array<T>
fun test() {
val array = arrayOf(arrayOf(1))
array checkType { _<Array<Array<Int>>>() }
}
| 0
|
Java
|
0
| 0
|
d90585624f631b5b016ff7ce4ceffa0e563596da
| 171
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/foobarust/deliverer/usecases/maps/GetElapsedDistanceUseCase.kt
|
foobar-UST
| 326,433,137
| false
| null |
package com.foobarust.deliverer.usecases.maps
import com.foobarust.deliverer.data.models.GeolocationPoint
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.SphericalUtil
import javax.inject.Inject
/**
* Created by kevin on 4/1/21
*/
class GetElapsedDistanceUseCase @Inject constructor() {
private var lastLocation: GeolocationPoint? = null
operator fun invoke(currentLocation: GeolocationPoint): Double? {
val distance = lastLocation?.let {
SphericalUtil.computeDistanceBetween(
LatLng(it.latitude, it.longitude),
LatLng(currentLocation.latitude, currentLocation.longitude)
)
}
lastLocation = currentLocation
return distance
}
}
| 0
|
Kotlin
|
1
| 0
|
99c8b007436a9b192ca83eebff1bcc6aae1c095a
| 766
|
foobar-deliverer
|
MIT License
|
app/src/main/java/com/sawyer/component/manage/StartupManager.kt
|
sawyer-lee
| 710,204,764
| false
|
{"Kotlin": 58356, "Java": 15232}
|
package com.sawyer.component.manage
import android.content.Context
import android.os.Looper
import com.sawyer.common.utils.Logger
import com.sawyer.component.sort.TopologySort
import com.sawyer.component.startup.*
import java.lang.RuntimeException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicInteger
class StartupManager(
val context: Context,
private val startupList: MutableList<Startup<Any>>,
private val awaitLatch: CountDownLatch
) {
lateinit var startupSortStore: StartupSortStore
fun start(): StartupManager{
if (Looper.myLooper() != Looper.getMainLooper()){
throw RuntimeException("start函数需在主线程调用!")
}
startupSortStore = TopologySort.sort(startupList)
for (startup in startupSortStore.result){
//异步策略
val runnable = StartupRunnable(context,startup,this)
if (startup.callCreateOnMainThread()){
runnable.run()
}else{
startup.executor()?.execute(runnable)
}
}
return this
}
fun notifyChildren(startup: Startup<Any>){
if (!startup.callCreateOnMainThread() && startup.waitOnMainThread()){
awaitLatch.countDown()
}
//获得当前已经完成任务的所有子任务
if (startupSortStore.startupChildrenMap.containsKey(startup.javaClass)){
val childClsList = startupSortStore.startupChildrenMap[startup.javaClass]
childClsList?.let {
for (childCls in childClsList){
//通知子任务,父任务已完成
startupSortStore.startupMap[childCls]?.toNotify()
}
}
}
}
companion object class Builder{
private var startupList = mutableListOf<Startup<Any>>()
//记录需要主线程等待完成的异步任务
private val needAwaitCount = AtomicInteger()
fun addStartup(startup: AndroidStartup<*>): Builder{
startupList.add(startup)
return this
}
fun addAllStartup(startups: List<Startup<Any>>): Builder{
startupList.addAll(startups)
return this
}
fun build(context: Context): StartupManager{
//场景:处理主线程需要等待其他线程的任务执行
for (startup in startupList){
if (!startup.callCreateOnMainThread() && startup.waitOnMainThread()){
needAwaitCount.incrementAndGet()
}
}
val awaitLatch = CountDownLatch(needAwaitCount.get())
return StartupManager(context, startupList, awaitLatch)
}
}
//场景:处理主线程需要等待其他线程的任务执行
fun await(){
try {
awaitLatch.await()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8c82e3daa8d97d1b35f26a7d16fbff7caad48887
| 2,790
|
KotlinComponentWanAndroid
|
Apache License 2.0
|
src/main/kotlin/no/nav/bidrag/vedtak/BidragVedtak.kt
|
navikt
| 331,260,160
| false
| null |
package no.nav.bidrag.vedtak
import no.nav.security.token.support.spring.api.EnableJwtTokenValidation
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
@EnableJwtTokenValidation(ignore = ["org.springdoc", "org.springframework"])
@SpringBootApplication(exclude = [UserDetailsServiceAutoConfiguration::class])
class BidragVedtak
const val ISSUER = "aad"
fun main(args: Array<String>) {
val profile = if (args.isEmpty()) LIVE_PROFILE else args[0]
val app = SpringApplication(BidragVedtak::class.java)
app.setAdditionalProfiles(profile)
app.run(*args)
}
| 2
|
Kotlin
|
0
| 1
|
253d24239f07192a6a2a832ccafe0dad982f0ee3
| 737
|
bidrag-vedtak
|
MIT License
|
core/src/commonMain/kotlin/dev/carlsen/flagkit/flagicons/DO.kt
|
acarlsen
| 722,319,804
| false
|
{"Kotlin": 1629077, "Batchfile": 2673, "Swift": 590}
|
package dev.carlsen.flagkit.flagicons
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush.Companion.linearGradient
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 dev.carlsen.flagkit.FlagIcons
val FlagIcons.DO: ImageVector
get() {
if (_do != null) {
return _do!!
}
_do = Builder(name = "Do", defaultWidth = 21.0.dp, defaultHeight = 15.0.dp, viewportWidth =
21.0f, viewportHeight = 15.0f).apply {
path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0), start =
Offset(10.5f,0.0f), end = Offset(10.5f,15.0f)), stroke =
SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt,
strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(0.0f, 0.0f)
horizontalLineToRelative(21.0f)
verticalLineToRelative(15.0f)
horizontalLineToRelative(-21.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFF083D7A), 1.0f to Color(0xFF032F61), start =
Offset(4.5f,0.0f), end = Offset(4.5f,6.0f)), stroke =
SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt,
strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(0.0f, 0.0f)
horizontalLineToRelative(9.0f)
verticalLineToRelative(6.0f)
horizontalLineToRelative(-9.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFF083D7A), 1.0f to Color(0xFF032F61), start =
Offset(16.5f,9.0f), end = Offset(16.5f,15.0f)), stroke =
SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt,
strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(12.0f, 9.0f)
horizontalLineToRelative(9.0f)
verticalLineToRelative(6.0f)
horizontalLineToRelative(-9.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFFDF1E35), 1.0f to Color(0xFFCC162C), start =
Offset(4.5f,9.0f), end = Offset(4.5f,15.0f)), stroke =
SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt,
strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(0.0f, 9.0f)
horizontalLineToRelative(9.0f)
verticalLineToRelative(6.0f)
horizontalLineToRelative(-9.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFFDF1E35), 1.0f to Color(0xFFCC162C), start =
Offset(16.5f,0.0f), end = Offset(16.5f,6.0f)), stroke =
SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt,
strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(12.0f, 0.0f)
horizontalLineToRelative(9.0f)
verticalLineToRelative(6.0f)
horizontalLineToRelative(-9.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0), start =
Offset(10.5f,0.0f), end = Offset(10.5f,15.0f)), stroke =
SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt,
strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(9.0f, 6.0f)
lineTo(0.0f, 6.0f)
lineTo(0.0f, 9.0f)
lineTo(9.0f, 9.0f)
lineTo(9.0f, 15.0f)
lineTo(12.0f, 15.0f)
lineTo(12.0f, 9.0f)
lineTo(21.0f, 9.0f)
lineTo(21.0f, 6.0f)
lineTo(12.0f, 6.0f)
lineTo(12.0f, 0.0f)
lineTo(9.0f, 0.0f)
lineTo(9.0f, 6.0f)
close()
}
path(fill = SolidColor(Color(0xFFC93127)), stroke = SolidColor(Color(0x00000000)),
fillAlpha = 0.2f, strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin =
Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(9.4393f, 6.4393f)
curveTo(8.8536f, 7.0251f, 8.8536f, 7.9749f, 9.4393f, 8.5607f)
curveTo(10.0251f, 9.1464f, 10.9749f, 9.1464f, 11.5607f, 8.5607f)
lineTo(11.5607f, 8.5607f)
curveTo(12.1464f, 7.9749f, 12.1464f, 7.0251f, 11.5607f, 6.4393f)
}
path(fill = SolidColor(Color(0xFF042F60)), stroke = SolidColor(Color(0x00000000)),
strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(10.5f, 7.5f)
moveToRelative(-1.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, 2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f)
}
path(fill = SolidColor(Color(0xFF0F6D1A)), stroke = SolidColor(Color(0x00000000)),
strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(11.5607f, 8.5607f)
curveTo(10.9749f, 9.1464f, 10.0251f, 9.1464f, 9.4393f, 8.5607f)
curveTo(8.8536f, 7.9749f, 8.8536f, 7.0251f, 9.4393f, 6.4393f)
lineTo(9.7929f, 6.7929f)
curveTo(9.4024f, 7.1834f, 9.4024f, 7.8166f, 9.7929f, 8.2071f)
curveTo(10.1834f, 8.5976f, 10.8166f, 8.5976f, 11.2071f, 8.2071f)
curveTo(11.5976f, 7.8166f, 11.5976f, 7.1834f, 11.2071f, 6.7929f)
lineTo(11.5607f, 6.4393f)
curveTo(12.1464f, 7.0251f, 12.1464f, 7.9749f, 11.5607f, 8.5607f)
close()
moveTo(11.5607f, 8.5607f)
curveTo(10.9749f, 9.1464f, 10.0251f, 9.1464f, 9.4393f, 8.5607f)
curveTo(8.8536f, 7.9749f, 8.8536f, 7.0251f, 9.4393f, 6.4393f)
lineTo(9.7929f, 6.7929f)
curveTo(9.4024f, 7.1834f, 9.4024f, 7.8166f, 9.7929f, 8.2071f)
curveTo(10.1834f, 8.5976f, 10.8166f, 8.5976f, 11.2071f, 8.2071f)
curveTo(11.5976f, 7.8166f, 11.5976f, 7.1834f, 11.2071f, 6.7929f)
lineTo(11.5607f, 6.4393f)
curveTo(12.1464f, 7.0251f, 12.1464f, 7.9749f, 11.5607f, 8.5607f)
close()
}
}
.build()
return _do!!
}
private var _do: ImageVector? = null
| 0
|
Kotlin
|
1
| 21
|
a630a5cdbb9749db3d83ad3b751740da42d84e16
| 7,494
|
kmp-flagkit
|
MIT License
|
app/src/main/java/pl/skipcode/basekotlinapp/feature/auth/AuthContract.kt
|
Michax94
| 152,717,481
| false
| null |
package pl.skipcode.basekotlinapp.feature.auth
import pl.skipcode.basekotlinapp.feature.commons.BaseContract
interface AuthContract {
interface View : BaseContract.View{
fun showMessage(message: Int)
fun clickLogin()
fun readEtUsername() : String
}
interface Router : BaseContract.Router{
fun goToMainActivity()
}
interface Presenter : BaseContract.Presenter{
fun checkCameraPermission()
fun validateUsername(): Boolean
fun callLogin()
}
}
| 1
|
Kotlin
|
0
| 0
|
ca757e617063825e3ce3939d0cb96c3c854458a1
| 524
|
BaseKotlinApp
|
Apache License 2.0
|
app/src/main/java/com/capyreader/app/ui/articles/list/ArticleListItem.kt
|
jocmp
| 610,083,236
| false
| null |
package com.capyreader.app.ui.articles.list
import androidx.compose.foundation.layout.Arrangement
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.size
import androidx.compose.material3.ListItemColors
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme.typography
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.capyreader.app.ui.articles.FaviconBadge
import com.capyreader.app.ui.components.ProvideContentColorTextStyle
import com.capyreader.app.ui.theme.CapyTheme
@Composable
fun ArticleListItem(
headlineContent: @Composable () -> Unit,
overlineContent: @Composable() (() -> Unit)? = null,
supportingContent: @Composable() (() -> Unit)? = null,
leadingContent: @Composable() (() -> Unit)? = null,
trailingContent: @Composable() (() -> Unit)? = null,
colors: ListItemColors = ListItemDefaults.colors()
) {
Surface(
color = colors.containerColor,
) {
val leadingSize = 16.dp
val overlineStartPadding = if (leadingContent != null) {
leadingSize + VerticalPadding
} else {
0.dp
}
Column(
modifier = Modifier
.fillMaxWidth()
.padding(
top = TopPadding,
start = VerticalPadding,
end = VerticalSpacing,
bottom = BottomPadding,
)
) {
overlineContent?.let {
Row(Modifier.padding(start = overlineStartPadding)) {
ProvideTextStyleFromToken(
colors.overlineColor,
typography.labelSmall,
it,
)
}
}
Row(
horizontalArrangement = Arrangement.spacedBy(VerticalSpacing)
) {
leadingContent?.let {
Column(Modifier.size(leadingSize)) { it() }
}
Column(Modifier.weight(1f)) {
ProvideTextStyleFromToken(
colors.headlineColor,
typography.bodyLarge,
) {
headlineContent()
}
supportingContent?.let {
ProvideTextStyleFromToken(
colors.supportingTextColor,
typography.bodyMedium,
it,
)
}
}
trailingContent?.let {
Column {
ProvideTextStyleFromToken(
colors.trailingIconColor,
typography.labelSmall,
it,
)
}
}
}
}
}
}
private val VerticalSpacing = 16.dp
private val VerticalPadding = 16.dp
private val TopPadding = 8.dp
private val BottomPadding = 16.dp
@Composable
private fun ProvideTextStyleFromToken(
color: Color,
textStyle: TextStyle,
content: @Composable () -> Unit,
) =
ProvideContentColorTextStyle(
contentColor = color,
textStyle = textStyle,
content = content
)
@Preview
@Composable
private fun ArticleListItemPreview() {
CapyTheme {
ArticleListItem(
headlineContent = {
Text("Headline")
},
overlineContent = {
Text("Overline")
},
supportingContent = {
Text("Supporting")
},
leadingContent = {
FaviconBadge(url = null)
},
trailingContent = {
Text("Trailing")
},
)
}
}
| 33
| null |
4
| 147
|
196690b776eebdecd4562e357a629277fec9cfe9
| 4,340
|
capyreader
|
MIT License
|
app/src/main/java/com/capyreader/app/ui/articles/list/ArticleListItem.kt
|
jocmp
| 610,083,236
| false
| null |
package com.capyreader.app.ui.articles.list
import androidx.compose.foundation.layout.Arrangement
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.size
import androidx.compose.material3.ListItemColors
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme.typography
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.capyreader.app.ui.articles.FaviconBadge
import com.capyreader.app.ui.components.ProvideContentColorTextStyle
import com.capyreader.app.ui.theme.CapyTheme
@Composable
fun ArticleListItem(
headlineContent: @Composable () -> Unit,
overlineContent: @Composable() (() -> Unit)? = null,
supportingContent: @Composable() (() -> Unit)? = null,
leadingContent: @Composable() (() -> Unit)? = null,
trailingContent: @Composable() (() -> Unit)? = null,
colors: ListItemColors = ListItemDefaults.colors()
) {
Surface(
color = colors.containerColor,
) {
val leadingSize = 16.dp
val overlineStartPadding = if (leadingContent != null) {
leadingSize + VerticalPadding
} else {
0.dp
}
Column(
modifier = Modifier
.fillMaxWidth()
.padding(
top = TopPadding,
start = VerticalPadding,
end = VerticalSpacing,
bottom = BottomPadding,
)
) {
overlineContent?.let {
Row(Modifier.padding(start = overlineStartPadding)) {
ProvideTextStyleFromToken(
colors.overlineColor,
typography.labelSmall,
it,
)
}
}
Row(
horizontalArrangement = Arrangement.spacedBy(VerticalSpacing)
) {
leadingContent?.let {
Column(Modifier.size(leadingSize)) { it() }
}
Column(Modifier.weight(1f)) {
ProvideTextStyleFromToken(
colors.headlineColor,
typography.bodyLarge,
) {
headlineContent()
}
supportingContent?.let {
ProvideTextStyleFromToken(
colors.supportingTextColor,
typography.bodyMedium,
it,
)
}
}
trailingContent?.let {
Column {
ProvideTextStyleFromToken(
colors.trailingIconColor,
typography.labelSmall,
it,
)
}
}
}
}
}
}
private val VerticalSpacing = 16.dp
private val VerticalPadding = 16.dp
private val TopPadding = 8.dp
private val BottomPadding = 16.dp
@Composable
private fun ProvideTextStyleFromToken(
color: Color,
textStyle: TextStyle,
content: @Composable () -> Unit,
) =
ProvideContentColorTextStyle(
contentColor = color,
textStyle = textStyle,
content = content
)
@Preview
@Composable
private fun ArticleListItemPreview() {
CapyTheme {
ArticleListItem(
headlineContent = {
Text("Headline")
},
overlineContent = {
Text("Overline")
},
supportingContent = {
Text("Supporting")
},
leadingContent = {
FaviconBadge(url = null)
},
trailingContent = {
Text("Trailing")
},
)
}
}
| 33
| null |
4
| 147
|
196690b776eebdecd4562e357a629277fec9cfe9
| 4,340
|
capyreader
|
MIT License
|
demo/src/main/java/eu/kevin/demo/screens/payment/usecases/GetCreditorsUseCase.kt
|
getkevin
| 375,151,388
| false
| null |
package eu.kevin.demo.main.usecases
import eu.kevin.demo.data.KevinDataClient
import eu.kevin.demo.data.entities.Creditor
class GetCreditorsUseCase constructor(
private val kevinDataClient: KevinDataClient
) {
suspend fun getCreditors(countryIso: String): List<Creditor> {
return kevinDataClient.getCreditorsByCountry(
if (countryIso != "LT") "EE" else countryIso
).data
}
}
| 0
|
Kotlin
|
2
| 5
|
a3b45fc47badf33fb733c508db7a6563dc69b228
| 416
|
kevin-android
|
MIT License
|
src/main/kotlin/team/msg/hiv2/domain/user/application/usecase/SearchStudentByNameKeywordUseCase.kt
|
GSM-MSG
| 634,687,373
| false
|
{"Kotlin": 212144, "Dockerfile": 177}
|
package team.msg.hiv2.domain.user.application.usecase
import team.msg.hiv2.domain.user.application.service.UserService
import team.msg.hiv2.domain.user.domain.constant.UserRole
import team.msg.hiv2.domain.user.presentation.data.request.SearchUserKeywordRequest
import team.msg.hiv2.domain.user.presentation.data.response.StudentResponse
import team.msg.hiv2.global.annotation.usecase.ReadOnlyUseCase
@ReadOnlyUseCase
class SearchStudentByNameKeywordUseCase(
private val userService: UserService
) {
fun execute(request: SearchUserKeywordRequest): List<StudentResponse> {
val users = userService.queryAllUserByNameContainingAndRolesContainingOrderByEmail(request.keyword, UserRole.ROLE_STUDENT)
return users.map { StudentResponse.of(it) }
}
}
| 1
|
Kotlin
|
0
| 9
|
031f334c00e6beacdb27fe11cff09c117fcb32b0
| 772
|
Hi-v2-BackEnd
|
MIT License
|
src/test/kotlin/ru/qiwi/devops/mission/control/platform/kubernetes/KubernetesHelper.kt
|
qiwi
| 329,911,226
| false
| null |
package ru.qiwi.devops.mission.control.platform.kubernetes
import io.kubernetes.client.openapi.ApiClient
import io.kubernetes.client.openapi.ApiException
import io.kubernetes.client.openapi.apis.AppsV1Api
import io.kubernetes.client.openapi.models.V1Deployment
import ru.qiwi.devops.mission.control.service.health.cluster.DisabledClusterHealthReceiver
import ru.qiwi.devops.mission.control.service.k8s.KubernetesClientImpl
import ru.qiwi.devops.mission.control.utils.getLogger
class KubernetesHelper(
val clusterName: String,
private val apiClient: ApiClient,
private val clusterConfig: ClusterConfig
) {
private val logger = getLogger<KubernetesHelper>()
val deleters = mutableListOf<() -> Unit>()
val client = KubernetesClientImpl({ apiClient }, clusterName, DisabledClusterHealthReceiver())
fun applyDeployment(deployment: V1Deployment) {
val ns = deployment.metadata?.namespace ?: throw IllegalArgumentException("Namespace should be provided")
val name = deployment.metadata?.name ?: throw IllegalArgumentException("Name should be provided")
logger.info("Applying deployment $ns/$name to ${clusterConfig.host}...")
val api = AppsV1Api(apiClient)
val existsDeployment = client.findDeployment(ns, name)
logApiExceptions {
if (existsDeployment == null) {
api.createNamespacedDeployment(ns, deployment, null, null, null)
} else {
api.replaceNamespacedDeployment(name, ns, deployment, null, null, null)
}
}
deleters.add { deleteDeployment(deployment) }
}
fun deleteDeployment(deployment: V1Deployment) {
val ns = deployment.metadata?.namespace ?: throw IllegalArgumentException("Namespace should be provided")
val name = deployment.metadata?.name ?: throw IllegalArgumentException("Name should be provided")
logger.info("Deleting deployment $ns/$name from ${clusterConfig.host}...")
val api = AppsV1Api(apiClient)
logApiExceptions {
api.deleteNamespacedDeployment(name, ns, null, null, null, null, null, null)
}
}
fun deleteAllCreatedResources() {
deleters.forEach {
try {
it()
} catch (e: Exception) {
logger.error("Can't delete resource", e)
}
}
}
private fun <T> logApiExceptions(fn: () -> T): T {
try {
return fn()
} catch (e: ApiException) {
logger.error("Cluster $clusterName returned an error: ${e.code} ${e.message} ${e.responseBody}", e)
throw e
} catch (e: Exception) {
logger.error("Unexpected error occurred while requesting cluster api", e)
throw e
}
}
}
| 1
|
Kotlin
|
1
| 1
|
a5b4a1dc716841bbf0439fa309e3a2b85bbeb1d3
| 2,803
|
k8s-mission-control
|
MIT License
|
app/src/main/java/com/android/tvflix/config/FeatureFlagAnnotations.kt
|
reactivedroid
| 98,877,626
| false
|
{"Kotlin": 98758}
|
package com.android.tvflix.config
import javax.inject.Qualifier
@Qualifier
@Target(
AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.FIELD
)
annotation class FavoritesFeatureFlag
| 0
|
Kotlin
|
59
| 412
|
3f36749698316000b6dfbe2195f8be9cdf10e155
| 251
|
TvFlix
|
MIT License
|
data/src/main/java/com/begines/christian/data/models/WorkerApiModel.kt
|
christianbegines
| 544,189,847
| false
|
{"Kotlin": 29231}
|
package com.begines.christian.data.models
import com.google.gson.annotations.SerializedName
data class WorkerApiModel(
@SerializedName("first_name") var firstName: String,
@SerializedName("last_name") var lastName: String,
@SerializedName("favorite") var favoriteApiModel: FavoriteApiModel,
@SerializedName("gender") var gender: String,
@SerializedName("image") var image: String,
@SerializedName("profession") var profession: String,
@SerializedName("email") var email: String,
@SerializedName("age") var age: Int,
@SerializedName("country") var country: String,
@SerializedName("height") var height: Int,
@SerializedName("id") var id: Int,
@SerializedName("quota") var quote: String,
@SerializedName("description") var description: String
)
| 0
|
Kotlin
|
0
| 0
|
b5fdbf58c036b83f81c35320c9ab21803e4779bd
| 798
|
WonkaManagementJetpackComposeMVVMHilt
|
Apache License 2.0
|
modules/wasm-binary/src/commonMain/kotlin/tree/TableType.kt
|
wasmium
| 761,480,110
| false
|
{"Kotlin": 661510, "JavaScript": 203}
|
package org.wasmium.wasm.binary.tree
public class TableType(public val elementType: WasmType, public val limits: Limits)
| 0
|
Kotlin
|
0
| 3
|
f219d7133574e8ea81ce905393991212ca293cf4
| 122
|
wasmium-wasm-binary
|
Apache License 2.0
|
web/src/main/kotlin/com/github/niuhf0452/exile/web/internal/TypeSafeServerHandler.kt
|
niuhf0452
| 240,633,641
| false
| null |
package com.github.niuhf0452.exile.web.internal
import com.github.niuhf0452.exile.web.*
import com.github.niuhf0452.exile.web.serialization.VariableTypeConverters
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.KVisibility
import kotlin.reflect.full.callSuspend
import kotlin.reflect.full.callSuspendBy
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.functions
class TypeSafeServerHandler(
private val method: KFunction<*>,
private val parameters: List<ParameterExtractor>
) : WebHandler {
override suspend fun onRequest(context: RequestContext): WebResponse<Any> {
val params = parameters.map { it.get(context) }
val callByDefault = params.find { it === defaultValuePlaceHolder } != null
val result = if (callByDefault) {
val map = mutableMapOf<KParameter, Any?>()
for (i in parameters.indices) {
if (params[i] !== defaultValuePlaceHolder) {
map[parameters[i].parameter] = params[i]
}
}
if (method.isSuspend) {
method.callSuspendBy(map)
} else {
method.callBy(map)
}
} else {
val args = params.toTypedArray()
if (method.isSuspend) {
method.callSuspend(*args)
} else {
method.call(*args)
}
}
return when (result) {
null, Unit -> WebResponse.newBuilder().statusCode(204).build()
else -> WebResponse.newBuilder().statusCode(200).entity(result).build()
}
}
interface ParameterExtractor {
val parameter: KParameter
fun get(context: RequestContext): Any?
}
private class InjectionParameterExtractor(
override val parameter: KParameter,
private val injector: TypeSafeHandlerInjector
) : ParameterExtractor {
private val instanceClass = parameter.type.classifier as? KClass<*>
?: throw IllegalArgumentException("@WebEndpoint instance can't be created: $parameter")
override fun get(context: RequestContext): Any? {
return injector.getInstance(instanceClass)
}
}
private abstract class ConvertibleExtractor(
final override val parameter: KParameter
) : ParameterExtractor {
private val isList: Boolean
private val converter: VariableTypeConverter<*>
private val name: String
init {
var c = parameter.type.classifier as? KClass<*>
?: throw IllegalArgumentException("@WebMethod parameter type is not supported: $parameter")
if (c == List::class) {
isList = true
c = parameter.type.arguments[0].type?.classifier as? KClass<*>
?: throw IllegalArgumentException("@WebMethod parameter type is not supported: $parameter")
} else {
isList = false
}
converter = VariableTypeConverters.getConverter(c)
?: throw IllegalArgumentException("@WebMethod parameter type is not supported: $parameter")
@Suppress("LeakingThis")
var value = getAnnotatedName()
if (value == null || value.isEmpty()) {
value = parameter.name
}
name = value ?: throw IllegalArgumentException("@WebMethod parameter name is missing: $parameter")
}
protected abstract fun getAnnotatedName(): String?
protected abstract fun getValue(context: RequestContext, name: String): String?
protected abstract fun getValueList(context: RequestContext, name: String): List<String>
override fun get(context: RequestContext): Any? {
if (isList) {
val list = getValueList(context, name)
if (list.isEmpty()) {
if (parameter.isOptional) {
return defaultValuePlaceHolder
}
return emptyList<Any>()
}
return list.map { text ->
converter.parse(text)
}
} else {
val text = getValue(context, name)
if (text == null) {
if (parameter.isOptional) {
return defaultValuePlaceHolder
}
throw FailureResponseException(400, "Parameter is missing: $name")
}
return converter.parse(text)
}
}
}
private class PathParamExtractor(parameter: KParameter) : ConvertibleExtractor(parameter) {
override fun getAnnotatedName(): String? {
return parameter.findAnnotation<WebQueryParam>()?.value
}
override fun getValue(context: RequestContext, name: String): String? {
return context.pathParams[name]
?: context.queryParams.get(name).firstOrNull()
}
override fun getValueList(context: RequestContext, name: String): List<String> {
return context.queryParams.get(name).toList()
}
}
private class QueryParamExtractor(parameter: KParameter) : ConvertibleExtractor(parameter) {
override fun getAnnotatedName(): String? {
return parameter.findAnnotation<WebQueryParam>()?.value
}
override fun getValue(context: RequestContext, name: String): String? {
return context.pathParams[name]
?: context.queryParams.get(name).firstOrNull()
}
override fun getValueList(context: RequestContext, name: String): List<String> {
return context.queryParams.get(name).toList()
}
}
private class HeaderExtractor(parameter: KParameter) : ConvertibleExtractor(parameter) {
override fun getAnnotatedName(): String? {
return parameter.findAnnotation<WebHeader>()?.value
}
override fun getValue(context: RequestContext, name: String): String? {
return context.request.headers.get(name).firstOrNull()
}
override fun getValueList(context: RequestContext, name: String): List<String> {
return context.request.headers.get(name).toList()
}
}
private class EntityExtractor(
override val parameter: KParameter
) : ParameterExtractor {
private val cls = parameter.type.classifier as? KClass<*>
?: throw IllegalArgumentException("@WebMethod parameter type is unsupported: $parameter")
override fun get(context: RequestContext): Any? {
val value = context.request.entity?.convertTo(cls)
if (value != null) {
return value
}
if (!parameter.isOptional) {
throw FailureResponseException(400, "Entity is missing")
}
return defaultValuePlaceHolder
}
}
companion object {
private val defaultValuePlaceHolder = Any()
fun addHandlers(router: Router, handlerClass: KClass<*>, injector: TypeSafeHandlerInjector) {
val a = handlerClass.findAnnotation<WebEndpoint>()
?: throw IllegalArgumentException("Type-safe web handler should be annotated " +
"with @WebEndpoint: $handlerClass")
val basePath = a.value
parseClass(router, handlerClass, basePath, injector)
}
private fun parseClass(router: Router, handlerClass: KClass<*>, basePath: String,
injector: TypeSafeHandlerInjector) {
handlerClass.functions.forEach { m ->
val a = m.findAnnotation<WebMethod>()
if (a != null) {
if (m.visibility != KVisibility.PUBLIC) {
throw IllegalArgumentException("@WebMethod should be public: $m")
}
if (m.typeParameters.isNotEmpty()) {
throw IllegalArgumentException("@WebMethod should not have type parameter: $m")
}
parseMethod(router, m, a.method, Util.joinPath(basePath, a.path), injector)
}
}
}
private fun parseMethod(router: Router, handlerMethod: KFunction<*>, method: String, path: String,
injector: TypeSafeHandlerInjector) {
val params = handlerMethod.parameters.map { p ->
when {
p.kind == KParameter.Kind.INSTANCE -> InjectionParameterExtractor(p, injector)
p.kind == KParameter.Kind.EXTENSION_RECEIVER -> InjectionParameterExtractor(p, injector)
p.findAnnotation<WebPathParam>() != null -> PathParamExtractor(p)
p.findAnnotation<WebQueryParam>() != null -> QueryParamExtractor(p)
p.findAnnotation<WebHeader>() != null -> HeaderExtractor(p)
p.findAnnotation<WebEntity>() != null -> EntityExtractor(p)
else -> InjectionParameterExtractor(p, injector)
}
}
try {
router.addRoute(method, path, TypeSafeServerHandler(handlerMethod, params))
} catch (ex: Exception) {
throw IllegalArgumentException("Can't add @WebMethod to router: $handlerMethod", ex)
}
}
}
}
| 0
|
Kotlin
|
1
| 2
|
8020cb1ab799f7b1e75c73f762a9ee1ed493a003
| 9,573
|
exile
|
Apache License 2.0
|
wire-tests/src/jvmKotlinInteropTest/proto-kotlin/com/squareup/wire/protos/custom_options/MyFieldOptionFiveOption.kt
|
square
| 12,274,147
| false
| null |
// Code generated by Wire protocol buffer compiler, do not edit.
// Source: squareup.protos.custom_options.my_field_option_five in custom_options.proto
@file:Suppress(
"DEPRECATION",
"RUNTIME_ANNOTATION_NOT_SUPPORTED",
)
package com.squareup.wire.protos.custom_options
import kotlin.IntArray
import kotlin.Suppress
import kotlin.`annotation`.AnnotationRetention
import kotlin.`annotation`.AnnotationTarget
import kotlin.`annotation`.Retention
import kotlin.`annotation`.Target
@Retention(AnnotationRetention.RUNTIME)
@Target(
AnnotationTarget.PROPERTY,
AnnotationTarget.FIELD,
)
public annotation class MyFieldOptionFiveOption(
public val `value`: IntArray,
)
| 148
| null |
570
| 4,244
|
74715088d7d2ee1fdd6d3e070c8b413eefc7e5bd
| 673
|
wire
|
Apache License 2.0
|
app/src/main/java/com/sjn/stamp/ui/SongAdapter.kt
|
sjnyag
| 81,733,859
| false
| null |
package com.sjn.stamp.ui
import com.sjn.stamp.ui.item.AbstractItem
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
class SongAdapter(items: List<AbstractFlexibleItem<*>>, listeners: Any) : FlexibleAdapter<AbstractFlexibleItem<*>>(items, listeners, true) {
private var originalItemListener: OriginalItemListener? = null
interface OriginalItemListener {
fun onNeedOriginalItem(): List<AbstractFlexibleItem<*>>
}
val originalItems: List<AbstractFlexibleItem<*>>
get() {
return originalItemListener?.onNeedOriginalItem() ?: emptyList()
}
override fun addListener(listener: Any?): FlexibleAdapter<AbstractFlexibleItem<*>> {
if (listener is OriginalItemListener) {
originalItemListener = listener
}
return super.addListener(listener)
}
fun showLayoutInfo(item: AbstractItem<*>, scrollToPosition: Boolean) {
if (!hasSearchText()) {
addScrollableHeaderWithDelay(item, 1200L, scrollToPosition)
removeScrollableHeaderWithDelay(item, 4000L)
}
}
}
| 59
|
Kotlin
|
3
| 9
|
cb145824f9e06cd17266502a5e85d8a9fa276bb0
| 1,149
|
stamp
|
Apache License 2.0
|
src/main/java/com/cumulocity/client/model/SystemOption.kt
|
SoftwareAG
| 525,378,320
| false
| null |
// Copyright (c) 2014-2023 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors.
// Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG.
package com.cumulocity.client.model
import com.google.gson.Gson
/**
* A tuple storing tenant configuration.
*/
class SystemOption {
/**
* Name of the system option category.
*/
var category: String? = null
/**
* A unique identifier for this system option.
*/
var key: String? = null
/**
* Value of this system option.
*/
var value: String? = null
override fun toString(): String {
return Gson().toJson(this).toString()
}
}
| 1
| null |
1
| 3
|
b9e366de1d8d21fa479a42497d45a4efa4de2268
| 781
|
cumulocity-clients-kotlin
|
Apache License 2.0
|
src/main/java/com/dzen/campfire/server/admin_votes/PAdminVoteAccountPunish.kt
|
timas130
| 443,572,543
| true
|
{"Kotlin": 1072092}
|
package com.dzen.campfire.server.admin_votes
import com.dzen.campfire.api.models.admins.MAdminVoteAccountPunish
import com.dzen.campfire.server.controllers.ControllerAccounts
class PAdminVoteAccountPunish {
fun cancel(m: MAdminVoteAccountPunish, cancelAdminAccountId:Long){
ControllerAccounts.removePunishment(ControllerAccounts.getAccount(cancelAdminAccountId)!!, m.comment, m.punishId)
}
}
| 0
|
Kotlin
|
0
| 0
|
40a2fbdbbdbe6706ed852f7218cb10fd57e50445
| 413
|
CampfireServer
|
Apache License 2.0
|
lib/src/main/kotlin/controller/WorkbenchMQDispatcher.kt
|
FHNW-IP5-IP6
| 462,228,811
| false
| null |
package controller
import MQ_INTERNAL_EDITOR_STATE_UNSAVED
import MQ_INTERNAL_TOPIC_PATH_EDITOR
import model.data.MQClientImpl
import java.util.concurrent.Executors
internal class WorkbenchMQDispatcher(
val onActionRequired: (Action) -> Unit
)
{
private var mqClient: MQClientImpl = MQClientImpl
init {
mqClient.subscribe("$MQ_INTERNAL_TOPIC_PATH_EDITOR/#", ::dispatchEditorMessages, Executors.newSingleThreadExecutor())
}
private fun dispatchEditorMessages(topic: String, msg: String) {
val splitTopic = topic.split("/")
if (splitTopic.size == 4) {
val type = splitTopic[splitTopic.size-2]
try {
val dataId = splitTopic[splitTopic.size-1].toInt()
if (msg == MQ_INTERNAL_EDITOR_STATE_UNSAVED) {
onActionRequired(WorkbenchAction.AddUnsavedModule(type, dataId))
}
} catch (exception: NumberFormatException) {
return
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
57e4ecb262807e4dc131b4f0d01d25af787687e4
| 1,014
|
ComposeWorkbench
|
Apache License 2.0
|
example/src/main/java/com/spruceid/mobilesdkexample/verifiersettings/VerificationActivityLogScreen.kt
|
spruceid
| 741,512,330
| false
|
{"Kotlin": 5118229, "Makefile": 1753}
|
package com.spruceid.mobilesdkexample.verifiersettings
import androidx.compose.foundation.layout.Arrangement
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.spruceid.mobilesdkexample.db.VerificationActivityLogs
import com.spruceid.mobilesdkexample.ui.theme.CodeBorder
import com.spruceid.mobilesdkexample.ui.theme.Inter
import com.spruceid.mobilesdkexample.ui.theme.SpruceBlue
import com.spruceid.mobilesdkexample.ui.theme.TextBody
import com.spruceid.mobilesdkexample.ui.theme.TextHeader
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@Composable
fun VerificationActivityLogsScreen() {
// val verificationActivityLogs by verificationActivityLogsViewModel.verificationActivityLogs.collectAsState()
val verificationActivityLogs = listOf<VerificationActivityLogs>()
val dateFormatter = SimpleDateFormat("MM/dd/yyyy", Locale.getDefault())
LazyColumn(
Modifier
.padding(horizontal = 20.dp)
.padding(top = 10.dp),
) {
item {
Text(
text = "Coming Soon",
fontFamily = Inter,
fontWeight = FontWeight.SemiBold,
fontSize = 17.sp,
color = TextHeader,
modifier = Modifier.padding(bottom = 4.dp),
)
}
items(verificationActivityLogs) { log ->
Column {
Text(
text = log.name,
fontFamily = Inter,
fontWeight = FontWeight.SemiBold,
fontSize = 17.sp,
color = TextHeader,
modifier = Modifier.padding(bottom = 4.dp),
)
Text(
text = log.credentialTitle,
fontFamily = Inter,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
color = TextBody,
modifier = Modifier.padding(bottom = 4.dp),
)
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier =
Modifier
.fillMaxWidth(),
) {
Text(
text = log.status,
fontFamily = Inter,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
color = TextBody,
modifier =
Modifier
.padding(bottom = 4.dp),
)
Text(
text = "${
if (log.expirationDate.before(
Date(),
)
) {
"expired"
} else {
"expires"
}
} on ${dateFormatter.format(log.expirationDate)}",
fontFamily = Inter,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
color = TextBody,
modifier = Modifier.padding(bottom = 4.dp),
)
}
Text(
text = "Scanned on ${dateFormatter.format(log.date)}",
fontFamily = Inter,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
fontStyle = FontStyle.Italic,
textAlign = TextAlign.End,
color = CodeBorder,
modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),
)
HorizontalDivider(modifier = Modifier.padding(bottom = 12.dp))
}
}
item {
Button(
onClick = {
// settingsViewModel.exportMetrics(logsViewModel.generateActivityLogCSV(), "activity_logs.csv")
},
modifier =
Modifier
.fillMaxWidth()
.padding(20.dp),
colors =
ButtonDefaults.buttonColors(
containerColor = SpruceBlue,
contentColor = Color.White,
),
) {
Text(
text = "Export",
fontFamily = Inter,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
color = Color.White,
)
}
}
}
}
| 6
|
Kotlin
|
0
| 1
|
7e675c4d654bec864c4e276d59c4787c9e92aa44
| 5,511
|
mobile-sdk-kt
|
Apache License 2.0
|
komapper-core/src/test/kotlin/org/komapper/core/template/expression/ExprTokenizerTest.kt
|
komapper
| 349,909,214
| false
|
{"Kotlin": 2922039, "Java": 57131}
|
package org.komapper.core.template.expression
import org.komapper.core.template.expression.ExprTokenType.AND
import org.komapper.core.template.expression.ExprTokenType.BIG_DECIMAL
import org.komapper.core.template.expression.ExprTokenType.CLASS_REF
import org.komapper.core.template.expression.ExprTokenType.DOUBLE
import org.komapper.core.template.expression.ExprTokenType.EOE
import org.komapper.core.template.expression.ExprTokenType.EOL
import org.komapper.core.template.expression.ExprTokenType.FALSE
import org.komapper.core.template.expression.ExprTokenType.FLOAT
import org.komapper.core.template.expression.ExprTokenType.INT
import org.komapper.core.template.expression.ExprTokenType.LONG
import org.komapper.core.template.expression.ExprTokenType.NULL
import org.komapper.core.template.expression.ExprTokenType.PROPERTY
import org.komapper.core.template.expression.ExprTokenType.SAFE_CALL_PROPERTY
import org.komapper.core.template.expression.ExprTokenType.STRING
import org.komapper.core.template.expression.ExprTokenType.TRUE
import org.komapper.core.template.expression.ExprTokenType.VALUE
import org.komapper.core.template.expression.ExprTokenType.WHITESPACE
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class ExprTokenizerTest {
@Test
fun value() {
val tokenizer = ExprTokenizer("name")
assertEquals(VALUE, tokenizer.next())
assertEquals("name", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun classRef() {
val tokenizer = ExprTokenizer("@aaa.bbb.Ccc@")
assertEquals(CLASS_REF, tokenizer.next())
assertEquals("@aaa.bbb.Ccc@", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun stringLiteral() {
val tokenizer = ExprTokenizer("\"aaa bbb\"")
assertEquals(STRING, tokenizer.next())
assertEquals("\"aaa bbb\"", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun intLiteral() {
val tokenizer = ExprTokenizer("+13")
assertEquals(INT, tokenizer.next())
assertEquals("+13", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun longLiteral() {
val tokenizer = ExprTokenizer("+13L")
assertEquals(LONG, tokenizer.next())
assertEquals("+13L", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun floatLiteral() {
val tokenizer = ExprTokenizer("+13F")
assertEquals(FLOAT, tokenizer.next())
assertEquals("+13F", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun doubleLiteral() {
val tokenizer = ExprTokenizer("+13D")
assertEquals(DOUBLE, tokenizer.next())
assertEquals("+13D", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun bigDecimalLiteral() {
val tokenizer = ExprTokenizer("+13B")
assertEquals(BIG_DECIMAL, tokenizer.next())
assertEquals("+13B", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun nullLiteral() {
val tokenizer = ExprTokenizer("null")
assertEquals(NULL, tokenizer.next())
assertEquals("null", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun trueLiteral() {
val tokenizer = ExprTokenizer("true")
assertEquals(TRUE, tokenizer.next())
assertEquals("true", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun falseLiteral() {
val tokenizer = ExprTokenizer("false")
assertEquals(FALSE, tokenizer.next())
assertEquals("false", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun expressions() {
val tokenizer = ExprTokenizer("manager.aaa && name.bbb")
assertEquals(VALUE, tokenizer.next())
assertEquals("manager", tokenizer.token)
assertEquals(PROPERTY, tokenizer.next())
assertEquals(".aaa", tokenizer.token)
assertEquals(WHITESPACE, tokenizer.next())
assertEquals(" ", tokenizer.token)
assertEquals(AND, tokenizer.next())
assertEquals("&&", tokenizer.token)
assertEquals(WHITESPACE, tokenizer.next())
assertEquals(" ", tokenizer.token)
assertEquals(VALUE, tokenizer.next())
assertEquals("name", tokenizer.token)
assertEquals(PROPERTY, tokenizer.next())
assertEquals(".bbb", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun columnNumber() {
val tokenizer = ExprTokenizer("aaa bbb ccc")
assertEquals(1, tokenizer.location.columnNumber)
assertEquals(VALUE, tokenizer.next())
assertEquals("aaa", tokenizer.token)
assertEquals(1, tokenizer.location.columnNumber)
assertEquals(WHITESPACE, tokenizer.next())
assertEquals(" ", tokenizer.token)
assertEquals(4, tokenizer.location.columnNumber)
assertEquals(VALUE, tokenizer.next())
assertEquals("bbb", tokenizer.token)
assertEquals(5, tokenizer.location.columnNumber)
assertEquals(WHITESPACE, tokenizer.next())
assertEquals(" ", tokenizer.token)
assertEquals(8, tokenizer.location.columnNumber)
assertEquals(VALUE, tokenizer.next())
assertEquals("ccc", tokenizer.token)
assertEquals(9, tokenizer.location.columnNumber)
}
@Test
fun eol() {
val tokenizer = ExprTokenizer("aaa\r\nbbb\rccc\nddd")
assertEquals(1, tokenizer.location.lineNumber)
assertEquals(1, tokenizer.location.columnNumber)
assertEquals(VALUE, tokenizer.next())
assertEquals("aaa", tokenizer.token)
assertEquals(1, tokenizer.location.lineNumber)
assertEquals(1, tokenizer.location.columnNumber)
assertEquals(EOL, tokenizer.next())
assertEquals("\r\n", tokenizer.token)
assertEquals(2, tokenizer.location.lineNumber)
assertEquals(4, tokenizer.location.columnNumber)
assertEquals(VALUE, tokenizer.next())
assertEquals("bbb", tokenizer.token)
assertEquals(2, tokenizer.location.lineNumber)
assertEquals(1, tokenizer.location.columnNumber)
assertEquals(EOL, tokenizer.next())
assertEquals("\r", tokenizer.token)
assertEquals(3, tokenizer.location.lineNumber)
assertEquals(4, tokenizer.location.columnNumber)
assertEquals(VALUE, tokenizer.next())
assertEquals("ccc", tokenizer.token)
assertEquals(3, tokenizer.location.lineNumber)
assertEquals(1, tokenizer.location.columnNumber)
assertEquals(EOL, tokenizer.next())
assertEquals("\n", tokenizer.token)
assertEquals(4, tokenizer.location.lineNumber)
assertEquals(4, tokenizer.location.columnNumber)
assertEquals(VALUE, tokenizer.next())
assertEquals("ddd", tokenizer.token)
assertEquals(4, tokenizer.location.lineNumber)
assertEquals(1, tokenizer.location.columnNumber)
assertEquals(EOE, tokenizer.next())
}
@Test
fun property() {
val tokenizer = ExprTokenizer("aaa.bbb")
assertEquals(VALUE, tokenizer.next())
assertEquals("aaa", tokenizer.token)
assertEquals(PROPERTY, tokenizer.next())
assertEquals(".bbb", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun safeCallProperty() {
val tokenizer = ExprTokenizer("aaa?.bbb")
assertEquals(VALUE, tokenizer.next())
assertEquals("aaa", tokenizer.token)
assertEquals(SAFE_CALL_PROPERTY, tokenizer.next())
assertEquals("?.bbb", tokenizer.token)
assertEquals(EOE, tokenizer.next())
assertEquals("", tokenizer.token)
}
@Test
fun `The end of single quotation mark is not found`() {
val tokenizer = ExprTokenizer("'aaa")
val exception = assertFailsWith<ExprException> { tokenizer.next() }
println(exception)
}
@Test
fun `The end of double quotation mark is not found`() {
val tokenizer = ExprTokenizer("\"aaa")
val exception = assertFailsWith<ExprException> { tokenizer.next() }
println(exception)
}
@Test
fun `Either property or function name must follow the dot`() {
val tokenizer = ExprTokenizer(".")
val exception = assertFailsWith<ExprException> { tokenizer.next() }
println(exception)
}
@Test
fun `The character is illegal as an identifier start`() {
val tokenizer = ExprTokenizer(".!")
val exception = assertFailsWith<ExprException> { tokenizer.next() }
println(exception)
}
}
| 8
|
Kotlin
|
14
| 301
|
9fbc0b5652ee732583e977180cdc493e116e1022
| 9,305
|
komapper
|
Apache License 2.0
|
TabLayout/src/main/java/com/angcyo/tablayout/DslTabDivider.kt
|
angcyo
| 223,463,340
| false
| null |
package com.angcyo.tablayout
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.widget.LinearLayout
/**
* 垂直分割线
* Email:<EMAIL>
* @author angcyo
* @date 2019/11/27
* Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved.
*/
open class DslTabDivider : DslGradientDrawable() {
var dividerWidth = 2 * dpi
var dividerHeight = 2 * dpi
var dividerMarginLeft = 0
var dividerMarginRight = 0
var dividerMarginTop = 0
var dividerMarginBottom = 0
/**
* [LinearLayout.SHOW_DIVIDER_BEGINNING]
* [LinearLayout.SHOW_DIVIDER_MIDDLE]
* [LinearLayout.SHOW_DIVIDER_END]
* */
var dividerShowMode = LinearLayout.SHOW_DIVIDER_MIDDLE
override fun initAttribute(context: Context, attributeSet: AttributeSet?) {
super.initAttribute(context, attributeSet)
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.DslTabLayout)
dividerWidth = typedArray.getDimensionPixelOffset(
R.styleable.DslTabLayout_tab_divider_width,
dividerWidth
)
dividerHeight = typedArray.getDimensionPixelOffset(
R.styleable.DslTabLayout_tab_divider_height,
dividerHeight
)
dividerMarginLeft = typedArray.getDimensionPixelOffset(
R.styleable.DslTabLayout_tab_divider_margin_left,
dividerMarginLeft
)
dividerMarginRight = typedArray.getDimensionPixelOffset(
R.styleable.DslTabLayout_tab_divider_margin_right,
dividerMarginRight
)
dividerMarginTop = typedArray.getDimensionPixelOffset(
R.styleable.DslTabLayout_tab_divider_margin_top,
dividerMarginTop
)
dividerMarginBottom = typedArray.getDimensionPixelOffset(
R.styleable.DslTabLayout_tab_divider_margin_bottom,
dividerMarginBottom
)
gradientSolidColor = typedArray.getColor(
R.styleable.DslTabLayout_tab_divider_solid_color,
gradientSolidColor
)
gradientStrokeColor = typedArray.getColor(
R.styleable.DslTabLayout_tab_divider_stroke_color,
gradientStrokeColor
)
gradientStrokeWidth = typedArray.getDimensionPixelOffset(
R.styleable.DslTabLayout_tab_divider_stroke_width,
0
)
val radiusSize =
typedArray.getDimensionPixelOffset(
R.styleable.DslTabLayout_tab_divider_radius_size,
2 * dpi
)
cornerRadius(radiusSize.toFloat())
originDrawable = typedArray.getDrawable(R.styleable.DslTabLayout_tab_divider_drawable)
dividerShowMode =
typedArray.getInt(R.styleable.DslTabLayout_tab_divider_show_mode, dividerShowMode)
typedArray.recycle()
if (originDrawable == null) {
//无自定义的drawable, 那么自绘.
updateOriginDrawable()
}
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
originDrawable?.apply {
bounds = this@DslTabDivider.bounds
draw(canvas)
}
}
val _tabLayout: DslTabLayout?
get() = if (callback is DslTabLayout) callback as DslTabLayout else null
/**
* [childIndex]位置前面是否需要分割线
* */
open fun haveBeforeDivider(childIndex: Int, childCount: Int): Boolean {
val tabLayout = _tabLayout
if (tabLayout != null && tabLayout.isHorizontal() && tabLayout.isLayoutRtl) {
if (childIndex == 0) {
return dividerShowMode and LinearLayout.SHOW_DIVIDER_END != 0
}
return dividerShowMode and LinearLayout.SHOW_DIVIDER_MIDDLE != 0
}
if (childIndex == 0) {
return dividerShowMode and LinearLayout.SHOW_DIVIDER_BEGINNING != 0
}
return dividerShowMode and LinearLayout.SHOW_DIVIDER_MIDDLE != 0
}
/**
* [childIndex]位置后面是否需要分割线
* */
open fun haveAfterDivider(childIndex: Int, childCount: Int): Boolean {
val tabLayout = _tabLayout
if (tabLayout != null && tabLayout.isHorizontal() && tabLayout.isLayoutRtl) {
if (childIndex == childCount - 1) {
return dividerShowMode and LinearLayout.SHOW_DIVIDER_BEGINNING != 0
}
}
if (childIndex == childCount - 1) {
return dividerShowMode and LinearLayout.SHOW_DIVIDER_END != 0
}
return false
}
}
| 9
| null |
94
| 949
|
583943afd05c8dee28102518fcb5221291bb4e2d
| 4,533
|
DslTabLayout
|
MIT License
|
app/src/main/java/com/steleot/jetpackcompose/playground/JetpackComposePlaygroundApplication.kt
|
pranavjayaraj
| 399,202,946
| true
|
{"Kotlin": 831952}
|
package com.steleot.jetpackcompose.playground
import android.app.Application
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.steleot.jetpackcompose.playground.datastore.ProtoManager
import com.steleot.jetpackcompose.playground.helpers.InAppReviewHelper
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
@HiltAndroidApp
class JetpackComposePlaygroundApplication : Application() {
private val scope = CoroutineScope(Dispatchers.Main)
@Inject
lateinit var inAppReviewHelper: InAppReviewHelper
@Inject
lateinit var firebaseAnalytics: FirebaseAnalytics
@Inject
lateinit var firebaseCrashlytics: FirebaseCrashlytics
@Inject
lateinit var protoManager: ProtoManager
override fun onCreate() {
super.onCreate()
inAppReviewHelper.resetCounter()
scope.launch {
protoManager.isAnalyticsEnabled.collect { isEnabled ->
Timber.d("Analytics collection: $isEnabled")
firebaseAnalytics.setAnalyticsCollectionEnabled(isEnabled)
}
}
scope.launch {
protoManager.isCrashlyticsEnabled.collect { isEnabled ->
Timber.d("Crashlytics collection: $isEnabled")
firebaseCrashlytics.setCrashlyticsCollectionEnabled(isEnabled)
}
}
}
}
| 0
| null |
0
| 0
|
e80e7c6670484ebf584986e0b27d5194f9372b66
| 1,585
|
Jetpack-Compose-Playground-1
|
Apache License 2.0
|
sdk/src/jsMain/kotlin/lib/module/Events.kt
|
zimoyin
| 675,280,596
| false
|
{"Kotlin": 306501, "JavaScript": 18388, "HTML": 15259}
|
package lib.module
@JsName("events")
external object Events {
/**
* 按键事件接口
*/
interface KeyEvent {
fun getAction(): dynamic
fun getKeyCode(): Int
fun getEventTime(): Double
fun getDownTime(): Double
fun keyCodeToString(keyCode: Int): String
}
fun emitter(): EventEmitter
fun observeKey(): Unit
fun setKeyInterceptionEnabled(key: Keys, enabled: Boolean): Unit
fun setKeyInterceptionEnabled(enabled: Boolean): Unit
fun onKeyDown(keyName: Keys, listener: (e: KeyEvent) -> Unit): Unit
fun onceKeyUp(keyName: Keys, listener: (e: KeyEvent) -> Unit): Unit
fun removeAllKeyDownListeners(keyName: Keys): Unit
fun removeAllKeyUpListeners(keyName: Keys): Unit
fun observeTouch(): Unit
fun setTouchEventTimeout(timeout: Double): Unit
fun getTouchEventTimeout(): Double
fun onTouch(listener: (point: Point) -> Unit): Unit
fun removeAllTouchListeners(): Unit
fun on(event: String /* 'key' | 'key_down' | 'key_up' */, listener: (keyCode: Int, e: KeyEvent) -> Unit): Unit
fun on(event: String /* 'exit' */, listener: () -> Unit): Unit
fun observeNotification(): Unit
fun observeToast(): Unit
/**
* 系统Toast对象
*/
interface Toast {
/**
* 获取Toast的文本内容
*/
fun getText(): String
/**
* 获取发出Toast的应用包名
*/
fun getPackageName(): String
}
fun onToast(listener: (toast: Toast) -> Unit): Unit
/**
* 通知对象,可以获取通知详情,包括通知标题、内容、发出通知的包名、时间等,也可以对通知进行操作,比如点击、删除。
*/
interface Notification {
var number: Int
var `when`: Double
fun getPackageName(): String
fun getTitle(): String
fun getText(): String
fun click(): Unit
fun delete(): Unit
}
fun on(event: String /* 'notification' */, listener: (notification: Notification) -> Unit): Unit
}
/**
* 按键事件中所有可用的按键名称
*/
external enum class Keys {
home,
back,
menu,
volume_up,
volume_down
}
external interface EventEmitter {
var defaultMaxListeners: Int
fun addListener(eventName: String, listener: (args: Array<Any>) -> Unit): EventEmitter
fun emit(eventName: String, vararg args: Any): Boolean
fun eventNames(): Array<String>
fun getMaxListeners(): Int
fun listenerCount(eventName: String): Int
fun on(eventName: String, listener: (args: Array<Any>) -> Unit): EventEmitter
fun once(eventName: String, listener: (args: Array<Any>) -> Unit): EventEmitter
fun prependListener(eventName: String, listener: (args: Array<Any>) -> Unit): EventEmitter
fun prependOnceListener(eventName: String, listener: (args: Array<Any>) -> Unit): EventEmitter
fun removeAllListeners(eventName: String? = definedExternally): EventEmitter
fun removeListener(eventName: String, listener: (args: Array<Any>) -> Unit): EventEmitter
fun setMaxListeners(n: Int): EventEmitter
}
| 0
|
Kotlin
|
5
| 10
|
aa85a176280ce3a17a59454fbbe6bddd56044335
| 2,963
|
Autojsx.WIFI
|
Apache License 2.0
|
src/test/kotlin/api/integrationtests/ColorApiIntegrationTests.kt
|
moritzploss
| 225,383,253
| false
| null |
package api.integrationtests
import api.colors.services.Color
import org.junit.Assert.assertNotNull
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.http.HttpStatus
import org.springframework.test.context.junit4.SpringRunner
import org.junit.Assert.assertEquals as assertEquals1
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ColorApiIntegrationTests {
@Autowired
lateinit var testRestTemplate: TestRestTemplate
private val name = "testcolor"
private val hex = "#ABCDEF"
private val testColor = Color(name, hex)
@Test
fun testGetOne() {
val response = testRestTemplate.postForEntity("/api/v1/colors", testColor, Color::class.java)
val result = testRestTemplate.getForEntity("/api/v1/colors/${(response.body ?: return).id}", Color::class.java)
assertNotNull(result)
assertEquals1(HttpStatus.OK, result.statusCode)
assertEquals1("testcolor", (response.body ?: return).name)
assertEquals1("#ABCDEF", (response.body ?: return).hex)
}
@Test
fun testCreateOne() {
val response = testRestTemplate.postForEntity("/api/v1/colors", testColor, Color::class.java)
assertNotNull(response)
assertEquals1(HttpStatus.CREATED, response.statusCode)
assertEquals1(name, (response.body ?: return).name)
assertEquals1(hex, (response.body ?: return).hex)
}
@Test
fun testDeleteOne() {
testRestTemplate.delete("/api/v1/colors/blue")
}
}
| 0
|
Kotlin
|
0
| 0
|
4b93ebe786c0f6daec76754b380605edf81f2351
| 1,755
|
colorAPI
|
MIT License
|
feature/image/src/main/java/com/uragiristereo/mikansei/feature/image/more/tags/MoreTagItem.kt
|
uragiristereo
| 583,834,091
| false
|
{"Kotlin": 978568}
|
package com.uragiristereo.mikansei.feature.image.more.tags
import android.os.Build
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.uragiristereo.mikansei.core.domain.module.danbooru.entity.Tag
import com.uragiristereo.mikansei.core.domain.module.danbooru.entity.getCategoryColor
import com.uragiristereo.mikansei.core.ui.extension.backgroundElevation
@Composable
internal fun MoreTagItem(
tag: Tag,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
MoreTagItem(
tag = tag,
selected = false,
onSelectedChange = {
onClick()
},
modifier = modifier,
)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun MoreTagItem(
tag: Tag,
selected: Boolean,
onSelectedChange: (Boolean) -> Unit,
modifier: Modifier = Modifier,
) {
val clipboardManager = LocalClipboardManager.current
val hapticFeedback = LocalHapticFeedback.current
val context = LocalContext.current
val isLight = MaterialTheme.colors.isLight
val tagColor = remember(tag, isLight) {
tag.category.getCategoryColor(isLight)
}
val backgroundColor = when {
selected -> tagColor
else -> MaterialTheme.colors.background.backgroundElevation(3.dp)
}
val contentColor = when {
!selected -> tagColor
else -> Color.White.copy(alpha = 0.7f)
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.width(IntrinsicSize.Max)
.clip(RoundedCornerShape(size = 8.dp))
.background(backgroundColor)
.combinedClickable(
onClick = {
onSelectedChange(!selected)
},
onLongClick = {
clipboardManager.setText(AnnotatedString(tag.name))
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.TIRAMISU) {
Toast
.makeText(context, "Tag copied to the clipboard!", Toast.LENGTH_SHORT)
.show()
}
}
)
.padding(
vertical = 6.dp,
horizontal = 10.dp,
),
) {
Text(
text = tag.name,
fontWeight = FontWeight.Medium,
color = contentColor,
modifier = Modifier
.weight(1f)
.padding(end = 8.dp),
)
Text(
text = tag.postCountFormatted,
color = contentColor,
fontWeight = FontWeight.Light,
)
}
}
| 3
|
Kotlin
|
2
| 62
|
4f136b0479ee7772f3d7ba48927cef9389d5c2be
| 3,804
|
Mikansei
|
Apache License 2.0
|
test-impact-gradle-plugin/src/main/kotlin/dev/sunnyday/test/impact/plugin/TestImpactPlugin.kt
|
SunnyDayDev
| 638,632,486
| false
| null |
package dev.sunnyday.test.impact.plugin
import dev.sunnyday.test.impact.plugin.extension.TestImpactExtension
import dev.sunnyday.test.impact.plugin.domain.graph.ProjectGraphResolver
import dev.sunnyday.test.impact.plugin.task.testimpact.TestImpactTask
import dev.sunnyday.test.impact.plugin.task.testimpact.TestImpactTaskOutput
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.TaskProvider
import java.io.File
class TestImpactPlugin : Plugin<Project> {
override fun apply(target: Project) {
PluginApplier(target).apply()
}
private class PluginApplier(
private val target: Project
) {
private val extension = registerExtension()
private val startParameterTaskNamesProvider = registerStartParameterTaskNamesProvider()
private val graphResolverProvider = registerGraphResolverProvider()
private val testImpactTaskOutputProvider = registerTestImpactTaskOutputProvider()
private val testImpactTaskProvider = registerTestImpactTask()
fun apply() {
if (!isGradleStartedForTestImpact()) {
return
}
target.gradle.projectsEvaluated {
buildGraph()
buildTestImpactTasksGraph()
}
}
private fun registerExtension(): TestImpactExtension {
return target.extensions.create("testImpact", TestImpactExtension::class.java)
}
private fun registerGraphResolverProvider(): Provider<ProjectGraphResolver> {
val graphResolver = ProjectGraphResolver(target)
return target.provider { graphResolver }
}
private fun registerStartParameterTaskNamesProvider(): Provider<List<String>> {
return target.provider { target.gradle.startParameter.taskNames }
}
private fun registerTestImpactTask(): TaskProvider<TestImpactTask> {
return target.tasks.register("testImpact", TestImpactTask::class.java) {
group = "verification"
if (!(isWrapperTask() || isGradleStartedForTestImpact())) {
throw IllegalStateException(
"""
Currently :testImpact allowed to run only as a gradle start task.
Current start tasks: ${target.gradle.startParameter.taskNames}"
""".trimIndent()
)
}
changesSource = extension.changesSource
inputImpactGraph = graphResolverProvider.get().getProjectsGraph()
taskOutput = testImpactTaskOutputProvider.get()
}
}
private fun registerTestImpactTaskOutputProvider(): Provider<TestImpactTaskOutput> {
return target.provider {
TestImpactTaskOutput(getTestImpactOutputFile())
}
}
private fun buildGraph() {
val graphResolver = graphResolverProvider.get()
iterateOverProjects(graphResolver::onProjectEvaluated)
graphResolver.markGraphCompleted()
}
private fun buildTestImpactTasksGraph() {
iterateOverProjects { project ->
val projectTestTasks = extension.testTaskNameProvider.getTestTasks(project)
projectTestTasks.forEach { testTask ->
project.tasks.findByName(testTask)
?.let(::setupTestTaskDependency)
}
}
}
private fun setupTestTaskDependency(testTask: Task) {
val testImpactTask = testImpactTaskProvider.get()
testTask.apply {
dependsOn(testImpactTask.path)
val testImpactTaskOutputProvider = testImpactTaskOutputProvider
val testProjectPath = testTask.project.path
setOnlyIf {
val testTaskOutputGraph = testImpactTaskOutputProvider.get()
.readImpactGraph()
testTaskOutputGraph.getProjectByProjectPath(testProjectPath).hasChanges
}
doFirst {
// TODO: setup tests filter
}
}
val startTasks = startParameterTaskNamesProvider.get()
if (startTasks.last() == getTestImpactStartTaskName()) {
testImpactTask.finalizedBy(testTask.path)
}
}
private fun iterateOverProjects(action: (Project) -> Unit) {
val projectsQueue = ArrayDeque<Project>()
projectsQueue.add(target)
while (projectsQueue.isNotEmpty()) {
val project = projectsQueue.removeFirst()
action.invoke(project)
project.childProjects.values.forEach(projectsQueue::add)
}
}
private fun isGradleStartedForTestImpact(): Boolean {
return startParameterTaskNamesProvider.get().contains(getTestImpactStartTaskName())
}
private fun getTestImpactStartTaskName(): String {
return if (target.rootProject === target) "testImpact" else "${target.path}:testImpact"
}
private fun isWrapperTask(): Boolean {
return startParameterTaskNamesProvider.get() == listOf("wrapper")
}
private fun getTestImpactOutputFile(): File {
return File(target.buildDir, "tmp/testImpact/output.txt")
}
}
}
| 0
|
Kotlin
|
0
| 1
|
a5eb97508f021ca67f455d7fb641a00db62ca51e
| 5,560
|
test-impact-plugin
|
MIT License
|
app/src/main/java/ms/imagine/foodiemate/Presenter/FbDatabasePresenter.kt
|
egg-bread
| 130,767,136
| true
|
{"Kotlin": 48259}
|
package ms.imagine.foodiemate.Presenter
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
open class FbDatabasePresenter(_uid: String?){
var fbInstance:FirebaseDatabase = FirebaseDatabase.getInstance()
var firebaseDB:DatabaseReference = fbInstance.reference.child(_uid)
}
| 0
|
Kotlin
|
0
| 0
|
fb9f4c7aaa4390d15e4dd829df01be7542ac169e
| 339
|
hachy-android
|
MIT License
|
android/src/main/java/com/reactnativeapphudsdk/ApphudListenerHandler.kt
|
apphud
| 249,636,120
| false
|
{"YAML": 4, "JSON with Comments": 1, "JSON": 8, "JavaScript": 7, "Markdown": 2, "Text": 1, "Ignore List": 2, "Git Attributes": 1, "EditorConfig": 1, "Ruby": 2, "TSX": 8, "XML": 10, "INI": 5, "Gradle": 4, "Shell": 2, "Batchfile": 2, "Kotlin": 4, "Java Properties": 1, "Java": 4, "Dotenv": 2, "Swift": 5, "C": 1, "OpenStep Property List": 2, "Objective-C": 7}
|
package com.reactnativeapphudsdk
import android.util.Log
import com.android.billingclient.api.ProductDetails
import com.android.billingclient.api.SkuDetails
import com.apphud.sdk.ApphudListener
import com.apphud.sdk.domain.ApphudPaywall
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.WritableMap
import com.facebook.react.bridge.WritableNativeArray
import com.facebook.react.bridge.WritableNativeMap
import com.facebook.react.modules.core.DeviceEventManagerModule
enum class ApphudSdkDelegateEvents(val value: String) {
PAYWALLS_DID_FULLY_LOAD("paywallsDidFullyLoad"),
APPHUD_DID_LOAD_STORE_PRODUCTS("apphudDidLoadStoreProducts"),
APPHUD_DID_CHANGE_USER_ID("apphudDidChangeUserID"),
APPHUD_SUBSCRIPTIONS_UPDATED("apphudSubscriptionsUpdated"),
APPHUD_NON_RENEWING_PURCHASES_UPDATED("apphudNonRenewingPurchasesUpdated"),
APPHUD_PRODUCT_IDENTIFIERS("apphudProductIdentifiers"),
APPHUD_DID_PURCHASE("apphudDidPurchase"),
APPHUD_WILL_PURCHASE("apphudWillPurchase"),
APPHUD_DID_FAIL_PURCHASE("apphudDidFailPurchase"),
APPHUD_DID_SELECT_SURVEY_ANSWER("apphudDidSelectSurveyAnswer")
}
class ApphudListenerHandler(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext), ApphudListener {
override fun apphudDidChangeUserID(userId: String) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit(ApphudSdkDelegateEvents.APPHUD_DID_CHANGE_USER_ID.value, userId)
}
override fun apphudFetchProductDetails(details: List<ProductDetails>) {
val map = details.map { detail -> ApphudDataTransformer.getProductMap(detail) }
val nativeProducts: WritableNativeArray = WritableNativeArray()
map.forEach {
nativeProducts.pushMap(it)
}
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit(ApphudSdkDelegateEvents.APPHUD_DID_LOAD_STORE_PRODUCTS.value, nativeProducts)
}
override fun paywallsDidFullyLoad(paywalls: List<ApphudPaywall>) {
val paywallsMap = paywalls.map { paywall -> ApphudDataTransformer.getApphudPaywallMap(paywall) }
val nativeArray = WritableNativeArray()
paywallsMap.forEach {
nativeArray.pushMap(it)
}
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit(ApphudSdkDelegateEvents.PAYWALLS_DID_FULLY_LOAD.value, nativeArray);
}
override fun userDidLoad() {
// do nothing
}
override fun getName(): String {
return "ApphudSdkEvents";
}
}
| 0
|
TypeScript
|
5
| 8
|
7d2bc5281d53d1e78e6f639797a466959d344863
| 2,622
|
ApphudSDK-React-Native
|
MIT License
|
app/src/main/java/com/forcetower/uefs/core/storage/repository/SagresDataRepository.kt
|
Matoro17
| 171,460,349
| false
| null |
/*
* Copyright (c) 2019.
* João Paulo Sena <joaopaulo761@gmail.com>
*
* This file is part of the UNES Open Source Project.
*
* UNES is licensed under the MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.forcetower.uefs.core.storage.repository
import com.forcetower.sagres.SagresNavigator
import com.forcetower.uefs.AppExecutors
import com.forcetower.uefs.core.storage.database.UDatabase
import com.google.firebase.auth.FirebaseAuth
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SagresDataRepository @Inject constructor(
private val database: UDatabase,
private val executor: AppExecutors,
private val firebaseAuth: FirebaseAuth
) {
fun getMessages() = database.messageDao().getAllMessages()
fun logout() {
executor.diskIO().execute {
firebaseAuth.signOut()
database.accessDao().deleteAll()
database.accessTokenDao().deleteAll()
database.profileDao().deleteMe()
database.classDao().deleteAll()
database.semesterDao().deleteAll()
database.messageDao().deleteAll()
SagresNavigator.instance.logout()
}
}
fun getFlags() = database.flagsDao().getFlags()
}
| 1
| null |
1
| 1
|
000e7aa8b9123959d2704ee5dc9b45b03b46dbb1
| 2,282
|
Melon
|
MIT License
|
src/main/java/com/ygpedroso/feedParser/transformers/DateTransformer.kt
|
ygpedroso
| 128,825,955
| false
| null |
package com.ygpedroso.feedParser.transformers
import com.ygpedroso.feedParser.utils.Constants
import org.simpleframework.xml.transform.Transform
import java.text.SimpleDateFormat
import java.util.*
class DateTransformer: Transform<Date> {
var formatter = SimpleDateFormat(Constants.RFC_822_DATE_STANDARD)
override fun write(value: Date?): String {
return formatter.format(value)
}
override fun read(value: String?): Date {
return formatter.parse(value)
}
}
| 1
| null |
1
| 1
|
5cf0b099a95ffbb8df8a4a82488a1adbea2ed8d0
| 497
|
feedParser
|
MIT License
|
app/src/main/java/com/huanchengfly/tieba/api/models/NewUpdateBean.kt
|
ShellWen
| 286,489,136
| true
|
{"Gradle": 4, "INI": 1, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "XML": 306, "Java": 323, "Proguard": 1, "Kotlin": 73, "JavaScript": 4, "JSON": 1, "YAML": 1}
|
package com.huanchengfly.tieba.api.models
import com.google.gson.annotations.SerializedName
class NewUpdateBean {
val isSuccess: Boolean? = null
@SerializedName("has_update")
val isHasUpdate: Boolean? = null
@SerializedName("error_code")
val errorCode: Int? = null
@SerializedName("error_message")
val errorMsg: String? = null
val result: ResultBean? = null
class ResultBean {
val isCancelable: Boolean? = null
@SerializedName("update_content")
val updateContent: List<String>? = null
@SerializedName("version_code")
val versionCode: Int? = null
@SerializedName("version_name")
val versionName: String? = null
@SerializedName("version_type")
val versionType: Int? = null
val downloads: List<DownloadBean>? = null
}
class DownloadBean {
val name: String? = null
val url: String? = null
}
}
| 26
|
Java
|
198
| 5
|
e4f5961692731145d7a95c6a68b6b459e35545f6
| 943
|
TiebaLite
|
Apache License 2.0
|
src/main/kotlin/pl/kremblewski/expressionevaluator/Token.kt
|
cregus
| 237,510,544
| false
| null |
package pl.kremblewski.expressionevaluator
import java.math.BigDecimal
sealed class Token {
abstract val value: BigDecimal
data class Number(override val value: BigDecimal) : Token() {
constructor(value: kotlin.Number) : this(value.toBigDecimal())
}
sealed class Unary : Token() {
abstract val token: Token
data class Plus(override val token: Token) : Unary() {
override val value: BigDecimal
get() = token.value.plus()
}
data class Minus(override val token: Token) : Unary() {
override val value: BigDecimal
get() = token.value.negate()
}
}
data class Operator(
val leftToken: Token,
val rightToken: Token,
val operation: Function2<BigDecimal>
) : Token() {
override val value: BigDecimal
get() = operation(leftToken.value, rightToken.value)
}
data class Variable(val name: String, override val value: BigDecimal) : Token() {
constructor(name: String, value: kotlin.Number) : this(name, value.toBigDecimal())
}
sealed class Function : Token() {
abstract val name: String
data class OneParam(
override val name: String,
val token: Token,
val function1: Function1<BigDecimal>
) : Function() {
override val value: BigDecimal
get() = function1(token.value)
}
data class TwoParams(
override val name: String,
val firstToken: Token,
val secondToken: Token,
val function2: Function2<BigDecimal>
) : Function() {
override val value: BigDecimal
get() = function2(firstToken.value, secondToken.value)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fee5f9e8b6ecc13409795ddac22286eb40346c79
| 1,808
|
expression-evaluator
|
MIT License
|
kradle-plugin/src/main/kotlin/net/bnb1/kradle/support/tasks/GenerateBuildPropertiesTask.kt
|
mrkuz
| 400,078,467
| false
| null |
package net.bnb1.kradle.support.tasks
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
open class GenerateBuildPropertiesTask : DefaultTask() {
init {
// Ensure that this task is always executed
outputs.upToDateWhen { false }
}
@get:Internal
val gitCommit = project.objects.property(String::class.java)
@get:Internal
val profile = project.objects.property(String::class.java)
@SuppressWarnings("MagicNumber")
@TaskAction
fun run() {
val output = project.buildDir.resolve("resources/main/build.properties")
output.parentFile.mkdirs()
output.printWriter().use {
it.println("project.name=${project.name}")
it.println("project.group=${project.group}")
it.println("project.version=${project.properties["version"]}")
if (profile.isPresent) {
it.println("build.profile=${profile.get()}")
}
it.println("build.timestamp=${System.currentTimeMillis() / 1000}")
if (gitCommit.isPresent) {
it.println("git.commit-id=${gitCommit.get()}")
}
}
}
}
| 1
|
Kotlin
|
1
| 80
|
c558342752499ea657167fb6651bdac6b57552f3
| 1,215
|
kradle
|
MIT License
|
app/src/main/java/io/appwrite/messagewrite/models/views/Chat.kt
|
abnegate
| 777,669,864
| false
|
{"Kotlin": 59858}
|
package io.appwrite.messagewrite.models.views
data class Chat(
val id: String,
val profileImageUrl: String,
val username: String,
val lastMessage: String,
val lastMessageTime: String,
)
| 0
|
Kotlin
|
0
| 0
|
c8a3574c53c211cb98ea445f645865412716a91a
| 207
|
hackathon-chat
|
MIT License
|
app/src/main/java/kz/nextstep/movify/ui/movieDetailedInfo/ProductionCompanyViewModel.kt
|
ejeksenov
| 203,191,418
| false
| null |
package kz.nextstep.movify.ui.movieDetailedInfo
import androidx.lifecycle.MutableLiveData
import kz.nextstep.movify.base.BaseViewModel
import kz.nextstep.movify.data.ProductionCompaniesData
class ProductionCompanyViewModel: BaseViewModel() {
private val logo_path = MutableLiveData<String>()
private val name = MutableLiveData<String>()
fun bind(productionCompaniesData: ProductionCompaniesData) {
logo_path.value = productionCompaniesData.logo_path
name.value = productionCompaniesData.name
}
fun getLogoPath(): MutableLiveData<String> {
return logo_path
}
fun getName(): MutableLiveData<String> {
return name
}
}
| 0
|
Kotlin
|
2
| 6
|
7fbab48a18cb3a7e1a2873ce5276d1cd4a2ce1eb
| 685
|
Movify
|
MIT License
|
app/src/main/java/dev/news/newsnow/ui/ArticleOpenFragment.kt
|
sabinmhx
| 671,589,676
| false
| null |
package dev.news.newsnow.ui
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebViewClient
import androidx.navigation.NavController
import androidx.navigation.Navigation
import dev.news.newsnow.data.remote.models.entities.Article
import dev.jaym21.newsnow.databinding.FragmentArticleOpenBinding
class ArticleOpenFragment : Fragment() {
private var binding: FragmentArticleOpenBinding? = null
private lateinit var navController: NavController
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentArticleOpenBinding.inflate(inflater, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//initializing navController
navController = Navigation.findNavController(view)
//getting the article passed as argument from other fragment
val article = arguments?.getSerializable("OpenArticle") as Article
//passing the url of the clicked article to webViewClient to view full article
if (article.url != null) {
binding?.webView?.apply {
webViewClient = WebViewClient()
loadUrl(article.url)
}
} else {
//back to news fragment if link to article is null
navController.popBackStack()
}
binding?.fabShare?.setOnClickListener {
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.type="text/plain"
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Share this article...")
shareIntent.putExtra(Intent.EXTRA_TEXT, article.url)
startActivity(shareIntent)
}
}
override fun onDestroy() {
super.onDestroy()
binding = null
}
}
| 0
|
Kotlin
|
0
| 1
|
f8840f5677ba711027086e55e71ecc181db8f748
| 2,145
|
minimal-news-app
|
MIT License
|
app/src/main/java/com/kickstarter/viewmodels/DiscoveryViewModel.kt
|
kickstarter
| 76,278,501
| false
| null |
package com.kickstarter.viewmodels
import android.content.Intent
import android.net.Uri
import android.util.Pair
import com.kickstarter.R
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.featureflag.FlagKey
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.DiscoveryUtils
import com.kickstarter.libs.utils.extensions.deriveNavigationDrawerData
import com.kickstarter.libs.utils.extensions.getTokenFromQueryParams
import com.kickstarter.libs.utils.extensions.intValueOrZero
import com.kickstarter.libs.utils.extensions.isNonZero
import com.kickstarter.libs.utils.extensions.isNotNull
import com.kickstarter.libs.utils.extensions.isNull
import com.kickstarter.libs.utils.extensions.isTrue
import com.kickstarter.libs.utils.extensions.isVerificationEmailUrl
import com.kickstarter.libs.utils.extensions.positionFromSort
import com.kickstarter.models.Category
import com.kickstarter.models.User
import com.kickstarter.services.DiscoveryParams
import com.kickstarter.services.apiresponses.ErrorEnvelope
import com.kickstarter.services.apiresponses.InternalBuildEnvelope
import com.kickstarter.ui.SharedPreferenceKey.CONSENT_MANAGEMENT_PREFERENCE
import com.kickstarter.ui.SharedPreferenceKey.HAS_SEEN_NOTIF_PERMISSIONS
import com.kickstarter.ui.activities.DiscoveryActivity
import com.kickstarter.ui.adapters.DiscoveryDrawerAdapter
import com.kickstarter.ui.adapters.DiscoveryPagerAdapter
import com.kickstarter.ui.adapters.data.NavigationDrawerData
import com.kickstarter.ui.intentmappers.DiscoveryIntentMapper
import com.kickstarter.ui.viewholders.discoverydrawer.ChildFilterViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.LoggedInViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.LoggedOutViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.ParentFilterViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.TopFilterViewHolder
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
import java.util.Locale.filter
interface DiscoveryViewModel {
interface Inputs : DiscoveryDrawerAdapter.Delegate, DiscoveryPagerAdapter.Delegate {
/** Call when a new build is available. */
fun newerBuildIsAvailable(envelope: InternalBuildEnvelope)
/** Call when you want to open or close the drawer. */
fun openDrawer(open: Boolean)
/** Call when the user selects a sort tab. */
fun sortClicked(sortPosition: Int)
/** Call when the user has seen the notifications permission request. */
fun hasSeenNotificationsPermission(hasShown: Boolean)
}
interface Outputs {
/** Emits a boolean that determines if the drawer is open or not. */
fun drawerIsOpen(): Observable<Boolean>
/** Emits the drawable resource ID of the drawer menu icon. */
fun drawerMenuIcon(): Observable<Int>
/** Emits a boolean that determines if the sort tab layout should be expanded/collapsed. */
fun expandSortTabLayout(): Observable<Boolean>
/** Emits when params change so that the tool bar can adjust accordingly. */
fun updateToolbarWithParams(): Observable<DiscoveryParams>
/** Emits when the params of a particular page should be updated. The page will be responsible for
* taking those params and creating paginating projects from it. */
fun updateParamsForPage(): Observable<DiscoveryParams>
fun navigationDrawerData(): Observable<NavigationDrawerData>
/** Emits the root categories and position. Position is used to determine the appropriate fragment
* to pass the categories to. */
fun rootCategoriesAndPosition(): Observable<Pair<List<Category>, Int>>
/** Emits a list of pages that should be cleared of all their content. */
fun clearPages(): Observable<List<Int>>
/** Emits when a newer build is available and an alert should be shown. */
fun showBuildCheckAlert(): Observable<InternalBuildEnvelope>
/** Start activity feed activity. */
fun showActivityFeed(): Observable<Void?>
/** Start help activity. */
fun showHelp(): Observable<Void?>
/** Start internal tools activity. */
fun showInternalTools(): Observable<Void?>
/** Start login tout activity for result. */
fun showLoginTout(): Observable<Void?>
/** Start [com.kickstarter.ui.activities.MessageThreadsActivity]. */
fun showMessages(): Observable<Void?>
/** Start profile activity. */
fun showProfile(): Observable<Void?>
/** Start settings activity. */
fun showSettings(): Observable<Void?>
/** Emits the success message from verify endpoint */
fun showSuccessMessage(): Observable<String>
/** Emits if the user should be shown the notification permission request */
fun showNotifPermissionsRequest(): Observable<Void?>
/** Emits if the user should be shown the consent management dialog */
fun showConsentManagementDialog(): Observable<Void?>
/** Emits the error message from verify endpoint */
fun showErrorMessage(): Observable<String?>
}
class ViewModel(environment: Environment) : ActivityViewModel<DiscoveryActivity?>(environment), Inputs, Outputs {
val inputs = this
val outputs = this
private val apiClient = requireNotNull(environment.apiClient())
private val apolloClient = requireNotNull(environment.apolloClient())
private val buildCheck = requireNotNull(environment.buildCheck())
private val currentUserType = requireNotNull(environment.currentUser())
private val currentConfigType = requireNotNull(environment.currentConfig())
private val sharedPreferences = requireNotNull(environment.sharedPreferences())
private val webClient = requireNotNull(environment.webClient())
private val ffClient = environment.featureFlagClient()
private fun currentDrawerMenuIcon(user: User?): Int {
if (user.isNull()) {
return R.drawable.ic_menu
}
val erroredBackingsCount = user?.erroredBackingsCount().intValueOrZero()
val unreadMessagesCount = user?.unreadMessagesCount().intValueOrZero()
val unseenActivityCount = user?.unseenActivityCount().intValueOrZero()
return when {
erroredBackingsCount.isNonZero() -> R.drawable.ic_menu_error_indicator
(unreadMessagesCount + unseenActivityCount + erroredBackingsCount).isNonZero() -> R.drawable.ic_menu_indicator
else -> R.drawable.ic_menu
}
}
private val activityFeedClick = PublishSubject.create<Void?>()
private val childFilterRowClick = PublishSubject.create<NavigationDrawerData.Section.Row?>()
private val internalToolsClick = PublishSubject.create<Void?>()
private val loggedOutLoginToutClick = PublishSubject.create<Void?>()
private val loggedOutSettingsClick = PublishSubject.create<Void?>()
private val messagesClick = PublishSubject.create<Void?>()
private val newerBuildIsAvailable = PublishSubject.create<InternalBuildEnvelope>()
private val openDrawer = PublishSubject.create<Boolean>()
private val pagerSetPrimaryPage = PublishSubject.create<Int>()
private val parentFilterRowClick = PublishSubject.create<NavigationDrawerData.Section.Row>()
private val profileClick = PublishSubject.create<Void?>()
private val showNotifPermissionRequest = BehaviorSubject.create<Void?>()
private val showConsentManagementDialog = BehaviorSubject.create<Void?>()
private val settingsClick = PublishSubject.create<Void?>()
private val sortClicked = PublishSubject.create<Int>()
private val hasSeenNotificationsPermission = PublishSubject.create<Boolean>()
private val topFilterRowClick = PublishSubject.create<NavigationDrawerData.Section.Row?>()
private val clearPages = BehaviorSubject.create<List<Int>>()
private val drawerIsOpen = BehaviorSubject.create<Boolean>()
private val drawerMenuIcon = BehaviorSubject.create<Int>()
private val expandSortTabLayout = BehaviorSubject.create<Boolean>()
private val navigationDrawerData = BehaviorSubject.create<NavigationDrawerData>()
private val rootCategoriesAndPosition = BehaviorSubject.create<Pair<List<Category>, Int>>()
private val showActivityFeed: Observable<Void?>
private val showBuildCheckAlert: Observable<InternalBuildEnvelope>
private val showHelp: Observable<Void?>
private val showInternalTools: Observable<Void?>
private val showLoginTout: Observable<Void?>
private val showMessages: Observable<Void?>
private val showProfile: Observable<Void?>
private val showSettings: Observable<Void?>
private val updateParamsForPage = BehaviorSubject.create<DiscoveryParams>()
private val updateToolbarWithParams = BehaviorSubject.create<DiscoveryParams>()
private val successMessage = PublishSubject.create<String>()
private val messageError = PublishSubject.create<String?>()
init {
buildCheck.bind(this, webClient)
showActivityFeed = activityFeedClick
showBuildCheckAlert = newerBuildIsAvailable
showHelp = loggedOutSettingsClick
showInternalTools = internalToolsClick
showLoginTout = loggedOutLoginToutClick
showMessages = messagesClick
showProfile = profileClick
showSettings = settingsClick
val currentUser = currentUserType.observable()
val changedUser = currentUser
.distinctUntilChanged()
changedUser
.compose(bindToLifecycle())
.subscribe {
apiClient.config()
.compose(Transformers.neverError())
.subscribe { currentConfigType.config(it) }
}
// Seed params when we are freshly launching the app with no data.
val paramsFromInitialIntent = intent()
.take(1)
.map { it.action }
.filter { Intent.ACTION_MAIN == it }
.compose(Transformers.combineLatestPair(changedUser))
.map { DiscoveryParams.getDefaultParams(it.second) }
.share()
val uriFromVerification = intent()
.map { it.data }
.ofType(Uri::class.java)
.filter { it.isVerificationEmailUrl() }
val verification = uriFromVerification
.map { it.getTokenFromQueryParams() }
.filter { it.isNotNull() }
.switchMap { apiClient.verifyEmail(it) }
.materialize()
.share()
.distinctUntilChanged()
verification
.compose(Transformers.values())
.map { it.message() }
.compose(bindToLifecycle())
.subscribe(successMessage)
verification
.compose(Transformers.errors())
.map { ErrorEnvelope.fromThrowable(it) }
.map { it?.errorMessage() }
.filter { it.isNotNull() }
.compose(bindToLifecycle())
.subscribe(messageError)
currentUserType.isLoggedIn
.filter { it }
.distinctUntilChanged()
.take(1)
.filter { !sharedPreferences.getBoolean(HAS_SEEN_NOTIF_PERMISSIONS, false) }
.compose(bindToLifecycle())
.subscribe { showNotifPermissionRequest.onNext(null) }
hasSeenNotificationsPermission
.compose(bindToLifecycle())
.subscribe { sharedPreferences.edit().putBoolean(HAS_SEEN_NOTIF_PERMISSIONS, it).apply() }
Observable.just(sharedPreferences.contains(CONSENT_MANAGEMENT_PREFERENCE))
.filter { !it }
.filter { ffClient?.getBoolean(FlagKey.ANDROID_CONSENT_MANAGEMENT) }
.compose(bindToLifecycle())
.subscribe { showConsentManagementDialog.onNext(null) }
val paramsFromIntent = intent()
.flatMap { DiscoveryIntentMapper.params(it, apiClient, apolloClient) }
val pagerSelectedPage = pagerSetPrimaryPage.distinctUntilChanged()
val drawerParamsClicked = childFilterRowClick
.mergeWith(topFilterRowClick)
.withLatestFrom(
pagerSelectedPage.map { DiscoveryUtils.sortFromPosition(it) }
) { drawerClickParams, currentParams ->
if (drawerClickParams.params().sort() == null)
drawerClickParams.params().toBuilder().sort(currentParams).build()
else drawerClickParams.params()
}
// Merge various param data sources.
val params = Observable.merge(
paramsFromInitialIntent,
paramsFromIntent,
drawerParamsClicked
)
val sortToTabOpen = Observable.merge(
pagerSelectedPage.map { DiscoveryUtils.sortFromPosition(it) },
params.map { it.sort() }
)
.filter { it.isNotNull() }
// Combine params with the selected sort position.
val paramsWithSort = Observable.combineLatest(
params,
sortToTabOpen
) { p, s -> p.toBuilder().sort(s).build() }
paramsWithSort
.compose(bindToLifecycle())
.subscribe(updateParamsForPage)
paramsWithSort
.compose(Transformers.takePairWhen(sortClicked.map { DiscoveryUtils.sortFromPosition(it) }))
.map<Pair<DiscoveryParams.Sort, DiscoveryParams>> {
Pair.create(
it.first.sort(),
it.first.toBuilder().sort(it.second).build()
)
}
.compose(bindToLifecycle())
.subscribe { analyticEvents.trackDiscoverSortCTA(it.first, it.second) }
paramsWithSort
.compose(Transformers.takeWhen(drawerParamsClicked))
.compose(bindToLifecycle())
.subscribe {
analyticEvents.trackDiscoverFilterCTA(it)
}
val categories = apolloClient.fetchCategories()
.compose(Transformers.neverError())
.flatMapIterable { it }
.toSortedList()
.share()
// Combine root categories with the selected sort position.
Observable.combineLatest<List<Category>?, Int, Pair<List<Category>, Int>>(
categories
.flatMapIterable { it }
.filter { it.isRoot }
.toList(),
pagerSelectedPage
) { c, psp -> Pair.create(c, psp) }
.compose(bindToLifecycle())
.subscribe(rootCategoriesAndPosition)
val drawerClickedParentCategory = parentFilterRowClick
.map { it.params().category() }
val expandedCategory = Observable.merge(
topFilterRowClick.map { null },
drawerClickedParentCategory
)
.scan(
null
) { previous: Category?, next: Category? ->
if (previous != null && next != null && previous == next) {
return@scan null
}
next
}
// Accumulate a list of pages to clear when the params or user changes,
// to avoid displaying old data.
pagerSelectedPage
.compose(Transformers.takeWhen(params))
.compose(Transformers.combineLatestPair(changedUser))
.map { it.first }
.flatMap {
Observable.from(DiscoveryParams.Sort.defaultSorts)
.map { sort: DiscoveryParams.Sort? -> sort.positionFromSort() }
.filter { sortPosition: Int -> sortPosition != it }
.toList()
}
.compose(bindToLifecycle())
.subscribe(clearPages)
params
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(updateToolbarWithParams)
updateParamsForPage
.map { true }
.compose(bindToLifecycle())
.subscribe(expandSortTabLayout)
Observable.combineLatest<List<Category>, DiscoveryParams, Category?, User, NavigationDrawerData>(
categories,
params,
expandedCategory,
currentUser
) { c, s, ec, u -> s.deriveNavigationDrawerData(c, ec, u) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(navigationDrawerData)
val drawerOpenObservables = listOf(
openDrawer,
childFilterRowClick.map { false },
topFilterRowClick.map { false },
internalToolsClick.map { false },
loggedOutLoginToutClick.map { false },
loggedOutSettingsClick.map { false },
activityFeedClick.map { false },
messagesClick.map { false },
profileClick.map { false },
settingsClick.map { false }
)
Observable.merge(drawerOpenObservables)
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(drawerIsOpen)
val drawerOpened = openDrawer
.filter { bool: Boolean? -> bool.isTrue() }
currentUser
.map { currentDrawerMenuIcon(it) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe { drawerMenuIcon.onNext(it) }
}
override fun childFilterViewHolderRowClick(viewHolder: ChildFilterViewHolder, row: NavigationDrawerData.Section.Row) {
childFilterRowClick.onNext(row)
}
override fun discoveryPagerAdapterSetPrimaryPage(adapter: DiscoveryPagerAdapter, position: Int) {
pagerSetPrimaryPage.onNext(position)
}
override fun loggedInViewHolderActivityClick(viewHolder: LoggedInViewHolder) { activityFeedClick.onNext(null) }
override fun loggedInViewHolderInternalToolsClick(viewHolder: LoggedInViewHolder) { internalToolsClick.onNext(null) }
override fun loggedInViewHolderMessagesClick(viewHolder: LoggedInViewHolder) { messagesClick.onNext(null) }
override fun loggedInViewHolderProfileClick(viewHolder: LoggedInViewHolder, user: User) { profileClick.onNext(null) }
override fun loggedInViewHolderSettingsClick(viewHolder: LoggedInViewHolder, user: User) { settingsClick.onNext(null) }
override fun loggedOutViewHolderActivityClick(viewHolder: LoggedOutViewHolder) { activityFeedClick.onNext(null) }
override fun loggedOutViewHolderInternalToolsClick(viewHolder: LoggedOutViewHolder) { internalToolsClick.onNext(null) }
override fun loggedOutViewHolderLoginToutClick(viewHolder: LoggedOutViewHolder) { loggedOutLoginToutClick.onNext(null) }
override fun loggedOutViewHolderHelpClick(viewHolder: LoggedOutViewHolder) { loggedOutSettingsClick.onNext(null) }
override fun topFilterViewHolderRowClick(viewHolder: TopFilterViewHolder, row: NavigationDrawerData.Section.Row) {
topFilterRowClick.onNext(row)
}
// - Inputs
override fun newerBuildIsAvailable(envelope: InternalBuildEnvelope) { newerBuildIsAvailable.onNext(envelope) }
override fun openDrawer(open: Boolean) { openDrawer.onNext(open) }
override fun parentFilterViewHolderRowClick(viewHolder: ParentFilterViewHolder, row: NavigationDrawerData.Section.Row) {
parentFilterRowClick.onNext(row)
}
override fun sortClicked(sortPosition: Int) { sortClicked.onNext(sortPosition) }
override fun hasSeenNotificationsPermission(hasShown: Boolean) { hasSeenNotificationsPermission.onNext(hasShown) }
// - Outputs
override fun clearPages(): Observable<List<Int>> { return clearPages }
override fun drawerIsOpen(): Observable<Boolean> { return drawerIsOpen }
override fun drawerMenuIcon(): Observable<Int> { return drawerMenuIcon }
override fun expandSortTabLayout(): Observable<Boolean> { return expandSortTabLayout }
override fun navigationDrawerData(): Observable<NavigationDrawerData> { return navigationDrawerData }
override fun rootCategoriesAndPosition(): Observable<Pair<List<Category>, Int>> { return rootCategoriesAndPosition }
override fun showActivityFeed(): Observable<Void?> { return showActivityFeed }
override fun showBuildCheckAlert(): Observable<InternalBuildEnvelope> { return showBuildCheckAlert }
override fun showHelp(): Observable<Void?> { return showHelp }
override fun showInternalTools(): Observable<Void?> { return showInternalTools }
override fun showLoginTout(): Observable<Void?> { return showLoginTout }
override fun showMessages(): Observable<Void?> { return showMessages }
override fun showProfile(): Observable<Void?> { return showProfile }
override fun showSettings(): Observable<Void?> { return showSettings }
override fun updateParamsForPage(): Observable<DiscoveryParams> { return updateParamsForPage }
override fun updateToolbarWithParams(): Observable<DiscoveryParams> { return updateToolbarWithParams }
override fun showSuccessMessage(): Observable<String> { return successMessage }
override fun showErrorMessage(): Observable<String?> { return messageError }
override fun showNotifPermissionsRequest(): Observable<Void?> { return showNotifPermissionRequest }
override fun showConsentManagementDialog(): Observable<Void?> { return showConsentManagementDialog }
}
}
| 9
| null |
995
| 5,752
|
a9187fb484c4d12137c7919a2a53339d67cab0cb
| 22,663
|
android-oss
|
Apache License 2.0
|
app/src/main/java/edu/galileo/mvp/LoginModelImp.kt
|
steve1rm
| 96,331,673
| false
| null |
package edu.galileo.mvp
import android.os.AsyncTask
/**
* Created by steve on 7/5/17.
*/
class LoginModelImp : LoginModel {
private lateinit var listener: LoginModel.OnLoginFinishedListener
private val DUMMY_CREDENTIALS =
arrayOf("<EMAIL>:testtest", "<EMAIL>:testtest")
override
fun login(username: String, password: String, listener: LoginModel.OnLoginFinishedListener) {
this.listener = listener
UserLoginTask(username, password).execute()
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
inner class UserLoginTask internal constructor(private val mEmail: String, private val mPassword: String) : AsyncTask<Void, Void, Boolean>() {
override
fun doInBackground(vararg params: Void): Boolean? {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000)
} catch (e: InterruptedException) {
return false
}
for(credential in DUMMY_CREDENTIALS) {
val pieces = credential.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (pieces[0] == mEmail) {
// Account exists, return true if the password matches.
return pieces[1] == mPassword
}
}
// TODO: register the new account here.
return false
}
override
fun onPostExecute(success: Boolean?) {
if(success!!) {
listener.onSuccess()
}
else {
listener.onPasswordError()
}
}
override
fun onCancelled() {
listener.onCanceled()
}
}
}
| 1
| null |
1
| 1
|
8775100959b44edb7dc8cca75eca7ea99e6c7480
| 1,873
|
BusbyChat
|
MIT License
|
data/similar/api/src/commonMain/kotlin/com/thomaskioko/tvmaniac/similar/api/SimilarShowsDao.kt
|
c0de-wizard
| 361,393,353
| false
| null |
package com.thomaskioko.tvmaniac.similar.api
import com.thomaskioko.tvmaniac.core.db.SimilarShows
import kotlinx.coroutines.flow.Flow
interface SimilarShowsDao {
fun upsert(showId: Long, similarShowId: Long)
fun observeSimilarShows(traktId: Long): Flow<List<SimilarShows>>
fun delete(id: Long)
fun deleteAll()
}
| 9
|
Kotlin
|
28
| 98
|
8bc3853d84c58520dffe26ddb260a2e7b6482ae9
| 334
|
tv-maniac
|
Apache License 2.0
|
demo-databinding/src/main/java/com/outs/demo_databinding/dialog/DateTimePicker.kt
|
Outs3
| 424,166,410
| false
| null |
package com.outs.demo_databinding.dialog
import android.content.Context
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import androidx.lifecycle.MutableLiveData
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.outs.demo_databinding.R
import com.outs.utils.android.onClickOrRepeat
import com.outs.utils.android.postOnNot
import com.outs.utils.kotlin.format
import com.outs.utils.kotlin.parseDate
import java.util.*
/**
* author: Outs3
* e-mail: <EMAIL>
* date: 2021/10/2 9:59
* desc:
*/
open class BaseDatePicker(
context: Context,
type: BooleanArray = booleanArrayOf(
true,
true,
true,
false,
false,
false
),
onTimeSelect: (Long) -> Unit
) {
val view: TimePickerView by lazy {
TimePickerBuilder(context) { date: Date?, v: View? -> date?.time?.let(onTimeSelect) }
.setLayoutRes(
R.layout.view_time_picker
) { v ->
v?.findViewById<Button>(R.id.btnCancel)?.onClickOrRepeat { view.dismiss() }
v?.findViewById<Button>(R.id.btnSubmit)?.onClickOrRepeat {
view.apply {
returnData()
dismiss()
}
}
}
.setType(type)
.setContentTextSize(16)
.isDialog(true)
.build()
.also {
it.dialogContainerLayout?.layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
)
it.dialog?.window?.apply {
setGravity(Gravity.BOTTOM)
setDimAmount(0.7f)
}
}
}
fun show(date: Calendar? = null) {
date?.let(view::setDate)
view.show()
}
}
open class DatePicker(
context: Context,
private val pattern: String,
type: BooleanArray = booleanArrayOf(true, true, true, false, false, false),
onTimeSelect: (String) -> Unit
) : BaseDatePicker(context, type, { it.format(pattern).let(onTimeSelect) }) {
fun show(date: String?) =
show(Calendar.getInstance().also { it.timeInMillis = date?.parseDate(pattern) ?: 0 })
}
open class LiveDatePicker(
context: Context,
pattern: String,
type: BooleanArray = booleanArrayOf(true, true, true, false, false, false),
val target: MutableLiveData<String>
) : DatePicker(
context, pattern, type, target::postOnNot
) {
fun show() = super.show(target.value)
}
| 0
|
Kotlin
|
0
| 2
|
29ba56113bf788782cbefb48e28fca6df3509eda
| 2,777
|
subahayai
|
MIT License
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/emr/CfnClusterPlacementTypePropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.emr
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.emr.CfnCluster
/**
* `PlacementType` is a property of the `AWS::EMR::Cluster` resource.
*
* `PlacementType` determines the Amazon EC2 Availability Zone configuration of the cluster (job
* flow).
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.emr.*;
* PlacementTypeProperty placementTypeProperty = PlacementTypeProperty.builder()
* .availabilityZone("availabilityZone")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-placementtype.html)
*/
@CdkDslMarker
public class CfnClusterPlacementTypePropertyDsl {
private val cdkBuilder: CfnCluster.PlacementTypeProperty.Builder =
CfnCluster.PlacementTypeProperty.builder()
/**
* @param availabilityZone The Amazon EC2 Availability Zone for the cluster.
* `AvailabilityZone` is used for uniform instance groups, while `AvailabilityZones` (plural) is
* used for instance fleets.
*/
public fun availabilityZone(availabilityZone: String) {
cdkBuilder.availabilityZone(availabilityZone)
}
public fun build(): CfnCluster.PlacementTypeProperty = cdkBuilder.build()
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 1,597
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
light/src/main/kotlin/net/kotlinx/aws/lambda/dispatch/AbstractRequestHandler.kt
|
mypojo
| 565,799,715
| false
|
{"Kotlin": 1234575, "Java": 9531, "Jupyter Notebook": 7080}
|
package net.kotlinx.aws.lambda.dispatch
import com.amazonaws.services.lambda.runtime.RequestHandler
import mu.KotlinLogging
import net.kotlinx.system.ResourceHolder
import net.kotlinx.time.TimeUtil
import org.crac.Context
import org.crac.Resource
/**
* 람다의 기본 진입점
* 편의상 만들었음
*
* 스냅스타트 적용시
* init 에서 Core.getGlobalContext().register(this) 해줄것
* beforeCheckpoint 에서 koin 초기화 & 스냅스타트 로직 실행
*
* 도커 사용시 공식 이미지를 사용해야함! 그게 아니라면 의존성 추가 필요!
*/
abstract class AbstractRequestHandler : RequestHandler<Map<String, Any>, Map<String, Any>>, Resource {
private val log = KotlinLogging.logger {}
/**
* 스탭스타트 이미지 전
* 보통 여기서 스냅스타트 로직한번 돌려주고 시작객체 초기화 (koin 등) -> 초기화 안하면 http pool 등이 캐시에 남아서 오류남
* */
override fun beforeCheckpoint(context: Context<out Resource>?) {
log.info { "AWS snapstart beforeCheckpoint" }
}
/**
* 스탭스타트 복구이후.
* 딱히 할거 없음
* */
override fun afterRestore(context: Context<out Resource>?) {
log.info { "AWS snapstart afterRestore" }
}
init {
TimeUtil.initTimeZone()
//아직 셧다운 훅은 지원안함.
Runtime.getRuntime().addShutdownHook(Thread {
log.warn { "### 람다가 셧다운 됩니다 ###" }
ResourceHolder.finish()
})
}
}
| 0
|
Kotlin
|
0
| 1
|
e99e287495c673bcf4255e2794af0e8477580959
| 1,251
|
kx_kotlin_support
|
MIT License
|
buildSrc/src/main/kotlin/karakum/browser/Generator.kt
|
karakum-team
| 393,199,102
| false
| null |
package karakum.browser
import karakum.common.GENERATOR_COMMENT
import karakum.common.Suppress
import karakum.common.Suppress.*
import karakum.common.fileSuppress
import java.io.File
private val DEFAULT_IMPORTS = """
import kotlin.js.Date
import kotlin.js.Promise
import js.core.ArrayLike
import js.core.BigInt
import js.core.JsIterable
import js.core.EpochTimeStamp
import js.buffer.ArrayBuffer
import js.buffer.ArrayBufferLike
import js.buffer.ArrayBufferView
import js.buffer.BufferSource
import js.typedarrays.Float32Array
import js.typedarrays.Float64Array
import js.core.HighResTimeStamp
import js.typedarrays.Int32Array
import js.collections.ReadonlyMap
import js.core.Record
import js.core.ReadonlyArray
import js.core.ReadonlyRecord
import js.typedarrays.Uint8Array
import js.typedarrays.Uint32Array
import js.typedarrays.Uint8ClampedArray
import js.core.JsLong
import js.core.Void
import web.canvas.OffscreenCanvas
import web.cssom.CSSStyleDeclaration
import web.cssom.CSSStyleSheet
import web.dom.Document
import web.dom.DocumentFragment
import web.dom.DOMStringList
import web.dom.DOMTokenList
import web.dom.DocumentOrShadowRoot
import web.dom.DocumentVisibilityState
import web.dom.Element
import web.dom.ElementNamespace
import web.dom.HTMLOrSVGElement
import web.dom.InnerHTML
import web.dom.Node
import web.dom.NodeList
import web.dom.NodeListOf
import web.dom.Range
import web.scroll.ScrollIntoViewOptions
import web.scroll.ScrollToOptions
import web.dom.GlobalEventHandlers
import web.window.WindowEventHandlers
import web.aria.ARIAMixin
import web.dom.css.LinkStyle
import web.dom.css.ElementCSSInlineStyle
import web.data.DataTransfer
import web.geometry.DOMMatrix
import web.geometry.DOMMatrixReadOnly
import web.geometry.DOMMatrix2DInit
import web.geometry.DOMPoint
import web.geometry.DOMPointInit
import web.geometry.DOMPointReadOnly
import web.geometry.DOMRect
import web.geometry.DOMRectInit
import web.geometry.DOMRectReadOnly
import web.geometry.DOMRectList
import web.fullscreen.FullscreenOptions
import web.html.HTMLCanvasElement
import web.html.HTMLCollectionOf
import web.html.HTMLCollection
import web.html.HTMLElement
import web.html.HTMLMediaElement
import web.html.HTMLSlotElement
import web.html.HtmlTagName
import web.html.ShadowRoot
import web.html.ShadowRootInit
import web.keyboard.KeyCode
import web.keyboard.ModifierKeyCode
import web.window.PictureInPictureWindow
import web.window.Window
import web.window.WindowProxy
import web.window.WindowTarget
import web.selection.Selection
import web.svg.SVG_NAMESPACE
import web.svg.SVGElement
import web.svg.SvgTagName
import web.mathml.MATHML_NAMESPACE
import web.mathml.MathMLElement
import web.mathml.MathMLTagName
import web.xml.XMLDocument
import web.media.capabilities.MediaCapabilities
import web.media.session.MediaSession
import web.media.key.MediaKeys
import web.media.source.TimeRanges
import web.media.streams.MediaStream
import web.media.streams.MediaStreamConstraints
import web.media.streams.MediaStreamTrack
import web.media.streams.MediaTrackConstraints
import web.media.streams.MediaTrackSupportedConstraints
import web.remoteplayback.RemotePlayback
import web.abort.AbortSignal
import web.animations.Animation
import web.buffer.Blob
import web.buffer.BlobPart
import web.buffer.BlobPropertyBag
import web.crypto.Algorithm
import web.events.Event
import web.events.EventInit
import web.events.EventType
import web.events.EventHandler
import web.events.EventTarget
import web.errors.DOMException
import web.file.File
import web.file.FileList
import web.filesystem.FileSystemDirectoryHandle
import web.filesystem.FileSystemEntry
import web.http.BodyInit
import web.http.FormData
import web.http.ReferrerPolicy
import web.http.Request
import web.http.RequestCredentials
import web.http.Response
import web.locks.LockManager
import web.messaging.MessagePort
import web.messaging.Transferable
import web.messaging.StructuredSerializeOptions
import web.notifications.Notification
import web.notifications.NotificationOptions
import web.permissions.Permissions
import web.permissions.PermissionState
import web.push.PushManager
import web.share.ShareData
import web.storage.StorageManager
import web.streams.ReadableStream
import web.streams.WritableStream
import web.url.URL
import web.vibration.VibratePattern
import web.workers.AbstractWorker
import web.workers.WorkerType
import web.worklets.Worklet
import websockets.BinaryType
import webvtt.TextTrack
import webvtt.TextTrackKind
import webvtt.TextTrackList
""".trimIndent()
fun generateKotlinDeclarations(
definitionsDir: File,
webDefinitionsFile: File,
serviceworkerDefinitionsFile: File,
sourceDir: File,
) {
IterableRegistry.fill(definitionsDir)
val content = webDefinitionsFile
.readText()
.applyPatches()
val webglTargetDir = sourceDir
.resolve("webgl")
.also { it.mkdirs() }
for ((name, body, optPkg) in eventDeclarations(content, webWorkersContent(serviceworkerDefinitionsFile))) {
val suppresses = mutableSetOf<Suppress>().apply {
if ("override val type: EventType<" in body)
add(EXTERNAL_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER)
if ("JsName(\"\"\"(" in body || name == "TouchEvent")
add(NAME_CONTAINS_ILLEGAL_CHARS)
if ("companion object" in body && !name.endsWith("Event"))
add(NESTED_CLASS_IN_EXTERNAL_INTERFACE)
if ("inline fun " in body)
add(NOTHING_TO_INLINE)
}.toTypedArray()
val annotations = if (suppresses.isNotEmpty()) {
fileSuppress(*suppresses)
} else ""
val pkg = optPkg ?: EVENT_INFO_MAP.getValue(name.substringBefore("."))
.fqn
.substringBeforeLast(".")
val targetDir = sourceDir
.resolve(pkg.replace(".", "/"))
.also { it.mkdirs() }
targetDir.resolve("$name.kt")
.also { check(!it.exists()) { "Duplicated file: ${it.name}" } }
.writeText(fileContent(annotations, "", body, pkg))
}
val aliases = domAliases()
.plus(htmlFactories(content))
.plus(htmlDeclarations(content))
.plus(htmlUnions())
.plus(browserConstants(content))
.plus(browserTypes(content))
.plus(browserFunctionTypes(content))
.plus(keyboardTypes())
.plus(windowTypes())
.plus(tagNames(content))
.plus(intlDeclarations(definitionsDir))
.plus(webWorkersDeclarations(serviceworkerDefinitionsFile))
for ((name, body, pkg) in aliases) {
pkg!!
val suppresses = mutableSetOf<Suppress>().apply {
if ("override val type: EventType<" in body)
add(EXTERNAL_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER)
if ("JsName(\"\"\"(" in body || "JsName(\"'" in body)
add(NAME_CONTAINS_ILLEGAL_CHARS)
when (name) {
RENDERING_CONTEXT_ID,
"KeyFormat",
"WindowTarget",
-> add(NESTED_CLASS_IN_EXTERNAL_INTERFACE)
}
if ("inline fun " in body)
add(NOTHING_TO_INLINE)
if (name == "Locale")
add(VIRTUAL_MEMBER_HIDDEN)
// TEMP Remove HTML classes fix
if (name in HTML_FACTORIES)
add(ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED)
// TEMP Remove after inheritance fix
if (name == "TextDecoder" || name == "TextDecoderStream")
add(ABSTRACT_MEMBER_NOT_IMPLEMENTED)
if (name == "WorkerNavigator")
add(SEALED_INHERITOR_IN_DIFFERENT_PACKAGE)
}.toTypedArray()
val annotations = sequenceOf(
if (suppresses.isNotEmpty()) {
fileSuppress(*suppresses)
} else "",
if (pkg == "js.intl" && "external class" in body) """@file:JsQualifier("Intl")""" else "",
).filter { it.isNotEmpty() }
.joinToString("\n\n")
val imports = when (name) {
"Document",
"DocumentOrShadowRoot",
-> """
import web.cssom.StyleSheetList
import web.fonts.FontFaceSource
import web.html.*
import web.xpath.XPathEvaluatorBase
""".trimIndent()
"HTMLCanvasElement" -> """
import web.canvas.*
import webgl.*
""".trimIndent()
"OffscreenCanvas" -> """
import webgl.WebGLRenderingContext
import webgl.WebGL2RenderingContext
""".trimIndent()
"Navigator" -> """
import web.media.devices.MediaDevices
import web.media.key.MediaKeySystemAccess
import web.media.key.MediaKeySystemConfiguration
import web.serviceworker.ServiceWorkerContainer
import web.clipboard.Clipboard
import web.geolocation.Geolocation
import web.gamepad.Gamepad
import web.midi.MIDIOptions
import web.midi.MIDIAccess
""".trimIndent()
"Window",
-> """
import web.device.DeviceMotionEvent
import web.device.DeviceOrientationEvent
""".trimIndent()
"GlobalEventHandlers",
"WindowEventHandlers",
"FileReader",
-> """
import web.cssom.TransitionEvent
import web.html.FormDataEvent
import web.html.SubmitEvent
import web.uievents.*
import web.animations.AnimationEvent
import web.clipboard.ClipboardEvent
import web.csp.SecurityPolicyViolationEvent
import web.events.ProgressEvent
import web.gamepad.GamepadEvent
import web.history.HashChangeEvent
import web.history.PageTransitionEvent
import web.history.PopStateEvent
import web.messaging.MessageEvent
import web.storage.StorageEvent
""".trimIndent()
"EventSource",
"XMLHttpRequestEventTarget",
"RTCDataChannel",
"ServiceWorkerContainer",
"BroadcastChannel",
-> """
import web.events.ProgressEvent
import web.messaging.MessageEvent
""".trimIndent()
"AbstractWorker",
"Worker",
"WebSocket",
-> """
import web.events.IEventTarget
import web.errors.ErrorEvent
import web.messaging.MessageEvent
""".trimIndent()
"DedicatedWorkerGlobalScope",
"WorkerGlobalScope",
-> """
import web.fonts.FontFaceSource
import web.window.PromiseRejectionEvent
import web.errors.ErrorEvent
import web.messaging.MessageEvent
""".trimIndent()
"WorkerNavigator",
-> """
import web.navigator.*
import web.messaging.MessageEvent
""".trimIndent()
else -> ""
}
val targetDir = sourceDir
.resolve(pkg.replace(".", "/"))
.also { it.mkdirs() }
targetDir.resolve("$name.kt")
.also { check(!it.exists()) { "Duplicated file: ${it.name}" } }
.writeText(
fileContent(
annotations = annotations,
imports = imports,
body = body,
pkg = pkg,
)
)
}
for ((name, body) in webglDeclarations(content)) {
val suppresses = mutableSetOf<Suppress>().apply {
if ("JsName(\"\"\"(" in body)
add(NAME_CONTAINS_ILLEGAL_CHARS)
if (name == "WebGLExtension")
add(NESTED_CLASS_IN_EXTERNAL_INTERFACE)
}.toTypedArray()
val annotations = if (suppresses.isNotEmpty()) {
fileSuppress(*suppresses)
} else ""
webglTargetDir.resolve("$name.kt")
.also { check(!it.exists()) { "Duplicated file: ${it.name}" } }
.writeText(fileContent(annotations, "", body, "webgl"))
}
}
private fun fileContent(
annotations: String = "",
imports: String = "",
body: String,
pkg: String,
): String {
var result = sequenceOf(
"// $GENERATOR_COMMENT",
annotations,
"package $pkg",
DEFAULT_IMPORTS,
imports,
body,
).filter { it.isNotEmpty() }
.joinToString("\n\n")
if (!result.endsWith("\n"))
result += "\n"
return result
}
| 0
| null |
6
| 22
|
00321b7e81352bc3d7243dd6631e1fb178f528c8
| 12,752
|
types-kotlin
|
Apache License 2.0
|
library/src/main/java/com/jiwenjie/basepart/adapters/BaseRecyclerAdapter.kt
|
jiwenjie
| 179,411,368
| false
| null |
package com.jiwenjie.basepart.adapters
import android.content.Context
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jiwenjie.basepart.utils.LogUtils
/**
* author:Jiwenjie
* email:<EMAIL>
* time:2019/04/04
* desc:
* version:1.0
*/
abstract class BaseRecyclerAdapter<T : Any>(context: Context, dataList: ArrayList<T>? = null) :
RecyclerView.Adapter<BaseRecyclerAdapter.BaseRecyclerHolder>() {
private val mHeaderViews: SparseArray<View> = SparseArray() // SparseArray 用来代替 HashMap
private val mFooterViews: SparseArray<View> = SparseArray() // 内部的实现是 两个数组
protected val mContext = context
var mDataList = dataList
protected var mSelectedPosition = -1
private val mInflater = LayoutInflater.from(mContext)
private var mOnItemClickListener: ((position: Int, view: View) -> Unit)? = null
private var mOnItemLongClickListener: ((position: Int, view: View) -> Unit)? = null
fun setOnItemClickListener(listener: ((position: Int, view: View) -> Unit)?) {
this.mOnItemClickListener = listener
}
fun setOnItemLongClickListener(listener: ((position: Int, view: View) -> Unit)?) {
this.mOnItemLongClickListener = listener
}
/** update all data **/
fun updateAdapterData(dataList: ArrayList<T>?) {
this.mDataList = dataList
notifyDataSetChanged()
}
fun getSelectedPosition(): Int = mSelectedPosition
fun updateSelectItem(position: Int) {
this.mSelectedPosition = position
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseRecyclerHolder =
if (haveHeader() && mHeaderViews.get(viewType) != null) BaseRecyclerHolder(mHeaderViews.get(viewType))
else if (haveFooter() && mFooterViews.get(viewType) != null) BaseRecyclerHolder(mFooterViews.get(viewType))
else BaseRecyclerHolder(mInflater.inflate(getAdapterLayoutId(viewType), parent, false))
abstract fun getAdapterLayoutId(viewType: Int): Int
override fun getItemCount(): Int = getHeaderSize() + getDataSize() + getFooterSize()
override fun onBindViewHolder(holder: BaseRecyclerHolder, position: Int) {
if (!isHeader(position) && !isFooter(position)) {
val pos = position - getHeaderSize()
convertView(holder.itemView, mDataList!![pos], pos) // this position not include header and footer
LogUtils.e("HashCode0" + holder.itemView.hashCode())
holder.itemView.setOnClickListener { v ->
mOnItemClickListener?.invoke(pos, v)
}
holder.itemView.setOnLongClickListener { v ->
mOnItemLongClickListener?.invoke(pos, v)
false
}
}
}
/** position is the data position in list, not item position **/
abstract fun convertView(itemView: View, data: T, position: Int)
@Deprecated("we suggest to use addHeadView")
fun addHeader(header: View) {
mHeaderViews.put(HEADER + getHeaderSize(), header)
notifyItemInserted(getHeaderSize())
}
@Deprecated("we suggest to use addFooterView")
fun addFooter(footer: View) {
mFooterViews.put(FOOTER + getFooterSize(), footer)
var pos = if (mDataList == null) getFooterSize() else getFooterSize() + getDataSize() - 1
if (haveHeader()) pos += getHeaderSize()
notifyItemInserted(pos)
}
/**
* return the key of view in SparseArray, save it and you will use it in
* @see removeHeaderView,
* or you can call this by removeHeaderView(view.tag as Int)
*/
fun addHeaderView(header: View): Int {
val headKey = HEADER + getHeaderSize()
mHeaderViews.put(headKey, header)
header.tag = headKey
notifyItemInserted(getHeaderSize())
return headKey
}
/**
* tag is returned by addHeaderView or (yourHeaderView.tag as Int)
*/
fun removeHeaderView(tag: Int) {
mHeaderViews.remove(tag)
notifyDataSetChanged()
}
/**
* return the key of view in SparseArray, save it and you will use it in
* @see removeFooterView,
* or you can call this by removeFooterView(view.tag as Int)
*/
fun addFooterView(footer: View): Int {
val footKey = FOOTER + getFooterSize()
mFooterViews.put(footKey, footer)
footer.tag = footKey
var pos = if (mDataList == null) getFooterSize() else getFooterSize() + getDataSize() - 1
if (haveHeader()) pos += getHeaderSize()
notifyItemInserted(pos)
return footKey
}
/**
* tag is returned by addFooterView or (yourFooterView.tag as Int)
*/
fun removeFooterView(tag: Int) {
mFooterViews.remove(tag)
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int =
when {
isHeader(position) -> mHeaderViews.keyAt(position)
isFooter(position) -> mFooterViews.keyAt(position - getDataSize() - getHeaderSize())
else -> getConvertType(position)
}
protected open fun getConvertType(position: Int): Int = 0
private fun getHeaderSize(): Int = mHeaderViews.size()
private fun getDataSize(): Int = mDataList?.size ?: 0
private fun getFooterSize(): Int = mFooterViews.size()
private fun haveHeader(): Boolean = mHeaderViews.size() > 0
private fun haveFooter(): Boolean = mFooterViews.size() > 0
private fun isHeader(position: Int): Boolean = haveHeader() && position < getHeaderSize()
private fun isFooter(position: Int): Boolean = haveFooter() && position >= getHeaderSize() + getDataSize()
/** return the position of item in recyclerView include the headerViews and footerViews */
private fun getRealPosition(viewHolder: RecyclerView.ViewHolder): Int = viewHolder.layoutPosition
fun getAdapterData(): ArrayList<T>? = mDataList
fun addData(data: T) {
if (mDataList != null) {
this.mDataList!!.add(data)
notifyDataSetChanged()
} else {
throw IllegalStateException("data list has not been initial")
}
}
fun addDataAtPosition(position: Int, data: T) {
if (mDataList != null) {
this.mDataList!!.add(position, data)
notifyDataSetChanged()
} else {
throw IllegalStateException("data list has not been initial")
}
}
fun addAllData(dataList: ArrayList<T>) {
if (mDataList != null) {
this.mDataList!!.addAll(dataList)
notifyDataSetChanged()
} else {
throw IllegalStateException("data list has not been initial")
}
}
fun removeDataAtPosition(position: Int) {
if (mDataList != null) {
this.mDataList!!.removeAt(position)
notifyDataSetChanged()
} else {
throw IllegalStateException("data list has not been initial")
}
}
fun removeData(data: T) {
if (mDataList != null && data in mDataList!!) {
mDataList!!.remove(data)
notifyDataSetChanged()
} else {
throw IllegalStateException("data not in data list and check it before remove")
}
}
fun clearData() {
if (mDataList != null) {
mDataList!!.clear()
notifyDataSetChanged()
} else {
throw IllegalStateException("data list has not been initial")
}
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
val lm = recyclerView.layoutManager
if (lm is GridLayoutManager)
lm.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int =
if (isHeader(position) || isFooter(position)) lm.spanCount
else 1
}
}
override fun onViewAttachedToWindow(holder: BaseRecyclerHolder) {
super.onViewAttachedToWindow(holder)
val lp = holder.itemView.layoutParams
if (lp is StaggeredGridLayoutManager.LayoutParams)
lp.isFullSpan = isHeader(getRealPosition(holder)) || isFooter(getRealPosition(holder))
}
class BaseRecyclerHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
companion object {
private const val HEADER = 0x00100000
private const val FOOTER = 0x00200000
}
}
| 1
|
Kotlin
|
3
| 9
|
a3730f1758f8fe8d13cdd1d53045fa229f7e166d
| 8,718
|
Graduation_App
|
Apache License 2.0
|
runtime/src/commonMain/kotlin/space/jetbrains/api/runtime/SpaceAuth.kt
|
JetBrains
| 239,972,147
| false
| null |
package space.jetbrains.api.runtime
import io.ktor.client.HttpClient
import io.ktor.http.Parameters
import kotlinx.datetime.Instant
public interface SpaceAuth {
public suspend fun token(client: HttpClient, appInstance: SpaceAppInstance): SpaceTokenInfo
public class Token private constructor(
private val token: SpaceTokenInfo,
private val gapSecondsForExpiredCheck: Long = 5,
) : SpaceAuth {
public constructor(accessToken: String) : this(SpaceTokenInfo(accessToken, expires = null))
public constructor(
accessToken: String,
expires: Instant? = null,
gapSecondsForExpiredCheck: Long = 5,
) : this(SpaceTokenInfo(accessToken, expires), gapSecondsForExpiredCheck)
/** If token is expired, throws [TokenExpiredException] */
override suspend fun token(client: HttpClient, appInstance: SpaceAppInstance): SpaceTokenInfo {
if (token.expired(gapSeconds = gapSecondsForExpiredCheck)) throw TokenExpiredException()
return token
}
}
public class ClientCredentials(
scope: String = "**",
) : SpaceAuth by expiringTokenSourceAuth(getToken = { spaceClient, appInstance ->
auth(
ktorClient = spaceClient,
url = appInstance.spaceServer.oauthTokenUrl,
methodBody = Parameters.build {
append("grant_type", "client_credentials")
append("scope", scope)
},
authHeaderValue = "Basic " + base64("${appInstance.clientId}:${appInstance.clientSecret}"),
)
})
public class RefreshToken(
refreshToken: String,
scope: String,
) : SpaceAuth by expiringTokenSourceAuth(getToken = { spaceClient, appInstance ->
auth(
ktorClient = spaceClient,
url = appInstance.spaceServer.oauthTokenUrl,
methodBody = Parameters.build {
append("grant_type", "refresh_token")
append("refresh_token", value = refreshToken)
append("scope", value = scope)
},
authHeaderValue = "Basic " + base64("${appInstance.clientId}:${appInstance.clientSecret}"),
)
})
}
public class TokenExpiredException : Exception()
public fun expiringTokenSourceAuth(getToken: suspend (HttpClient, SpaceAppInstance) -> SpaceTokenInfo): SpaceAuth {
var currentToken: SpaceTokenInfo? = null
return object : SpaceAuth {
override suspend fun token(client: HttpClient, appInstance: SpaceAppInstance): SpaceTokenInfo {
val current = currentToken
return if (current?.expired() != false) {
getToken(client, appInstance).also { currentToken = it }
} else current
}
}
}
@Deprecated(
"Create SpaceClient with SpaceAuth.Token",
ReplaceWith(
"SpaceClient(this, serverUrl = serverUrl, token = token)",
"space.jetbrains.api.runtime.SpaceClient"
),
)
public fun HttpClient.withPermanentToken(token: String, serverUrl: String): SpaceClient =
SpaceClient(this, serverUrl = serverUrl, token = token)
@Deprecated(
"Create SpaceClient with SpaceAuth.ClientCredentials",
ReplaceWith(
"SpaceClient(this, InstalledApp(clientId, clientSecret, serverUrl), SpaceAuth.ClientCredentials(scope))",
"space.jetbrains.api.runtime.SpaceClient",
"space.jetbrains.api.runtime.InstalledApp"
),
)
public fun HttpClient.withServiceAccountTokenSource(
clientId: String,
clientSecret: String,
serverUrl: String,
scope: String = "**",
): SpaceClient = SpaceClient(this, SpaceAppInstance(clientId, clientSecret, serverUrl), SpaceAuth.ClientCredentials(scope))
@Deprecated("Use SpaceAuth", ReplaceWith("SpaceAuth"))
public typealias TokenSource = SpaceAuth
| 1
|
Kotlin
|
1
| 40
|
3784f0fb21026edcedf70f81cf4030fc74f0a126
| 3,835
|
space-kotlin-sdk
|
Apache License 2.0
|
pensjon-brevbaker-api-model/src/main/kotlin/no/nav/pensjon/brev/api/model/maler/legacy/vedtaksbrev/vedtaksdata/beregningsdata/beregningufore/beregningytelseskomp/BeregningYtelsesKomp.kt
|
navikt
| 375,334,697
| false
|
{"Kotlin": 3083129, "TypeScript": 433625, "TeX": 12813, "Shell": 8848, "CSS": 7595, "Python": 4661, "JavaScript": 4298, "Dockerfile": 2406, "HTML": 1053}
|
package no.nav.pensjon.brev.api.model.maler.legacy.vedtaksbrev.vedtaksdata.beregningsdata.beregningufore.beregningytelseskomp
data class BeregningYtelsesKomp(
val uforetrygdordiner: UforetrygdOrdiner?,
val barnetilleggfelles: BarnetilleggFelles?,
val barnetilleggserkull: BarnetilleggSerkull?,
val ektefelletillegg: Ektefelletillegg?,
val gjenlevendetillegg: Gjenlevendetillegg?,
)
| 4
|
Kotlin
|
3
| 1
|
b02455b82f8aa4ffed7ee4ad558dc57f784e9cd6
| 402
|
pensjonsbrev
|
MIT License
|
modules/transactions/sources-jvm/RaptorTransactionScope.kt
|
cybernetics
| 323,978,106
| true
|
{"Kotlin": 350742}
|
package io.fluidsonic.raptor
interface RaptorTransactionScope : RaptorScope {
@RaptorDsl
override val context: RaptorTransactionContext
}
| 0
| null |
0
| 0
|
19cf33c0c7ecae6ddc2fcef2387830d367ad52be
| 143
|
raptor
|
Apache License 2.0
|
influence-maximization/src/main/kotlin/seedcalculation/InputMessage.kt
|
fpeterek
| 432,835,229
| false
| null |
package org.fpeterek.pa.im.seedcalculation
import org.fpeterek.pa.im.graph.Node
sealed class InputMessage {
object End : InputMessage()
class NodeInfluence(val node: Node) : InputMessage()
}
| 0
|
Kotlin
|
0
| 0
|
9557c73bd66d58283c3b03a03a4ea024ccdcbd3a
| 201
|
parallel-algorithms
|
MIT License
|
app/src/main/java/com/example/espressorobot/ProfileActivity.kt
|
faruktoptas
| 115,795,521
| false
| null |
package com.example.espressorobot
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_profile.*
/**
* Created by ftoptas on 20/12/17.
*/
class ProfileActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
btnSettings.setOnClickListener { startActivity(Intent(this, SettingsActivity::class.java)) }
intent.data?.let {
Log.i("asd", "host: " + it.host)
Log.i("asd", "q: " + it.query)
it.queryParameterNames.forEach { Log.i("asd", "param: " + it) }
}
}
}
| 1
|
Kotlin
|
7
| 40
|
b35302df16ec22d28d613b5ee8bd118d5d2ffc74
| 771
|
espresso-robot-pattern-sample
|
Apache License 2.0
|
src/main/java/com/github/shynixn/blockball/enumeration/MenuCommand.kt
|
Shynixn
| 78,865,055
| false
| null |
package com.github.shynixn.blockball.api.business.enumeration
/**
* Created by Shynixn 2019.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2019 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
enum class MenuCommand(val key: MenuPageKey, private val internalCommand: String) {
BACK(MenuPageKey.OPEN, "back"),
CLOSE(MenuPageKey.OPEN, "close"),
OPEN(MenuPageKey.OPEN, ""),
ARENA_RELOAD(MenuPageKey.MAINCONFIGURATION, "reload"),
OPEN_EDIT_ARENA(MenuPageKey.OPEN, "edit-arenas"),
OPEN_DELETE_ARENA(MenuPageKey.OPEN, "delete-arenas"),
ARENA_CREATE(MenuPageKey.MAINCONFIGURATION, "create-arena"),
ARENA_EDIT(MenuPageKey.MAINCONFIGURATION, "edit-arena"),
ARENA_DELETE(MenuPageKey.MAINCONFIGURATION, "delete-arena"),
ARENA_MAINCONFIGURATION(MenuPageKey.MAINCONFIGURATION, "main-configuration"),
ARENA_SETDISPLAYNAME(MenuPageKey.MAINCONFIGURATION, "set-displayname"),
ARENA_ENABLE(MenuPageKey.MAINCONFIGURATION, "set-enable"),
ARENA_SETBALLSPAWNPOINT(MenuPageKey.MAINCONFIGURATION, "set-ballspawnpoint"),
ARENA_SETAREA(MenuPageKey.MAINCONFIGURATION, "set-area"),
ARENA_SETGOALRED(MenuPageKey.MAINCONFIGURATION, "set-goalred"),
ARENA_SETGOALBLUE(MenuPageKey.MAINCONFIGURATION, "set-goalblue"),
ARENA_SAVE(MenuPageKey.MAINCONFIGURATION, "save-arena"),
SETTINGS_OPEN(MenuPageKey.MAINSETTING, "open_settings"),
MATCHTIMES_OPEN(MenuPageKey.MATCHTIMES, "open_matcht"),
MATCHTIMES_CALLBACK(MenuPageKey.MATCHTIMES, "callback"),
MATCHTIMES_CALLBACKCLOSETYPE(MenuPageKey.MATCHTIMES, "callbclot"),
MATCHTIMES_CREATE(MenuPageKey.MATCHTIMES, "create"),
MATCHTIMES_DELETE(MenuPageKey.MATCHTIMES, "del"),
MATCHTIMES_DURATION(MenuPageKey.MATCHTIMES, "dur"),
MATCHTIMES_SWITCHGOAL(MenuPageKey.MATCHTIMES, "swgo"),
MATCHTIMES_CLOSECONDITION(MenuPageKey.MATCHTIMES, "clc"),
MATCHTIMES_BALLAVAILABLE(MenuPageKey.MATCHTIMES, "bav"),
MATCHTIMES_RESPAWN(MenuPageKey.MATCHTIMES, "res"),
MATCHTIMES_STARTSUBTITLEMESSAGE(MenuPageKey.MATCHTIMES, "sstlm"),
MATCHTIMES_STARTTITLEMESSAGE(MenuPageKey.MATCHTIMES, "stlm"),
TEAM_RED_CONFIGURE(MenuPageKey.TEAMMETA, "team_red"),
TEAM_BLUE_CONFIGURE(MenuPageKey.TEAMMETA, "team_blue"),
TEAM_NAME(MenuPageKey.TEAMMETA, "name"),
TEAM_PREFIX(MenuPageKey.TEAMMETA, "prefix"),
TEAM_SPAWNPOINT(MenuPageKey.TEAMMETA, "spawnpoint"),
TEAM_MINAMOUNT(MenuPageKey.TEAMMETA, "mina"),
TEAM_MAXAMOUNT(MenuPageKey.TEAMMETA, "maxa"),
TEAM_ARMOR(MenuPageKey.TEAMMETA, "armor"),
TEAM_INVENTORY(MenuPageKey.TEAMMETA, "invent"),
TEAM_WALKSPEED(MenuPageKey.TEAMMETA, "wspeed"),
TEAM_POINTSGOAL(MenuPageKey.TEAMMETA, "ppgoal"),
TEAM_POINTSDEATH(MenuPageKey.TEAMMETA, "ppdeath"),
TEAM_SIGN(MenuPageKey.TEAMMETA, "sign"),
TEAM_MSGLEAVE(MenuPageKey.TEAMMETA, "mleave"),
TEAM_MSGJOIN(MenuPageKey.TEAMMETA, "mjoin"),
TEAM_SCORETITLE(MenuPageKey.TEAMMETA, "sct"),
TEAM_SCORESUBTITLE(MenuPageKey.TEAMMETA, "scst"),
TEAM_WINTITLE(MenuPageKey.TEAMMETA, "wct"),
TEAM_WINSUBTITLE(MenuPageKey.TEAMMETA, "wcst"),
EFFECTS_OPEN(MenuPageKey.EFFECTS, "general"),
EFFECTS_BOSSBAR(MenuPageKey.EFFECTS, "bossbar"),
EFFECTS_HOLOGRAMS(MenuPageKey.EFFECTS, "holograms"),
EFFECTS_SCOREBOARD(MenuPageKey.EFFECTS, "scoreboard"),
MULTILINES_ANY(MenuPageKey.MULTIPLELINES, "any"),
MULTILINES_ADD(MenuPageKey.MULTIPLELINES, "add"),
MULTILINES_SET(MenuPageKey.MULTIPLELINES, "set"),
MULTILINES_REMOVE(MenuPageKey.MULTIPLELINES, "rmv"),
MULTILINES_SCOREBOARD(MenuPageKey.MULTIPLELINES, "show_scoreboard"),
MULTILINES_HOLOGRAM(MenuPageKey.MULTIPLELINES, "show_hologram"),
MULTILINES_TEAMSIGNTEMPLATE(MenuPageKey.MULTIPLELINES, "show_teamsign"),
MULTILINES_HUBGAMEJOINMESSAGE(MenuPageKey.MULTIPLELINES, "hubgame_join"),
MULTILINES_SPECTATEJOINMESSAGE(MenuPageKey.MULTIPLELINES, "minigame_spectate"),
BALL_OPEN(MenuPageKey.BALL, "open"),
BALL_SIZE_CALLBACK(MenuPageKey.BALL, "size-callback"),
BALL_PARTICLEACTION_CALLBACK(MenuPageKey.BALL, "part-callback"),
BALL_SOUNDACTION_CALLBACK(MenuPageKey.BALL, "sound-callback"),
BALL_SKIN(MenuPageKey.BALL, "skin"),
BALL_INTERACTION_HITBOX(MenuPageKey.BALL, "inhitbox"),
BALL_KICKPASS_HITBOX(MenuPageKey.BALL, "kphitbox"),
BALL_TOGGLE_CARRYABLE(MenuPageKey.BALL, "tgl-car"),
BALL_TOGGLE_ALWAYSBOUNCE(MenuPageKey.BALL, "tgl-bounce"),
BALL_TOGGLE_ROTATING(MenuPageKey.BALL, "tgl-rotate"),
BALL_INTERACT_COOLDOWN(MenuPageKey.BALL, "intrkp"),
BALL_KICKPASS_DELAY(MenuPageKey.BALL, "kpdelay"),
BALLMOD_OPEN(MenuPageKey.BALLMODIFIER, "open"),
BALLMOD_HORIZONTALTOUCH(MenuPageKey.BALLMODIFIER, "touch-horizontal"),
BALLMOD_VERTICALTOUCH(MenuPageKey.BALLMODIFIER, "touch-vertical"),
BALLMOD_SHOTVELOCITY(MenuPageKey.BALLMODIFIER, "shot-velocity"),
BALLMOD_PASSVELOCITY(MenuPageKey.BALLMODIFIER, "pass-velocity"),
BALLMOD_MAXSPIN(MenuPageKey.BALLMODIFIER, "max-spin"),
BALLMOD_MAXPITCH(MenuPageKey.BALLMODIFIER, "max-pitch"),
BALLMOD_MINPITCH(MenuPageKey.BALLMODIFIER, "min-pitch"),
BALLMOD_DEFAULTPITCH(MenuPageKey.BALLMODIFIER, "default-pitch"),
BALLMOD_GRAVITY(MenuPageKey.BALLMODIFIER, "gravity"),
BALLMOD_AIRRESISTANCE(MenuPageKey.BALLMODIFIER, "air-resistance"),
BALLMOD_ROLLINGRESISTANCE(MenuPageKey.BALLMODIFIER, "rolling-resistance"),
MULTIPLEITEMS_BOSSBAR(MenuPageKey.MULTIPLEITEMS, "show_bossbar"),
MULTIPLEITEMS_OPEN(MenuPageKey.MULTIPLEITEMS, "open"),
MULTIPLEITEMS_REMOVE(MenuPageKey.MULTIPLEITEMS, "rmv"),
SCOREBOARD_OPEN(MenuPageKey.SCOREBOARD, "open"),
SCOREBOARD_TOGGLE(MenuPageKey.SCOREBOARD, "tgl"),
SCOREBOARD_TITLE(MenuPageKey.SCOREBOARD, "title"),
ABILITIES_OPEN(MenuPageKey.ABILITIES, "open"),
DOUBLEJUMP_OPEN(MenuPageKey.DOUBLEJUMP, "open"),
DOUBLEJUMP_TOGGLE(MenuPageKey.DOUBLEJUMP, "tgl"),
DOUBLEJUMP_COOLDOWN(MenuPageKey.DOUBLEJUMP, "cool"),
DOUBLEJUMP_VERTICAL_STRENGTH(MenuPageKey.DOUBLEJUMP, "vstr"),
DOUBLEJUMP_HORIZONTAL_STRENGTH(MenuPageKey.DOUBLEJUMP, "hstr"),
HOLOGRAM_OPEN(MenuPageKey.HOLOGRAM, "open"),
HOLOGRAM_CALLBACK(MenuPageKey.HOLOGRAM, "callback"),
HOLOGRAM_CREATE(MenuPageKey.HOLOGRAM, "create"),
HOLOGRAM_DELETE(MenuPageKey.HOLOGRAM, "del"),
HOLOGRAM_LOCATION(MenuPageKey.HOLOGRAM, "loc"),
HOLOGRAM_TOGGLE(MenuPageKey.HOLOGRAM, "tgl"),
BOSSBAR_OPEN(MenuPageKey.BOSSBAR, "open"),
BOSSBAR_MESSAGE(MenuPageKey.BOSSBAR, "msg"),
BOSSBAR_PERCENT(MenuPageKey.BOSSBAR, "prc"),
BOSSBAR_TOGGLE(MenuPageKey.BOSSBAR, "tgl"),
BOSSBAR_CALLBACKFLAGS(MenuPageKey.BOSSBAR, "fla"),
BOSSBAR_CALLBACKCOLORS(MenuPageKey.BOSSBAR, "colo"),
GAMESETTINGS_CALLBACK_BUKKITGAMEMODES(MenuPageKey.GAMESETTINGS, "bukkitgame"),
GAMESETTINGS_OPEN(MenuPageKey.GAMESETTINGS, "open"),
GAMESETTINGS_MAXSCORE(MenuPageKey.GAMESETTINGS, "maxscore"),
GAMESETTINGS_MAXDURATION(MenuPageKey.GAMESETTINGS, "matchduration"),
GAMESETTINGS_LOBBYDURATION(MenuPageKey.GAMESETTINGS, "lobbyduration"),
GAMESETTINGS_BUNGEEKICKMESSAGE(MenuPageKey.GAMESETTINGS, "kickmes"),
GAMESETTINGS_BUNGEELEAVEKICKMESSAGE(MenuPageKey.GAMESETTINGS, "levkikmes"),
GAMESETTINGS_BUNGEEFALLBACKSERVER(MenuPageKey.GAMESETTINGS, "falbac"),
GAMESETTINGS_REMAININGPLAYERSMESSAGE(MenuPageKey.GAMESETTINGS, "remainmes"),
GAMESETTINGS_LEAVESPAWNPOINT(MenuPageKey.GAMESETTINGS, "lspawn"),
GAMESETTINGS_LOBBYSPAWNPOINT(MenuPageKey.GAMESETTINGS, "lobspawn"),
GAMESETTINGS_JOINMESSAGE(MenuPageKey.GAMESETTINGS, "joinm"),
GAMESETTINGS_TOGGLE_EVENTEAMS(MenuPageKey.GAMESETTINGS, "tlgeven"),
GAMESETTINGS_TOGGLE_RESETEMPTY(MenuPageKey.GAMESETTINGS, "resemp"),
GAMESETTINGS_TOGGLE_INSTATFORCEFIELD(MenuPageKey.GAMESETTINGS, "iforce"),
GAMESETTINGS_TOGGLE_TELEPORTONJOIN(MenuPageKey.GAMESETTINGS, "tglteleport"),
SIGNS_OPEN(MenuPageKey.SIGNS, "open"),
SIGNS_ADDTEAMRED(MenuPageKey.SIGNS, "adteamr"),
SIGNS_ADDJOINANY(MenuPageKey.SIGNS, "addjoin"),
SIGNS_LEAVE(MenuPageKey.SIGNS, "leave"),
SIGNS_ADDTEAMBLUE(MenuPageKey.SIGNS, "adteamb"),
PARTICLE_DOUBLEJUMP(MenuPageKey.PARTICLEFFECTS, "doub"),
SOUND_DOUBLEJUMP(MenuPageKey.SOUNDEFFECTS, "doub"),
PARTICLE_BALL(MenuPageKey.PARTICLEFFECTS, "ball-par"),
PARTICLE_CALLBACK_EFFECTING(MenuPageKey.PARTICLEFFECTS, "caleffecting"),
PARTICLE_CALLBACK_TYPE(MenuPageKey.PARTICLEFFECTS, "caltype"),
PARTICLE_OPEN(MenuPageKey.PARTICLEFFECTS, "open"),
PARTICLE_EFFECTING(MenuPageKey.PARTICLEFFECTS, "ef"),
PARTICLE_TYPE(MenuPageKey.PARTICLEFFECTS, "type"),
PARTICLE_AMOUNT(MenuPageKey.PARTICLEFFECTS, "amount"),
PARTICLE_SPEED(MenuPageKey.PARTICLEFFECTS, "speed"),
PARTICLE_OFFSET_X(MenuPageKey.PARTICLEFFECTS, "offx"),
PARTICLE_OFFSET_Y(MenuPageKey.PARTICLEFFECTS, "offy"),
PARTICLE_OFFSET_Z(MenuPageKey.PARTICLEFFECTS, "offz"),
SOUND_BALL(MenuPageKey.SOUNDEFFECTS, "ball-sound"),
SOUND_OPEN(MenuPageKey.SOUNDEFFECTS, "open"),
SOUND_EFFECTING(MenuPageKey.SOUNDEFFECTS, "ef"),
SOUND_TYPE(MenuPageKey.SOUNDEFFECTS, "type"),
SOUND_VOLUME(MenuPageKey.SOUNDEFFECTS, "volume"),
SOUND_PITCH(MenuPageKey.SOUNDEFFECTS, "pitch"),
SOUND_CALLBACK_EFFECTING(MenuPageKey.SOUNDEFFECTS, "caleffecting"),
SOUND_CALLBACK_TYPE(MenuPageKey.SOUNDEFFECTS, "caltype"),
REWARD_OPEN(MenuPageKey.REWARDSPAGE, "open"),
REWARD_EDIT_MONEY(MenuPageKey.REWARDSPAGE, "money"),
REWARD_EDIT_COMMAND(MenuPageKey.REWARDSPAGE, "command"),
REWARD_CALLBACK_MONEY(MenuPageKey.REWARDSPAGE, "calmoney"),
REWARD_CALLBACK_COMMAND(MenuPageKey.REWARDSPAGE, "calcommand"),
REWARD_CALLBACK_COMMANDMODE(MenuPageKey.REWARDSPAGE, "calcommode"),
SPECTATOR_OPEN(MenuPageKey.SPECTATING, "open"),
SPECTATE_OPEN(MenuPageKey.SPECTATE, "open"),
SPECTATE_TOGGLE(MenuPageKey.SPECTATE, "tgl-sp"),
SPECTATE_SPAWNPOINT(MenuPageKey.SPECTATE, "spawn"),
MISC_OPEN(MenuPageKey.MISC, "open"),
GAMEPROPERTIES_OPEN(MenuPageKey.GAMEEXTENSIONS, "open"),
GAMEPROPERTIES_TOGGLE_BALLFORCEFIELD(MenuPageKey.GAMEEXTENSIONS, "tglbaf"),
GAMEPROPERTIES_TOGGLE_DAMAGE(MenuPageKey.GAMEEXTENSIONS, "tglda"),
GAMEPROPERTIES_TOGGLE_EVENTEAMS(MenuPageKey.GAMEEXTENSIONS, "tgle"),
GAMEPROPERTIES_TOGGLE_TELEPORTBACK(MenuPageKey.GAMEEXTENSIONS, "tgltelback"),
GAMEPROPERTIES_TOGGLE_KEEPINVENTORY(MenuPageKey.GAMEEXTENSIONS, "tglkeepinv"),
GAMEPROPERTIES_TELEPORTBACKDELAY(MenuPageKey.GAMEEXTENSIONS, "telbackdelay"),
NOTIFICATIONS_OPEN(MenuPageKey.NOTIFICATIONS, "open"),
NOTIFICATIONS_TOGGLE(MenuPageKey.NOTIFICATIONS, "togl"),
NOTIFICATIONS_RADIUS(MenuPageKey.NOTIFICATIONS, "radius"),
AREAPROTECTION_OPEN(MenuPageKey.AREAPROTECTION, "open"),
AREAPROTECTION_TOGGLE_ENTITYFORCEFIELD(MenuPageKey.AREAPROTECTION, "enforce"),
AREAPROTECTION_SET_ENTITYFORCEFIELD(MenuPageKey.AREAPROTECTION, "enprot"),
AREAPROTECTION_TOGGLE_PLAYERJOINFORCEFIELD(MenuPageKey.AREAPROTECTION, "plforce"),
AREAPROTECTION_SET_PLAYERJOINFORCEFIELD(MenuPageKey.AREAPROTECTION, "plprot"),
TEXTBOOK_OPEN(MenuPageKey.TEAMTEXTBOOK, "open"),
TEXTBOOK_JOINMESSAGE(MenuPageKey.TEAMTEXTBOOK, "join"),
TEXTBOOK_LEAVEMESSAGE(MenuPageKey.TEAMTEXTBOOK, "leave"),
TEXTBOOK_SCORETIELE(MenuPageKey.TEAMTEXTBOOK, "scoretitle"),
TEXTBOOK_SCORESUBTITLE(MenuPageKey.TEAMTEXTBOOK, "scorestitle"),
TEXTBOOK_WINTIELE(MenuPageKey.TEAMTEXTBOOK, "wintitle"),
TEXTBOOK_WINSUBTITLE(MenuPageKey.TEAMTEXTBOOK, "winstitle"),
TEXTBOOK_DRAWTIELE(MenuPageKey.TEAMTEXTBOOK, "drawtitle"),
TEXTBOOK_DRAWSUBTITLE(MenuPageKey.TEAMTEXTBOOK, "drawstitle"),
TEMPLATE_OPEN(MenuPageKey.TEMPLATEPAGE, "open"),
TEMPLATE_SELECT_CALLBACK(MenuPageKey.TEMPLATEPAGE, "calls"),
LIST_TEMPLATES(MenuPageKey.LISTABLE, "show_templates"),
LIST_BUKKITGAMESMODES(MenuPageKey.LISTABLE, "show_bukkitgamemodes"),
LIST_BALL_SOUNDEFFECTS(MenuPageKey.LISTABLE, "show_ballsounds"),
LIST_BALL_PARTICLEFFECTS(MenuPageKey.LISTABLE, "show_ballparticles"),
LIST_LINES(MenuPageKey.LISTABLE, "show_lines"),
LIST_COMMANDMODES(MenuPageKey.LISTABLE, "show_commandmodes"),
LIST_BALLSIZES(MenuPageKey.LISTABLE, "show_ballsizes"),
LIST_PARTICLE_EFFECTINGTYPES(MenuPageKey.LISTABLE, "particlef"),
LIST_PARTICLE_TYPES(MenuPageKey.LISTABLE, "particles"),
LIST_SOUND_TYPES(MenuPageKey.LISTABLE, "sounds"),
LIST_REWARDED_MONEY(MenuPageKey.LISTABLE, "rewmoney"),
LIST_REWARDED_COMMAND(MenuPageKey.LISTABLE, "recommand"),
LIST_SOUND_EFFECTINGTYPES(MenuPageKey.LISTABLE, "soundf"),
LIST_BOSSBARFLAGS(MenuPageKey.LISTABLE, "show_bossbarflags"),
LIST_BOSSBARSTYLES(MenuPageKey.LISTABLE, "show_bossbarstyles"),
LIST_BOSSBARCOLORS(MenuPageKey.LISTABLE, "show_bossbarcolors"),
LIST_HOLOGRAMS(MenuPageKey.LISTABLE, "show_holograms"),
LIST_GAMETYPES(MenuPageKey.LISTABLE, "show_gametypes"),
LIST_MATCHTIMES(MenuPageKey.LISTABLE, "show_matchtimes"),
LIST_MATCHCLOSETYPES(MenuPageKey.LISTABLE, "show_closetypes")
;
/**
* Gets the command.
*/
val command: String
get() {
return "/blockball " + this.key.key + ' '.toString() + this.internalCommand + ' '.toString()
}
companion object {
/**
* Generates a menu command from args.
*/
fun from(args: Array<out String>): MenuCommand? {
if (args.isEmpty()) {
return OPEN
}
if (args.isNotEmpty()) {
for (command in MenuCommand.values()) {
if (command.key.key.equals(args[0], ignoreCase = true) && command.internalCommand.equals(args[1], ignoreCase = true)) {
return command
}
}
}
return null
}
}
}
| 6
| null |
26
| 67
|
a79f7a7bb1c58d27607281754b3f6e45466891fc
| 14,933
|
BlockBall
|
Apache License 2.0
|
app/src/main/java/com/example/bysj2020/base/BaseFragment.kt
|
Xingzuo888
| 238,856,307
| false
|
{"Kotlin": 319568, "Java": 159225}
|
package com.example.bysj2020.base
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleObserver
import com.example.bysj2020.statelayout.EmptyView
import com.example.bysj2020.statelayout.ErrorView
import com.example.bysj2020.statelayout.LoadHelper
import com.example.bysj2020.statelayout.LoadingView
import io.reactivex.disposables.CompositeDisposable
/**
* Author : wxz
* Time : 2020/02/16
* Desc : BaseFragment
*/
abstract class BaseFragment : Fragment(), View.OnTouchListener, View.OnClickListener {
/**
* 控件是否初始化完成
*/
private var isViewInitiated: Boolean = false
/**
* 页面是否显示
*/
private var isVisibleToUser: Boolean = false
/**
* 数据是否加载
*/
var isDataInitiated: Boolean = false
private var mActivity: AppCompatActivity? = null
private var rootView: View? = null
private var helper: LoadHelper? = null
var compositeDisposable = CompositeDisposable()
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser && isResumed) {
onResume()
}
this.isVisibleToUser = isVisibleToUser
prepareFetchData(false)
}
private fun prepareFetchData(forceUpdate: Boolean) {
if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
loadData()
isDataInitiated = true
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
this.mActivity = context as AppCompatActivity
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(getLayoutId(), container, false)
return rootView
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
isViewInitiated = true
prepareFetchData(false)
setViewClick()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
}
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when (event?.action) {
MotionEvent.ACTION_DOWN -> v?.alpha = 0.5f
MotionEvent.ACTION_UP -> v?.alpha = 1.0f
}
return false
}
/**
* 加入生命周期管理
*/
fun addLifecycle(observer: LifecycleObserver) {
lifecycle.addObserver(observer)
}
/**
* 空布局、网络异常布局、点击事件初始化
*/
fun initStateLayout(click: LoadHelper.EmptyClickListener) {
helper = mActivity?.let {
LoadHelper.Builder(it)
.setContentView(getContentView())
.setEmptyView(getEmptyView())
.setErrorView(getErrorView())
.setLoadingView(getLoadingView())
.build()
}
helper?.init()
helper?.addEmptyClickListener(click)
}
/**
* 设置内容视图布局
*/
open fun getContentView(): View? {
return if (rootView is ViewGroup) {
(rootView as ViewGroup).getChildAt(0)
} else {
rootView
}
}
/**
* 空布局
*/
private fun getEmptyView(): EmptyView {
return EmptyView(mActivity!!)
}
/**
* 空布局
*/
fun getCurrEmptyView(): EmptyView {
return helper!!.getEmptyView()
}
/**
* 网络错误布局
*/
private fun getErrorView(): ErrorView {
return ErrorView(mActivity!!)
}
/**
* 加载中布局
*/
private fun getLoadingView(): LoadingView {
return LoadingView(mActivity!!)
}
/**
* 显示内容布局
*/
fun showContent() {
helper?.showContent()
}
/**
* 显示错误布局
*/
fun showError() {
helper?.showError()
}
/**
* 显示错误布局
*/
fun showError(title:String,content:String) {
helper?.showError(title,content)
}
/**
* 显示空布局
*/
fun showEmpty() {
helper?.showEmpty()
}
/**
* 显示加载中布局
*/
fun showLoading() {
helper?.showLoading()
}
/**
* 是否正常显示内容
*/
fun isShowContent(): Boolean {
return helper!!.isShowContent()
}
/**
* toast提示
* @param msg 提示内容
*/
fun showToast(msg: String) {
if (null != mActivity) {
Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show()
}
}
/**
* 加载数据
*/
abstract fun loadData()
/**
* 设置监听
*/
abstract fun setViewClick()
/**
* 页面布局id
*/
protected abstract fun getLayoutId(): Int
/**
* 视图初始化
*/
protected abstract fun initViews()
override fun onDetach() {
super.onDetach()
mActivity = null
}
override fun onDestroy() {
compositeDisposable.clear()
super.onDestroy()
}
/**
* 隐藏软键盘
*/
fun hideKeyboard(view: View) {
val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
/**
* 隐藏软键盘
*/
fun hideKeyboard() {
val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(activity?.window?.decorView?.windowToken, 0)
}
}
| 0
|
Kotlin
|
0
| 0
|
a734212631b74f6a28a98379e4109d28b26d9693
| 5,765
|
bysj2020
|
Apache License 2.0
|
app/src/main/java/com/spitchenko/pokeapp/feature/list/presentation/model/ProgressUiModel.kt
|
Onotole1
| 212,967,916
| false
| null |
package com.spitchenko.pokeapp.feature.list.presentation.model
import androidx.databinding.ViewDataBinding
import com.spitchenko.pokeapp.component.binderadapter.BindingClass
import kotlinx.android.parcel.Parcelize
private const val DEFAULT_ID = 3490343L
@Parcelize
object ProgressUiModel : BindingClass {
@Suppress("PLUGIN_WARNING")
override val itemId: Long = DEFAULT_ID
override fun bind(viewDataBinding: ViewDataBinding) = Unit
}
| 1
|
Kotlin
|
0
| 1
|
e8576bd4aa9bb91b5ea82d9c79b6f1fc2290e3d2
| 449
|
PokeApp
|
Apache License 2.0
|
app/src/main/java/io/mainframe/hacs/ssh/RunSshAsync.kt
|
ktt-ol
| 75,970,953
| false
|
{"Kotlin": 111905, "HTML": 4091, "JavaScript": 1200}
|
package io.mainframe.hacs.ssh
import android.os.AsyncTask
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import io.mainframe.hacs.common.Constants.DoorServer
import org.pmw.tinylog.Logger
import java.io.ByteArrayOutputStream
import java.util.Locale
import java.util.Properties
/**
* Created by holger on 09.11.15.
*/
class RunSshAsync(
private val onSshFinish: (Result) -> Unit,
private val server: DoorServer,
private val credentials: PkCredentials,
private val command: DoorCommand,
private val checkServerFingerprint: Boolean
) : AsyncTask<Void, Void, RunSshAsync.Result>() {
@Deprecated("Deprecated in Java")
override fun doInBackground(vararg voids: Void): Result {
val jsch = JSch()
try {
val privateKey =
checkNotNull(credentials.privateKey) { "Expected a private key to be set here." }
val password =
checkNotNull(credentials.password) { "Expected a password to be set here." }
jsch.addIdentity(
privateKey.name,
privateKey.data,
null,
password.toByteArray()
)
val session = jsch.getSession(server.user, server.host, server.port)
// Avoid asking for key confirmation
val prop = Properties().apply {
this["StrictHostKeyChecking"] = "no"
}
session.setConfig(prop)
session.connect()
val hostKey = session.hostKey.getFingerPrint(jsch)
Logger.debug("Server host key: {}", hostKey)
if (this.checkServerFingerprint && !server.hostKey.equals(hostKey, ignoreCase = true)) {
session.disconnect()
val msg =
"Invalid host key. Expected '${server.hostKey.uppercase(Locale.getDefault())}', " +
"but got '${hostKey.uppercase(Locale.getDefault())}' instead."
Logger.info(msg)
return Result(command.get(), Status.WRONG_HOST_KEY, msg)
}
// SSH Channel
val channelssh = session.openChannel("exec") as ChannelExec
val errorOut = ByteArrayOutputStream()
channelssh.setErrStream(errorOut)
// Execute command
Logger.debug("ssh exec: {}", command.get())
channelssh.setCommand(command.get())
channelssh.connect()
channelssh.start()
val resultStr = channelssh.inputStream.bufferedReader().use { it.readText() }
channelssh.disconnect()
val errorStr = errorOut.toString("utf8")
Logger.debug("ssh output: {}", resultStr)
if (errorStr.isNotEmpty()) {
Logger.warn("ssh error output: {}, ", errorStr)
return Result(command.get(), Status.UNKNOWN_ERROR, errorStr)
}
return Result(command.get(), Status.SUCCESS, resultStr)
} catch (e: Exception) {
val msg = "Error running ssh: ${e.message}"
Logger.error(e, msg)
return Result(command.get(), Status.UNKNOWN_ERROR, msg)
}
}
@Deprecated("Deprecated in Java")
override fun onPostExecute(result: Result) {
onSshFinish(result)
}
enum class Status {
SUCCESS, UNKNOWN_ERROR, WRONG_HOST_KEY
}
data class Result(val command: String, val status: Status, val msg: String)
}
| 9
|
Kotlin
|
2
| 24
|
436a68ca87ec2e187811ea002d5d3d7e71116f74
| 3,473
|
hacs
|
MIT License
|
app/src/main/java/com/shashank/anywheregpt/data/interceptors/AuthInterceptor.kt
|
Shashank02051997
| 623,487,054
| false
|
{"Kotlin": 59143}
|
package com.shashank.anywheregpt.data.interceptors
import android.content.Context
import com.shashank.anywheregpt.utils.SharedPref
import okhttp3.Interceptor
import okhttp3.Response
import timber.log.Timber
/**
* Interceptor to add auth token to requests
*/
class AuthInterceptor(private val context: Context) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val requestBuilder = chain.request().newBuilder()
val apiKey = SharedPref.getStringPref(context, SharedPref.KEY_API_KEY)
if (apiKey.isNotBlank()) {
Timber.i("Token = Bearer $apiKey")
requestBuilder.addHeader("Authorization", "Bearer $apiKey")
}
return chain.proceed(requestBuilder.build())
}
}
| 11
|
Kotlin
|
14
| 92
|
f0254ac6768d41724f8a6d71c494243c9ec923ad
| 758
|
AnywhereGPT-Android
|
Apache License 2.0
|
lib/src/main/java/com/drew/imaging/png/PngHeader.kt
|
baelec
| 231,688,360
| false
|
{"Git Config": 1, "Gradle": 4, "Markdown": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "YAML": 1, "Java Properties": 1, "CSS": 1, "SVG": 2, "Java": 60, "Kotlin": 362, "DIGITAL Command Language": 3}
|
/*
* Copyright 2002-2019 <NAME> and contributors
*
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.imaging.png
import com.drew.imaging.png.PngColorType.Companion.fromNumericValue
import com.drew.lang.SequentialByteArrayReader
import com.drew.lang.SequentialReader
import java.io.IOException
/**
* @author <NAME> https://drewnoakes.com
*/
class PngHeader(bytes: ByteArray) {
var imageWidth = 0
var imageHeight = 0
var bitsPerSample: Byte = 0
val colorType: PngColorType
var compressionType: Byte = 0
var filterMethod: Byte = 0
var interlaceMethod: Byte = 0
init {
if (bytes.size != 13) {
throw PngProcessingException("PNG header chunk must have 13 data bytes")
}
val reader: SequentialReader = SequentialByteArrayReader(bytes)
try {
imageWidth = reader.getInt32()
imageHeight = reader.getInt32()
bitsPerSample = reader.getInt8()
val colorTypeNumber = reader.getInt8()
val colorType = fromNumericValue(colorTypeNumber.toInt())
?: throw PngProcessingException("Unexpected PNG color type: $colorTypeNumber")
this.colorType = colorType
compressionType = reader.getInt8()
filterMethod = reader.getInt8()
interlaceMethod = reader.getInt8()
} catch (e: IOException) {
// Should never happen
throw PngProcessingException(e)
}
}
}
| 1
| null |
1
| 1
|
2df8efc24efa24aca040bc4f392d9b9285d23369
| 2,062
|
metadata-extractor
|
Apache License 2.0
|
rest-api-server/src/main/kotlin/eu/tib/orkg/prototype/statements/adapter/output/neo4j/spring/internal/Neo4jPredicate.kt
|
TIBHannover
| 197,416,205
| false
| null |
package eu.tib.orkg.prototype.statements.adapter.output.neo4j.spring.internal
import com.fasterxml.jackson.annotation.JsonIgnore
import eu.tib.orkg.prototype.contributions.domain.model.ContributorId
import eu.tib.orkg.prototype.statements.domain.model.Predicate
import eu.tib.orkg.prototype.statements.domain.model.PredicateId
import eu.tib.orkg.prototype.statements.domain.model.neo4j.AuditableEntity
import eu.tib.orkg.prototype.statements.domain.model.neo4j.Neo4jThing
import eu.tib.orkg.prototype.statements.domain.model.neo4j.mapping.ContributorIdConverter
import eu.tib.orkg.prototype.statements.domain.model.toRdfModel
import org.neo4j.ogm.annotation.GeneratedValue
import org.neo4j.ogm.annotation.Id
import org.neo4j.ogm.annotation.NodeEntity
import org.neo4j.ogm.annotation.Property
import org.neo4j.ogm.annotation.Relationship
import org.neo4j.ogm.annotation.Required
import org.neo4j.ogm.annotation.typeconversion.Convert
@NodeEntity(label = "Predicate")
data class Neo4jPredicate(
@Id
@GeneratedValue
var id: Long? = null,
@Property("label")
@Required
override var label: String? = null,
@Property("predicate_id")
@Required
@Convert(PredicateIdConverter::class)
private var predicateId: PredicateId? = null,
@Property("created_by")
@Convert(ContributorIdConverter::class)
var createdBy: ContributorId = ContributorId.createUnknownContributor(),
@Relationship(type = "RELATED", direction = Relationship.OUTGOING)
@JsonIgnore
var subjectOf: MutableSet<Neo4jStatement> = mutableSetOf()
) : Neo4jThing, AuditableEntity() {
fun toPredicate(): Predicate {
val pred = Predicate(predicateId, label!!, createdAt!!, createdBy = createdBy)
pred.rdf = pred.toRdfModel() // TODO: not ideal, find a better way
if (subjectOf.isNotEmpty())
pred.description = subjectOf.firstOrNull { it.predicateId?.value == "description" }?.`object`?.label
return pred
}
override val thingId: String?
get() = predicateId?.value
override fun toThing() = toPredicate()
}
| 0
|
Kotlin
|
1
| 3
|
9612eddb54c2427d7d5ae20b25dd5402aec79771
| 2,090
|
orkg-backend
|
MIT License
|
app/src/main/java/com/devmanishpatole/githubusers/adapter/UserLoadStateAdapter.kt
|
devmanishpatole
| 310,791,098
| false
| null |
package com.devmanishpatole.githubusers.adapter
import android.view.ViewGroup
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import com.devmanishpatole.githubusers.viewholder.UserLoadStateViewHolder
/**
* Adapter to handle lazy loading buffering and error.
*/
class UserLoadStateAdapter(private val retry: () -> Unit) :
LoadStateAdapter<UserLoadStateViewHolder>() {
override fun onBindViewHolder(holder: UserLoadStateViewHolder, loadState: LoadState) =
holder.bind(loadState)
override fun onCreateViewHolder(
parent: ViewGroup,
loadState: LoadState
) = UserLoadStateViewHolder.create(parent, retry)
}
| 0
|
Kotlin
|
0
| 0
|
7984da2938e993508f3bd2bb7003d5cfbdf86a2e
| 672
|
SearchGitHubUsers
|
MIT License
|
kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/spec/annotation/AnnotationSpecBeforeAfterTest.kt
|
kotest
| 47,071,082
| false
| null |
package com.sksamuel.kotest.engine.spec.annotation
import io.kotest.core.annotation.AutoScan
import io.kotest.core.listeners.TestListener
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.Spec
import io.kotest.core.spec.style.AnnotationSpec
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestCaseOrder
import io.kotest.core.test.TestResult
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.delay
import java.util.concurrent.atomic.AtomicInteger
import kotlin.reflect.KClass
class AnnotationSpecBeforeAfterTest : AnnotationSpec() {
companion object {
var counterBeforeAll = AtomicInteger(0)
var counterBeforeEach = AtomicInteger(0)
var counterAfterAll = AtomicInteger(0)
var counterAfterEach = AtomicInteger(0)
}
// All annotations are repeated sometimes, to validate that all annotations are correctly read by the engine
@BeforeAll
fun beforeSpec1() {
counterBeforeAll.incrementAndGet()
}
@BeforeClass
fun beforeSpec2() = counterBeforeAll.incrementAndGet()
@BeforeEach
fun beforeTest1() {
counterBeforeEach.incrementAndGet()
}
@Before
fun beforeTest2() = counterBeforeEach.incrementAndGet()
@Before
suspend fun beforeSuspendTest() {
delay(10)
counterBeforeEach.incrementAndGet()
}
@AfterEach
fun afterTest1() = counterAfterEach.incrementAndGet()
@After
fun afterTest2() = counterAfterEach.incrementAndGet()
@After
suspend fun afterSuspendTest() {
delay(10)
counterAfterEach.incrementAndGet()
}
@AfterAll // You're my wonderwall
fun afterSpec1() {
counterAfterAll.incrementAndGet()
}
@AfterClass
fun afterSpec2() {
counterAfterAll.incrementAndGet()
}
// Testing depends on method discovery happening in this order, verifying the assertions in the order tests are declared
@Test
fun test1() {
counterBeforeAll.get() shouldBe 2 // Both BeforeSpec should be executed once
counterBeforeEach.get() shouldBe 3 // All 3 BeforeTest should be executed once
// No tests finished executing yet, both should be 0
counterAfterAll.get() shouldBe 0
counterAfterEach.get() shouldBe 0
}
@Test
fun test2() {
counterBeforeAll.get() shouldBe 2 // BeforeSpecs should not be executed again
counterBeforeEach.get() shouldBe 6 // Before tests should be executed twice (test1 + test2)
counterAfterAll.get() shouldBe 0 // Not all tests finished yet, it shouldn't have executed
counterAfterEach.get() shouldBe 3 // AfterTest should be executed (after test1)
}
@Test
fun test3() {
counterBeforeAll.get() shouldBe 2
counterBeforeEach.get() shouldBe 9
counterAfterAll.get() shouldBe 0
counterAfterEach.get() shouldBe 6 // three sets of after test executed for test1/test2
}
override fun isolationMode() = IsolationMode.SingleInstance
override fun testCaseOrder() = TestCaseOrder.Sequential
}
@AutoScan
object AssertionListener : TestListener {
override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) {
if (kclass == AnnotationSpecBeforeAfterTest::class) {
AnnotationSpecBeforeAfterTest.counterBeforeEach.get() shouldBe 6
AnnotationSpecBeforeAfterTest.counterBeforeAll.get() shouldBe 2
AnnotationSpecBeforeAfterTest.counterAfterEach.get() shouldBe 6
AnnotationSpecBeforeAfterTest.counterAfterAll.get() shouldBe 2
}
}
}
| 51
| null |
648
| 4,435
|
2ce83d0f79e189c90e2d7bb3d16bd4f75dec9c2f
| 3,529
|
kotest
|
Apache License 2.0
|
src/commonMain/kotlin/org/angproj/crypt/sec/Sect409Koblitz1.kt
|
angelos-project
| 677,062,617
| false
|
{"Kotlin": 18071377}
|
/**
* Copyright (c) 2023 by <NAME> <<EMAIL>>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* <NAME> - initial implementation
*/
package org.angproj.crypt.sec
import org.angproj.crypt.number.BigInt
public object Sect409Koblitz1 : SecTKoblitz {
public override val name: String = "sect409k1"
public override val strength: Int = 192
public override val size: Int = 409
private val _a: BigInt by fromHex {
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000"
}
private val _b: BigInt by fromHex {
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000001"
}
private val _G: BigInt by fromHex {
"03" +
"0060F05F" +
"658F49C1" +
"AD3AB189" +
"0F718421" +
"0EFD0987" +
"E307C84C" +
"27ACCFB8" +
"F9F67CC2" +
"C460189E" +
"B5AAAA62" +
"EE222EB1" +
"B35540CF" +
"E9023746"
}
private val _Gc: Pair<BigInt, BigInt> by xyFromHex {
"04" +
"0060F05F" +
"658F49C1" +
"AD3AB189" +
"0F718421" +
"0EFD0987" +
"E307C84C" +
"27ACCFB8" +
"F9F67CC2" +
"C460189E" +
"B5AAAA62" +
"EE222EB1" +
"B35540CF" +
"E9023746" +
"01E36905" +
"0B7C4E42" +
"ACBA1DAC" +
"BF04299C" +
"3460782F" +
"918EA427" +
"E6325165" +
"E9EA10E3" +
"DA5F6C42" +
"E9C55215" +
"AA9CA27A" +
"5863EC48" +
"D8E0286B"
}
private val _n: BigInt by fromHex {
"7FFFFF" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFE5F" +
"83B2D4EA" +
"20400EC4" +
"557D5ED3" +
"E3E7CA5B" +
"4B5C83B8" +
"E01E5FCF"
}
private val _h: BigInt by fromHex {
"04"
}
override val a: BigInt
get() = _a.copyOf()
override val b: BigInt
get() = _b.copyOf()
override val G: BigInt
get() = _G.copyOf()
override val Gc: Pair<BigInt, BigInt>
get() = _Gc.copy()
override val n: BigInt
get() = _n.copyOf()
override val h: BigInt
get() = _h.copyOf()
}
| 0
|
Kotlin
|
0
| 0
|
ed191fa0bc60aa5ed01fe8ef63a86c742890d243
| 3,562
|
angelos-project-crypt
|
MIT License
|
src/commonMain/kotlin/org/angproj/crypt/sec/Sect409Koblitz1.kt
|
angelos-project
| 677,062,617
| false
|
{"Kotlin": 18071377}
|
/**
* Copyright (c) 2023 by <NAME> <<EMAIL>>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* <NAME> - initial implementation
*/
package org.angproj.crypt.sec
import org.angproj.crypt.number.BigInt
public object Sect409Koblitz1 : SecTKoblitz {
public override val name: String = "sect409k1"
public override val strength: Int = 192
public override val size: Int = 409
private val _a: BigInt by fromHex {
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000"
}
private val _b: BigInt by fromHex {
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000000" +
"00000001"
}
private val _G: BigInt by fromHex {
"03" +
"0060F05F" +
"658F49C1" +
"AD3AB189" +
"0F718421" +
"0EFD0987" +
"E307C84C" +
"27ACCFB8" +
"F9F67CC2" +
"C460189E" +
"B5AAAA62" +
"EE222EB1" +
"B35540CF" +
"E9023746"
}
private val _Gc: Pair<BigInt, BigInt> by xyFromHex {
"04" +
"0060F05F" +
"658F49C1" +
"AD3AB189" +
"0F718421" +
"0EFD0987" +
"E307C84C" +
"27ACCFB8" +
"F9F67CC2" +
"C460189E" +
"B5AAAA62" +
"EE222EB1" +
"B35540CF" +
"E9023746" +
"01E36905" +
"0B7C4E42" +
"ACBA1DAC" +
"BF04299C" +
"3460782F" +
"918EA427" +
"E6325165" +
"E9EA10E3" +
"DA5F6C42" +
"E9C55215" +
"AA9CA27A" +
"5863EC48" +
"D8E0286B"
}
private val _n: BigInt by fromHex {
"7FFFFF" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFE5F" +
"83B2D4EA" +
"20400EC4" +
"557D5ED3" +
"E3E7CA5B" +
"4B5C83B8" +
"E01E5FCF"
}
private val _h: BigInt by fromHex {
"04"
}
override val a: BigInt
get() = _a.copyOf()
override val b: BigInt
get() = _b.copyOf()
override val G: BigInt
get() = _G.copyOf()
override val Gc: Pair<BigInt, BigInt>
get() = _Gc.copy()
override val n: BigInt
get() = _n.copyOf()
override val h: BigInt
get() = _h.copyOf()
}
| 0
|
Kotlin
|
0
| 0
|
ed191fa0bc60aa5ed01fe8ef63a86c742890d243
| 3,562
|
angelos-project-crypt
|
MIT License
|
src/main/kotlin/com/github/rafaelldi/tyeplugin/settings/TyeSettingsConfigurable.kt
|
rohan-buechner
| 399,365,891
| true
|
{"Kotlin": 77343, "Java": 6341}
|
package com.github.rafaelldi.tyeplugin.settings
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project
import javax.swing.JComponent
class TyeSettingsConfigurable(private val project: Project) : Configurable {
private val component = TyeSettingsComponent()
override fun createComponent(): JComponent = component.getPanel()
override fun getPreferredFocusedComponent(): JComponent = component.getPreferredFocusedComponent()
override fun isModified(): Boolean {
val settings = TyeSettingsState.getInstance(project)
return (component.getTyeToolPath() != settings.tyeToolPath) or
(component.getOverwriteTyeFile() != settings.overwriteTyeFile) or
(component.getCheckTyeNewVersions() != settings.checkTyeNewVersions)
}
override fun apply() {
val settings = TyeSettingsState.getInstance(project)
settings.tyeToolPath = component.getTyeToolPath()
settings.tyeHost = component.getTyeHost()
settings.overwriteTyeFile = component.getOverwriteTyeFile()
settings.checkTyeNewVersions = component.getCheckTyeNewVersions()
}
override fun reset() {
val settings = TyeSettingsState.getInstance(project)
component.setTyeToolPath(settings.tyeToolPath)
component.setTyeHost(settings.tyeHost)
component.setOverwriteTyeFile(settings.overwriteTyeFile)
component.setCheckTyeNewVersions(settings.checkTyeNewVersions)
}
override fun getDisplayName(): String = "Tye"
}
| 0
|
Kotlin
|
0
| 0
|
6cfe645b1360a700085d17a450e59c80ec654e6e
| 1,554
|
tye-plugin
|
MIT License
|
app/src/main/java/de/dkutzer/tcgwatcher/settings/presentation/SettingsScreen.kt
|
HaVonTe1
| 718,649,216
| false
|
{"Kotlin": 177630, "HTML": 103411}
|
package de.dkutzer.tcgwatcher.settings.presentation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.MutableCreationExtras
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.compose.TCGWatcherTheme
import de.dkutzer.tcgwatcher.R
import de.dkutzer.tcgwatcher.settings.data.SettingsDatabase
import de.dkutzer.tcgwatcher.settings.data.SettingsRepositoryImpl
import de.dkutzer.tcgwatcher.settings.domain.Engines
import de.dkutzer.tcgwatcher.settings.domain.Languages
import de.dkutzer.tcgwatcher.settings.domain.SettingsRepository
import de.dkutzer.tcgwatcher.settings.presentation.components.SettingsView
import io.github.oshai.kotlinlogging.KotlinLogging
private val logger = KotlinLogging.logger {}
@Composable
fun SettingsScreen() {
val availableLanguages = mapOf(
Languages.DE to stringResource(id = R.string.german) ,
Languages.EN to stringResource(id = R.string.english))
val availableEngines = Engines.entries.map { it.displayName }.toList()
val context = LocalContext.current
val settingsRepository: SettingsRepository by lazy {
SettingsRepositoryImpl(SettingsDatabase.getDatabase(context).settingsDao)
}
val settingsViewModel = viewModel<SettingsViewModel>(
factory = SettingsViewModel.Factory,
extras = MutableCreationExtras().apply {
set(SettingModelCreationKeys.LanguagesIdKey, availableLanguages)
set(SettingModelCreationKeys.SettingsRepoIdKey, settingsRepository)
}
)
val setingsState = settingsViewModel.uiState.collectAsState()
SettingsView(
settingsState = setingsState.value,
availableLanguages = availableLanguages,
availableEngines = availableEngines,
onLanguageChanged = {
val key =
availableLanguages.entries.find { entry -> entry.value.compareTo(it) == 0 }?.key
settingsViewModel.onLanguageChanged(key!!)
},
onEngineChanged = {
val key = Engines.fromDisplayName(it)
settingsViewModel.onEngineChanged(key!!)
}
)
}
data class SettingsState(val currentLanguage: String = "", val currentEngine: String = "")
@Preview
@Composable
fun SettingsViewPreview() {
val availableLanguages = mapOf(
Languages.DE to "German" ,
Languages.EN to "English")
val availableEngines = listOf("Steam", "Epic Games")
TCGWatcherTheme {
SettingsView(
settingsState = SettingsState(),
availableLanguages = availableLanguages,
availableEngines = availableEngines,
onLanguageChanged = {},
onEngineChanged = {}
)
}
}
| 5
|
Kotlin
|
0
| 0
|
e7895889ddec764d8ab13e814f34eddf868a73ff
| 2,935
|
TCGWatcherApp
|
MIT License
|
src/main/kotlin/graphics/rendertargets/RenderTargetManager.kt
|
MJARuijs
| 238,959,670
| false
| null |
//package com.blazeit.game.graphics.rendertargets
//
//import com.blazeit.game.graphics.rendertargets.attachments.AttachmentType
//import devices.Window
//
//object RenderTargetManager {
//
// class RenderTargetUsage(val renderTarget: RenderTarget, var unusedFrames: Int)
//
// private var window: Window? = null
// private lateinit var default: RenderTarget
//
// private val renderTargets = ArrayList<RenderTargetUsage>()
//
// fun setWindow(window: Window) {
// this.window = window
// default = RenderTarget(window.width, window.height, AttachmentType.COLOR_TEXTURE, AttachmentType.DEPTH_TEXTURE)
// }
//
// fun default() = default
//
// fun update(window: Window) {
//
// if (window.resized) {
// renderTargets.forEach { it.renderTarget.resize(window.width, window.height) }
// }
// }
//
// fun getAvailableTarget(vararg types: AttachmentType, width: Int = default.getWidth(), height: Int = default.getHeight()): RenderTarget {
// val requestedTarget = renderTargets.find { it.renderTarget.matches(width, height, *types) && it.renderTarget.isAvailable() } ?: return createTarget(*types, width = width, height = height)
// requestedTarget.unusedFrames = 0
// return requestedTarget.renderTarget
// }
//
// private fun createTarget(vararg types: AttachmentType, width: Int, height: Int): RenderTarget {
// return try {
// val target = RenderTarget(width, height, *types)
// renderTargets.add(RenderTargetUsage(target, 0))
// target
// } catch (e: NullPointerException) {
// throw NullPointerException("Default renderTarget was not yet initialized. Set a Window first!")
// }
// }
//
// fun size() = renderTargets.size
//
//}
| 0
|
Kotlin
|
0
| 0
|
ba34391da0b523907d84d71e47b70f4ad3c12173
| 1,794
|
Morgan
|
MIT License
|
app/shared/f8e-client/public/src/commonMain/kotlin/build/wallet/f8e/partnerships/GetSaleQuoteListF8eClient.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
|
package build.wallet.f8e.partnerships
import build.wallet.bitkey.f8e.FullAccountId
import build.wallet.f8e.F8eEnvironment
import build.wallet.ktor.result.NetworkingError
import build.wallet.money.BitcoinMoney
import build.wallet.money.currency.FiatCurrency
import build.wallet.partnerships.SaleQuote
import com.github.michaelbull.result.Result
import kotlinx.collections.immutable.ImmutableList
interface GetSaleQuoteListF8eClient {
suspend fun getSaleQuotes(
fullAccountId: FullAccountId,
f8eEnvironment: F8eEnvironment,
cryptoAmount: BitcoinMoney,
fiatCurrency: FiatCurrency,
): Result<Success, NetworkingError>
/**
* A struct containing a list of sale quotes
*/
data class Success(val quotes: ImmutableList<SaleQuote>)
}
| 3
|
C
|
16
| 113
|
694c152387c1fdb2b6be01ba35e0a9c092a81879
| 757
|
bitkey
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/TextRotateUpSharp.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/TextRotateUpSharp")
package mui.icons.material
@JsName("default")
external val TextRotateUpSharp: SvgIconComponent
| 10
| null |
5
| 983
|
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
| 198
|
kotlin-wrappers
|
Apache License 2.0
|
play/plugin/src/main/kotlin/com/github/triplet/gradle/play/internal/Plugins.kt
|
ychescale9
| 294,072,956
| true
|
{"Kotlin": 455760, "HTML": 390}
|
package com.github.triplet.gradle.play.internal
import com.android.build.api.variant.ApplicationVariant
import com.android.build.api.variant.ApplicationVariantProperties
import com.github.triplet.gradle.common.utils.PLUGIN_GROUP
import com.github.triplet.gradle.common.utils.nullOrFull
import com.github.triplet.gradle.play.PlayPublisherExtension
import com.github.triplet.gradle.play.tasks.CommitEdit
import com.github.triplet.gradle.play.tasks.GenerateEdit
import com.github.triplet.gradle.play.tasks.internal.EditTaskBase
import org.gradle.api.InvalidUserDataException
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.register
import java.util.*
internal val ApplicationVariantProperties.flavorNameOrDefault
get() = flavorName.nullOrFull() ?: "main"
internal val ApplicationVariantProperties.playPath get() = "$RESOURCES_OUTPUT_PATH/$name/$PLAY_PATH"
internal fun Project.newTask(
name: String,
description: String? = null,
block: Task.() -> Unit = {}
) = newTask(name, description, emptyArray(), block)
internal inline fun <reified T : Task> Project.newTask(
name: String,
description: String? = null,
constructorArgs: Array<Any> = emptyArray(),
noinline block: T.() -> Unit = {}
): TaskProvider<T> {
val config: T.() -> Unit = {
this.description = description
this.group = PLUGIN_GROUP.takeUnless { description.isNullOrBlank() }
block()
}
return tasks.register<T>(name, *constructorArgs).apply { configure(config) }
}
internal fun Project.getGenEditTask(
appId: String,
extension: PlayPublisherExtension
) = rootProject.getOrRegisterEditTask<GenerateEdit>("generateEditFor", extension, appId)
internal fun Project.getCommitEditTask(
appId: String,
extension: PlayPublisherExtension
) = rootProject.getOrRegisterEditTask<CommitEdit>("commitEditFor", extension, appId)
internal fun ApplicationVariant<ApplicationVariantProperties>.buildExtension(
extensionContainer: NamedDomainObjectContainer<PlayPublisherExtension>,
baseExtension: PlayPublisherExtension,
cliOptionsExtension: PlayPublisherExtension
): PlayPublisherExtension = buildExtensionInternal(
this,
extensionContainer,
baseExtension,
cliOptionsExtension
)
private fun buildExtensionInternal(
variant: ApplicationVariant<ApplicationVariantProperties>,
extensionContainer: NamedDomainObjectContainer<PlayPublisherExtension>,
baseExtension: PlayPublisherExtension,
cliOptionsExtension: PlayPublisherExtension
): PlayPublisherExtension {
val variantExtension = extensionContainer.findByName(variant.name)
val flavorExtension = variant.productFlavors.mapNotNull { (_, flavor) ->
extensionContainer.findByName(flavor)
}.singleOrNull()
val buildTypeExtension = variant.buildType?.let { extensionContainer.findByName(it) }
val result = extensionContainer.create(UUID.randomUUID().toString())
val extensions = listOfNotNull(
result,
cliOptionsExtension,
variantExtension,
flavorExtension,
buildTypeExtension,
baseExtension
).distinctBy {
it.name
}
return mergeExtensions(extensions)
}
private inline fun <reified T : EditTaskBase> Project.getOrRegisterEditTask(
baseName: String,
extension: PlayPublisherExtension,
appId: String
): TaskProvider<T> {
val taskName = baseName + appId.split(".").joinToString("Dot") { it.capitalize() }
return try {
tasks.register<T>(taskName, extension).apply {
configure {
editIdFile.set(layout.buildDirectory.file("$OUTPUT_PATH/$appId.txt"))
}
}
} catch (e: InvalidUserDataException) {
@Suppress("UNCHECKED_CAST")
tasks.named(taskName) as TaskProvider<T>
}
}
| 0
|
Kotlin
|
0
| 0
|
c2c71983f0075eb6cf468c7d449c17ba796ae7fa
| 4,040
|
gradle-play-publisher-1
|
MIT License
|
kafkistry-service-logic/src/main/kotlin/com/infobip/kafkistry/service/topic/validation/rules/ValidationRule.kt
|
infobip
| 456,885,171
| false
| null |
package com.infobip.kafkistry.service.topic.validation.rules
import com.infobip.kafkistry.kafka.ClusterInfo
import com.infobip.kafkistry.kafka.TOPIC_CONFIG_PROPERTIES
import com.infobip.kafkistry.model.*
import com.infobip.kafkistry.model.ClusterRef
import com.infobip.kafkistry.service.Placeholder
import com.infobip.kafkistry.service.RuleViolation
import com.infobip.kafkistry.service.renderMessage
import com.infobip.kafkistry.service.topic.*
interface ValidationRule {
fun check(topicDescriptionView: TopicDescriptionView, clusterMetadata: ClusterMetadata): RuleViolation?
fun fixConfig(
topicDescription: TopicDescription, clusterMetadata: ClusterMetadata, existingTopicInfo: ExistingTopicInfo?,
): TopicDescription {
if (!isViolated(topicDescription, clusterMetadata, existingTopicInfo)) {
return topicDescription
}
return doFixConfig(topicDescription, clusterMetadata, existingTopicInfo)
}
fun doFixConfig(topicDescription: TopicDescription, clusterMetadata: ClusterMetadata): TopicDescription = topicDescription
fun doFixConfig(
topicDescription: TopicDescription, clusterMetadata: ClusterMetadata, existingTopicInfo: ExistingTopicInfo?
): TopicDescription = doFixConfig(topicDescription, clusterMetadata)
fun isViolated(
topicDescription: TopicDescription,
clusterMetadata: ClusterMetadata,
existingTopicInfo: ExistingTopicInfo?,
): Boolean {
val clusterDefaults = clusterMetadata.info?.config?.let { clusterConfig ->
TOPIC_CONFIG_PROPERTIES.associateWith {
ConfigValueInspector().clusterDefaultValue(clusterConfig, it)?.value
}
}.orEmpty()
val topicDescriptionView = TopicDescriptionView(
name = topicDescription.name,
properties = topicDescription.propertiesForCluster(clusterMetadata.ref),
config = clusterDefaults + topicDescription.configForCluster(clusterMetadata.ref),
presentOnCluster = topicDescription.presence.needToBeOnCluster(clusterMetadata.ref),
originalDescription = topicDescription,
existingTopicInfo = existingTopicInfo,
)
val violation = check(topicDescriptionView, clusterMetadata)
return violation != valid()
}
fun violated(
message: String,
placeholders: Map<String, Placeholder> = emptyMap(),
severity: RuleViolation.Severity = RuleViolation.Severity.WARNING
) = RuleViolation(
severity = severity,
ruleClassName = javaClass.name,
message = message,
placeholders = placeholders,
)
fun valid(): RuleViolation? = null
}
data class ClusterMetadata(
val ref: ClusterRef,
val info: ClusterInfo? = null,
)
data class TopicDescriptionView(
val name: TopicName,
val properties: TopicProperties,
val config: TopicConfigMap,
val presentOnCluster: Boolean,
val originalDescription: TopicDescription,
val existingTopicInfo: ExistingTopicInfo?,
)
fun RuleViolationIssue.renderMessage(): String = violation.renderMessage()
| 2
| null |
6
| 42
|
06616ab58ca8bf7708fb8c62d584394f4fa303ab
| 3,132
|
kafkistry
|
Apache License 2.0
|
app/src/main/java/com/dnar/dicodingsubmissionbfaa/util/ConstantUtil.kt
|
dimas-nur
| 267,992,206
| false
| null |
package com.dnar.dicodingsubmissionbfaa.util
// Util for api; Keyword : Util
/* --- Url --- */
const val BASE_URL = "https://api.github.com/"
/* --- Token --- */
const val ACCESS_TOKEN = "429ab84e3da1db8210bb9c6e2474c492f81146b3"
/* --- Bundle --- */
const val ARG_FRAGMENT_KEY = "fragment_key"
const val ARG_FRAGMENT_VALUE_USERNAME = "fragment_value_username"
const val ARG_FRAGMENT_VALUE_USER = "fragment_value_user"
/* --- Alarm --- */
const val ALARM_ID_REPEATING = 100
const val ALARM_CHANNEL_ID = "channel_reminder"
const val ALARM_CHANNEL_NAME = "Reminder Channel"
const val ALARM_TITTLE = "alarm_tittle"
const val ALARM_MESSAGE = "alarm_message"
/* --- SharedPreferences --- */
const val SP_NAME = "dicoding_shared_preferences"
const val SP_KEY_REMINDER = "shared_preferences_reminder"
/* --- Database --- */
const val DATABASE_NAME = "DicodingSubmissionBFAA.db"
const val DATABASE_AUTHORITY = "com.dnar.dicodingsubmissionbfaa"
const val DATABASE_SCHEME = "content"
const val DATABASE_CONTENT_URI = "$DATABASE_SCHEME://$DATABASE_AUTHORITY"
/* --- Database Table User --- */
const val USER_TABLE_NAME = "users_favorite"
const val USER_CONTENT_URI = "$DATABASE_CONTENT_URI/$USER_TABLE_NAME"
const val USER_ID = "id"
const val USER_AVATAR_URL = "avatar_url"
const val USER_BIO = "bio"
const val USER_BLOG = "blog"
const val USER_COMPANY = "company"
const val USER_CREATED_AT = "created_at"
const val USER_EMAIL = "email"
const val USER_EVENTS_URL = "events_url"
const val USER_FOLLOWERS = "followers"
const val USER_FOLLOWERS_URL = "followers_url"
const val USER_FOLLOWING = "following"
const val USER_FOLLOWING_URL = "following_url"
const val USER_GISTS_URL = "gists_url"
const val USER_GRAVATAR_ID = "gravatar_id"
const val USER_HIREABLE = "hireable"
const val USER_HTML_URL = "html_url"
const val USER_LOCATION = "location"
const val USER_LOGIN = "login"
const val USER_NAME = "name"
const val USER_NODE_ID = "node_id"
const val USER_ORGANIZATIONS_URL = "organizations_url"
const val USER_PUBLIC_GISTS = "public_gists"
const val USER_PUBLIC_REPOS = "public_repos"
const val USER_RECEIVED_EVENTS_URL = "received_events_url"
const val USER_REPOS_URL = "repos_url"
const val USER_SITE_ADMIN = "site_admin"
const val USER_STARRED_URL = "starred_url"
const val USER_SUBSCRIPTIONS_URL = "subscriptions_url"
const val USER_TWITTER_USERNAME = "twitter_username"
const val USER_TYPE = "type"
const val USER_UPDATED_AT = "updated_at"
const val USER_URL = "url"
| 0
|
Kotlin
|
19
| 58
|
48bc4fb7209d5b116a0794fd26828699bfbaab14
| 2,473
|
dicoding-belajar-fundamental-aplikasi-android
|
Apache License 2.0
|
debugdrawer-leakcanary/src/main/kotlin/au/com/gridstone/debugdrawer/leakcanary/LeakCanaryModule.kt
|
Gridstone
| 145,801,108
| false
| null |
package au.com.gridstone.debugdrawer.leakcanary
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Switch
import au.com.gridstone.debugdrawer.DebugDrawerModule
import leakcanary.LeakCanary
object LeakCanaryModule : DebugDrawerModule {
private const val SHARED_PREFS_NAME = "DebugDrawer_LeakCanary"
private const val KEY_ENABLE_HEAP_DUMPS = "enableHeapDumps"
override fun onAttach(context: Context) {
val sharedPrefs = context.getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE)
val enableHeapDumps = sharedPrefs.getBoolean(KEY_ENABLE_HEAP_DUMPS, true)
LeakCanary.config = LeakCanary.config.copy(dumpHeap = enableHeapDumps)
}
override fun onCreateView(parent: ViewGroup): View {
val inflater = LayoutInflater.from(parent.context)
val view: View = inflater.inflate(R.layout.drawer_leakcanary, parent, false)
val sharedPrefs = parent.context.getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE)
val enableHeapDumps = sharedPrefs.getBoolean(KEY_ENABLE_HEAP_DUMPS, true)
val toggle: Switch = view.findViewById(R.id.drawer_leakcanaryToggle)
toggle.isChecked = enableHeapDumps
toggle.setOnCheckedChangeListener { _, checked ->
LeakCanary.config = LeakCanary.config.copy(dumpHeap = checked)
sharedPrefs.edit().putBoolean(KEY_ENABLE_HEAP_DUMPS, checked).apply()
}
val button: Button = view.findViewById(R.id.drawer_leakcanaryViewButton)
button.setOnClickListener {
parent.context.startActivity(LeakCanary.newLeakDisplayActivityIntent())
}
return view
}
}
| 3
|
Kotlin
|
9
| 91
|
2c745c6b3462284340d77c39f0a2d7a3c043d731
| 1,713
|
DebugDrawer
|
Apache License 2.0
|
benchmark/benchmark-macro/src/main/java/androidx/benchmark/macro/IdeSummaryString.kt
|
RikkaW
| 389,105,112
| 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
*
* 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.benchmark.macro
import androidx.benchmark.Outputs
import androidx.benchmark.Stats
import java.util.Collections
import kotlin.math.max
/**
* Returns a pair of ideSummaryStrings - v1 (pre Arctic-fox) and v2 (Arctic-fox+)
*
* These strings are to be displayed in Studio, depending on the version.
*
* The V2 string embeds links to trace files relative to the output path sent to the IDE via
* `[link](file://<relative/path/to/trace>)`
*
* @see androidx.benchmark.InstrumentationResultScope#ideSummaryRecord
*/
internal fun ideSummaryStrings(
warningLines: String,
benchmarkName: String,
statsList: List<Stats>,
absoluteTracePaths: List<String>
): Pair<String, String> {
require(statsList.isNotEmpty()) { "Require non-empty list of stats." }
val maxLabelLength = Collections.max(statsList.map { it.name.length })
// max string length of any printed min/median/max is the largest max value seen. used to pad.
val maxValueLength = statsList
.map { it.max }
.reduce { acc, maxValue -> max(acc, maxValue) }
.toString().length
fun ideSummaryString(
transform: (name: String, min: String, median: String, max: String, stats: Stats) -> String
): String {
return warningLines + benchmarkName + "\n" + statsList.joinToString("\n") {
transform(
it.name.padStart(maxLabelLength),
it.min.toString().padStart(maxValueLength),
it.median.toString().padStart(maxValueLength),
it.max.toString().padStart(maxValueLength),
it
)
} + "\n"
}
val relativeTracePaths = absoluteTracePaths.map { absolutePath ->
Outputs.relativePathFor(absolutePath)
.replace("(", "\\(")
.replace(")", "\\)")
}
return Pair(
first = ideSummaryString { name, min, median, max, _ ->
" $name min $min, median $median, max $max"
},
second = ideSummaryString { name, min, median, max, stats ->
" $name" +
" [min $min](file://${relativeTracePaths[stats.minIndex]})," +
" [median $median](file://${relativeTracePaths[stats.medianIndex]})," +
" [max $max](file://${relativeTracePaths[stats.maxIndex]})"
} + " Traces: Iteration " + relativeTracePaths.mapIndexed { index, path ->
"[$index](file://$path)"
}.joinToString(separator = " ") + "\n"
)
}
| 0
| null |
0
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 3,122
|
androidx
|
Apache License 2.0
|
ontrack-service/src/main/java/net/nemerosa/ontrack/service/elasticsearch/ElasticSearchIndexService.kt
|
nemerosa
| 19,351,480
| false
| null |
package net.nemerosa.ontrack.extension.elastic
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.json.asJson
import net.nemerosa.ontrack.model.search.SearchQuery
import net.nemerosa.ontrack.model.structure.*
import net.nemerosa.ontrack.model.support.OntrackConfigProperties
import org.elasticsearch.action.DocWriteRequest
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest
import org.elasticsearch.action.bulk.BulkRequest
import org.elasticsearch.action.delete.DeleteRequest
import org.elasticsearch.action.get.GetRequest
import org.elasticsearch.action.index.IndexRequest
import org.elasticsearch.action.search.SearchRequest
import org.elasticsearch.client.RequestOptions
import org.elasticsearch.client.RestHighLevelClient
import org.elasticsearch.client.indices.CreateIndexRequest
import org.elasticsearch.client.indices.GetIndexRequest
import org.elasticsearch.client.indices.PutMappingRequest
import org.elasticsearch.search.builder.SearchSourceBuilder
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
@ConditionalOnProperty(
name = [OntrackConfigProperties.SEARCH_ENGINE_PROPERTY],
havingValue = ElasticSearchConfigProperties.SEARCH_ENGINE_ELASTICSEARCH
)
class ElasticSearchIndexService(
private val client: RestHighLevelClient,
private val ontrackConfigProperties: OntrackConfigProperties
) : SearchIndexService {
private val logger: Logger = LoggerFactory.getLogger(ElasticSearchIndexService::class.java)
private fun <T : SearchItem> refreshIndex(indexer: SearchIndexer<T>) {
logger.debug("Refreshing index ${indexer.indexName}")
val refreshRequest = RefreshRequest(indexer.indexName)
client.indices().refresh(refreshRequest, RequestOptions.DEFAULT)
}
override fun <T : SearchItem> index(indexer: SearchIndexer<T>) {
val batchSize = indexer.indexBatch ?: ontrackConfigProperties.search.index.batch
logger.debug("Full indexation for ${indexer.indexName} with batch size = $batchSize")
val buffer = mutableListOf<T>()
indexer.indexAll { item ->
buffer.add(item)
if (buffer.size == batchSize) {
index(indexer, buffer)
buffer.clear()
}
}
// Remaining items
index(indexer, buffer)
// Refreshes the index
immediateRefreshIfRequested(indexer)
}
override fun <T : SearchItem> initIndex(indexer: SearchIndexer<T>) {
logger.info("[elasticsearch][index][${indexer.indexName}] Init")
val indexExists = client.indices().exists(GetIndexRequest(indexer.indexName), RequestOptions.DEFAULT)
if (indexExists) {
logger.info("[elasticsearch][index][${indexer.indexName}] Already exists")
indexer.indexMapping?.let { mapping ->
val mappingSource = mappingToMap(mapping)
logger.info("[elasticsearch][index][${indexer.indexName}] Updating mapping: $mappingSource")
val request = PutMappingRequest(indexer.indexName).source(mappingSource)
client.indices().putMapping(request, RequestOptions.DEFAULT)
}
} else {
logger.info("[elasticsearch][index][${indexer.indexName}] Creating index")
val request = CreateIndexRequest(indexer.indexName).run {
indexer.indexMapping?.let {
val mappingSource = mappingToMap(it)
logger.info("[elasticsearch][index][${indexer.indexName}] Mapping=$mappingSource")
mapping(mappingSource)
} ?: this
}
client.indices().create(request, RequestOptions.DEFAULT)
}
}
/**
* Converts a generic mapping into an ElasticSearch mapping.
*/
private fun mappingToMap(mapping: SearchIndexMapping): Map<String, Any> {
return mapOf(
"properties" to mapping.fields
.filter { it.types.isNotEmpty() }
.associate { fieldMapping ->
// Property mapping
val property = mutableMapOf<String, Any>()
// Primary type
val primary = fieldMapping.types[0]
setType(property, primary, nested = false)
// Other fields
if (fieldMapping.types.size > 1) {
val fields = mutableMapOf<String, Any>()
property["fields"] = fields
fieldMapping.types.drop(1)
.forEach { type ->
if (!type.type.isNullOrBlank()) {
val typeMap = mutableMapOf<String, Any>()
fields[type.type!!] = typeMap
setType(typeMap, type, nested = true)
}
}
}
// OK
fieldMapping.name to property
}
)
}
private fun setType(property: MutableMap<String, Any>, type: SearchIndexMappingFieldType, nested: Boolean) {
type.type?.let { property["type"] = it }
type.index?.let { property["index"] = it }
if (!nested) {
type.scoreBoost?.let { property["boost"] = it }
}
}
override fun <T : SearchItem> resetIndex(indexer: SearchIndexer<T>, reindex: Boolean): Boolean {
// Deletes the index
client.indices().delete(DeleteIndexRequest(indexer.indexName), RequestOptions.DEFAULT)
// Re-creates the index
initIndex(indexer)
// Re-index if requested
if (reindex) {
index(indexer)
}
// Refreshes the index always
refreshIndex(indexer)
// OK
return true
}
private fun <T : SearchItem> index(indexer: SearchIndexer<T>, items: List<T>) {
// Bulk indexation of the items
val bulk = items.fold(BulkRequest(indexer.indexName)) { acc, item ->
acc.add(IndexRequest().id(item.id).source(item.fields))
}
if (bulk.numberOfActions() > 0) {
// Launching the indexation of this batch
client.bulk(bulk, RequestOptions.DEFAULT)
// Refreshes the index
immediateRefreshIfRequested(indexer)
}
}
private fun <T : SearchItem> immediateRefreshIfRequested(indexer: SearchIndexer<T>) {
if (ontrackConfigProperties.search.index.immediate) {
refreshIndex(indexer)
}
}
override val searchIndexesAvailable: Boolean = true
override fun <T : SearchItem> createSearchIndex(indexer: SearchIndexer<T>, item: T) {
logger.debug("Create index ${indexer.indexName}")
client.index(
IndexRequest(indexer.indexName).id(item.id).source(item.fields),
RequestOptions.DEFAULT
)
// Refreshes the index
immediateRefreshIfRequested(indexer)
}
override fun <T : SearchItem> updateSearchIndex(indexer: SearchIndexer<T>, item: T) {
logger.debug("Update index ${indexer.indexName}")
client.index(
IndexRequest(indexer.indexName).id(item.id).source(item.fields),
RequestOptions.DEFAULT
)
}
override fun <T : SearchItem> deleteSearchIndex(indexer: SearchIndexer<T>, id: String) {
logger.debug("Delete index ${indexer.indexName}")
client.delete(
DeleteRequest(indexer.indexName).id(id),
RequestOptions.DEFAULT
)
// Refreshes the index
immediateRefreshIfRequested(indexer)
}
override fun <T : SearchItem> batchSearchIndex(indexer: SearchIndexer<T>, items: Collection<T>, mode: BatchIndexMode): BatchIndexResults {
// Building the list of actions to take
val bulk = items.fold(BatchSearchIndexBulk(indexer.indexName)) { acc, item ->
val action = batchSearchIndexAction(indexer, item, mode)
acc + action
}
// Launching the indexation of this batch
if (bulk.bulk.numberOfActions() > 0) {
client.bulk(bulk.bulk, RequestOptions.DEFAULT)
// Refreshes the index
immediateRefreshIfRequested(indexer)
}
// OK
return bulk.results
}
override fun <T : SearchItem> query(indexer: SearchIndexer<T>, size: Int, query: SearchQuery, handler: (source: JsonNode) -> Unit) {
val source = SearchSourceBuilder().query(ElasticSearchQuery().of(query)).size(size)
// Starts the pagination
var next = true
var offset = 0
while (next) {
// Gets current page
val request = SearchRequest(indexer.indexName).source(source.from(offset))
val response = client.search(request, RequestOptions.DEFAULT)
// Processing the hits as JSON nodes
val hits = response.hits.hits
hits.forEach { hit ->
handler(hit.sourceAsMap.asJson())
}
// Next page if hits' count >= size
next = hits.size >= size
offset += size
}
}
private fun <T : SearchItem> batchSearchIndexAction(indexer: SearchIndexer<T>, item: T, mode: BatchIndexMode): BatchSearchIndexAction {
// Gets the existing item using its ID
val response = client.get(GetRequest(indexer.indexName).id(item.id), RequestOptions.DEFAULT)
// If item exists
return if (response.isExists) {
when (mode) {
BatchIndexMode.KEEP -> BatchSearchIndexAction(null, BatchIndexResults.KEEP)
BatchIndexMode.UPDATE -> BatchSearchIndexAction(IndexRequest(indexer.indexName).id(item.id).source(item.fields), BatchIndexResults.UPDATE)
}
}
// If not existing
else {
BatchSearchIndexAction(IndexRequest(indexer.indexName).id(item.id).source(item.fields), BatchIndexResults.ADD)
}
}
private class BatchSearchIndexBulk private constructor(
val bulk: BulkRequest,
val results: BatchIndexResults
) {
constructor(indexName: String) : this(
BulkRequest(indexName),
BatchIndexResults.NONE
)
operator fun plus(action: BatchSearchIndexAction) =
BatchSearchIndexBulk(
bulk = action.action?.let { bulk.add(it) } ?: bulk,
results = results + action.results
)
}
private class BatchSearchIndexAction(
val action: DocWriteRequest<*>?,
val results: BatchIndexResults
)
}
| 57
| null |
27
| 97
|
7c71a3047401e088ba0c6d43aa3a96422024857f
| 11,276
|
ontrack
|
MIT License
|
src/main/kotlin/nl/jvhaastert/springutils/security/handlers/JsonAuthenticationFailureHandler.kt
|
jaspervhaastert
| 320,839,795
| false
| null |
package nl.jvhaastert.springutils.security.handlers
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class JsonAuthenticationFailureHandler(
private val objectMapper: ObjectMapper
) : AuthenticationFailureHandler {
override fun onAuthenticationFailure(
request: HttpServletRequest,
response: HttpServletResponse,
exception: AuthenticationException
) {
val responseBody = mapOf(
"timestamp" to Date(),
"status" to 401,
"error" to "Unauthorized",
"message" to "Unauthenticated",
"path" to request.servletPath
)
response.status = HttpServletResponse.SC_UNAUTHORIZED
response.contentType = "application/json"
objectMapper.writeValue(response.outputStream, responseBody)
}
}
| 0
|
Kotlin
|
0
| 0
|
675616770b903dc6840298cf5372da39f726bbd9
| 1,076
|
spring-utils
|
MIT License
|
cpg-core/src/main/kotlin/de/fraunhofer/aisec/cpg/graph/edges/collections/EdgeList.kt
|
Fraunhofer-AISEC
| 225,386,107
| false
|
{"Kotlin": 3497495, "LLVM": 170593, "C++": 49795, "Java": 34147, "C": 34038, "Go": 12206, "TypeScript": 4908, "Python": 4498, "Shell": 3094, "JavaScript": 751, "Ruby": 201}
|
/*
* Copyright (c) 2024, Fraunhofer AISEC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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 de.fraunhofer.aisec.cpg.graph.edges.collections
import de.fraunhofer.aisec.cpg.graph.Node
import de.fraunhofer.aisec.cpg.graph.edges.Edge
import java.util.function.Predicate
/** This class extends a list of edges. This allows us to use lists of edges more conveniently. */
abstract class EdgeList<NodeType : Node, EdgeType : Edge<NodeType>>(
override var thisRef: Node,
override var init: (start: Node, end: NodeType) -> EdgeType,
override var outgoing: Boolean = true,
override var postAdd: ((EdgeType) -> Unit)? = null,
override var postRemove: ((EdgeType) -> Unit)? = null
) : ArrayList<EdgeType>(), EdgeCollection<NodeType, EdgeType> {
override fun add(e: EdgeType): Boolean {
// Make sure, the index is always set
if (e.index == null) {
e.index = this.size
}
val ok = super<ArrayList>.add(e)
if (ok) {
handlePostAdd(e)
}
return ok
}
override fun remove(o: EdgeType): Boolean {
val ok = super<ArrayList>.remove(o)
if (ok) {
handlePostRemove(o)
}
return ok
}
override fun removeAll(c: Collection<EdgeType>): Boolean {
val ok = super.removeAll(c)
if (ok) {
c.forEach { handlePostRemove(it) }
}
return ok
}
override fun removeRange(fromIndex: Int, toIndex: Int) {
super.removeRange(fromIndex, toIndex)
}
override fun removeAt(index: Int): EdgeType {
var edge = super.removeAt(index)
handlePostRemove(edge)
return edge
}
override fun removeIf(predicate: Predicate<in EdgeType>): Boolean {
var edges = filter { predicate.test(it) }
val ok = super<ArrayList>.removeIf(predicate)
if (ok) {
edges.forEach { handlePostRemove(it) }
}
return ok
}
override fun clear() {
var edges = this.toList()
super.clear()
edges.forEach { handlePostRemove(it) }
}
override fun add(index: Int, element: EdgeType) {
// Make sure, the index is always set
element.index = this.size
super<ArrayList>.add(index, element)
handlePostAdd(element)
// We need to re-compute all edges with an index > inserted index
for (i in index until this.size) {
this[i].index = i
}
}
override fun toNodeCollection(outgoing: Boolean): List<NodeType> {
return internalToNodeCollection(this, outgoing, ::ArrayList)
}
/**
* Returns an [UnwrappedEdgeList] magic container which holds a structure that provides easy
* access to the "target" nodes without edge information.
*/
override fun unwrap(): UnwrappedEdgeList<NodeType, EdgeType> {
return UnwrappedEdgeList(this)
}
override fun equals(o: Any?): Boolean {
if (o !is EdgeList<*, *>) return false
// Otherwise, try to compare the contents of the lists with the propertyEquals method
if (this.size == o.size) {
for (i in this.indices) {
if (this[i] != o[i]) {
return false
}
}
return true
}
return false
}
override fun hashCode(): Int {
return internalHashcode(this, outgoing)
}
}
| 96
|
Kotlin
|
60
| 268
|
9562371fd01a98614a1050dbf5927e3b19444067
| 4,389
|
cpg
|
Apache License 2.0
|
app/src/main/java/kanda/lab/rickandmorty/common/DataModule.kt
|
jcaiqueoliveira
| 439,944,782
| false
| null |
package kanda.lab.rickandmorty.common
import android.app.Application
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kanda.lab.rickandmorty.common.data.BuildRetrofit
import kanda.lab.rickandmorty.common.data.RickAndMortyGateway
import kanda.lab.rickandmorty.common.data.RickAndMortyInfraStructure
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal class InfraModule {
@Provides
@Singleton
fun bindRickAndMortyService(service: RickAndMortyGateway): RickAndMortyInfraStructure =
RickAndMortyInfraStructure(service)
@Provides
@Singleton
fun provideRickAndMortyGateway(app: Application): RickAndMortyGateway =
BuildRetrofit(app).create(RickAndMortyGateway::class.java)
}
| 5
|
Kotlin
|
0
| 0
|
fd628fbfc6e2bf5e9ebd457794852ce860ffbce9
| 826
|
psychic-meme
|
MIT License
|
component/component-kaiheila-parent/kaiheila-core/src/main/java/love/forte/simbot/kaiheila/event/system/guild/UpdatedGuild.kt
|
simple-robot
| 554,852,615
| false
| null |
package love.forte.simbot.kaiheila.event.system.guild
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* 服务器信息更新
*
* `updated_guild`
*
* @author ForteScarlet
*/
@Serializable
public data class UpdatedGuildExtraBody(
/**
* 服务器id
*/
val id: String,
/**
* 服务器主id
*/
val name: String,
/**
* 服务器icon的地址
*/
val icon: String,
/**
* 通知类型, 0代表默认使用服务器通知设置,1代表接收所有通知, 2代表仅@被提及,3代表不接收通知
*/
@SerialName("notify_type")
val notifyType: Int,
/**
* 服务器默认使用语音区域
*/
val region: String,
/**
* 是否为公开服务器
*/
@SerialName("enable_open")
val enableOpen: Boolean,
/**
* 公开服务器id
*/
@SerialName("open_id")
val openId: String,
/**
* 默认频道id
*/
@SerialName("default_channel_id")
val defaultChannelId: String,
/**
* 欢迎频道id
*/
@SerialName("welcome_channel_id")
val welcomeChannelId: String,
) : GuildEventExtraBody {
init {
check(notifyType in 0..3) { "Parameter notify_type must be 0|1|2|3, but $notifyType" }
}
}
| 0
|
Kotlin
|
0
| 3
|
c5d7c9ca8c81b2bddc250090739d7c7d0c110328
| 1,126
|
simple-robot-v2
|
Apache License 2.0
|
app/src/main/java/com/schedule/domain/model/date/Week.kt
|
FredNekrasov
| 760,139,354
| false
|
{"Kotlin": 109148}
|
package com.schedule.domain.model.date
data class Week(
val semester: String,
val weekNumber: Int
)
| 0
|
Kotlin
|
0
| 0
|
73e90ff38e831c6fbfa175f4e4ffe780ed572500
| 108
|
Android-app-for-viewing-schedules
|
MIT License
|
app/src/main/java/com/akhris/composeutils/MainActivity.kt
|
akhris
| 448,849,347
| false
| null |
/*
* Copyright (c) 2022. <NAME>. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.akhris.composeutils
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.*
import androidx.compose.runtime.*
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 com.akhris.composeutils.swipetoreveal.*
import com.akhris.composeutils.ui.theme.ComposeUtilsTheme
@ExperimentalMaterialApi
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeUtilsTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
TestList()
}
}
}
}
@Composable
private fun TestList() {
var peekStart by remember { mutableStateOf(false) }
var peekEnd by remember { mutableStateOf(false) }
Column(
Modifier
.fillMaxWidth()
.verticalScroll(state = rememberScrollState())
) {
Button(modifier = Modifier.align(Alignment.CenterHorizontally), onClick = {
peekStart = !peekStart
}) {
Text(text = "peek start to end!")
}
Button(modifier = Modifier.align(Alignment.CenterHorizontally), onClick = {
peekEnd = !peekEnd
}) {
Text(text = "peek end to start!")
}
MakeRevealItem(
text = "Stretching buttons",
peekStart = peekStart,
peekEnd = peekEnd,
buttonBehavior = StretchingBehavior(),
onStartPeeked = { peekStart = false },
onEndPeeked = { peekEnd = false }
)
MakeRevealItem(
text = "Overlapping buttons",
withSecondaryText = true,
buttonBehavior = OverlappingBehavior()
)
MakeRevealItem(
text = "Fixed buttons",
buttonBehavior = FixedPositionBehavior()
)
MakeRevealItem(
text = "Overlapping with no auto-firing",
buttonBehavior = OverlappingBehavior(),
withCommit = false
)
}
}
@ExperimentalMaterialApi
@Composable
fun MakeRevealItem(
text: String = "List item with reveal",
withSecondaryText: Boolean = false,
peekStart: Boolean = false,
peekEnd: Boolean = false,
buttonBehavior: IButtonBehavior,
onStartPeeked: (() -> Unit)? = null,
onEndPeeked: (() -> Unit)? = null,
withCommit: Boolean = true
) {
val revealState = rememberRevealState()
var isFavorite by remember { mutableStateOf(false) }
val startButtons = listOf(
IconRevealButton(
icon = if (isFavorite) Icons.Rounded.Favorite else Icons.Rounded.FavoriteBorder,
callback = {
isFavorite = !isFavorite
},
backgroundColor = Color.Yellow,
startCornersRadius = 4.dp
),
IconRevealButton(
icon = Icons.Rounded.Edit,
callback = {
},
backgroundColor = Color.Magenta
)
)
val endButtons = listOf(
IconRevealButton(
icon = Icons.Rounded.Delete,
callback = {},
iconTint = Color.Red,
endCornersRadius = 4.dp
),
IconRevealButton(
icon = Icons.Rounded.Share,
callback = {}
),
IconRevealButton(
icon = Icons.Rounded.Settings,
callback = {}
)
)
SwipeToReveal(
state = revealState,
modifier = Modifier.fillMaxWidth(),
startButtons = startButtons,
endButtons = endButtons,
startButtonsBehavior = buttonBehavior,
endButtonsBehavior = buttonBehavior,
withEndCommit = withCommit,
withStartCommit = withCommit
) {
Card {
ListItem(
secondaryText = if (withSecondaryText) {
{
Text(text = "WIDE ELEMENT")
}
} else null,
text = {
Text(
text = text
)
})
}
}
LaunchedEffect(key1 = peekStart, key2 = peekEnd) {
if (peekStart) {
revealState.peek(RevealDirection.StartToEnd)
onStartPeeked?.invoke()
}
if (peekEnd) {
revealState.peek(RevealDirection.EndToStart)
onEndPeeked?.invoke()
}
}
}
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
ComposeUtilsTheme {
Greeting("Android")
}
}
| 0
|
Kotlin
|
0
| 0
|
e82494063147549a0d38fb049a9ab12c1ae7b50a
| 6,380
|
compose-utils
|
Apache License 2.0
|
app/src/main/java/com/suihan74/nedge/database/notification/BlackListEntity.kt
|
suihan74
| 314,771,954
| false
| null |
package com.suihan74.nedge.database.notification
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.suihan74.nedge.models.KeywordMatchingType
@Entity
data class BlackListEntity(
/** 対象パッケージ名 (com.suihan74.satena など) */
val packageName : String,
/** 追加のキーワード */
val keyword : String = "",
/** キーワードの検索方法 */
val keywordMatchingType : KeywordMatchingType = KeywordMatchingType.NONE,
@PrimaryKey(autoGenerate = true)
val id : Long = 0,
)
| 0
|
Kotlin
|
0
| 0
|
8d1569d9ee6c51a803212ae7fdff7e493d02cf41
| 491
|
nEdge
|
MIT License
|
intellij-plugin/src/main/kotlin/com/apollographql/ijplugin/normalizedcache/PullFromDevice.kt
|
apollographql
| 69,469,299
| false
|
{"Kotlin": 3463807, "Java": 198208, "CSS": 34435, "HTML": 5844, "JavaScript": 1191}
|
package com.apollographql.ijplugin.normalizedcache
import com.android.ddmlib.AndroidDebugBridge
import com.android.ddmlib.IDevice
import com.android.ddmlib.SyncService
import com.android.tools.idea.adb.AdbShellCommandsUtil
import com.apollographql.ijplugin.util.logd
import com.apollographql.ijplugin.util.logw
import java.io.File
import java.util.concurrent.TimeUnit
val isAndroidPluginPresent = try {
Class.forName("com.android.ddmlib.AndroidDebugBridge")
true
} catch (e: ClassNotFoundException) {
false
}
fun getConnectedDevices(): List<IDevice> {
return AndroidDebugBridge.createBridge(1, TimeUnit.SECONDS).devices.sortedBy { it.name }
}
fun IDevice.getDebuggablePackageList(): Result<List<String>> {
val commandResult = runCatching {
AdbShellCommandsUtil.create(this).executeCommandBlocking(
// List all packages, and try run-as on them - if it succeeds, the package is debuggable
"for p in \$(pm list packages -3 | cut -d : -f 2); do (run-as \$p true >/dev/null 2>&1 && echo \$p); done; true"
)
}
if (commandResult.isFailure) {
val e = commandResult.exceptionOrNull()!!
logw(e, "Could not list debuggable packages")
return Result.failure(e)
}
val result = commandResult.getOrThrow()
if (result.isError) {
val message = "Could not list debuggable packages: ${result.output.joinToString()}"
logw(message)
return Result.failure(Exception(message))
}
return Result.success(result.output.filterNot { it.isEmpty() }.sorted())
}
fun IDevice.getDatabaseList(packageName: String, databasesDir: String): Result<List<String>> {
val commandResult = runCatching {
AdbShellCommandsUtil.create(this).executeCommandBlocking("run-as $packageName ls -1 $databasesDir")
}
if (commandResult.isFailure) {
val e = commandResult.exceptionOrNull()!!
logw(e, "Could not list databases")
return Result.failure(e)
}
val result = commandResult.getOrThrow()
if (result.isError) {
if (result.output.any { it.contains("No such file or directory") }) {
return Result.success(emptyList())
}
val message = "Could not list databases: ${result.output.joinToString()}"
logw(message)
return Result.failure(Exception(message))
}
return Result.success(result.output.filter { it.isDatabaseFileName() }.sorted())
}
fun pullFile(device: IDevice, appPackageName: String, remoteDirName: String, remoteFileName: String): Result<File> {
val remoteFilePath = "$remoteDirName/$remoteFileName"
val localFile = File.createTempFile(remoteFileName.substringBeforeLast(".") + "-tmp", ".db")
logd("Pulling $remoteFilePath to ${localFile.absolutePath}")
val intermediateRemoteFilePath = "/data/local/tmp/${localFile.name}"
val shellCommandsUtil = AdbShellCommandsUtil.create(device)
return runCatching {
var commandResult = shellCommandsUtil.executeCommandBlocking("touch $intermediateRemoteFilePath")
if (commandResult.isError) {
throw Exception("'touch' command failed")
}
commandResult = shellCommandsUtil.executeCommandBlocking("run-as $appPackageName sh -c 'cp $remoteFilePath $intermediateRemoteFilePath'")
if (commandResult.isError) {
throw Exception("'copy' command failed")
}
try {
device.syncService.pullFile(intermediateRemoteFilePath, localFile.absolutePath, NullSyncProgressMonitor)
} finally {
commandResult = shellCommandsUtil.executeCommandBlocking("rm $intermediateRemoteFilePath")
if (commandResult.isError) {
logw("'rm' command failed")
}
}
localFile
}
}
private object NullSyncProgressMonitor : SyncService.ISyncProgressMonitor {
override fun isCanceled() = false
override fun start(totalWork: Int) {}
override fun startSubTask(name: String) {}
override fun advance(work: Int) {}
override fun stop() {}
}
// See https://www.sqlite.org/tempfiles.html
fun String.isDatabaseFileName() = isNotEmpty() && !endsWith("-journal") && !endsWith("-wal") && !endsWith("-shm")
| 198
|
Kotlin
|
657
| 3,750
|
174cb227efe76672cf2beac1affc7054f6bb2892
| 3,981
|
apollo-kotlin
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.