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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
javascript/js-type-analysis/src/org/jetbrains/dukat/js/type/constraint/resolution/ResolutionState.kt | Kotlin | 159,510,660 | false | {"Kotlin": 2656818, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333} | package org.jetbrains.dukat.js.type.constraint.resolution
internal enum class ResolutionState {
UNRESOLVED,
RESOLVING,
RESOLVED
} | 244 | Kotlin | 42 | 535 | d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e | 142 | dukat | Apache License 2.0 |
mokkery-plugin/src/main/kotlin/dev/mokkery/plugin/diagnostics/MokkeryDiagnosticRendererFactory.kt | lupuuss | 652,785,006 | false | {"Kotlin": 556906} | package dev.mokkery.plugin.diagnostics
import dev.mokkery.plugin.core.Mokkery.Errors
import dev.mokkery.plugin.fir.renderTypeCompat
import org.jetbrains.kotlin.diagnostics.KtDiagnosticFactoryToRendererMap
import org.jetbrains.kotlin.diagnostics.rendering.BaseDiagnosticRendererFactory
import org.jetbrains.kotlin.diagnostics.rendering.CommonRenderers
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticParameterRenderer
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirDiagnosticRenderers
import org.jetbrains.kotlin.fir.types.ConeKotlinType
class MokkeryDiagnosticRendererFactory : BaseDiagnosticRendererFactory() {
private val typeRenderer: DiagnosticParameterRenderer<ConeKotlinType> = FirDiagnosticRenderers.renderTypeCompat()
override val MAP = KtDiagnosticFactoryToRendererMap("MokkeryDiagnostic").apply {
put(
factory = MokkeryDiagnostics.INDIRECT_INTERCEPTION,
message = Errors.indirectCall(typeArgument = "{1}", functionName = "{0}"),
rendererA = CommonRenderers.NAME,
rendererB = typeRenderer
)
put(
factory = MokkeryDiagnostics.FUNCTIONAL_PARAM_MUST_BE_LAMBDA,
message = Errors.notLambdaExpression(functionName = "{0}", param = "{1}"),
rendererA = CommonRenderers.NAME,
rendererB = FirDiagnosticRenderers.SYMBOL,
)
put(
factory = MokkeryDiagnostics.SEALED_TYPE_CANNOT_BE_INTERCEPTED,
message = Errors.sealedTypeCannotBeIntercepted(typeName = "{1}", functionName = "{0}"),
rendererA = CommonRenderers.NAME,
rendererB = typeRenderer,
)
put(
factory = MokkeryDiagnostics.FINAL_TYPE_CANNOT_BE_INTERCEPTED,
message = Errors.finalTypeCannotBeIntercepted(typeName = "{1}", functionName = "{0}"),
rendererA = CommonRenderers.NAME,
rendererB = typeRenderer,
)
put(
factory = MokkeryDiagnostics.PRIMITIVE_TYPE_CANNOT_BE_INTERCEPTED,
message = Errors.primitiveTypeCannotBeIntercepted(typeName = "{1}", functionName = "{0}"),
rendererA = CommonRenderers.NAME,
rendererB = typeRenderer,
)
put(
factory = MokkeryDiagnostics.FINAL_MEMBERS_TYPE_CANNOT_BE_INTERCEPTED,
message = Errors.finalMembersTypeCannotBeIntercepted(
typeName = "{1}",
functionName = "{0}",
nonAbstractMembers = "{2}"
),
rendererA = CommonRenderers.NAME,
rendererB = typeRenderer,
rendererC = CommonRenderers.commaSeparated(FirDiagnosticRenderers.SYMBOL)
)
put(
factory = MokkeryDiagnostics.NO_PUBLIC_CONSTRUCTOR_TYPE_CANNOT_BE_INTERCEPTED,
message = Errors.noPublicConstructorTypeCannotBeIntercepted(
typeName = "{1}",
functionName = "{0}",
),
rendererA = CommonRenderers.NAME,
rendererB = typeRenderer,
)
put(
factory = MokkeryDiagnostics.MULTIPLE_SUPER_CLASSES_FOR_MOCK_MANY,
message = Errors.singleSuperClass("{0}", "{1}"),
rendererA = CommonRenderers.NAME,
rendererB = CommonRenderers.commaSeparated(typeRenderer)
)
put(
factory = MokkeryDiagnostics.DUPLICATE_TYPES_FOR_MOCK_MANY,
message = Errors.noDuplicatesForMockMany("{0}", "{1}", "{2}"),
rendererA = typeRenderer,
rendererB = CommonRenderers.NAME,
rendererC = CommonRenderers.STRING
)
put(
factory = MokkeryDiagnostics.FUNCTIONAL_TYPE_ON_JS_FOR_MOCK_MANY,
message = Errors.functionalTypeNotAllowedOnJs("{0}", "{1}"),
rendererA = typeRenderer,
rendererB = CommonRenderers.NAME
)
}
}
| 9 | Kotlin | 8 | 185 | 71c8e946d1a3e9ab015e160304e2f85e5333c395 | 3,909 | Mokkery | Apache License 2.0 |
wasi-emscripten-host/src/commonMain/kotlin/emscripten/function/SyscallReadlinkatFunctionHandle.kt | illarionov | 769,429,996 | false | {"Kotlin": 1444270} | /*
* Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package ru.pixnews.wasm.sqlite.open.helper.host.emscripten.function
import ru.pixnews.wasm.sqlite.open.helper.host.EmbedderHost
import ru.pixnews.wasm.sqlite.open.helper.host.base.WasmPtr
import ru.pixnews.wasm.sqlite.open.helper.host.base.function.HostFunctionHandle
import ru.pixnews.wasm.sqlite.open.helper.host.base.memory.Memory
import ru.pixnews.wasm.sqlite.open.helper.host.base.memory.readNullTerminatedString
import ru.pixnews.wasm.sqlite.open.helper.host.castFileSystem
import ru.pixnews.wasm.sqlite.open.helper.host.emscripten.EmscriptenHostFunction
import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.FileSystem
import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.Path
import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.SysException
import ru.pixnews.wasm.sqlite.open.helper.host.include.DirFd
import ru.pixnews.wasm.sqlite.open.helper.host.wasi.preview1.type.Errno
public class SyscallReadlinkatFunctionHandle(
host: EmbedderHost,
) : HostFunctionHandle(EmscriptenHostFunction.SYSCALL_READLINKAT, host) {
public fun execute(
memory: Memory,
rawDirFd: Int,
pathnamePtr: WasmPtr<Byte>,
buf: WasmPtr<Byte>,
bufSize: Int,
): Int {
val fs: FileSystem<Path> = host.castFileSystem()
val dirFd = DirFd(rawDirFd)
val path = memory.readNullTerminatedString(pathnamePtr)
if (bufSize < 0) {
return -Errno.INVAL.code
}
return try {
val linkPath = fs.readLinkAt(dirFd, path)
val linkpathByteArray = linkPath.encodeToByteArray()
val len = linkpathByteArray.size.coerceAtMost(bufSize)
memory.write(buf, linkpathByteArray, 0, len)
len
} catch (e: SysException) {
logger.v {
"readlinkat(rawdirfd: $rawDirFd path: $path, buf: $buf, bufsiz: $bufSize) error: ${e.errNo}"
}
-e.errNo.code
}
}
}
| 0 | Kotlin | 0 | 2 | 323cb253bac83b17cf1699b2c1d6d433f28714f8 | 2,225 | wasm-sqlite-open-helper | Apache License 2.0 |
samples/random/core/src/commonMain/kotlin/random/Random.kt | oolong-kt | 264,744,447 | false | null | package random
import oolong.Effect
import oolong.Init
import oolong.Update
import oolong.View
import oolong.effect.none
import oolong.random.nextInt
object Random {
data class Model(
val face: Int = 0
)
sealed class Msg {
object Roll : Msg()
data class NewFace(val face: Int) : Msg()
}
data class Props(
val dieFace: Int,
val onRoll: () -> Msg
)
val init: Init<Model, Msg> = {
Model() to rollDie()
}
val update: Update<Model, Msg> = { msg, model ->
when (msg) {
Msg.Roll -> model to rollDie()
is Msg.NewFace -> Model(msg.face) to none()
}
}
val view: View<Model, Props> = { model ->
Props(
model.face,
{ Msg.Roll }
)
}
private val rollDie: () -> Effect<Msg> = {
nextInt(1..6) { Msg.NewFace(it) }
}
}
| 0 | Kotlin | 1 | 3 | 5bc011bd99a680c9a29ac7b0936d2b2dc1d44a21 | 903 | samples | Apache License 2.0 |
app/src/main/java/com/dreamsoftware/saborytv/ui/screens/category/CategoryDetailScreenViewModel.kt | sergio11 | 527,221,243 | false | {"Kotlin": 558422} | package com.dreamsoftware.saborytv.ui.screens.category
import com.dreamsoftware.saborytv.domain.model.CategoryBO
import com.dreamsoftware.saborytv.domain.usecase.GetCategoryByIdUseCase
import com.dreamsoftware.saborytv.domain.usecase.GetRecipesByCategoryUseCase
import com.dreamsoftware.fudge.core.FudgeTvViewModel
import com.dreamsoftware.fudge.core.SideEffect
import com.dreamsoftware.fudge.core.UiState
import com.dreamsoftware.saborytv.domain.model.RecipeBO
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class CategoryDetailScreenViewModel @Inject constructor(
private val getRecipesByCategoryUseCase: GetRecipesByCategoryUseCase,
private val getCategoryByIdUseCase: GetCategoryByIdUseCase
) : FudgeTvViewModel<CategoryDetailUiState, CategoryDetailSideEffects>(), CategoryDetailActionListener {
fun fetchData(id: String) {
fetchCategoryDetail(id)
}
override fun onGetDefaultState(): CategoryDetailUiState = CategoryDetailUiState()
override fun onRecipeOpened(recipeBO: RecipeBO) {
with(recipeBO) {
launchSideEffect(CategoryDetailSideEffects.OpenRecipeDetail(id = id))
}
}
private fun fetchRecipesByCategory(id: String) {
executeUseCaseWithParams(
useCase = getRecipesByCategoryUseCase,
params = GetRecipesByCategoryUseCase.Params(id),
onSuccess = ::onGetRecipesByCategorySuccessfully
)
}
private fun fetchCategoryDetail(id: String) {
executeUseCaseWithParams(
useCase = getCategoryByIdUseCase,
params = GetCategoryByIdUseCase.Params(id),
onSuccess = ::onGetCategoryDetailSuccessfully
)
}
private fun onGetRecipesByCategorySuccessfully(recipes: List<RecipeBO>) {
updateState { it.copy(recipes = recipes) }
}
private fun onGetCategoryDetailSuccessfully(category: CategoryBO) {
updateState { it.copy(category = category) }
fetchRecipesByCategory(category.id)
}
}
data class CategoryDetailUiState(
override val isLoading: Boolean = false,
override val errorMessage: String? = null,
val recipes: List<RecipeBO> = emptyList(),
val category: CategoryBO? = null
): UiState<CategoryDetailUiState>(isLoading, errorMessage) {
override fun copyState(isLoading: Boolean, errorMessage: String?): CategoryDetailUiState =
copy(isLoading = isLoading, errorMessage = errorMessage)
}
sealed interface CategoryDetailSideEffects : SideEffect {
data class OpenRecipeDetail(val id: String): CategoryDetailSideEffects
} | 0 | Kotlin | 1 | 1 | 93b8bc2fffd10601d5015621da0caeda114a6cce | 2,613 | saborytv_android | MIT License |
core/src/commonMain/kotlin/dev/kryptonreborn/blockfrost/network/CardanoNetworkApi.kt | KryptonReborn | 803,884,694 | false | {"Kotlin": 608832, "Swift": 594, "HTML": 323} | package dev.kryptonreborn.blockfrost.network
import dev.kryptonreborn.blockfrost.ktor.fetchResource
import dev.kryptonreborn.blockfrost.network.model.EraSummary
import dev.kryptonreborn.blockfrost.network.model.NetworkInformation
import io.ktor.client.HttpClient
internal class CardanoNetworkApi(private val httpClient: HttpClient) {
companion object {
const val GET_NETWORK_INFORMATION = "/api/v0/network"
const val QUERY_SUMMARY_BLOCKCHAIN_ERAS = "/api/v0/network/eras"
}
suspend fun getNetworkInformation() = httpClient.fetchResource<NetworkInformation>(GET_NETWORK_INFORMATION)
suspend fun querySummaryBlockchainEras() = httpClient.fetchResource<List<EraSummary>>(QUERY_SUMMARY_BLOCKCHAIN_ERAS)
}
| 0 | Kotlin | 1 | 1 | f04fa182b1599042702f6ab36047c9a1826d4522 | 737 | blockfrost-kotlin-sdk | Apache License 2.0 |
app/src/main/java/com/falcon/stackoverflow/network/RetrofitInterface.kt | muhammed-ahmad | 571,477,751 | false | {"Kotlin": 41789} | package com.falcon.stackoverflow.network
import com.falcon.stackoverflow.network.answer.AnswerItemNet
import com.falcon.stackoverflow.network.answer.AnswerResultNet
import com.falcon.stackoverflow.network.question.QuestionResultNet
import com.falcon.stackoverflow.network.results.ResultNet
import io.reactivex.Single
import retrofit2.http.*
interface RetrofitInterface {
@GET("search/advanced?order=desc&sort=activity&accepted=True&site=stackoverflow")
fun getResult(@Query("q") q: String ): Single<ResultNet>
@GET("answers/{answer_id}?order=desc&sort=activity&site=stackoverflow&filter=withbody")
fun getAcceptedAnswer(@Path("answer_id") answerId: Long ): Single<AnswerResultNet>
@GET("questions/{question_id}?order=desc&sort=activity&site=stackoverflow&filter=withbody")
fun getQuestionBody(@Path("question_id") questionId: Long ): Single<QuestionResultNet>
@GET("questions/{question_id}/answers?order=desc&sort=activity&site=stackoverflow&filter=withbody")
fun getAllQuestionAnswers(@Path("question_id") questionId: Long ): Single<AnswerResultNet>
}
| 0 | Kotlin | 0 | 2 | f04f6ceb7b4fe20d0023686898932cc854a21a6c | 1,095 | StackOverflow-Accepted-Answer | MIT License |
sample/src/main/java/com/seiko/immersionbar/sample/activity/BackActivity.kt | qdsfdhvh | 273,822,575 | true | {"Kotlin": 79797} | package com.seiko.immersionbar.sample.activity
import android.os.Bundle
import com.seiko.immersionbar.immersionBar
import com.seiko.immersionbar.sample.AppManager
import com.seiko.immersionbar.sample.R
import com.seiko.immersionbar.sample.utils.getResColor
import com.seiko.immersionbar.setTitleBar
import me.imid.swipebacklayout.lib.app.SwipeBackActivity
/**
* @author geyifeng
* @date 2017/5/8
*/
class BackActivity : SwipeBackActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppManager.getInstance().addActivity(this)
setContentView(R.layout.activity_swipe_back)
setTitleBar(findViewById(R.id.toolbar))
immersionBar {
navigationBarColor(getResColor(R.color.colorPrimary))
}
}
override fun onDestroy() {
super.onDestroy()
AppManager.getInstance().removeActivity(this)
}
} | 0 | Kotlin | 0 | 1 | 70e0969f96eae5cbf665e8edd38a32c63d3172c5 | 924 | immersionbar | Apache License 2.0 |
app/src/main/java/com/partokarwat/showcase/ui/MainActivity.kt | partokarwat | 869,065,220 | false | {"Kotlin": 86932} | package com.partokarwat.showcase.ui
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.partokarwat.showcase.ui.theme.CoinsTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CoinsTheme {
ShowcaseApp()
}
}
}
}
| 0 | Kotlin | 0 | 0 | 698e67795425135c17d3ec976a57a24976d01e3a | 518 | showcase-app | MIT License |
app/src/main/java/com/vlad1m1r/watchface/config/ConfigAdapter.kt | msoftware | 154,970,237 | true | {"Kotlin": 38310} | package com.vlad1m1r.watchface.config
import android.support.v7.widget.RecyclerView
import android.support.wearable.complications.ComplicationProviderInfo
import android.view.LayoutInflater
import android.view.ViewGroup
import com.vlad1m1r.watchface.R
import com.vlad1m1r.watchface.utils.DataProvider
import java.lang.IllegalArgumentException
const val TYPE_PREVIEW_AND_COMPLICATIONS_CONFIG = 0
const val TYPE_COMPLICATIONS_AMBIENT_MODE = 1
class ConfigAdapter(private val dataProvider: DataProvider) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private lateinit var complicationsViewHolder: ComplicationsViewHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
var viewHolder: RecyclerView.ViewHolder? = null
when (viewType) {
TYPE_PREVIEW_AND_COMPLICATIONS_CONFIG -> {
complicationsViewHolder = ComplicationsViewHolder(
LayoutInflater.from(parent.context)
.inflate(
R.layout.item_complications,
parent,
false
)
)
viewHolder = complicationsViewHolder
}
TYPE_COMPLICATIONS_AMBIENT_MODE -> viewHolder = ComplicationsAmbientViewHolder(
LayoutInflater.from(parent.context)
.inflate(
R.layout.item_ambient_complications,
parent,
false
),
dataProvider
)
}
return viewHolder!!
}
override fun getItemCount(): Int {
return 2
}
override fun getItemViewType(position: Int) =
when (position) {
0 -> TYPE_PREVIEW_AND_COMPLICATIONS_CONFIG
1 -> TYPE_COMPLICATIONS_AMBIENT_MODE
else -> throw IllegalArgumentException("Unsupported View Type position: $position")
}
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
}
fun updateSelectedComplication(complicationProviderInfo: ComplicationProviderInfo?) {
complicationsViewHolder.updateComplicationViews(complicationProviderInfo)
}
fun setComplication(complicationProviderInfo: ComplicationProviderInfo?, watchFaceComplicationId: Int) {
complicationsViewHolder.setComplication(complicationProviderInfo, watchFaceComplicationId)
}
} | 0 | Kotlin | 0 | 0 | d26ee2a170a376299811f1d2692a6b2111739727 | 2,513 | AnalogWatchFace | Apache License 2.0 |
app/src/main/java/nolambda/stiker/motionviews/widget/entity/ImageEntity.kt | esafirm | 178,912,659 | false | null | package nolambda.stiker.motionviews.widget.entity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import androidx.annotation.DrawableRes
import androidx.annotation.IntRange
import nolambda.stiker.motionviews.serialized.BaseEntitySavedState
import nolambda.stiker.motionviews.serialized.ImageEntitySavedState
import nolambda.stiker.motionviews.serialized.PaintData
import nolambda.stiker.motionviews.utils.MotionViewUtils
import nolambda.stiker.motionviews.viewmodel.Layer
import java.io.Serializable
class ImageEntity(
layer: Layer,
private val bitmapProvider: BitmapProvider,
@IntRange(from = 1) canvasWidth: Int,
@IntRange(from = 1) canvasHeight: Int
) : MotionEntity(layer, canvasWidth, canvasHeight) {
private val bitmap by lazy { bitmapProvider.image }
init {
val width = bitmap.width.toFloat()
val height = bitmap.height.toFloat()
val widthAspect = 1.0f * canvasWidth / width
val heightAspect = 1.0f * canvasHeight / height
// fit the smallest size
holyScale = Math.min(widthAspect, heightAspect)
// initial position of the entity
srcPoints[0] = 0f
srcPoints[1] = 0f
srcPoints[2] = width
srcPoints[3] = 0f
srcPoints[4] = width
srcPoints[5] = height
srcPoints[6] = 0f
srcPoints[7] = height
srcPoints[8] = 0f
srcPoints[8] = 0f
}
public override fun drawContent(canvas: Canvas, drawingPaint: Paint?) {
canvas.drawBitmap(bitmap, matrix, drawingPaint)
}
override val width: Int get() = bitmap.width
override val height: Int get() = bitmap.height
override fun release() {
if (!bitmap.isRecycled) {
bitmap.recycle()
}
}
override fun serialize(): BaseEntitySavedState? = ImageEntitySavedState(
layer,
MotionViewUtils.getMatrixValues(matrix),
holyScale,
canvasWidth,
canvasHeight,
PaintData(borderPaint.strokeWidth, borderPaint.color),
bitmapProvider
)
interface BitmapProvider : Serializable {
val image: Bitmap
}
class FileBitmapProvider(private val filePath: String) : BitmapProvider {
override val image: Bitmap
get() = BitmapFactory.decodeFile(filePath)
}
class ResourceBitmapProvider(
private val context: Context,
@DrawableRes private val resourceId: Int
) : BitmapProvider {
override val image: Bitmap
get() = BitmapFactory.decodeResource(context.resources, resourceId)
}
}
| 0 | Kotlin | 1 | 3 | 8b64ffdd771b78f9a1a213768181a5c54c4b7fe3 | 2,687 | stiker | MIT License |
src/commonMain/kotlin/com/github/shaart/pstorage/multiplatform/service/mapper/UserMapper.kt | shaart | 643,580,361 | false | null | package com.github.shaart.pstorage.multiplatform.service.mapper
import com.github.shaart.pstorage.multiplatform.dto.UserViewDto
import com.github.shaart.pstorage.multiplatform.model.encryption.CryptoResult
import migrations.Dct_roles
import migrations.Usr_passwords
import migrations.Usr_settings
import migrations.Usr_users
import java.time.LocalDateTime
class UserMapper(
private val roleMapper: RoleMapper,
private val passwordMapper: PasswordMapper,
private val userSettingsMapper: UserSettingsMapper,
) {
fun entityToViewDto(
user: Usr_users,
passwords: List<Usr_passwords>,
role: Dct_roles,
encryptedMasterPassword: CryptoResult,
settings: List<Usr_settings>,
): UserViewDto {
return UserViewDto(
id = user.id.toString(),
name = user.name,
masterPassword = encryptedMasterPassword.value,
encryptionType = encryptedMasterPassword.encryptionType,
role = roleMapper.entityToViewDto(role),
createdAt = LocalDateTime.parse(user.created_at),
passwords = passwords.map { passwordMapper.entityToViewDto(it) },
settings = userSettingsMapper.entityToViewDtoWithDefaultSettings(settings)
)
}
}
| 4 | Kotlin | 0 | 0 | b2ea9f75cf972ae5ce1bd2a38c7eceabbaf19877 | 1,267 | pstorage-multiplatform | Apache License 2.0 |
presentation/src/main/java/com/mikhaellopez/presentation/AndroidApplication.kt | lopspower | 522,617,808 | false | {"Kotlin": 168656, "Java": 749} | package com.mikhaellopez.presentation
import android.app.Application
import com.mikhaellopez.data.di.koinDataSourceModules
import com.mikhaellopez.domain.di.koinDomainModules
import com.mikhaellopez.presentation.di.koinPresentationModules
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
/**
* Copyright (C) 2022 <NAME>
* Licensed under the Apache License Version 2.0
* Android Main Application
*/
class AndroidApplication : Application() {
override fun onCreate() {
// Koin
startKoin {
androidContext(this@AndroidApplication)
modules(koinDataSourceModules)
modules(koinDomainModules)
modules(koinPresentationModules)
}
super.onCreate()
}
}
| 0 | Kotlin | 6 | 111 | ce41ce693cdb09facc455224b8af8fedcff74ad1 | 774 | PokeCardCompose | Apache License 2.0 |
src/main/kotlin/org/jboss/dmr/DataOutput.kt | hal | 262,060,586 | false | null | package org.jboss.dmr
import org.khronos.webgl.ArrayBuffer
import org.khronos.webgl.DataView
import org.khronos.webgl.Int8Array
import org.khronos.webgl.get
class DataOutput {
private var pos: Int = 0
private var bytes: ByteArray = ByteArray(256)
fun writeBoolean(v: Boolean) {
growToFit(1)
bytes[pos++] = if (v) 1.toByte() else 0.toByte()
}
fun writeByte(v: Int) {
growToFit(1)
bytes[pos++] = v.toByte()
}
fun writeBytes(b: ByteArray) {
growToFit(b.size)
b.copyInto(bytes, pos)
pos += b.size
}
fun writeDouble(v: Double) {
val buffer = ArrayBuffer(8)
val array = Int8Array(buffer)
val view = DataView(buffer)
view.setFloat64(0, v)
for (i in 0 until array.length) {
bytes[pos++] = array[i]
}
}
fun writeInt(v: Int) {
growToFit(4)
bytes[pos++] = (v ushr 24).toByte()
bytes[pos++] = (v ushr 16 and 0xFF).toByte()
bytes[pos++] = (v ushr 8 and 0xFF).toByte()
bytes[pos++] = (v and 0xFF).toByte()
}
fun writeLong(v: Long) {
growToFit(8)
bytes[pos++] = (v ushr 56).toByte()
bytes[pos++] = (v ushr 48 and 0xFF).toByte()
bytes[pos++] = (v ushr 40 and 0xFF).toByte()
bytes[pos++] = (v ushr 32 and 0xFF).toByte()
bytes[pos++] = (v ushr 24 and 0xFF).toByte()
bytes[pos++] = (v ushr 16 and 0xFF).toByte()
bytes[pos++] = (v ushr 8 and 0xFF).toByte()
bytes[pos++] = (v and 0xFF).toByte()
}
fun writeUTF(s: String) {
var bp = 0
val b = ByteArray(s.length * 3)
for (c in s) {
when {
c.toInt() in 1..0x7f -> {
b[bp++] = c.toByte()
}
c.toInt() <= 0x07ff -> {
b[bp++] = (0xc0 or 0x1f and c.toInt() shr 6).toByte()
b[bp++] = (0x80 or 0x3f and c.toInt()).toByte()
}
else -> {
b[bp++] = (0xe0 or 0x0f and c.toInt() shr 12).toByte()
b[bp++] = (0x80 or 0x3f and c.toInt() shr 6).toByte()
b[bp++] = (0x80 or 0x3f and c.toInt()).toByte()
}
}
}
growToFit(2)
bytes[pos++] = (bp ushr 8).toByte()
bytes[pos++] = (bp and 0xFF).toByte()
for (i in 0 until bp) {
bytes[pos++] = b[i]
}
}
private fun growToFit(size: Int) {
if (pos + size >= bytes.size) {
bytes = bytes.copyInto(ByteArray(bytes.size + size))
}
}
override fun toString(): String = byteArrayToString(bytes.copyOfRange(0, pos))
}
| 0 | Kotlin | 2 | 0 | 2e445260734b9ca230c11c6b84ee3ac0df737c82 | 2,727 | halos-console | Apache License 2.0 |
packages/plugin-dropbox/src/main/java/com/openmobilehub/android/auth/plugin/dropbox/DropboxClient.kt | openmobilehub | 742,146,209 | false | {"Kotlin": 225728, "Java": 38806, "Shell": 1121} | package com.openmobilehub.android.auth.plugin.dropbox
import com.dropbox.core.DbxRequestConfig
import com.dropbox.core.oauth.DbxCredential
import com.dropbox.core.v2.DbxClientV2
internal object DropboxClient {
private var instance: DbxClientV2? = null
fun getInstance(credential: DbxCredential?, forceNewInstance: Boolean = false): DbxClientV2 {
if (instance == null || forceNewInstance) {
instance = DbxClientV2(DbxRequestConfig("db-${credential?.appKey}"), credential)
}
return instance!!
}
}
| 9 | Kotlin | 1 | 4 | e3cecfffc694385ef12dd5d1d565ed4c2415daac | 547 | android-omh-auth | Apache License 2.0 |
app/src/main/java/com/adityaverma/notes/db/NotesDatabase.kt | AdityaV025 | 334,470,108 | false | null | package com.adityaverma.notes.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
/**
* Created by <NAME> on 29-01-2021.
*/
@Database(entities = [Note::class],version = 1)
abstract class NoteDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDAO
companion object {
var instance: NoteDatabase? = null
fun getDatabase(context: Context): NoteDatabase? {
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext, NoteDatabase::class.java,
"notes_database"
).build()
}
return instance
}
}
} | 0 | Kotlin | 4 | 5 | 6608aaedcc91959b35b50c00a3a25d5a8dd42bda | 738 | Notes | Apache License 2.0 |
vtp-pensjon-application/src/main/kotlin/no/nav/pensjon/vtp/testmodell/personopplysning/PersonIndeks.kt | navikt | 254,055,233 | false | null | package no.nav.pensjon.vtp.testmodell.personopplysning
import org.springframework.stereotype.Component
@Component
class PersonIndeks(private val personIdentFooRepository: PersonIdentFooRepository) {
@Synchronized
fun indekserPersonopplysningerByIdent(pers: Personopplysninger) {
personIdentFooRepository.save(PersonIdentFoo(pers.søker.ident, pers))
pers.annenPart?.ident?.let { personIdentFooRepository.save(PersonIdentFoo(it, pers)) }
}
fun findById(id: String): Personopplysninger? {
return personIdentFooRepository.findById(id)
?.personopplysninger
}
}
| 14 | Kotlin | 0 | 2 | cd270b5f698c78c1eee978cd24bd788163c06a0c | 615 | vtp-pensjon | MIT License |
app/src/main/java/com/example/asm/travel/classloader/AsmClassLoader.kt | bitristan | 381,868,050 | false | {"Kotlin": 22881} | package com.example.asm.travel.classloader
class AsmClassLoader : ClassLoader() {
fun defineClass(name: String?, data: ByteArray): Class<*> {
return defineClass(name, data, 0, data.size)
}
} | 0 | Kotlin | 0 | 0 | 328be6af3500f366de0b43f0590c2253e7011247 | 209 | asm_travel | Apache License 2.0 |
src/commonMain/kotlin/io/rippledown/model/condition/Is.kt | TimLavers | 513,037,911 | false | null | package io.rippledown.model.condition
import io.rippledown.model.Attribute
import io.rippledown.model.RDRCase
import kotlinx.serialization.Serializable
@Serializable
data class Is(override val id: Int? = null, val attribute: Attribute, val toFind: String) : Condition() {
override fun holds(case: RDRCase): Boolean {
val latest = case.getLatest(attribute) ?: return false
return latest.value.text == toFind
}
override fun asText(): String {
return "${attribute.name} is \"$toFind\""
}
override fun sameAs(other: Condition): Boolean {
return if (other is Is) {
other.attribute == attribute
} else false
}
override fun alignAttributes(idToAttribute: (Int) -> Attribute) = Is(id, idToAttribute(attribute.id), toFind)
} | 0 | Kotlin | 0 | 0 | 1c305d766f5764166107eb08f3449873b4022fea | 801 | OpenRDR | MIT License |
app/src/main/java/com/cmj/wanandroid/user/login/LoginViewModel.kt | mikechenmj | 590,477,705 | false | null | package com.cmj.wanandroid.user.login
import android.app.Application
import androidx.lifecycle.ViewModel
import com.cmj.wanandroid.BaseViewModel
import com.cmj.wanandroid.kt.castAndTryEmit
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class LoginViewModel(app: Application) : BaseViewModel(app) {
val passwordCoverFlow: StateFlow<Boolean> = MutableStateFlow(true)
fun setPasswordCover(cover: Boolean) {
passwordCoverFlow.castAndTryEmit(cover)
}
} | 0 | Kotlin | 0 | 0 | b6ba391b5925a5ebff3040575a813ce9e140cbd3 | 513 | WanAndroid | Apache License 2.0 |
app/src/androidTest/java/com/growingio/demo/ui/dashboard/SdkInitFragmentTest.kt | growingio | 632,845,365 | false | null | /*
* Copyright (c) - 2023 Beijing Yishu Technology Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.growingio.demo.ui.dashboard
import androidx.appcompat.widget.AppCompatImageButton
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isChecked
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withParent
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth
import com.growingio.android.sdk.track.events.AutotrackEventType
import com.growingio.android.sdk.track.events.PageEvent
import com.growingio.android.sdk.track.events.ViewElementEvent
import com.growingio.demo.AbstractGrowingTestUnit
import com.growingio.demo.R
import com.growingio.demo.launchFragmentInHiltContainer
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.instanceOf
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* <p>
*
* @author cpacm 2023/7/24
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class SdkInitFragmentTest : AbstractGrowingTestUnit() {
val scenario = launchFragmentInHiltContainer<SdkInitFragment>()
@Before
override fun setup() {
super.setup()
}
@Test
fun onPageTest() {
runEventTest(AutotrackEventType.PAGE, onEvent = { baseEvent ->
if (baseEvent is PageEvent) {
Truth.assertThat(baseEvent.eventType).isEqualTo(AutotrackEventType.PAGE)
Truth.assertThat(baseEvent.title).isEqualTo("初始化")
Truth.assertThat(baseEvent.path).isEqualTo("/SdkInitFragment")
return@runEventTest true
}
false
}) {
}
}
@Test
fun onPageTabTest() {
runEventTest(AutotrackEventType.VIEW_CLICK, onEvent = { baseEvent ->
if (baseEvent is ViewElementEvent) {
Truth.assertThat(baseEvent.eventType).isEqualTo(AutotrackEventType.VIEW_CLICK)
Truth.assertThat(baseEvent.textValue).isEqualTo("CODE")
Truth.assertThat(baseEvent.path).isEqualTo("/SdkInitFragment")
Truth.assertThat(baseEvent.xpath)
.isEqualTo("/HiltTestActivity/SdkInitFragment/ConstraintLayout/MaterialButtonToggleGroup/MaterialButton")
Truth.assertThat(baseEvent.xIndex).isEqualTo("/0/content/0/tabGroup/codeTab")
return@runEventTest true
}
false
}) {
onView(withId(R.id.codeTab)).perform(click()).check(matches(isChecked()))
}
}
@Test
fun onBackTest() {
runEventTest(AutotrackEventType.VIEW_CLICK, onEvent = { baseEvent ->
if (baseEvent is ViewElementEvent) {
Truth.assertThat(baseEvent.eventType).isEqualTo(AutotrackEventType.VIEW_CLICK)
Truth.assertThat(baseEvent.textValue).isEmpty()
Truth.assertThat(baseEvent.path).isEqualTo("/SdkInitFragment")
Truth.assertThat(baseEvent.xpath)
.isEqualTo("/HiltTestActivity/SdkInitFragment/ConstraintLayout/AppBarLayout/Toolbar/AppCompatImageButton")
Truth.assertThat(baseEvent.xIndex).isEqualTo("/0/content/0/appbarLayout/toolbar/0")
return@runEventTest true
}
false
}) {
onView(
allOf(
instanceOf(AppCompatImageButton::class.java),
withParent(withId(R.id.toolbar)),
),
).perform(click())
}
}
}
| 0 | Kotlin | 0 | 1 | 76a24c4b43d9db046028acf365fcb98cab75840d | 4,313 | growingio-sdk-android-demo | Apache License 2.0 |
podcastindex-sdk-base/src/commonMain/kotlin/com/mr3y/podcastindex/services/Podcasts.kt | mr3y-the-programmer | 855,315,416 | false | {"Kotlin": 60865} | package com.mr3y.podcastindex.services
import com.mr3y.podcastindex.PodcastIndexClient
import com.mr3y.podcastindex.extensions.parameterLimit
import com.mr3y.podcastindex.extensions.withErrorHandling
import com.mr3y.podcastindex.model.Medium
import com.mr3y.podcastindex.model.MultiplePodcastsResult
import com.mr3y.podcastindex.model.SinglePodcastResult
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import io.ktor.client.request.parameter
public class Podcasts internal constructor(private val client: HttpClient) {
public suspend fun byFeedId(id: Long): SinglePodcastResult = withErrorHandling {
client.get("${PodcastIndexClient.BaseUrl}/podcasts/byfeedid") {
parameter("id", id)
}
}
public suspend fun byFeedUrl(url: String): SinglePodcastResult = withErrorHandling {
client.get("${PodcastIndexClient.BaseUrl}/podcasts/byfeedurl") {
parameter("url", url)
}
}
public suspend fun byItunesId(id: Long): SinglePodcastResult = withErrorHandling {
client.get("${PodcastIndexClient.BaseUrl}/podcasts/byitunesid") {
parameter("id", id)
}
}
public suspend fun byGuid(guid: String): SinglePodcastResult = withErrorHandling {
client.get("${PodcastIndexClient.BaseUrl}/podcasts/byguid") {
parameter("guid", guid)
}
}
public suspend fun byMedium(medium: Medium, limit: Int = 0): MultiplePodcastsResult = withErrorHandling {
client.get("${PodcastIndexClient.BaseUrl}/podcasts/bymedium") {
parameter("medium", medium.value)
parameterLimit(limit)
}
}
}
| 2 | Kotlin | 0 | 2 | 4697e1e510b99d611011f887ab0e2488950596d8 | 1,661 | PodcastIndex-SDK | Apache License 2.0 |
vector/src/main/java/im/vector/app/eachchat/contact/database/RoomInviteDao.kt | eachchat | 460,467,419 | true | {"Kotlin": 12319527, "Java": 696769, "HTML": 96269, "Shell": 31280, "Python": 19717, "FreeMarker": 7826, "JavaScript": 1782, "Ruby": 1574, "Gherkin": 163} | package im.vector.app.eachchat.contact.database
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import im.vector.app.eachchat.contact.data.RoomInviteDisplay
/**
* Created by chengww on 1/29/21
* @author chengww
*/
@Dao
interface RoomInviteDao {
@Query("SELECT * FROM contacts_rooms_invite ORDER BY `update` DESC")
fun getRoomsLive(): LiveData<List<RoomInviteDisplay>>
@Query("SELECT * FROM contacts_rooms_invite ORDER BY `update` DESC")
fun getRooms(): List<RoomInviteDisplay>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(vararg room: RoomInviteDisplay)
@Query("DELETE FROM contacts_rooms_invite where id = :id")
fun delete(id: Int)
@Query("DELETE FROM contacts_rooms_invite")
fun deleteAll()
}
| 4 | Kotlin | 0 | 0 | 9e975f4bc11da17705254923f54eba306021cc5f | 866 | yiqia-android | Apache License 2.0 |
app/src/main/java/com/furqonr/opencall/ui/components/chat/ChatTopBar.kt | furqonat | 571,502,025 | false | {"Java": 910505, "Kotlin": 70260} | package com.furqonr.opencall.ui.components.chat
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.capitalize
import androidx.compose.ui.text.intl.Locale
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.furqonr.opencall.models.User
import com.furqonr.opencall.ui.theme.Typography
import com.furqonr.opencall.ui.utils.DateConverter
import com.furqonr.opencall.R
// TODO: add navigation to profile
// TODO: when navigation back to chat, keyboard should be hidden first before navigating
@Composable
fun ChatTopBar(
user: User? = null,
navController: NavController
) {
Surface(
modifier = Modifier.fillMaxWidth(),
elevation = 4.dp
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = {
navController.popBackStack()
}
) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_arrow_back_24),
contentDescription = "Back",
tint = Color.Black
)
}
Surface(
modifier = Modifier
.width(40.dp)
.height(40.dp),
elevation = 0.dp,
shape = CircleShape,
color = Color.Gray
) {
}
Column(
modifier = Modifier
.weight(1f)
.padding(start = 8.dp)
) {
user?.displayName?.let { text ->
Text(
text = if (text.length > 13) {
text.substring(0, 13) + "...".capitalize(Locale.current)
} else {
text.replaceFirstChar { if (it.isLowerCase()) it.titlecase(java.util.Locale.ROOT) else it.toString() }
},
style = Typography.h6
)
}
user?.status?.let {
Text(
text = if (it == "online") it else {
DateConverter(it).convert()
}, style = Typography.caption
)
}
}
Column(
modifier = Modifier
.weight(1f)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End
) {
IconButton(onClick = { /*TODO*/ }) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_videocam_24),
contentDescription = "Video Call Icon"
)
}
IconButton(onClick = { /*TODO*/ }) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_call_24),
contentDescription = "Voice Call Icon"
)
}
IconButton(onClick = { /*TODO*/ }) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_more_vert_24),
contentDescription = "More menu"
)
}
}
}
}
}
} | 1 | null | 1 | 1 | f1a878d9b85e5cfe3310f8651f33abec5fff5439 | 4,147 | open-call | MIT License |
java/src/main/kotlin/org/taymyr/lagom/javadsl/api/ServiceCall.kt | gnuzzz | 303,825,959 | true | {"Kotlin": 23066, "Java": 11992, "Scala": 4875} | package org.taymyr.lagom.javadsl.api
import com.lightbend.lagom.javadsl.api.ServiceCall
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.future.future
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* Starts new coroutine and returns its result as an implementation of [ServiceCall].
*
* @param context additional to [CoroutineScope.coroutineContext] context of the coroutine.
* @param start coroutine start option. The default value is [CoroutineStart.DEFAULT].
* @param block the coroutine code.
*/
fun <Request, Response> serviceCall(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.(request: Request) -> Response
) = ServiceCall<Request, Response> {
CoroutineScope(Dispatchers.Unconfined).future(context, start) {
block(it)
}
} | 0 | null | 0 | 0 | 50d05c220b9ca822e014cbac7843b0118f9049ff | 990 | lagom-extensions | Apache License 2.0 |
ui/src/main/kotlin/com/aptopayments/sdk/features/selectcountry/CountryListAdapter.kt | AptoPayments | 197,800,853 | false | null | package com.aptopayments.sdk.features.selectcountry
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatRadioButton
import androidx.recyclerview.widget.RecyclerView
import com.aptopayments.mobile.data.geo.Country
import com.aptopayments.sdk.R
import com.aptopayments.sdk.core.platform.theme.themeManager
internal class CountryListAdapter(
private val countryList: List<CountryListItem>
) : RecyclerView.Adapter<CountryListAdapter.ViewHolder>() {
interface Delegate {
fun onCountryTapped(selectedCountry: Country)
}
var delegate: Delegate? = null
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal var flag: TextView = itemView.findViewById(R.id.tv_flag)
internal var name: TextView = itemView.findViewById(R.id.tv_country_name)
internal var selector: AppCompatRadioButton = itemView.findViewById(R.id.rb_country_selector)
internal var countryRow: RelativeLayout = itemView.findViewById(R.id.root_view)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val countryItemView = inflater.inflate(R.layout.country_item, parent, false)
return ViewHolder(countryItemView)
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
val countryItem = countryList[position]
themeManager().customizeMainItem(viewHolder.name)
themeManager().customizeRadioButton(viewHolder.selector)
viewHolder.name.text = countryItem.country.name
viewHolder.flag.text = countryItem.country.flag
viewHolder.selector.isChecked = countryItem.isSelected
viewHolder.countryRow.setOnClickListener { delegate?.onCountryTapped(countryItem.country) }
viewHolder.selector.setOnClickListener { delegate?.onCountryTapped(countryItem.country) }
}
override fun getItemCount(): Int {
return countryList.size
}
}
| 1 | Kotlin | 0 | 0 | 257af71aa439b3e90c150ae258c78eaa1a6ae817 | 2,278 | apto-ui-sdk-android | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/aws_apigatewayv2_authorizers/_aws_apigatewayv2_authorizers.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.aws_apigatewayv2_authorizers
import kotlin.String
import kotlin.Unit
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpJwtAuthorizer
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpJwtAuthorizerProps
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaAuthorizer
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaAuthorizerProps
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpUserPoolAuthorizer
import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpUserPoolAuthorizerProps
import software.amazon.awscdk.aws_apigatewayv2_authorizers.WebSocketLambdaAuthorizer
import software.amazon.awscdk.aws_apigatewayv2_authorizers.WebSocketLambdaAuthorizerProps
import software.amazon.awscdk.services.cognito.IUserPool
import software.amazon.awscdk.services.lambda.IFunction
public object aws_apigatewayv2_authorizers {
/**
* Authorize Http Api routes on whether the requester is registered as part of an AWS Cognito
* user pool.
*
* Example:
* ```
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpJwtAuthorizer;
* import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
* String issuer = "https://test.us.auth0.com";
* HttpJwtAuthorizer authorizer = HttpJwtAuthorizer.Builder.create("BooksAuthorizer", issuer)
* .jwtAudience(List.of("3131231"))
* .build();
* HttpApi api = new HttpApi(this, "HttpApi");
* api.addRoutes(AddRoutesOptions.builder()
* .integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
* .path("/books")
* .authorizer(authorizer)
* .build());
* ```
*/
public inline fun httpJwtAuthorizer(
id: String,
jwtIssuer: String,
block: HttpJwtAuthorizerDsl.() -> Unit = {},
): HttpJwtAuthorizer {
val builder = HttpJwtAuthorizerDsl(id, jwtIssuer)
builder.apply(block)
return builder.build()
}
/**
* Properties to initialize HttpJwtAuthorizer.
*
* Example:
* ```
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpJwtAuthorizer;
* import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
* String issuer = "https://test.us.auth0.com";
* HttpJwtAuthorizer authorizer = HttpJwtAuthorizer.Builder.create("BooksAuthorizer", issuer)
* .jwtAudience(List.of("3131231"))
* .build();
* HttpApi api = new HttpApi(this, "HttpApi");
* api.addRoutes(AddRoutesOptions.builder()
* .integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
* .path("/books")
* .authorizer(authorizer)
* .build());
* ```
*/
public inline fun httpJwtAuthorizerProps(
block: HttpJwtAuthorizerPropsDsl.() -> Unit = {}
): HttpJwtAuthorizerProps {
val builder = HttpJwtAuthorizerPropsDsl()
builder.apply(block)
return builder.build()
}
/**
* Authorize Http Api routes via a lambda function.
*
* Example:
* ```
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaAuthorizer;
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaResponseType;
* import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
* // This function handles your auth logic
* Function authHandler;
* HttpLambdaAuthorizer authorizer = HttpLambdaAuthorizer.Builder.create("BooksAuthorizer",
* authHandler)
* .responseTypes(List.of(HttpLambdaResponseType.SIMPLE))
* .build();
* HttpApi api = new HttpApi(this, "HttpApi");
* api.addRoutes(AddRoutesOptions.builder()
* .integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
* .path("/books")
* .authorizer(authorizer)
* .build());
* ```
*/
public inline fun httpLambdaAuthorizer(
id: String,
handler: IFunction,
block: HttpLambdaAuthorizerDsl.() -> Unit = {},
): HttpLambdaAuthorizer {
val builder = HttpLambdaAuthorizerDsl(id, handler)
builder.apply(block)
return builder.build()
}
/**
* Properties to initialize HttpTokenAuthorizer.
*
* Example:
* ```
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaAuthorizer;
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpLambdaResponseType;
* import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
* // This function handles your auth logic
* Function authHandler;
* HttpLambdaAuthorizer authorizer = HttpLambdaAuthorizer.Builder.create("BooksAuthorizer",
* authHandler)
* .responseTypes(List.of(HttpLambdaResponseType.SIMPLE))
* .build();
* HttpApi api = new HttpApi(this, "HttpApi");
* api.addRoutes(AddRoutesOptions.builder()
* .integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
* .path("/books")
* .authorizer(authorizer)
* .build());
* ```
*/
public inline fun httpLambdaAuthorizerProps(
block: HttpLambdaAuthorizerPropsDsl.() -> Unit = {}
): HttpLambdaAuthorizerProps {
val builder = HttpLambdaAuthorizerPropsDsl()
builder.apply(block)
return builder.build()
}
/**
* Authorize Http Api routes on whether the requester is registered as part of an AWS Cognito
* user pool.
*
* Example:
* ```
* import software.amazon.awscdk.services.cognito.*;
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.HttpUserPoolAuthorizer;
* import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
* UserPool userPool = new UserPool(this, "UserPool");
* HttpUserPoolAuthorizer authorizer = new HttpUserPoolAuthorizer("BooksAuthorizer", userPool);
* HttpApi api = new HttpApi(this, "HttpApi");
* api.addRoutes(AddRoutesOptions.builder()
* .integration(new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com"))
* .path("/books")
* .authorizer(authorizer)
* .build());
* ```
*/
public inline fun httpUserPoolAuthorizer(
id: String,
pool: IUserPool,
block: HttpUserPoolAuthorizerDsl.() -> Unit = {},
): HttpUserPoolAuthorizer {
val builder = HttpUserPoolAuthorizerDsl(id, pool)
builder.apply(block)
return builder.build()
}
/**
* Properties to initialize HttpUserPoolAuthorizer.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.*;
* import software.amazon.awscdk.services.cognito.*;
* UserPoolClient userPoolClient;
* HttpUserPoolAuthorizerProps httpUserPoolAuthorizerProps = HttpUserPoolAuthorizerProps.builder()
* .authorizerName("authorizerName")
* .identitySource(List.of("identitySource"))
* .userPoolClients(List.of(userPoolClient))
* .userPoolRegion("userPoolRegion")
* .build();
* ```
*/
public inline fun httpUserPoolAuthorizerProps(
block: HttpUserPoolAuthorizerPropsDsl.() -> Unit = {}
): HttpUserPoolAuthorizerProps {
val builder = HttpUserPoolAuthorizerPropsDsl()
builder.apply(block)
return builder.build()
}
/**
* Authorize WebSocket Api routes via a lambda function.
*
* Example:
* ```
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.WebSocketLambdaAuthorizer;
* import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketLambdaIntegration;
* // This function handles your auth logic
* Function authHandler;
* // This function handles your WebSocket requests
* Function handler;
* WebSocketLambdaAuthorizer authorizer = new WebSocketLambdaAuthorizer("Authorizer",
* authHandler);
* WebSocketLambdaIntegration integration = new WebSocketLambdaIntegration("Integration",
* handler);
* WebSocketApi.Builder.create(this, "WebSocketApi")
* .connectRouteOptions(WebSocketRouteOptions.builder()
* .integration(integration)
* .authorizer(authorizer)
* .build())
* .build();
* ```
*/
public inline fun webSocketLambdaAuthorizer(
id: String,
handler: IFunction,
block: WebSocketLambdaAuthorizerDsl.() -> Unit = {},
): WebSocketLambdaAuthorizer {
val builder = WebSocketLambdaAuthorizerDsl(id, handler)
builder.apply(block)
return builder.build()
}
/**
* Properties to initialize WebSocketTokenAuthorizer.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.aws_apigatewayv2_authorizers.*;
* WebSocketLambdaAuthorizerProps webSocketLambdaAuthorizerProps =
* WebSocketLambdaAuthorizerProps.builder()
* .authorizerName("authorizerName")
* .identitySource(List.of("identitySource"))
* .build();
* ```
*/
public inline fun webSocketLambdaAuthorizerProps(
block: WebSocketLambdaAuthorizerPropsDsl.() -> Unit = {}
): WebSocketLambdaAuthorizerProps {
val builder = WebSocketLambdaAuthorizerPropsDsl()
builder.apply(block)
return builder.build()
}
}
| 0 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 9,908 | awscdk-dsl-kotlin | Apache License 2.0 |
ref_code/leetcode-main/kotlin/1472-design-browser-history.kt | yennanliu | 66,194,791 | false | {"Java": 5396849, "Python": 4422387, "JavaScript": 490755, "Kotlin": 464977, "C++": 351516, "C": 246034, "C#": 177156, "Rust": 152545, "Jupyter Notebook": 152285, "TypeScript": 139873, "Go": 129930, "Swift": 102644, "Ruby": 41941, "Scala": 34913, "Dart": 9957, "Shell": 4032, "Dockerfile": 2000, "PLpgSQL": 1348} | /*
* Using an ArrayList
*/
class BrowserHistory(homepage: String) {
val history = ArrayList<String>()
var size = 0
var index = 0
init {
history.add(homepage)
size = 1
}
fun visit(url: String) {
if(history.size < index + 2)
history.add(url)
else
history[index + 1] = url
index++
size = index + 1
}
fun back(steps: Int): String {
index = maxOf(index - steps, 0)
return history[index]
}
fun forward(steps: Int): String {
index = minOf(index + steps, size - 1)
return history[index]
}
}
/*
* Using a Doubly-LinkedList
*/
class BrowserNode(val page: String) {
var next: BrowserNode? = null
var prev: BrowserNode? = null
}
class BrowserHistory(homepage: String) {
var current: BrowserNode? = null
init {
current = BrowserNode(homepage)
}
fun visit(url: String) {
val temp = BrowserNode(url)
current?.next = temp
temp.prev = current
current = current?.next
}
fun back(steps: Int): String {
var stepsTaken = 0
while(current?.prev != null && stepsTaken < steps) {
current = current?.prev
stepsTaken++
}
return current!!.page
}
fun forward(steps: Int): String {
var stepsTaken = 0
while(current?.next != null && stepsTaken < steps) {
current = current?.next
stepsTaken++
}
return current!!.page
}
}
/**
* Your BrowserHistory object will be instantiated and called as such:
* var obj = BrowserHistory(homepage)
* obj.visit(url)
* var param_2 = obj.back(steps)
* var param_3 = obj.forward(steps)
*/
| 0 | Java | 42 | 98 | 209db7daa15718f54f32316831ae269326865f40 | 1,751 | CS_basics | The Unlicense |
src/main/kotlin/g0301_0400/s0368_largest_divisible_subset/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994} | class Solution {
fun largestDivisibleSubset(nums: IntArray): List<Int> {
val n = nums.size
val count = IntArray(n)
val pre = IntArray(n)
nums.sort()
var max = 0
var index = -1
for (i in 0 until n) {
count[i] = 1
pre[i] = -1
for (j in i - 1 downTo 0) {
if (nums[i] % nums[j] == 0 && 1 + count[j] > count[i]) {
count[i] = count[j] + 1
pre[i] = j
}
}
if (count[i] > max) {
max = count[i]
index = i
}
}
val res: MutableList<Int> = ArrayList()
while (index != -1) {
res.add(nums[index])
index = pre[index]
}
return res
}
}
| 0 | Kotlin | 20 | 43 | 471d45c60f669ea1a2e103e6b4d8d54da55711df | 822 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/br/com/schumaker/data/model/ConsoleInMemoryRepository.kt | HudsonSchumaker | 407,621,343 | false | null | package br.com.schumaker.data.model
import org.springframework.stereotype.Repository
@Repository
class ConsoleInMemoryRepository(private var consoles: HashMap<String, Console>): CommonRepository<Console, String> {
override fun save(domain: Console): Console? {
val result = consoles.get(domain.id)
if (null != result) {
consoles.remove(domain.id)
consoles.put(domain.id, domain)
return result;
}
consoles.put(domain.id, domain)
return consoles.get(domain.id)
}
override fun save(domains: Collection<Console>): Iterable<Console> {
domains.forEach(this::save)
return findAll() // have to improve
}
override fun delete(domain: Console) {
consoles.remove(domain.id)
}
override fun findById(id: String): Console? {
return consoles.get(id)
}
override fun findAll(): Iterable<Console> {
return consoles.values
}
}
| 0 | Kotlin | 0 | 0 | 5d737138e15901c146941a583c6a755cc0e9e485 | 970 | SpringBoot-Rest-Resource | MIT License |
domain/src/main/kotlin/team/applemango/runnerbe/domain/runningitem/model/runningitem/information/RunningItemInformation.kt | ricky-buzzni | 485,390,072 | false | {"Kotlin": 615137} | /*
* RunnerBe © 2022 Team AppleMango. all rights reserved.
* RunnerBe license is under the MIT.
*
* [Result.kt] created by Ji Sungbin on 22. 2. 24. 오후 10:24
*
* Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE.
*/
package team.applemango.runnerbe.domain.runningitem.model.runningitem.information
import team.applemango.runnerbe.domain.runningitem.model.runner.Runner
import team.applemango.runnerbe.domain.runningitem.model.runningitem.RunningItem
/**
* @property isMyItem 내가 올린 러닝 아이템인지 여부 (owner boolean)
* @property bookmarked 내가 북마크 한 러닝 아이템인지 여부
* @property item 러닝 아이템 상새 정보
* @property joinRunners 참여한 러너들
* @property waitingRunners 참여 신청한 러너들
*/
data class RunningItemInformation(
val isMyItem: Boolean,
val bookmarked: Boolean,
val item: RunningItem,
val joinRunners: List<Runner>,
val waitingRunners: List<Runner>,
)
| 0 | null | 0 | 0 | f48fb298c07732a9c32afcff0bddb16f9fe2e37a | 900 | RunnerBe-Android | MIT License |
agent/src/main/java/com/code_intelligence/jazzer/instrumentor/EdgeCoverageInstrumentor.kt | tr4nc3 | 359,411,560 | false | {"JSON": 1, "Starlark": 19, "Markdown": 2, "Ignore List": 1, "YAML": 3, "Shell": 5, "C++": 26, "Java": 63, "Diff": 4, "Kotlin": 25, "C": 1} | // Copyright 2021 Code Intelligence GmbH
//
// 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.code_intelligence.jazzer.instrumentor
import com.code_intelligence.jazzer.generated.JAVA_NO_THROW_METHODS
import com.code_intelligence.jazzer.runtime.CoverageMap
import org.jacoco.core.internal.flow.ClassProbesAdapter
import org.jacoco.core.internal.flow.ClassProbesVisitor
import org.jacoco.core.internal.instr.ClassInstrumenter
import org.jacoco.core.internal.instr.IProbeArrayStrategy
import org.jacoco.core.internal.instr.IProbeInserterFactory
import org.jacoco.core.internal.instr.InstrSupport
import org.jacoco.core.internal.instr.ProbeInserter
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import kotlin.math.max
class EdgeCoverageInstrumentor(
private val initialEdgeId: Int,
private val coverageMapClass: Class<*> = CoverageMap::class.java
) : Instrumentor {
private var nextEdgeId = initialEdgeId
private val coverageMapInternalClassName = coverageMapClass.name.replace('.', '/')
override fun instrument(bytecode: ByteArray): ByteArray {
val reader = InstrSupport.classReaderFor(bytecode)
val writer = ClassWriter(reader, 0)
val version = InstrSupport.getMajorVersion(reader)
val visitor = EdgeCoverageClassProbesAdapter(
ClassInstrumenter(edgeCoverageProbeArrayStrategy, edgeCoverageProbeInserterFactory, writer),
InstrSupport.needsFrames(version)
)
reader.accept(visitor, ClassReader.EXPAND_FRAMES)
return writer.toByteArray()
}
val numEdges
get() = nextEdgeId - initialEdgeId
private val isTesting
get() = coverageMapClass != CoverageMap::class.java
private fun nextEdgeId(): Int {
if (nextEdgeId >= CoverageMap.mem.capacity()) {
if (!isTesting) {
CoverageMap.enlargeCoverageMap()
}
}
return nextEdgeId++
}
/**
* The maximal number of stack elements used by [loadCoverageMap].
*/
private val loadCoverageMapStackSize = 1
/**
* Inject bytecode that loads the coverage map into local variable [variable].
*/
private fun loadCoverageMap(mv: MethodVisitor, variable: Int) {
mv.apply {
visitFieldInsn(
Opcodes.GETSTATIC,
coverageMapInternalClassName,
"mem",
"Ljava/nio/ByteBuffer;"
)
// Stack: mem (maxStack: 1)
visitVarInsn(Opcodes.ASTORE, variable)
}
}
/**
* The maximal number of stack elements used by [instrumentControlFlowEdge].
*/
private val instrumentControlFlowEdgeStackSize = 5
/**
* Inject bytecode instrumentation on a control flow edge with ID [edgeId]. The coverage map can be loaded from
* local variable [variable].
*/
private fun instrumentControlFlowEdge(mv: MethodVisitor, edgeId: Int, variable: Int) {
mv.apply {
visitVarInsn(Opcodes.ALOAD, variable)
// Stack: mem
push(edgeId)
// Stack: mem | edgeId
visitInsn(Opcodes.DUP2)
// Stack: mem | edgeId | mem | edgeId
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/nio/ByteBuffer", "get", "(I)B", false)
// Increment the counter, but ensure that it never stays at 0 after an overflow by incrementing it again in
// that case.
// This approach performs better than saturating the counter at 255 (see Section 3.3 of
// https://www.usenix.org/system/files/woot20-paper-fioraldi.pdf)
// Stack: mem | edgeId | counter (sign-extended to int)
push(0xff)
// Stack: mem | edgeId | counter (sign-extended to int) | 0x000000ff
visitInsn(Opcodes.IAND)
// Stack: mem | edgeId | counter (zero-extended to int)
push(1)
// Stack: mem | edgeId | counter | 1
visitInsn(Opcodes.IADD)
// Stack: mem | edgeId | counter + 1
visitInsn(Opcodes.DUP)
// Stack: mem | edgeId | counter + 1 | counter + 1
push(8)
// Stack: mem | edgeId | counter + 1 | counter + 1 | 8 (maxStack: +5)
visitInsn(Opcodes.ISHR)
// Stack: mem | edgeId | counter + 1 | 1 if the increment overflowed to 0, 0 otherwise
visitInsn(Opcodes.IADD)
// Stack: mem | edgeId | counter + 2 if the increment overflowed, counter + 1 otherwise
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/nio/ByteBuffer", "put", "(IB)Ljava/nio/ByteBuffer;", false)
// Stack: mem
visitInsn(Opcodes.POP)
if (isTesting) {
visitMethodInsn(Opcodes.INVOKESTATIC, coverageMapInternalClassName, "updated", "()V", false)
}
}
}
/**
* The maximal number of stack elements used by [instrumentMethodEdge].
*/
private val instrumentMethodEdgeStackSize = instrumentControlFlowEdgeStackSize
/**
* Inject bytecode instrumentation right before a method invocation (if needed). The coverage map can be loaded from
* local variable [variable].
*
* Note: Since not every method invocation might need instrumentation, an edge ID should only be generated if needed
* by calling [nextEdgeId].
*/
private fun instrumentMethodEdge(
mv: MethodVisitor,
variable: Int,
internalClassName: String,
methodName: String,
descriptor: String
) {
if (internalClassName.startsWith("com/code_intelligence/jazzer/") && !isTesting)
return
if (isNoThrowMethod(internalClassName, methodName, descriptor))
return
instrumentControlFlowEdge(mv, nextEdgeId(), variable)
}
/**
* Checks whether a method is in a list of function known not to throw any exceptions (including subclasses of
* [java.lang.RuntimeException]).
*
* If a method is known not to throw any exceptions, calls to it do not need to be instrumented for coverage as it
* will always return to the same basic block.
*
* Note: According to the JVM specification, a [java.lang.VirtualMachineError] can always be thrown. As it is fatal
* for all practical purposes, we can ignore errors of this kind for coverage instrumentation.
*/
private fun isNoThrowMethod(internalClassName: String, methodName: String, descriptor: String): Boolean {
// We only collect no throw information for the Java standard library.
if (!internalClassName.startsWith("java/"))
return false
val key = "$internalClassName#$methodName#$descriptor"
return key in JAVA_NO_THROW_METHODS
}
// The remainder of this file interfaces with classes in org.jacoco.core.internal. Changes to this part should not be
// necessary unless JaCoCo is updated or the way we instrument for coverage changes fundamentally.
private inner class EdgeCoverageProbeInserter(
access: Int,
name: String,
desc: String,
mv: MethodVisitor,
arrayStrategy: IProbeArrayStrategy,
) : ProbeInserter(access, name, desc, mv, arrayStrategy) {
override fun insertProbe(id: Int) {
instrumentControlFlowEdge(mv, id, variable)
}
override fun visitMaxs(maxStack: Int, maxLocals: Int) {
val maxStackIncrease = max(instrumentControlFlowEdgeStackSize, instrumentMethodEdgeStackSize)
val newMaxStack = max(maxStack + maxStackIncrease, loadCoverageMapStackSize)
val newMaxLocals = maxLocals + 1
mv.visitMaxs(newMaxStack, newMaxLocals)
}
override fun visitMethodInsn(
opcode: Int,
owner: String,
name: String,
descriptor: String,
isInterface: Boolean
) {
instrumentMethodEdge(mv, variable, owner, name, descriptor)
mv.visitMethodInsn(opcode, owner, name, descriptor, isInterface)
}
}
private val edgeCoverageProbeInserterFactory =
IProbeInserterFactory { access, name, desc, mv, arrayStrategy ->
EdgeCoverageProbeInserter(access, name, desc, mv, arrayStrategy)
}
private inner class EdgeCoverageClassProbesAdapter(cv: ClassProbesVisitor, trackFrames: Boolean) :
ClassProbesAdapter(cv, trackFrames) {
override fun nextId(): Int = nextEdgeId()
}
private val edgeCoverageProbeArrayStrategy = object : IProbeArrayStrategy {
override fun storeInstance(mv: MethodVisitor, clinit: Boolean, variable: Int): Int {
loadCoverageMap(mv, variable)
return loadCoverageMapStackSize
}
override fun addMembers(cv: ClassVisitor, probeCount: Int) {}
}
private fun MethodVisitor.push(value: Int) {
InstrSupport.push(this, value)
}
}
| 1 | null | 1 | 1 | a295567eea872164d475921e9b0605b5bb810cd2 | 9,589 | jazzer | Apache License 2.0 |
wiki/versions/1.19/item/simple_item/kotlin/src/main/kotlin/org/quiltmc/wiki/simple_item/SimpleItemExample.kt | QuiltMC | 501,828,065 | false | null | package org.quiltmc.wiki.simple_item
import net.minecraft.item.Item
import net.minecraft.item.ItemGroup
import net.minecraft.util.registry.Registry
import org.quiltmc.loader.api.ModContainer
import org.quiltmc.qkl.wrapper.minecraft.registry.registryScope
import org.quiltmc.qkl.wrapper.qsl.items.itemSettingsOf
import org.quiltmc.qsl.base.api.entrypoint.ModInitializer
// @start Declaration
val EXAMPLE_ITEM: Item = Item(itemSettingsOf(group = ItemGroup.MISC))
// @end Declaration
object SimpleItemExample: ModInitializer {
override fun onInitialize(mod: ModContainer) {
// @start Registration
registryScope(mod.metadata().id()) {
EXAMPLE_ITEM withPath "example_item" toRegistry Registry.ITEM
}
// @end Registration
}
}
| 13 | Java | 23 | 30 | 3319fd65f485252791ea352f2314a18faa2b3a56 | 776 | developer-wiki | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/jaffa/rpc/lib/grpc/receivers/GrpcAsyncResponseReceiver.kt | dredwardhyde | 146,790,214 | false | null | package com.jaffa.rpc.lib.grpc.receivers
import com.jaffa.rpc.grpc.services.CallbackRequest
import com.jaffa.rpc.grpc.services.CallbackResponse
import com.jaffa.rpc.grpc.services.CallbackServiceGrpc.CallbackServiceImplBase
import com.jaffa.rpc.lib.common.RequestInvocationHelper
import com.jaffa.rpc.lib.exception.JaffaRpcSystemException
import com.jaffa.rpc.lib.grpc.MessageConverterHelper
import com.jaffa.rpc.lib.zookeeper.Utils
import io.grpc.Server
import io.grpc.netty.NettyServerBuilder
import io.grpc.stub.StreamObserver
import org.slf4j.LoggerFactory
import java.io.Closeable
import java.util.concurrent.Executors
class GrpcAsyncResponseReceiver : Runnable, Closeable {
private val log = LoggerFactory.getLogger(GrpcAsyncResponseReceiver::class.java)
private lateinit var server: Server
override fun run() {
try {
server = GrpcAsyncAndSyncRequestReceiver.addSecurityContext(NettyServerBuilder.forPort(Utils.callbackPort))
.executor(requestService).addService(CallbackServiceImpl()).build()
server.start()
server.awaitTermination()
} catch (zmqStartupException: Exception) {
log.error("Error during gRPC async response receiver startup:", zmqStartupException)
throw JaffaRpcSystemException(zmqStartupException)
}
log.info("{} terminated", this.javaClass.simpleName)
}
override fun close() {
try {
server.shutdown()
requestService.shutdown()
log.info("gRPC async response receiver stopped")
}catch (e: Exception){
//No-op
}
}
private class CallbackServiceImpl : CallbackServiceImplBase() {
private val log = LoggerFactory.getLogger(CallbackServiceImpl::class.java)
override fun execute(request: CallbackRequest, responseObserver: StreamObserver<CallbackResponse>) {
try {
RequestInvocationHelper.processCallbackContainer(MessageConverterHelper.fromGRPCCallbackRequest(request))
responseObserver.also { it.onNext(CallbackResponse.newBuilder().setResponse("OK").build()) }.also { it.onCompleted() }
} catch (exception: Exception) {
log.error("gRPC callback execution exception", exception)
}
}
}
companion object {
private val requestService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
}
} | 0 | Kotlin | 2 | 7 | 0a83770bcec4cb0ea4c93d3e2325ce0447fccfd3 | 2,474 | jaffa-rpc-library | Apache License 2.0 |
desktop/src/main/java/com/kaspersky/test_server/CommandExecutorImpl.kt | eakurnikov | 208,156,480 | true | {"Kotlin": 41009} | package com.kaspersky.test_server
import com.kaspersky.test_server.api.Command
import com.kaspersky.test_server.api.CommandExecutor
import com.kaspersky.test_server.api.CommandResult
import com.kaspresky.test_server.log.Logger
import java.lang.UnsupportedOperationException
internal class CommandExecutorImpl(
private val cmdCommandPerformer: CmdCommandPerformer,
private val deviceName: String,
private val adbServerPort: String?,
private val logger: Logger
) : CommandExecutor {
override fun execute(command: Command): CommandResult {
return when (command) {
is CmdCommand -> cmdCommandPerformer.perform(command.body)
is AdbCommand -> {
val adbCommand = "adb ${ adbServerPort?.let { "-P $adbServerPort " } ?: "" }-s $deviceName ${command.body}"
logger.i("CommandExecutorImpl", "execute", "adbCommand=$adbCommand")
cmdCommandPerformer.perform(adbCommand)
}
else -> throw UnsupportedOperationException("The command=$command is unsupported command")
}
}
} | 0 | null | 0 | 1 | d899bfc0f0399e4e25da2a21551e88c2b3d953aa | 1,093 | AdbServer | Apache License 2.0 |
block-tlb/src/ProtoListNext.kt | ton-community | 448,983,229 | false | {"Kotlin": 1194581} | package org.ton.block
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.ton.tlb.loadTlb
import org.ton.tlb.providers.TlbConstructorProvider
import org.ton.tlb.storeTlb
@SerialName("proto_list_next")
@Serializable
data class ProtoListNext(
val head: Protocol,
val tail: ProtoList
) : ProtoList {
override fun iterator(): Iterator<Protocol> = iterator {
yield(head)
yieldAll(tail)
}
companion object : TlbConstructorProvider<ProtoListNext> by ProtoListNextTlbConstructor
}
private object ProtoListNextTlbConstructor : org.ton.tlb.TlbConstructor<ProtoListNext>(
schema = "proto_list_next#1 head:Protocol tail:ProtoList = ProtoList;"
) {
override fun storeTlb(
cellBuilder: org.ton.cell.CellBuilder,
value: ProtoListNext
) {
cellBuilder.storeTlb(Protocol, value.head)
cellBuilder.storeTlb(ProtoList, value.tail)
}
override fun loadTlb(
cellSlice: org.ton.cell.CellSlice
): ProtoListNext {
val head = cellSlice.loadTlb(Protocol)
val tail = cellSlice.loadTlb(ProtoList)
return ProtoListNext(head, tail)
}
}
| 21 | Kotlin | 24 | 80 | 7eb82e9b04a2e518182ebfc56c165fbfcc916be9 | 1,177 | ton-kotlin | Apache License 2.0 |
shared/src/commonMain/kotlin/sanchez/sergio/kmp_test/persistence/api/location/ILocationRepository.kt | sergio11 | 352,054,073 | false | null | package sanchez.sergio.kmp_test.persistence.api.location
import sanchez.sergio.kmp_test.domain.models.Location
import sanchez.sergio.kmp_test.domain.models.PageData
import sanchez.sergio.kmp_test.persistence.api.RepoErrorException
import sanchez.sergio.kmp_test.persistence.api.RepoNoResultException
import kotlin.coroutines.cancellation.CancellationException
/**
* Location Repository
*/
interface ILocationRepository {
/**
* Find Paginated List
* @param page
*/
@Throws(RepoErrorException::class, RepoNoResultException::class, CancellationException::class)
suspend fun findPaginatedList(page: Long): PageData<Location>
/**
* Find By Id
*/
@Throws(RepoErrorException::class, RepoNoResultException::class, CancellationException::class)
suspend fun findById(id: Int): Location
} | 0 | Kotlin | 1 | 9 | c5d1ce52f7a5b86d370651c047901d46875126be | 833 | RickAndMortyKMP | Apache License 2.0 |
inngest/src/main/kotlin/com/inngest/Step.kt | inngest | 712,631,978 | false | {"Kotlin": 102709, "Java": 78871, "Makefile": 748, "Nix": 742, "Shell": 514} | package com.inngest
import java.time.Duration
typealias MemoizedRecord = HashMap<String, Any>
typealias MemoizedState = HashMap<String, MemoizedRecord>
data class InngestEvent(
val name: String,
val data: Any,
)
data class SendEventsResponse(
val ids: Array<String>,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SendEventsResponse
return ids.contentEquals(other.ids)
}
override fun hashCode(): Int = ids.contentHashCode()
}
class StepInvalidStateTypeException(
val id: String,
val hashedId: String,
) : Throwable("Step execution interrupted")
// TODO - Add State type mismatch checks
// class StepStateTypeMismatchException(
// val id: String,
// val hashedId: String,
// ) : Throwable("Step execution interrupted")
open class StepInterruptException(
val id: String,
val hashedId: String,
open val data: Any?,
) : Throwable("Interrupt $id")
class StepInterruptSleepException(
id: String,
hashedId: String,
override val data: String,
) : StepInterruptException(id, hashedId, data)
class StepInterruptSendEventException(
id: String,
hashedId: String,
val eventIds: Array<String>,
) : StepInterruptException(id, hashedId, eventIds)
class StepInterruptInvokeException(
id: String,
hashedId: String,
val appId: String,
val fnId: String,
data: Any?,
val timeout: String?,
) : StepInterruptException(id, hashedId, data)
class StepInterruptWaitForEventException(
id: String,
hashedId: String,
val waitEvent: String,
val timeout: String,
val ifExpression: String?,
) : StepInterruptException(id, hashedId, null)
class Step(
private val state: State,
val client: Inngest,
) {
/**
* Run a function
*
* @param id unique step id for memoization
* @param fn the function to run
*/
inline fun <reified T> run(
id: String,
noinline fn: () -> T,
): T = run(id, fn, T::class.java)
fun <T> run(
id: String,
fn: () -> T,
type: Class<T>,
): T {
val hashedId = state.getHashFromId(id)
try {
val stepResult = state.getState(hashedId, type)
if (stepResult != null) {
return stepResult
}
} catch (e: StateNotFound) {
// If there is no existing result, run the lambda
val data = fn()
throw StepInterruptException(id, hashedId, data)
}
// TODO - Catch Step Error here and throw it when error parsing is added to getState
// TODO - handle invalidly stored step types properly
throw Exception("step state incorrect type")
}
/**
* Invoke another Inngest function as a step
*
* @param id unique step id for memoization
* @param appId ID of the Inngest app which contains the function to invoke (see client)
* @param fnId ID of the function to invoke
* @param data the data to pass within `event.data` to the function
* @param timeout an optional timeout for the invoked function. If the invoked function does
* not finish within this time, the invoked function will be marked as failed.
*/
inline fun <reified T> invoke(
id: String,
appId: String,
fnId: String,
data: Any?,
timeout: String? = null,
): T = invoke(id, appId, fnId, data, timeout, T::class.java)
fun <T> invoke(
id: String,
appId: String,
fnId: String,
data: Any?,
timeout: String?,
type: Class<T>,
): T {
val hashedId = state.getHashFromId(id)
try {
val stepResult = state.getState(hashedId, type)
if (stepResult != null) {
return stepResult
}
} catch (e: StateNotFound) {
throw StepInterruptInvokeException(id, hashedId, appId, fnId, data, timeout)
}
// TODO - handle invalidly stored step types properly
throw Exception("step state incorrect type")
}
/**
* Sleep for a specific duration
*
* @param id unique step id for memoization
* @param duration the duration of time to sleep for
*/
fun sleep(
id: String,
duration: Duration,
) {
val hashedId = state.getHashFromId(id)
try {
// If this doesn't throw an error, it's null and that's what is expected
val stepState = state.getState<Any?>(hashedId)
if (stepState != null) {
throw Exception("step state expected sleep, got something else")
}
return
} catch (e: StateNotFound) {
val durationInSeconds = duration.seconds
throw StepInterruptSleepException(id, hashedId, "${durationInSeconds}s")
}
}
/**
* Sends multiple events to Inngest
*
* @param id Unique step id for memoization.
* @param event An event payload object.
*
*/
fun sendEvent(
id: String,
event: InngestEvent,
) = sendEvent(id, arrayOf(event))
/**
* Sends a single event to Inngest
*
* @param id Unique step id for memoization.
* @param events An array of event payload objects.
*
*/
fun sendEvent(
id: String,
events: Array<InngestEvent>,
): SendEventsResponse {
val hashedId = state.getHashFromId(id)
try {
val stepState = state.getState<Array<String>>(hashedId, "event_ids")
if (stepState != null) {
return SendEventsResponse(stepState)
}
throw Exception("step state expected sendEvent, got something else")
} catch (e: StateNotFound) {
val response = client.send<SendEventsResponse>(events)
throw StepInterruptSendEventException(id, hashedId, response!!.ids)
}
}
/**
* Waits for an event with the name provided in `waitEvent`, optionally check for a condition
* specified in `ifExpression`
*
* @param id Unique step id for memoization.
* @param waitEvent The name of the event we want the function to wait for
* @param timeout The amount of time to wait to receive an event. A time string compatible with https://www.npmjs.com/package/ms
* @param ifExpression An expression on which to conditionally match the original event trigger (`event`) and the wait event (`async`).
* Expressions are defined using the Common Expression Language (CEL) with the events accessible using dot-notation.
*
*/
fun waitForEvent(
id: String,
waitEvent: String,
timeout: String,
ifExpression: String?,
// TODO use better types for timeout and ifExpression that serialize to the relevant strings we send to the inngest server, instead of using raw strings
// TODO support `match` which is a convenience for checking the same expression in `event` and `async`. Also make it a mutually exclusive argument with
// ifExpression, possibly with a sealed class?
): Any? {
val hashedId = state.getHashFromId(id)
try {
val stepResult = state.getState<Any?>(hashedId)
if (stepResult != null) {
return stepResult
}
return null // TODO should this throw an exception? also look into `EventPayload` https://github.com/inngest/inngest-kt/pull/26#discussion_r150176713
} catch (e: StateNotFound) {
throw StepInterruptWaitForEventException(id, hashedId, waitEvent, timeout, ifExpression)
}
}
}
| 2 | Kotlin | 3 | 1 | cee727d267ffad760c85d5f8623df2d563cfa467 | 7,759 | inngest-kt | Apache License 2.0 |
android/app/src/main/kotlin/com/example/money_spender/MainActivity.kt | D-200021 | 397,201,801 | false | {"HTML": 3705, "Dart": 3419, "Objective-C": 1121, "Java": 642, "Shell": 585, "Swift": 404, "Kotlin": 130} | package com.example.money_spender
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | HTML | 0 | 1 | 94bc5b78df70d08c90450fcc68dadbd55f90f03c | 130 | Sheth-s-Money-Spender | MIT License |
app/src/main/java/com/alex/cooksample/ui/recipes/detail/RecipeDetailState.kt | oleksandr-riabykh | 452,447,704 | false | null | package com.alex.cooksample.ui.recipes.detail
import com.alex.cooksample.ui.models.RecipeUIModel
sealed class RecipeDetailState {
data class OnLoadCompleted(val data: RecipeUIModel) : RecipeDetailState()
data class OnError(val error: Exception) : RecipeDetailState()
} | 0 | Kotlin | 0 | 0 | 5c80926fbac618ab7929e67bce1361d07d947dfa | 278 | cookapp | MIT License |
test-app/src/androidTest/java/com/avito/android/ui/test/TabLayoutScreen.kt | dimorinny | 204,687,625 | true | {"Kotlin": 322614} | package com.avito.android.ui.test
import android.support.test.espresso.matcher.ViewMatchers.withId
import com.avito.android.test.page_object.PageObject
import com.avito.android.test.page_object.TabLayoutElement
import com.avito.android.ui.R
class TabLayoutScreen : PageObject() {
val tabs: TabLayoutElement = element(withId(R.id.tabs))
}
| 0 | Kotlin | 0 | 0 | ee35fc0f4a5f78dc93f960c0ca366233397f24f7 | 344 | android-ui-testing | MIT License |
src/jsMain/kotlin/net/dankito/ksoup/platform/AtomicInt.kt | dankito | 671,983,575 | false | null | package net.dankito.ksoup.platform
actual class AtomicInt actual constructor(private var value: Int) {
actual fun get() = this.value
actual fun set(newValue: Int) {
this.value = newValue
}
actual fun incrementAndGet(): Int {
this.value += 1
return this.value
}
} | 0 | Kotlin | 0 | 0 | f216a95e3b2668a4c046610b1370224c16ea3b0f | 311 | kSoup | MIT License |
AndroidTriviaNavigation/app/src/main/java/com/example/android/navigation/RulesFragment.kt | markgray | 230,240,820 | true | {"Kotlin": 1356167} | /*
* Copyright 2018, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.navigation
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* This [Fragment] just displays the rules of the game
*/
class RulesFragment : Fragment() {
/**
* Called to have the fragment instantiate its user interface view. We just return the [View]
* that the `inflate` method of our [LayoutInflater] parameter [inflater] returns when it
* inflates a new view hierarchy from our layout file [R.layout.fragment_rules] using our
* [ViewGroup] parameter [container] for our LayoutParams without attaching to it.
*
* @param inflater The [LayoutInflater] object that can be used to inflate
* any views in the fragment.
* @param container If non-null, this is the parent view that the fragment's
* UI will be attached to. The fragment should not add the view itself,
* but this can be used to generate the LayoutParams of the view.
* @param savedInstanceState If non-null, this fragment is being re-constructed
* from a previous saved state as given here.
*/
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_rules, container, false)
}
}
| 0 | Kotlin | 0 | 0 | d914a0382556892b880393e35689111af98d999f | 2,058 | android-kotlin-fundamentals-apps | Apache License 2.0 |
testerum-backend/testerum-runner/testerum-runner-cmdline/src/main/kotlin/com/testerum/runner_cmdline/module_di/submodules/RunnerTransformersModuleFactory.kt | testerum | 241,460,788 | false | null | package com.testerum.runner_cmdline.module_di.submodules
import com.testerum.common_di.BaseModuleFactory
import com.testerum.common_di.ModuleFactoryContext
import com.testerum.runner_cmdline.transformer.builtin.atomic.AtomicBooleanTransformer
import com.testerum.runner_cmdline.transformer.builtin.atomic.AtomicIntegerTransformer
import com.testerum.runner_cmdline.transformer.builtin.atomic.AtomicLongTransformer
import com.testerum.runner_cmdline.transformer.builtin.date.DateTransformer
import com.testerum.runner_cmdline.transformer.builtin.enums.EnumTransformer
import com.testerum.runner_cmdline.transformer.builtin.lang.*
import com.testerum.runner_cmdline.transformer.builtin.math.BigDecimalTransformer
import com.testerum.runner_cmdline.transformer.builtin.math.BigIntegerTransformer
import com.testerum_api.testerum_steps_api.transformer.Transformer
class RunnerTransformersModuleFactory(context: ModuleFactoryContext) : BaseModuleFactory(context) {
val globalTransformers: List<Transformer<*>> = listOf(
BooleanTransformer,
CharacterTransformer,
ByteTransformer,
ShortTransformer,
IntegerTransformer,
LongTransformer,
FloatTransformer,
DoubleTransformer,
BigIntegerTransformer,
BigDecimalTransformer,
AtomicBooleanTransformer(BooleanTransformer),
AtomicIntegerTransformer(IntegerTransformer),
AtomicLongTransformer(LongTransformer),
EnumTransformer,
DateTransformer
)
}
| 33 | null | 3 | 22 | 0a53c71b5f659e41282114127f595aad5ab1e4fb | 1,572 | testerum | Apache License 2.0 |
app/src/main/java/com/chc/watchtrack/movies/MovieBindings.kt | calsf | 282,465,774 | false | null | package com.chc.watchtrack.movies
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.chc.watchtrack.database.MovieEntity
/*
Bind and display Movie values in movie_item.xml text views
*/
@BindingAdapter("title")
fun TextView.setTitle(item: MovieEntity?) {
item?.let {
text = item.title
}
}
@BindingAdapter("hours")
fun TextView.setHours(item: MovieEntity?) {
item?.let {
text = item.hours.toString().padStart(2, '0')
}
}
@BindingAdapter("minutes")
fun TextView.setMinutes(item: MovieEntity?) {
item?.let {
text = item.minutes.toString().padStart(2, '0')
}
}
@BindingAdapter("seconds")
fun TextView.setSeconds(item: MovieEntity?) {
item?.let {
text = item.seconds.toString().padStart(2, '0')
}
} | 0 | Kotlin | 0 | 0 | ed3a15c5542782fd691b07c09bd31f8fd6e96f0c | 798 | watchtrack | MIT License |
Hoodies-Network/src/main/kotlin/com/gap/hoodies_network/cookies/persistentstorage/EncryptedDaoWrapperForCookies.kt | gapinc | 601,350,905 | false | {"Kotlin": 376353, "Java": 485} | package com.gap.hoodies_network.cookies.persistentstorage
import android.content.Context
import androidx.room.Room
import com.gap.hoodies_network.cache.EncryptedCache
import com.google.gson.Gson
import java.net.HttpCookie
import java.net.URI
import java.util.*
import javax.crypto.Cipher
class EncryptedDaoWrapperForCookies(instanceName: String, context: Context) {
private val db = Room.databaseBuilder(context, EncryptedCookieDatabase::class.java, instanceName).build().encryptedCookieDao()
fun getAll() : List<HttpCookie> {
return db.getAll().map{ decryptCookie(it).cookie }.toList()
}
fun getByHost(host: URI) : List<HttpCookie> {
return db.getByHost(uriToHost(host)).map{ decryptCookie(it).cookie }.toList()
}
private fun decryptCookie(encryptedCookie: EncryptedCookie) : CookieAndId {
val iv = Base64.getDecoder().decode(encryptedCookie.iv)
val decryptedCookieJson = EncryptedCache.runAES(Base64.getDecoder().decode(encryptedCookie.cookie), iv, Cipher.DECRYPT_MODE).decodeToString()
return CookieAndId(Gson().fromJson(decryptedCookieJson, HttpCookie::class.java), encryptedCookie.id)
}
fun deleteAll() {
db.deleteAll()
}
fun deleteCookie(cookie: HttpCookie) : Boolean {
return db.deleteByHash(cookie.hashCode()) > 0
}
fun getAllHosts() : List<URI> {
return db.getAllHosts().map{ URI(it) }.toList()
}
fun insert(host: URI, cookie: HttpCookie) {
val cookieJson = Gson().toJson(cookie)
var iv = EncryptedCache.genIV()
//Make sure the IV is unique
while (db.getByIv(Base64.getEncoder().encodeToString(iv)).isNotEmpty())
iv = EncryptedCache.genIV()
val encryptedCookieJson = Base64.getEncoder().encodeToString(EncryptedCache.runAES(cookieJson.encodeToByteArray(), iv, Cipher.ENCRYPT_MODE))
db.insert(EncryptedCookie(0, uriToHost(host), encryptedCookieJson, Base64.getEncoder().encodeToString(iv), cookie.hashCode()))
}
private fun uriToHost(uri: URI) : String {
return "${uri.scheme.replace("https", "http")}://${uri.host}"
}
data class CookieAndId(val cookie: HttpCookie, val id: Int)
} | 0 | Kotlin | 0 | 9 | 780da18597ae9f89b38e171055a99e3fd1298d24 | 2,207 | hoodies-network | MIT License |
src/commonMain/kotlin/ehn/techiop/hcert/kotlin/chain/impl/SchemaValidationAdapter.kt | digital-blueprint | 407,104,446 | true | {"Kotlin": 322195, "HTML": 16509, "JavaScript": 1695} | package ehn.techiop.hcert.kotlin.chain.impl
import ehn.techiop.hcert.kotlin.data.CborObject
import ehn.techiop.hcert.kotlin.data.GreenCertificate
//As of 1.3.0 our codebase handles all version equally well
//we need to work around Duplicate JVM class name bug → we can skip expect definitions altogether
abstract class SchemaLoader<T> {
companion object {
private const val BASE_VERSION = "1.3.0"
private val KNOWN_VERSIONS = arrayOf(
"1.0.0",
"1.0.1",
"1.1.0",
"1.2.0",
"1.2.1",
"1.3.0"
)
}
internal val validators = KNOWN_VERSIONS.mapIndexed { i, version ->
KNOWN_VERSIONS[i] to loadSchema(version)
}.toMap()
internal abstract fun loadSchema(version: String): T
internal abstract fun loadFallbackSchema(): T
}
expect class SchemaValidationAdapter(cbor: CborObject) {
fun hasValidator(versionString: String): Boolean
fun validateBasic(versionString: String): Collection<SchemaError>
fun toJson(): GreenCertificate
fun validateWithFallback(): Collection<SchemaError>
}
data class SchemaError(val error: String)
| 0 | Kotlin | 0 | 2 | fcfbe19408112e1ba964fdb9dea09049f1596bc6 | 1,168 | hcert-kotlin | Apache License 2.0 |
core/src/main/java/at/shockbytes/dante/core/network/google/gson/GoogleBooksSuggestionResponseDeserializer.kt | shockbytes | 92,944,830 | false | {"Kotlin": 790879} | package at.shockbytes.dante.core.network.google.gson
import at.shockbytes.dante.core.book.BookEntity
import at.shockbytes.dante.core.book.BookSuggestion
import at.shockbytes.dante.core.network.BookDownloader.Companion.MAX_FETCH_AMOUNT
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParseException
import java.lang.reflect.Type
/**
* Author: <NAME>
* Date: 13.02.2017
*/
class GoogleBooksSuggestionResponseDeserializer : JsonDeserializer<BookSuggestion> {
@Throws(JsonParseException::class)
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext
): BookSuggestion? {
return json.asJsonObject.getAsJsonArray("items")?.let {
var size = json.asJsonObject.getAsJsonArray("items").size()
if (size > 0) {
// Retrieve the main information from the json object
val volumeInfoMain = json.asJsonObject.getAsJsonArray("items").get(0)
.asJsonObject.get("volumeInfo").asJsonObject
// Look for main suggestion and check for fetching size
val mainSuggestion = grabBook(volumeInfoMain)
size = if (size >= MAX_FETCH_AMOUNT) MAX_FETCH_AMOUNT else size
// Because the data of other books is already fetched, let's convert them into objects
val otherSuggestions = (1 until size).map { idx ->
val volumeInfo = json.asJsonObject.getAsJsonArray("items")
.get(idx).asJsonObject.get("volumeInfo").asJsonObject
grabBook(volumeInfo)
}
BookSuggestion(mainSuggestion, otherSuggestions)
} else null
}
}
private fun grabBook(volumeInfo: JsonObject): BookEntity {
val title = volumeInfo.get("title").asString
val subtitle = getSubtitle(volumeInfo)
val author = getAuthors(volumeInfo)
val pageCount = getPageCount(volumeInfo)
val publishedDate = getPublishedDate(volumeInfo)
val isbn = getIsbn(volumeInfo)
val thumbnailAddress = getImageLink(volumeInfo)
val googleBooksLink = getGoogleBooksLink(volumeInfo)
val language = getLanguage(volumeInfo)
val summary = getSummary(volumeInfo)
return BookEntity(
title = title,
subTitle = subtitle,
author = author,
pageCount = pageCount,
publishedDate = publishedDate,
isbn = isbn,
thumbnailAddress = thumbnailAddress,
googleBooksLink = googleBooksLink,
language = language,
summary = summary
)
}
private fun getPublishedDate(volumeInfo: JsonObject): String {
return volumeInfo.get("publishedDate")?.asString ?: ""
}
private fun getGoogleBooksLink(volumeInfo: JsonObject): String {
return volumeInfo.get("infoLink")?.asString ?: ""
}
private fun getLanguage(volumeInfo: JsonObject): String {
return volumeInfo.get("language")?.asString ?: ""
}
private fun getSubtitle(volumeInfo: JsonObject): String {
return volumeInfo.get("subtitle")?.asString ?: ""
}
private fun getPageCount(volumeInfo: JsonObject): Int {
return volumeInfo.get("pageCount")?.asInt ?: 0
}
private fun getIsbn(volumeInfo: JsonObject): String {
if (volumeInfo.get("industryIdentifiers") != null) {
val allIsbn = volumeInfo.get("industryIdentifiers").asJsonArray
allIsbn
.map { it.asJsonObject }
.filter { it.get("type") != null && it.get("type").asString == "ISBN_13" }
.forEach { return it.get("identifier").asString }
}
return ""
}
private fun getAuthors(volumeInfo: JsonObject): String {
return volumeInfo.get("authors")?.let { authors ->
authors.asJsonArray
.joinToString(", ") { it.asString }
} ?: ""
}
private fun getImageLink(volumeInfo: JsonObject): String? {
return volumeInfo.get("imageLinks")?.asJsonObject?.get("thumbnail")?.asString
}
private fun getSummary(volumeInfo: JsonObject): String? {
return volumeInfo.get("description")?.asString
}
}
| 21 | Kotlin | 7 | 73 | 8b5b1043adac8360226628fac4114203605c1965 | 4,470 | Dante | Apache License 2.0 |
app/src/main/java/br/com/pedroabreudev/aluvery/ui/components/TestComponents.kt | pedroabreudev | 537,890,742 | false | {"Kotlin": 12668} | package br.com.pedroabreudev.aluvery.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
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 br.com.pedroabreudev.aluvery.ui.theme.AluveryTheme
@Preview(showBackground = true)
@Composable
fun ColumnPreview() {
Column {
Text("Texto 1")
Text("Texto 2")
}
}
@Preview(showBackground = true)
@Composable
fun RowPreview() {
Row {
Text(text = "Texto 1")
Text(text = "Texto 2")
}
}
@Preview(showBackground = true)
@Composable
fun BoxPreview() {
Box {
Text(text = "Texto 1")
Text(text = "Texto 2")
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun CustomLayoutPreview() {
Column(
Modifier
.padding(8.dp)
.background(color = Color.Blue)
.padding(all = 8.dp)
.fillMaxWidth()
.fillMaxHeight()
) {
Text(text = "Texto 1")
Text(text = "Texto 2")
Row(
modifier = Modifier
.padding(
horizontal = 8.dp,
vertical = 16.dp
)
.background(Color.Green)
.fillMaxWidth(0.9f)
) {
Text(text = "Texto 3")
Text(text = "Texto 4")
}
Box(
Modifier
.padding(8.dp)
.background(color = Color.Red)
.padding(all = 8.dp)
) {
Row(
Modifier
.padding(8.dp)
.background(color = Color.Cyan)
.padding(all = 8.dp)
.fillMaxWidth()
) {
Text(text = "Texto 5")
Text(text = "Texto 6")
}
Column(
Modifier
.padding(8.dp)
.background(color = Color.Yellow)
.padding(all = 8.dp)
) {
Text(text = "Texto 7")
Text(text = "Texto 8")
}
}
}
}
@Composable
fun MyFirstComposable() {
Text(text = "Meu primeiro texto")
Text(text = "Meu segundo texto maior")
}
@Preview
@Composable
fun MyFirstComposablePreview() {
AluveryTheme {
Surface {
MyFirstComposable()
}
}
} | 0 | Kotlin | 0 | 0 | 46241b3c60a8b57408f649ab4182381599ec941d | 2,637 | Jetpack-Compose-Criando-um-app-Android | MIT License |
app/src/sharedTest/java/me/vickychijwani/spectre/testing/GhostApiTestUtils.kt | TryGhost | 100,519,081 | false | null | package me.vickychijwani.spectre.testing
import io.reactivex.Observable
import me.vickychijwani.spectre.model.entity.AuthToken
import me.vickychijwani.spectre.network.GhostApiService
import me.vickychijwani.spectre.network.entity.*
import org.hamcrest.Matchers
import org.junit.Assert
import retrofit2.*
const val TEST_BLOG = "10.0.2.2:2368"
const val TEST_BLOG_WITH_PROTOCOL = "http://$TEST_BLOG"
const val TEST_USER = "<EMAIL>"
const val TEST_PWD = "<PASSWORD>"
// extension functions for the GhostApiService
fun GhostApiService.deleteDefaultPosts() {
this.doWithAuthToken { token ->
val posts = execute(this.getPosts(token.authHeader, "", null, 100)).body()!!
// A default Ghost install has 7 posts initially. If there are more than this, or the blog
// address is not localhost, abort. This is to avoid messing up a production blog by mistake.
val MAX_EXPECTED_POSTS = 7
if (posts.posts.size > MAX_EXPECTED_POSTS || TEST_BLOG_WITH_PROTOCOL != "http://10.0.2.2:2368") {
throw IllegalStateException("Aborting! Expected max $MAX_EXPECTED_POSTS posts, " +
"found ${posts.posts.size}")
}
for (post in posts.posts) {
execute(this.deletePost(token.authHeader, post.id))
}
}
}
fun GhostApiService.doWithAuthToken(callback: (AuthToken) -> Unit) {
val clientSecret = clientSecret // fetch the client secret only once
Assert.assertThat(clientSecret, Matchers.notNullValue())
val credentials = AuthReqBody.fromPassword(clientSecret, TEST_USER, TEST_PWD)
val token = execute(this.getAuthToken(credentials))
try {
callback(token)
} finally {
// revoke refresh token BEFORE access token, because the access token is needed for revocation!
val revokeReqs = arrayOf(
RevokeReqBody.fromRefreshToken(token.refreshToken, clientSecret),
RevokeReqBody.fromAccessToken(token.accessToken, clientSecret))
for (reqBody in revokeReqs) {
execute(this.revokeAuthToken(token.authHeader, reqBody))
}
}
}
val GhostApiService.clientSecret: String
get() = execute(this.configuration).clientSecret
fun <T> execute(call: Call<T>): Response<T> {
return call.execute()
}
fun <T> execute(observable: Observable<T>): T {
return observable.blockingFirst()
}
| 9 | null | 64 | 235 | 71b34abd3661efc1915ba08c555295a615070a74 | 2,372 | Ghost-Android | MIT License |
service/src/main/java/com/sd/demo/servicecompiler/service/LoginService.kt | zj565061763 | 588,864,539 | false | null | package com.sd.demo.servicecompiler.service
import com.sd.lib.service.FService
@FService
interface LoginService {
fun login()
} | 0 | Kotlin | 0 | 0 | 434aa6cd34d10171d636b0f6b2c796c62e9e8352 | 133 | service-compiler | MIT License |
pluto-plugins/plugins/network/core/lib/src/main/java/com/pluto/plugins/network/internal/interceptor/ui/list/ApiItemHolder.kt | androidPluto | 390,471,457 | false | {"Kotlin": 744352, "Shell": 646} | package com.pluto.plugins.network.internal.interceptor.ui.list
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewGroup
import com.pluto.plugins.network.R
import com.pluto.plugins.network.databinding.PlutoNetworkItemNetworkBinding
import com.pluto.plugins.network.intercept.NetworkData.Response
import com.pluto.plugins.network.internal.ApiCallData
import com.pluto.plugins.network.internal.interceptor.logic.RESPONSE_ERROR_STATUS_RANGE
import com.pluto.utilities.extensions.asTimeElapsed
import com.pluto.utilities.extensions.color
import com.pluto.utilities.extensions.inflate
import com.pluto.utilities.list.DiffAwareAdapter
import com.pluto.utilities.list.DiffAwareHolder
import com.pluto.utilities.list.ListItem
import com.pluto.utilities.setOnDebounceClickListener
import com.pluto.utilities.spannable.setSpan
import io.ktor.http.Url
internal class ApiItemHolder(parent: ViewGroup, actionListener: DiffAwareAdapter.OnActionListener) :
DiffAwareHolder(parent.inflate(R.layout.pluto_network___item_network), actionListener) {
private val binding = PlutoNetworkItemNetworkBinding.bind(itemView)
private val host = binding.host
private val url = binding.url
private val progress = binding.progress
private val status = binding.status
private val error = binding.error
private val timeElapsed = binding.timeElapsed
private val proxyIndicator = binding.proxyIndicator
override fun onBind(item: ListItem) {
if (item is ApiCallData) {
host.text = Url(item.request.url).host
timeElapsed.text = item.request.sentTimestamp.asTimeElapsed()
binding.root.setBackgroundColor(context.color(R.color.pluto___transparent))
url.setSpan {
append(fontColor(item.request.method.uppercase(), context.color(R.color.pluto___text_dark_60)))
append(" ${Url(item.request.url).encodedPath}")
}
progress.visibility = VISIBLE
status.visibility = INVISIBLE
error.visibility = INVISIBLE
proxyIndicator.visibility = GONE
item.exception?.let {
handleExceptionUI()
}
item.mock?.let {
proxyIndicator.visibility = VISIBLE
}
item.response?.let {
handleResponseUI(it)
}
binding.root.setOnDebounceClickListener(DEBOUNCE_DELAY) {
onAction("click")
}
}
}
private fun handleResponseUI(it: Response) {
error.visibility = INVISIBLE
progress.visibility = INVISIBLE
status.visibility = VISIBLE
status.text = it.status.code.toString()
status.setTextColor(
context.color(
if (it.isSuccessful) {
R.color.pluto___dull_green
} else {
if (it.status.code in RESPONSE_ERROR_STATUS_RANGE) {
R.color.pluto___orange
} else {
R.color.pluto___red
}
}
)
)
binding.root.setBackgroundColor(
context.color(
if (it.isSuccessful) {
R.color.pluto___dull_green_05
} else {
if (it.status.code in RESPONSE_ERROR_STATUS_RANGE) {
R.color.pluto___orange_05
} else {
R.color.pluto___red_05
}
}
)
)
}
private fun handleExceptionUI() {
error.visibility = VISIBLE
progress.visibility = INVISIBLE
status.visibility = INVISIBLE
binding.root.setBackgroundColor(context.color(R.color.pluto___red_05))
}
private companion object {
const val DEBOUNCE_DELAY = 1_000L
}
}
| 23 | Kotlin | 64 | 657 | 5562cb7065bcbcf18493820e287d87c7726f630b | 3,962 | pluto | Apache License 2.0 |
src/jvmTest/java/com/codeborne/selenide/commands/ExistsCommandTest.kt | TarCV | 358,762,107 | true | {"Kotlin": 998044, "Java": 322706, "HTML": 46587, "XSLT": 7418} | package com.codeborne.selenide.commands
import assertk.assertions.isFailure
import assertk.assertions.isFalse
import assertk.assertions.isInstanceOf
import assertk.assertions.isSuccess
import com.codeborne.selenide.Condition
import com.codeborne.selenide.Driver
import com.codeborne.selenide.DriverStub
import com.codeborne.selenide.SelenideElement
import com.codeborne.selenide.ex.ElementNotFound
import com.codeborne.selenide.impl.WebElementSource
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.assertj.core.api.WithAssertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import org.mockito.Mockito
import org.openqa.selenium.InvalidSelectorException
import org.openqa.selenium.WebDriverException
import org.openqa.selenium.WebElement
import java.io.File
@ExperimentalCoroutinesApi
internal class ExistsCommandTest : WithAssertions {
private val proxy = Mockito.mock(SelenideElement::class.java)
private val locator = Mockito.mock(WebElementSource::class.java)
private val element = Mockito.mock(WebElement::class.java)
private val existsCommand = Exists()
@TempDir
@JvmField
var tempDir: File? = null
@Test
fun testExistExecuteMethod() = runBlockingTest {
Mockito.`when`<Any>(locator.getWebElement()).thenReturn(element)
assertThat(existsCommand.executeBlocking(proxy, locator, arrayOf()))
.isTrue
}
@Test
fun testExistExecuteMethodWithWebDriverException() = runBlockingTest {
checkExecuteMethodWithException(WebDriverException())
}
private suspend fun <T : Throwable?> checkExecuteMethodWithException(exception: T) {
assertk.assertThat { executeMethodWithException(exception) }
.isSuccess()
.isFalse()
}
private suspend fun <T : Throwable?> executeMethodWithException(exception: T): Boolean {
Mockito.doThrow(exception).`when`(locator).getWebElement()
return existsCommand.execute(proxy, locator, arrayOf())
}
@Test
fun testExistExecuteMethodElementNotFoundException() = runBlockingTest {
val driver: Driver = DriverStub()
checkExecuteMethodWithException(ElementNotFound(driver, "", Condition.appear))
}
@Test
fun testExistsExecuteMethodInvalidSelectorException() = runBlockingTest {
assertk.assertThat { executeMethodWithException(InvalidSelectorException("Element is not selectable")) }
.isFailure()
.isInstanceOf(InvalidSelectorException::class.java)
}
@Test
fun testExistsExecuteMethodWithIndexOutOfBoundException() = runBlockingTest {
checkExecuteMethodWithException(IndexOutOfBoundsException("Out of bound"))
}
}
| 0 | Kotlin | 0 | 0 | c86103748bdf214adb8a027492d21765059d3629 | 2,769 | selenide.kt-js | MIT License |
fontawesome/src/de/msrd0/fontawesome/icons/FA_SPRAY_CAN.kt | msrd0 | 363,665,023 | false | null | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
object FA_SPRAY_CAN: Icon {
override val name get() = "Spray Can"
override val unicode get() = "f5bd"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M224 32c0-17.67-14.33-32-32-32h-64c-17.67 0-32 14.33-32 32v96h128V32zm256 96c-17.67 0-32 14.33-32 32s14.33 32 32 32 32-14.33 32-32-14.33-32-32-32zm-256 32H96c-53.02 0-96 42.98-96 96v224c0 17.67 14.33 32 32 32h256c17.67 0 32-14.33 32-32V256c0-53.02-42.98-96-96-96zm-64 256c-44.18 0-80-35.82-80-80s35.82-80 80-80 80 35.82 80 80-35.82 80-80 80zM480 96c17.67 0 32-14.33 32-32s-14.33-32-32-32-32 14.33-32 32 14.33 32 32 32zm-96 32c-17.67 0-32 14.33-32 32s14.33 32 32 32 32-14.33 32-32-14.33-32-32-32zm-96-96c-17.67 0-32 14.33-32 32s14.33 32 32 32 32-14.33 32-32-14.33-32-32-32zm96 0c-17.67 0-32 14.33-32 32s14.33 32 32 32 32-14.33 32-32-14.33-32-32-32zm96 192c-17.67 0-32 14.33-32 32s14.33 32 32 32 32-14.33 32-32-14.33-32-32-32z"/></svg>"""
else -> null
}
}
| 0 | Kotlin | 0 | 0 | e757d073562077a753280bf412eebfc4a9121b33 | 1,925 | fontawesome-kt | Apache License 2.0 |
presentation/src/main/java/com/moizaandroid/moiza/ui/board/BoardFragment.kt | Software-Meister-High-School-Community | 452,152,042 | false | null | package com.moizaandroid.moiza.ui.board
import com.moizaandroid.moiza.R
import com.moizaandroid.moiza.databinding.FragmentBoardBinding
import com.moizaandroid.moiza.ui.base.BaseFragment
class BoardFragment : BaseFragment<FragmentBoardBinding>(R.layout.fragment_board) {
override fun init() {
}
} | 8 | Kotlin | 0 | 4 | 9e2521871663805a4b50f23497dfee972bab1766 | 308 | MOIZA_Android | MIT License |
presentation/src/main/java/com/moizaandroid/moiza/ui/board/BoardFragment.kt | Software-Meister-High-School-Community | 452,152,042 | false | null | package com.moizaandroid.moiza.ui.board
import com.moizaandroid.moiza.R
import com.moizaandroid.moiza.databinding.FragmentBoardBinding
import com.moizaandroid.moiza.ui.base.BaseFragment
class BoardFragment : BaseFragment<FragmentBoardBinding>(R.layout.fragment_board) {
override fun init() {
}
} | 8 | Kotlin | 0 | 4 | 9e2521871663805a4b50f23497dfee972bab1766 | 308 | MOIZA_Android | MIT License |
androidApp/src/androidMain/kotlin/com/akjaw/ai/assistant/android/MainActivity.kt | AKJAW | 636,092,076 | false | null | package com.akjaw.ai.assistant.android
import com.akjaw.ai.assistant.shared.MainView
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import com.akjaw.ai.assistant.BuildConfig
import com.akjaw.ai.assistant.shared.chat.data.database.ProductionDriverFactory
import com.akjaw.ai.assistant.shared.chat.data.database.createDatabase
import com.akjaw.ai.assistant.shared.dashboard.domain.ChatType
import com.akjaw.ai.assistant.shared.utils.BuildInfo
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
BuildInfo.isDebug = BuildConfig.DEBUG
createDatabase(ProductionDriverFactory(context = applicationContext))
val type = intent.getStringExtra("chatType")?.toType()
setContent {
MainView(type)
}
}
fun String.toType(): ChatType? = when (this) {
"notion" -> ChatType.Notion
"ticktick" -> ChatType.TickTick
else -> null
}
} | 0 | Kotlin | 0 | 0 | 0768b4a1c4468f6d1bd8d2adb704c5913bae98f2 | 1,064 | AiAssistant | Apache License 2.0 |
AppDispensa/app/src/main/java/com/example/appdispensa/RegistrationActivity.kt | Cacciaa | 778,857,101 | false | {"Kotlin": 72096} | package com.example.appdispensa
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.example.appdispensa.dbhelper.MyDbHelper
import com.hololo.tutorial.library.TutorialActivity
class RegistrationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registration)
}
fun login(view: View) {
startActivity(Intent(this,LoginActivity::class.java))
clearData()
}
// Button Register
fun goLogin(view: View) {
var nome:String = findViewById<EditText>(R.id.editTextNome).text.toString()
var email:String = findViewById<EditText>(R.id.editTextEmail).text.toString()
var password:String = findViewById<EditText>(R.id.editTextPassword).text.toString()
if(nome.isNotEmpty() && email.isNotEmpty() && password.isNotEmpty()) {
var db: MyDbHelper = MyDbHelper(this@RegistrationActivity, "dbDispensa.db", 1)
if(db.registerUser(nome, email, password)){
// go to login
//startActivity(Intent(this,LoginActivity::class.java))
startActivity(Intent(this,IntroActivity::class.java))
}
}else{
Toast.makeText(this, "Campi non corretti", Toast.LENGTH_SHORT).show()
}
clearData()
}
private fun clearData() {
var nome = findViewById<EditText>(R.id.editTextNome)
var email = findViewById<EditText>(R.id.editTextEmail)
var password = findViewById<EditText>(R.id.editTextPassword)
nome.setText("")
email.setText("")
password.setText("")
}
} | 0 | Kotlin | 0 | 0 | fdbac4bfd829824867957c7c85737601f4f0133e | 1,839 | AppDispensa | Apache License 2.0 |
app/src/main/java/com/example/booklibrary/ui/info/InfoFragment.kt | NoBody313 | 573,783,064 | false | {"Kotlin": 37355} | package com.example.booklibrary.ui.info
import android.content.Intent
import android.os.Bundle
import android.service.controls.ControlsProviderService.TAG
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.activity.addCallback
import androidx.fragment.app.Fragment
import com.example.booklibrary.databinding.FragmentInfoBinding
import com.example.booklibrary.tools.user.SharedPreference
import com.example.booklibrary.ui.user.login.LoginActivity
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class InfoFragment : Fragment() {
// private var _binding: FragmentInfoBinding? = null
private lateinit var binding: FragmentInfoBinding
private lateinit var preference: SharedPreference
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentInfoBinding.inflate(layoutInflater)
// Session
checkLogin()
onCallBack()
clickLogout()
return (binding.root)
}
private fun checkLogin() {
preference = SharedPreference(activity)
if (preference.isLogin() == false) {
val intent = Intent(activity, LoginActivity::class.java)
startActivity(intent)
activity?.finish()
}
}
private fun clickLogout() {
binding.btnLogout.setOnClickListener {
preference.removeData()
val intent = Intent(activity, LoginActivity::class.java)
Firebase.auth.signOut()
startActivity(intent)
activity?.finish()
}
}
private fun onCallBack(): OnBackPressedCallback {
val callback =
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
fun handleOnBackPressed() {
Log.d(TAG, "Fragment back pressed invoke")
if (isEnabled) {
isEnabled = false
requireActivity().onBackPressedDispatcher.onBackPressed()
}
}
handleOnBackPressed()
}
return callback
}
} | 0 | Kotlin | 0 | 2 | 113e96b6045aaac927bc0b7e1917603409c04550 | 2,359 | Book_Library | MIT License |
app/src/main/java/com/mattskala/trezorwallet/Extensions.kt | MattSkala | 119,818,836 | false | null | package com.mattskala.trezorwallet
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
} | 4 | Kotlin | 4 | 8 | f3edc15ded7d79acb2ba8d5d65cd82c407b1fe95 | 320 | trezor-wallet | MIT License |
app/src/main/java/com/google/samples/apps/sunflower/compose/garden/GardenItemCard.kt | littlebug29 | 388,990,588 | true | {"Kotlin": 143996, "Shell": 1529} | package com.google.samples.apps.sunflower.compose.garden
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberImagePainter
import com.google.samples.apps.sunflower.R
import com.google.samples.apps.sunflower.viewmodels.PlantAndGardenPlantingsViewModel
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun GardenItemCard(
viewModel: PlantAndGardenPlantingsViewModel,
onItemClick: (String) -> Unit
) {
Card(
modifier = Modifier.padding(12.dp, 0.dp, 12.dp, 26.dp),
shape = RoundedCornerShape(bottomStart = 8.dp),
elevation = 2.dp,
onClick = { onItemClick(viewModel.plantId) }
) {
Column {
Image(
modifier = Modifier
.fillMaxWidth()
.height(dimensionResource(id = R.dimen.plant_item_image_height)),
painter = rememberImagePainter(
data = viewModel.imageUrl,
builder = {
crossfade(true)
}
),
contentDescription = stringResource(id = R.string.a11y_plant_item_image),
contentScale = ContentScale.Crop
)
Text(
text = viewModel.plantName,
modifier = Modifier
.fillMaxWidth(),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontFamily = FontFamily.SansSerif,
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Text(
text = stringResource(id = R.string.plant_date_header),
modifier = Modifier
.fillMaxWidth(),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colors.secondaryVariant,
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Text(
text = viewModel.plantDateString,
modifier = Modifier
.fillMaxWidth(),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
color = Color.Black,
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Text(
text = stringResource(id = R.string.watered_date_header),
modifier = Modifier
.fillMaxWidth(),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colors.secondaryVariant,
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Text(
text = viewModel.plantDateString,
modifier = Modifier
.fillMaxWidth(),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
color = Color.Black,
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Text(
text = LocalContext.current.resources.getQuantityString(
R.plurals.watering_next,
viewModel.wateringInterval,
viewModel.wateringInterval
),
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
color = Color.Black,
textAlign = TextAlign.Center,
fontSize = 16.sp
)
}
}
}
@Preview
@Composable
fun previewGarden() {
} | 0 | Kotlin | 0 | 0 | e397578f3a99115497d02810ce8ed69633242903 | 5,277 | sunflower | Apache License 2.0 |
yaorm/src/main/java/org/roylance/yaorm/models/CacheStore.kt | roylanceMichael | 43,471,745 | false | null | package org.roylance.yaorm.models
import com.google.protobuf.Message
import org.roylance.yaorm.utilities.ProtobufUtils
import java.util.*
class CacheStore {
private val types = HashMap<String, HashMap<String, Message.Builder>>()
fun seenObject(type: Message, key: String): Boolean {
if (types.containsKey(type.descriptorForType.name) &&
types[type.descriptorForType.name]!!.containsKey(key)) {
return true
}
return false
}
fun getObject(type: Message, key: String): Message.Builder {
if (types.containsKey(type.descriptorForType.name) &&
types[type.descriptorForType.name]!!.containsKey(key)) {
return types[type.descriptorForType.name]!![key]!!
}
if (!types.containsKey(type.descriptorForType.name)) {
types[type.descriptorForType.name] = HashMap()
}
val newBuilder = type.toBuilder()
ProtobufUtils.setIdForMessage(newBuilder, key)
types[type.descriptorForType.name]!![key] = newBuilder
return newBuilder
}
fun saveObject(actualObject: Message.Builder, key: String) {
if (types.containsKey(actualObject.descriptorForType.name) &&
types[actualObject.descriptorForType.name]!!.containsKey(key)) {
val existingObject = types[actualObject.descriptorForType.name]!![key]!!
existingObject.mergeFrom(actualObject.build())
return
}
else if (!types.containsKey(actualObject.descriptorForType.name)) {
types[actualObject.descriptorForType.name] = HashMap()
}
types[actualObject.descriptorForType.name]!![key] = actualObject
}
} | 1 | null | 1 | 1 | df672db4e16d84885ec3aa84e74c57e1e9bc1ce3 | 1,712 | yaorm | MIT License |
app/src/main/java/com/victorhvs/rnm/RNMApp.kt | VictorHVS | 671,715,586 | false | null | package com.victorhvs.rnm
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class RNMApp : Application()
| 5 | Kotlin | 0 | 1 | 56b170e881916003bf0cd861be033c238a8f0ac0 | 146 | rick-n-morty | Apache License 2.0 |
jms/src/main/kotlin/io/qalipsis/plugins/jms/producer/JmsProducerStepSpecificationConverter.kt | qalipsis | 428,400,884 | false | {"Kotlin": 125172} | /*
* Copyright 2022 AERIS IT Solutions GmbH
*
* 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 io.qalipsis.plugins.jms.producer
import io.qalipsis.api.annotations.StepConverter
import io.qalipsis.api.events.EventsLogger
import io.qalipsis.api.meters.CampaignMeterRegistry
import io.qalipsis.api.steps.StepCreationContext
import io.qalipsis.api.steps.StepSpecification
import io.qalipsis.api.steps.StepSpecificationConverter
import kotlinx.coroutines.ExperimentalCoroutinesApi
/**
* [StepSpecificationConverter] from [JmsProducerStepSpecificationImpl] to [JmsProducerStep]
* to use the Produce API.
*
* @author Alexander Sosnovsky
*/
@ExperimentalCoroutinesApi
@StepConverter
internal class JmsProducerStepSpecificationConverter(
private val meterRegistry: CampaignMeterRegistry,
private val eventsLogger: EventsLogger
) : StepSpecificationConverter<JmsProducerStepSpecificationImpl<*>> {
override fun support(stepSpecification: StepSpecification<*, *, *>): Boolean {
return stepSpecification is JmsProducerStepSpecificationImpl
}
override suspend fun <I, O> convert(creationContext: StepCreationContext<JmsProducerStepSpecificationImpl<*>>) {
val spec = creationContext.stepSpecification
val stepId = spec.name
val producer = JmsProducer(spec.connectionFactory, JmsProducerConverter(),
eventsLogger = eventsLogger.takeIf { spec.monitoringConfig.events },
meterRegistry = meterRegistry.takeIf { spec.monitoringConfig.meters }
)
@Suppress("UNCHECKED_CAST")
val step = JmsProducerStep(
stepId = stepId,
retryPolicy = spec.retryPolicy,
recordFactory = spec.recordsFactory,
jmsProducer = producer,
)
creationContext.createdStep(step)
}
}
| 0 | Kotlin | 0 | 0 | 8840a9cc8ff14651c61c75e8552cbc6f1ae47eed | 2,328 | qalipsis-plugin-jms | Apache License 2.0 |
app/src/main/java/com/example/lotus/src/Card.kt | gufernandez | 484,062,613 | false | {"Kotlin": 30974} | package com.example.lotus.src
class Card(private val cardName: String, private val cardGame: Int?,
private val competitiveMode: Boolean, private val soloMode: Boolean,
private val compQ: Int, private val soloQ: Int) {
val name: String = cardName
val game: Int? = cardGame
val isCompetitive: Boolean = competitiveMode
val isSolo: Boolean = soloMode
var competitiveQuantity: Int = compQ
var soloQuantity: Int = soloQ
} | 0 | Kotlin | 0 | 0 | 327c05803b8b471cc8a9c81b3046003cc2471e8e | 463 | Lotus | MIT License |
src/main/java/com/sayzen/campfiresdk/screens/post/view/CardInfo.kt | Daboo011 | 217,832,397 | false | {"Kotlin": 1107825} | package com.sayzen.campfiresdk.screens.post.view
import android.view.View
import com.dzen.campfire.api.models.units.post.UnitPost
import com.dzen.campfire.api.models.units.tags.UnitTag
import com.sayzen.campfiresdk.R
import com.sayzen.campfiresdk.adapters.*
import com.sayzen.campfiresdk.controllers.ControllerUnits
import com.sayzen.campfiresdk.screens.post.search.SPostsSearch
import com.sup.dev.android.libs.screens.navigator.Navigator
import com.sup.dev.android.tools.ToolsBitmap
import com.sup.dev.android.tools.ToolsImagesLoader
import com.sup.dev.android.tools.ToolsView
import com.sup.dev.android.views.cards.Card
import com.sup.dev.android.views.views.ViewAvatar
import com.sup.dev.android.views.views.ViewAvatarTitle
import com.sup.dev.android.views.views.ViewChip
import com.sup.dev.android.views.views.ViewSpace
import com.sup.dev.android.views.views.layouts.LayoutFlow
class CardInfo(
private val xUnit: XUnit,
private val tags: Array<UnitTag>
) : Card(R.layout.screen_post_card_info) {
init {
xUnit.xFandom.showLanguage = false
}
override fun bindView(view: View) {
super.bindView(view)
val vFlow: LayoutFlow = view.findViewById(R.id.vFlow)
val vMiddleDivider: View = view.findViewById(R.id.vMiddleDivider)
val tags = ControllerUnits.parseTags(this.tags)
if(tags.isEmpty()){
vMiddleDivider.visibility = View.GONE
vFlow.visibility = View.GONE
}else{
vMiddleDivider.visibility = View.VISIBLE
vFlow.visibility = View.VISIBLE
}
vFlow.removeAllViews()
for (tagParent in tags) {
addTag(tagParent.tag, vFlow)
for (tag in tagParent.tags) addTag(tag, vFlow)
}
updateFandom()
updateAccount()
updateKarma()
updateComments()
updateReports()
}
fun updateFandom(){
if(getView() == null) return
xUnit.xFandom.setView(getView()!!.findViewById<ViewAvatar>(R.id.vFandom))
}
fun updateAccount(){
if(getView() == null) return
xUnit.xAccount.setView(getView()!!.findViewById<ViewAvatarTitle>(R.id.vAvatar))
}
fun updateKarma(){
if(getView() == null) return
xUnit.xKarma.setView(getView()!!.findViewById(R.id.vKarma))
}
fun updateComments(){
if(getView() == null) return
xUnit.xComments.setView(getView()!!.findViewById(R.id.vComments))
}
fun updateReports(){
if(getView() == null) return
xUnit.xReports.setView(getView()!!.findViewById(R.id.vReports))
}
private fun addTag(t: UnitTag, vFlow: LayoutFlow) {
val vChip = if (t.parentUnitId == 0L) ViewChip.instance(vFlow.context) else ViewChip.instanceOutline(vFlow.context)
vChip.text = t.name
vChip.setOnClickListener { SPostsSearch.instance(t, Navigator.TO) }
ControllerUnits.createTagMenu(vChip, t)
if (vFlow.childCount != 0 && t.parentUnitId == 0L) vFlow.addView(ViewSpace(vFlow.context, ToolsView.dpToPx(1).toInt(), 0))
vFlow.addView(vChip)
if (t.imageId != 0L) ToolsImagesLoader.load(t.imageId).into { bytes -> vChip.setIcon(ToolsBitmap.decode(bytes)) }
}
}
| 0 | null | 1 | 0 | 33c46da49d3758a1a006ac660dc823d35c66baea | 3,237 | CampfireSDK | Apache License 2.0 |
src/main/kotlin/osahner/security/UserLoginDTO.kt | osahner | 118,467,935 | false | {"Kotlin": 49862, "Shell": 2424, "Dockerfile": 1167} | package osahner.security
data class UserLoginDTO(
val username: String,
val password: String,
val verificationCode: String? = null
)
| 0 | Kotlin | 22 | 69 | 02b172ddb111d41af062f39ced2546098e55de82 | 140 | kotlin-spring-boot-rest-jpa-jwt-starter | MIT License |
app/src/main/java/com/lihou/snakegame/SnakeGameUI.kt | Lihou | 502,325,998 | false | {"Kotlin": 16330} | package com.lihou.snakegame
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowLeft
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.lihou.snakegame.ui.theme.Pink80
import com.lihou.snakegame.ui.theme.Purple80
import com.lihou.snakegame.ui.theme.PurpleGrey80
import com.lihou.snakegame.ui.theme.SnakeGameTheme
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
enum class BoxType {
HEAD,
BODY,
FOOD;
}
data class UiModel(
val gameModel: SnakeGameModel = SnakeGameModel(),
val onStart: () -> Unit = {},
val onStop: () -> Unit = {},
val onUp: () -> Unit = {},
val onDown: () -> Unit = {},
val onRight: () -> Unit = {},
val onLeft: () -> Unit = {},
)
private val initialUiModel = UiModel()
private fun boxColor(boxType: BoxType) = when (boxType) {
BoxType.FOOD -> Pink80
BoxType.BODY -> PurpleGrey80
BoxType.HEAD -> Purple80
}
@Composable fun SnakeGameUI(uiModel: Flow<UiModel>) {
val model = uiModel.collectAsState(initial = initialUiModel)
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
ZoneUI(gameModel = model.value.gameModel)
Box(
Modifier
.height(8.dp)
.fillMaxWidth()
)
ControlsUI(
onUp = model.value.onUp,
onLeft = model.value.onLeft,
onRight = model.value.onRight,
onDown = model.value.onDown
)
}
}
@Composable fun ZoneUI(gameModel: SnakeGameModel) {
Box(
Modifier
.padding(8.dp)
.border(width = 1.dp, color = Color.Black)
) {
Canvas(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.padding(16.dp)
) {
val diam = size.width / NUMBER_OF_GRIDS_PER_SIDE
val boxSize = Size(diam - 2, diam - 2)
fun drawBox(type: BoxType, position: Position) {
drawRect(
boxColor(type), Offset(position.x * diam + 2, position.y * diam - 2), boxSize
)
}
// draw snake head
drawBox(BoxType.HEAD, gameModel.snakeHead)
// draw snake body
gameModel.snakeBody.forEach {
drawBox(BoxType.BODY, it)
}
// draw snake food
drawBox(BoxType.FOOD, gameModel.food)
}
}
}
@Composable fun ControlsUI(
onUp: () -> Unit, onLeft: () -> Unit, onRight: () -> Unit, onDown: () -> Unit
) {
Column(
modifier = Modifier
.size(200.dp)
.background(MaterialTheme.colorScheme.secondary, CircleShape)
.padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceBetween
) {
val buttonSize = 50.dp
IconButton(
onClick = onUp
) {
Icon(
modifier = Modifier.size(buttonSize),
imageVector = Icons.Default.KeyboardArrowUp,
contentDescription = "up",
tint = Color.White
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
IconButton(onClick = onLeft) {
Icon(
modifier = Modifier.size(buttonSize),
imageVector = Icons.Default.KeyboardArrowLeft,
contentDescription = "left",
tint = Color.White
)
}
IconButton(onClick = onRight) {
Icon(
modifier = Modifier.size(buttonSize),
imageVector = Icons.Default.KeyboardArrowRight,
contentDescription = "right",
tint = Color.White
)
}
}
IconButton(onClick = onDown) {
Icon(
modifier = Modifier.size(buttonSize),
imageVector = Icons.Default.KeyboardArrowDown,
contentDescription = "down",
tint = Color.White
)
}
}
}
@Preview(showBackground = true) @Composable fun DefaultPreview() {
SnakeGameTheme {
SnakeGameUI(channelFlow { trySend(initialUiModel) })
}
}
| 0 | Kotlin | 0 | 3 | dd1c467924d5c9e7822f367f45839be40a111911 | 5,138 | SnakeGame | Apache License 2.0 |
app/src/main/java/com/bankaccount/sagi_market/PostActivity.kt | Team-BankAccount | 579,811,258 | false | null | package com.bankaccount.sagi_market
import post.PostModel
import util.FirebaseAuth
import util.FirebaseRef
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.provider.MediaStore
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bankaccount.sagi_market.base.BaseActivity
import com.bankaccount.sagi_market.databinding.ActivityPostBinding
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.ktx.storage
import java.io.ByteArrayOutputStream
class PostActivity : BaseActivity<ActivityPostBinding>(R.layout.activity_post) {
var imgcheck = false
override fun viewSetting() {
binding.btnSuccess.setOnClickListener{
val title = binding.etTitle.text.toString()
val price = binding.etPrice.text.toString()
val detail = binding.etDetail.text.toString()
val uid = FirebaseAuth.getUid()
val time = FirebaseAuth.getTime()
val firebaseKey = FirebaseRef.postRef.push().key.toString()
FirebaseRef.postRef
.child(firebaseKey)
.setValue(PostModel(title,price,detail,uid,time))
Toast.makeText(this,"게시글 업로드 완료",Toast.LENGTH_SHORT).show()
if(imgcheck == true) {
imgUpload(firebaseKey)
}
finish()
}
binding.btnImg.setOnClickListener {
requestPermission()
}
binding.btnHome.setOnClickListener {
var intent = Intent(this,MainActivity::class.java)
startActivity(intent)
}
}
private fun imgUpload(firebaseKey : String){
// Get the data from an ImageView as bytes
val storage = Firebase.storage
val storageRef = storage.reference
val mountainsRef = storageRef.child(firebaseKey+".png")
val imageView = binding.btnImg
imageView.isDrawingCacheEnabled = true
imageView.buildDrawingCache()
val bitmap = (imageView.drawable as BitmapDrawable).bitmap
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()
var uploadTask = mountainsRef.putBytes(data)
uploadTask.addOnFailureListener {
// Handle unsuccessful uploads
}.addOnSuccessListener { taskSnapshot ->
// taskSnapshot.metadata contains file metadata such as size, content-type, etc.
// ...
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == RESULT_OK&&requestCode == 1004){
binding.btnImg.setImageURI(data?.data)
}
}
val PERMISSIONS_REQUEST_CODE = 100
var REQUIRED_PERMISSIONS = arrayOf<String>( android.Manifest.permission.READ_EXTERNAL_STORAGE)
private fun requestPermission(){
var permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
if(permissionCheck != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)){
//설명 필요 (사용자가 요청을 거부한 적이 있음)
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE )
}else{
//설명 필요하지 않음
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE )
}
}else{
imgcheck = true
val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
startActivityForResult(gallery,1004) //권한 허용
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>, grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when(requestCode){
PERMISSIONS_REQUEST_CODE -> {
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
imgcheck = true
val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
startActivityForResult(gallery,1004)
//권한 허용
}else{
//권한 거부됨
}
return
}
}
}
} | 2 | Kotlin | 0 | 0 | cf852a36813402fbd8257d31d20dcb882b1e540b | 4,694 | SaGi-Market | MIT License |
CODE/app/src/main/java/pt/isel/battleshipAndroid/main/BaseActivity.kt | RaulJCS5 | 611,442,288 | false | null | package pt.isel.battleshipAndroid.main
import androidx.activity.ComponentActivity
import pt.isel.battleshipAndroid.DependenciesContainer
open class BaseActivity : ComponentActivity() { //Experiment
protected val dependencies by lazy { application as DependenciesContainer }
}
| 0 | Kotlin | 0 | 2 | abe5e4633280e1b6729bb122ca0508b73dcff4ba | 282 | Battleship-android | MIT License |
data-local/src/main/java/tech/danielwaiguru/data_local/dao/MovieDao.kt | DanielWaiguru91 | 366,433,410 | false | null | package tech.danielwaiguru.data_local.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
import tech.danielwaiguru.data_local.models.MovieEntity
import tech.danielwaiguru.domain.models.Movie
@Dao
interface MovieDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun storeMovies(movies: List<MovieEntity>)
@Query("SELECT * FROM movies")
suspend fun getAllMovies(): List<MovieEntity>
/**
* Get single movie details
*/
@Query("SELECT * FROM movies WHERE id =:mId")
fun getMovie(mId: Int): MovieEntity
} | 0 | Kotlin | 2 | 0 | c876f9abbaae08a12f4e3967d1c09d09cbb4a91c | 662 | Qhala-Android-Test | MIT License |
app/src/main/java/com/nima/mymood/utils/Constants.kt | NimaKhajehpour | 597,004,058 | false | {"Kotlin": 261913} | package com.nima.mymood.utils
object Constants {
const val usdt_address = "0x55Fd62eC2DB8F3f88d3c5825c68ED4DA2AA1F82c"
const val btc_address = "1KUNrUPMZvcrQV6Eio3bSS1GgpCJn4Jk6A"
const val eth_address = "0x55Fd62eC2DB8F3f88d3c5825c68ED4DA2AA1F82c"
} | 7 | Kotlin | 1 | 20 | d504a860cde0f4e880e80ad54d822910bd5eb24b | 266 | MyMood | MIT License |
debop4k-data-mybatis/src/test/kotlin/debop4k/data/mybatis/kotlin/cache/EhCacheConfiguration.kt | debop | 60,844,667 | false | null | /*
* Copyright (c) 2016. <NAME> <<EMAIL>>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.data.mybatis.kotlin.cache
import debop4k.core.loggerOf
import debop4k.data.mybatis.kotlin.config.KotlinMyBatisConfiguration
import debop4k.data.mybatis.kotlin.mappers.KotlinActorMapper
import net.sf.ehcache.config.CacheConfiguration
import net.sf.ehcache.config.Configuration
import org.mybatis.spring.annotation.MapperScan
import org.springframework.cache.CacheManager
import org.springframework.cache.annotation.EnableCaching
import org.springframework.cache.ehcache.EhCacheCacheManager
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
@EnableCaching(proxyTargetClass = true)
@ComponentScan(basePackageClasses = arrayOf(EhCacheActorRepository::class))
@MapperScan(basePackageClasses = arrayOf(KotlinActorMapper::class))
open class EhCacheConfiguration : KotlinMyBatisConfiguration() {
private val log = loggerOf(javaClass)
/**
* EhCache 사용을 위한 환경설정 정보
*/
@Bean
open fun ehcacheConfiguration(): Configuration {
val cfg = Configuration()
// NOTE: EhCache 는 미리 cache 를 정의해주어야 한다. ( resources 의 ehcache.xml 을 보면 자세한 속성 및 설명이 있습니다 )
// 다른 캐시 서버는 그럴 필요가 없다. (Memcached, Redis, Hazelcast, Apache Ignite)
//
cfg.addCache(CacheConfiguration("kotlin-actors", 10000))
cfg.addCache(CacheConfiguration("kotlin-company", 10000))
cfg.name = "kotlin-mybatis-ehcache-manager-by-java-config"
return cfg
}
/**
* EhCache 의 CacheManager
* @param cfg EhCache 의 환경설정
*/
@Bean
open fun cacheManager(cfg: Configuration): net.sf.ehcache.CacheManager {
return net.sf.ehcache.CacheManager(cfg)
}
/**
* Spring 의 CacheManager
* @param ehcacheManager EhCache의 CacheManager
*/
@Bean
open fun ehcacheCacheManager(ehcacheManager: net.sf.ehcache.CacheManager): CacheManager {
val cm = EhCacheCacheManager(ehcacheManager)
if (cm.getCache("kotlin-actors") == null) {
throw RuntimeException("Cache 설정이 잘못되었습니다.")
}
log.info("Create EhCache CacheManagner instance.")
return cm
}
} | 1 | null | 10 | 40 | 5a621998b88b4d416f510971536abf3bf82fb2f0 | 2,650 | debop4k | Apache License 2.0 |
app/src/main/java/com/github/odaridavid/weatherapp/data/weather/remote/DefaultRemoteWeatherDataSource.kt | HarryRegel | 782,051,735 | false | {"Kotlin": 157840, "Swift": 4005} | package com.github.odaridavid.weatherapp.data.weather.remote
import com.github.odaridavid.weatherapp.BuildConfig
import com.github.odaridavid.weatherapp.model.DefaultLocation
import com.github.odaridavid.weatherapp.model.Result
import com.github.odaridavid.weatherapp.model.Weather
import javax.inject.Inject
class DefaultRemoteWeatherDataSource @Inject constructor(
private val openWeatherService: OpenWeatherService,
) : RemoteWeatherDataSource {
override suspend fun fetchWeatherData(
defaultLocation: DefaultLocation,
language: String,
units: String,
format: String,
excludedData: String,
): Result<Weather> =
try {
val response = openWeatherService.getWeatherData(
longitude = defaultLocation.longitude,
latitude = defaultLocation.latitude,
excludedInfo = excludedData,
units = units,
language = language,
appid = BuildConfig.OPEN_WEATHER_API_KEY,
)
if (response.isSuccessful && response.body() != null) {
val weatherData = response.body()!!.toCoreModel(unit = units, format = format)
Result.Success(data = weatherData)
} else {
val throwable = mapResponseCodeToThrowable(response.code())
throw throwable
}
} catch (e: Exception) {
throw e
}
}
| 0 | Kotlin | 1 | 3 | e45b8e9db540eb3cae7d19fd36a5e9aa9899dc39 | 1,462 | weather-app | Apache License 2.0 |
app/src/main/java/com/celzero/bravedns/database/DNSProxyEndpointRepository.kt | Aquaogen | 379,457,840 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Proguard": 1, "XML": 149, "Kotlin": 150, "Java": 13} | /*
Copyright 2020 RethinkDNS and its authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.celzero.bravedns.database
import androidx.lifecycle.LiveData
import androidx.paging.PagedList
import androidx.paging.toLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class DNSProxyEndpointRepository(private val dnsProxyEndpointDAO: DNSProxyEndpointDAO) {
fun updateAsync(dnsProxyEndpoint: DNSProxyEndpoint, coroutineScope: CoroutineScope = GlobalScope) {
coroutineScope.launch {
dnsProxyEndpointDAO.update(dnsProxyEndpoint)
}
}
fun deleteAsync(dnsProxyEndpoint: DNSProxyEndpoint, coroutineScope: CoroutineScope = GlobalScope) {
coroutineScope.launch {
dnsProxyEndpointDAO.delete(dnsProxyEndpoint)
}
}
fun insertAsync(dnsCryptEndpoint: DNSProxyEndpoint, coroutineScope: CoroutineScope = GlobalScope) {
coroutineScope.launch {
dnsProxyEndpointDAO.insert(dnsCryptEndpoint)
}
}
fun insertWithReplace(dnsProxyEndpoint: DNSProxyEndpoint, coroutineScope: CoroutineScope= GlobalScope){
coroutineScope.launch {
dnsProxyEndpointDAO.insertWithReplace(dnsProxyEndpoint)
}
}
fun getDNSProxyEndpointLiveData(): LiveData<PagedList<DNSProxyEndpoint>> {
return dnsProxyEndpointDAO.getDNSProxyEndpointLiveData().toLiveData(pageSize = 50)
}
fun deleteOlderData(date: Long, coroutineScope: CoroutineScope = GlobalScope) {
coroutineScope.launch {
dnsProxyEndpointDAO.deleteOlderData(date)
}
}
fun getDNSProxyEndpointLiveDataByType(query: String): LiveData<PagedList<DNSProxyEndpoint>> {
return dnsProxyEndpointDAO.getDNSProxyEndpointLiveDataByType(query).toLiveData(pageSize = 50)
}
fun deleteDNSProxyEndpoint(id : Int) {
dnsProxyEndpointDAO.deleteDNSProxyEndpoint(id)
}
fun removeConnectionStatus() {
dnsProxyEndpointDAO.removeConnectionStatus()
}
fun getCount(): Int {
return dnsProxyEndpointDAO.getCount()
}
fun getConnectedProxy(): DNSProxyEndpoint {
return dnsProxyEndpointDAO.getConnectedProxy()
}
} | 1 | null | 1 | 1 | a9bdd6d59b6d2e961fc478b78d90ade0fc67bca6 | 2,734 | redns | Apache License 2.0 |
app/src/main/java/com/getcode/ui/components/SelectionContainer.kt | code-payments | 723,049,264 | false | {"Kotlin": 2199788, "C": 198685, "C++": 83029, "Java": 52287, "Shell": 9082, "Ruby": 4626, "CMake": 2594} | package com.getcode.ui.components
import android.widget.Toast
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.boundsInParent
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalTextToolbar
import androidx.compose.ui.platform.TextToolbar
import androidx.compose.ui.text.AnnotatedString
import androidx.lifecycle.Lifecycle
import com.getcode.ui.utils.addIf
import com.getcode.ui.utils.rememberedLongClickable
import com.getcode.ui.utils.swallowClicks
import com.getcode.util.vibration.LocalVibrator
class SelectionContainerState(val words: String = "") {
var shown by mutableStateOf(false)
val scale : State<Float>
@Composable get() = animateFloatAsState(
targetValue = if (shown) 1.2f else 1f,
label = "access key scale"
)
}
@Composable
fun rememberSelectionState(content: String) = remember(content) { SelectionContainerState(words = content) }
@Composable
fun SelectionContainer(
modifier: Modifier = Modifier,
state: SelectionContainerState,
contentRect: Rect? = null,
content: @Composable BoxScope.(() -> Unit) -> Unit,
) {
val context = LocalContext.current
var _contentRect: Rect by remember(contentRect) {
mutableStateOf(contentRect ?: Rect.Zero)
}
val vibrator = LocalVibrator.current
val toolbar: TextToolbar = LocalTextToolbar.current
val clipboard = LocalClipboardManager.current
val copyAndToast = {
Toast.makeText(context, "Copied to clipboard.", Toast.LENGTH_LONG).show()
clipboard.setText(AnnotatedString(state.words))
state.shown = false
}
val onClick = {
vibrator.vibrate()
toolbar.showMenu(
rect = _contentRect,
onCopyRequested = { copyAndToast() }
)
state.shown = true
}
Box(modifier = modifier) {
Box(
modifier = Modifier
.addIf(contentRect == null) {
Modifier
.onPlaced { _contentRect = it.boundsInParent() }
.rememberedLongClickable {
onClick()
}
},
) {
content(onClick)
}
if (state.shown) {
Box(
modifier = Modifier
.fillMaxSize()
.swallowClicks {
state.shown = false
toolbar.hide()
}
)
}
}
OnLifecycleEvent { _, event ->
if (event == Lifecycle.Event.ON_STOP) {
state.shown = false
toolbar.hide()
}
}
}
| 3 | Kotlin | 13 | 14 | 3cda858e3f8be01e560d72293fcd801f5385adfd | 3,299 | code-android-app | MIT License |
data/local/src/commonMain/kotlin/io/spherelabs/data/local/mapper/PasswordMapper.kt | getspherelabs | 687,455,894 | false | {"Kotlin": 917584, "Ruby": 6814, "Swift": 1128, "Shell": 1048} | package io.spherelabs.data.local.mapper
import io.spherelabs.addnewpasswordapi.model.AddNewPassword
import io.spherelabs.addnewpasswordapi.model.Category as DomainCategory
import io.spherelabs.data.local.db.Category
import io.spherelabs.homeapi.models.HomePassword
import io.spherelabs.local.db.PasswordEntity
fun PasswordEntity.asDomain(): AddNewPassword {
return AddNewPassword(
id = this.id,
title = this.title ?: "",
category = this.category_id,
username = this.username ?: "",
email = this.email ?: "",
password = this.password ?: "",
websiteAddress = this.websiteAddress ?: "",
notes = this.notes ?: "",
image = this.image ?: ""
)
}
fun AddNewPassword.asEntity(): PasswordEntity {
return PasswordEntity(
id = this.id,
title = this.title,
category_id = this.category,
username = this.username,
email = this.email,
password = <PASSWORD>,
websiteAddress = this.websiteAddress,
notes = this.notes,
image = this.image
)
}
fun Category.asCategoryDomain(): DomainCategory {
return when (this) {
Category.Social -> DomainCategory.Social
Category.Browser -> DomainCategory.Browser
Category.Payment -> DomainCategory.Payment
Category.Unknown -> DomainCategory.Unknown
}
}
fun DomainCategory.asCategory(): Category {
return when (this) {
DomainCategory.Social -> Category.Social
DomainCategory.Browser -> Category.Browser
DomainCategory.Payment -> Category.Payment
DomainCategory.Unknown -> Category.Unknown
}
}
fun PasswordEntity.asHomeDomain(): HomePassword {
return HomePassword(
id = this.id,
title = this.title ?: "",
category = this.category_id,
username = this.username ?: "",
email = this.email ?: "",
password = this.password ?: "",
websiteAddress = this.websiteAddress ?: "",
notes = this.notes ?: "",
image = this.image ?: ""
)
}
| 15 | Kotlin | 27 | 236 | 902a0505c5eaf0f3848a5e06afaec98c1ed35584 | 2,062 | anypass-kmp | Apache License 2.0 |
src/main/kotlin/com/kurtraschke/gtfsrtdump/output/OutputMethod.kt | exu1977 | 293,678,253 | true | {"Kotlin": 36593} | package com.kurtraschke.gtfsrtdump.output
import com.google.transit.realtime.GtfsRealtime.FeedMessage
import com.kurtraschke.gtfsrtdump.Main
import picocli.CommandLine.*
import java.util.concurrent.Callable
@Command
abstract class OutputMethod : Callable<Int> {
@ParentCommand
private lateinit var main: Main
override fun call(): Int {
val fm = main.feedMessage
return format(fm)
}
abstract fun format(fm: FeedMessage): Int
} | 0 | null | 0 | 0 | d72efe1923fe9cb1f41e1ee187a6954a91a27794 | 465 | gtfs-rt-dump | Apache License 2.0 |
lib/src/main/java/com/thenewboston/common/model/Node.kt | amarjeet987 | 312,158,966 | true | {"Kotlin": 54193} | package com.thenewboston.common.model
import kotlinx.serialization.SerialName
abstract class Node(
@SerialName("network_id")
val networkId: String,
@SerialName("account_number")
val accountNumber: String,
@SerialName("tx_fee")
val txFee: Int,
val protocol: String,
@SerialName("ip_address")
val ipAddress: String,
val port: String,
val trust: Float,
val version: String
) {
} | 0 | Kotlin | 0 | 1 | 049b97294e52a811fcbd37612d95d049514b1322 | 426 | Kotlin-SDK | MIT License |
android/features/login/src/main/java/io/newm/feature/login/screen/createaccount/CreateAccountScreenPresenter.kt | projectNEWM | 435,674,758 | false | {"Kotlin": 241010, "Swift": 231424} | package io.newm.feature.login.screen.createaccount
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import com.slack.circuit.retained.rememberRetained
import com.slack.circuit.runtime.presenter.Presenter
import io.newm.feature.login.screen.TextFieldState
import io.newm.feature.login.screen.createaccount.CreateAccountUiState.EmailAndPasswordUiState
import io.newm.feature.login.screen.createaccount.CreateAccountUiState.EmailVerificationUiState
import io.newm.feature.login.screen.createaccount.CreateAccountUiState.SetNameUiState
import io.newm.feature.login.screen.email.EmailState
import io.newm.feature.login.screen.password.ConfirmPasswordState
import io.newm.feature.login.screen.password.PasswordState
import io.newm.shared.public.usecases.SignupUseCase
import kotlinx.coroutines.launch
class CreateAccountScreenPresenter constructor(
private val navigateHome: () -> Unit,
private val signupUseCase: SignupUseCase,
) : Presenter<CreateAccountUiState> {
@Composable
override fun present(): CreateAccountUiState {
var step by rememberRetained { mutableStateOf(Step.EmailAndPassword) }
val userEmail = rememberRetained { EmailState() }
val password = rememberRetained { PasswordState() }
val passwordConfirmation = rememberRetained { ConfirmPasswordState(password) }
val name = rememberRetained { TextFieldState() }
val verificationCode = rememberRetained { TextFieldState() }
val coroutineScope = rememberCoroutineScope()
val emailAndPasswordValid = remember(userEmail.isValid, password.isValid, passwordConfirmation.isValid) {
userEmail.isValid && password.isValid && passwordConfirmation.isValid
}
return when (step) {
Step.EmailAndPassword -> {
EmailAndPasswordUiState(
emailState = userEmail,
passwordState = password,
passwordConfirmationState = passwordConfirmation,
) { event ->
when (event) {
SignupFormUiEvent.Next -> {
if (!emailAndPasswordValid) return@EmailAndPasswordUiState // TODO handle error
coroutineScope.launch {
step = Step.Loading
step = try {
signupUseCase.requestEmailConfirmationCode(
email = userEmail.text,
)
Step.SetName
} catch (e: Throwable) {
// TODO handle error
Step.EmailAndPassword
}
}
}
}
}
}
Step.EmailVerification -> {
val nextEnabled = remember(emailAndPasswordValid, verificationCode.isValid, name.isValid) {
emailAndPasswordValid && verificationCode.isValid && name.isValid
}
EmailVerificationUiState(
verificationCode = verificationCode,
) { event ->
when (event) {
is EmailVerificationUiEvent.Next -> {
if (!nextEnabled) return@EmailVerificationUiState // TODO handle error
coroutineScope.launch {
step = Step.Loading
try {
signupUseCase.registerUser(
email = userEmail.text,
verificationCode = verificationCode.text,
password = <PASSWORD>.text,
passwordConfirmation = passwordConfirmation.text,
nickname = name.text,
)
navigateHome()
} catch (e: Throwable) {
step = Step.EmailVerification
// TODO handle error
e.printStackTrace()
}
}
}
}
}
}
Step.SetName -> SetNameUiState(
name = name,
) { event ->
when (event) {
SetNameUiEvent.Next -> {
if (!name.isValid) return@SetNameUiState // TODO handle error
step = Step.EmailVerification
}
}
}
Step.Loading -> CreateAccountUiState.Loading
}
}
}
private enum class Step {
Loading,
EmailAndPassword,
EmailVerification,
SetName,
}
| 1 | Kotlin | 8 | 9 | e374ab064c97aefe49b9b41db4d7a047becc95ea | 5,287 | newm-mobile | Apache License 2.0 |
app/src/main/java/com/chotaling/ownlibrary/ui/locations/AddShelfViewModel.kt | chotaling1 | 356,392,637 | false | {"Kotlin": 76258} | package com.chotaling.ownlibrary.ui.locations
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import com.chotaling.ownlibrary.domain.models.Location
import com.chotaling.ownlibrary.domain.models.Shelf
import com.chotaling.ownlibrary.domain.services.LocationService
import com.chotaling.ownlibrary.ui.BaseViewModel
import io.realm.RealmList
import io.realm.RealmResults
class AddShelfViewModel : BaseViewModel() {
private val _locationService = LocationService()
val shelfName : MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
val selectedLocation : MutableLiveData<Location> by lazy {
MutableLiveData<Location>()
}
val locations : MutableLiveData<Set<Location>> by lazy {
MutableLiveData<Set<Location>>()
}
private var realmLocations : RealmResults<Location>? = null
override fun viewAppearing(arguments: Bundle?) {
super.viewAppearing(arguments)
realmLocations = _locationService.getAllLocations();
realmLocations?.addChangeListener { allLocations ->
locations.value = allLocations.toSet()
}
}
fun addShelf()
{
val shelf = Shelf()
shelf.name = shelfName.value!!
_locationService.addShelf(shelf, selectedLocation.value!!.id)
}
} | 15 | Kotlin | 0 | 0 | 1c10ce7ee8a0f22d49475ed33df6d8ccd6b017e2 | 1,314 | ownLibrary-Android | Apache License 2.0 |
src/vision/alter/telekot/client/factories/concrete/GamesBotApiClientFactory.kt | alter-vision | 261,156,045 | false | null | package vision.alter.telekot.client.factories.concrete
import io.ktor.client.HttpClient
import vision.alter.telekot.client.clients.GamesBotApiClient
import vision.alter.telekot.client.factories.ApiClientFactory
import vision.alter.telekot.telegram.api.GamesBotApi
/**
* Factory for creating of Games Telegram Bot API Client.
*/
object GamesBotApiClientFactory :
ApiClientFactory<GamesBotApi> {
override fun createApiClient(
apiToken: String,
apiUrl: String?,
client: HttpClient?
): GamesBotApi =
GamesBotApiClient(apiToken, apiUrl, client)
}
| 10 | Kotlin | 0 | 2 | 28943db77d5ed7b0759ef180e61c1db78032a408 | 590 | telekot | Apache License 2.0 |
library/src/iosMain/kotlin/com/myunidays/launchdarkly/LDValue.ios.kt | MyUNiDAYS | 744,583,296 | false | {"Kotlin": 22160, "Shell": 1049} | package com.myunidays.launchdarkly
actual class LDValue internal constructor(val ios: cocoapods.LaunchDarkly.LDValue) {
actual fun stringValue(): String? = ios.stringValue()
actual fun type(): LDValueType = ios.getType().toValueType()
actual fun value(): Any? = when (type()) {
LDValueType.Null -> null
LDValueType.Boolean -> ios.boolValue()
LDValueType.Number -> ios.doubleValue()
LDValueType.String -> ios.stringValue()
LDValueType.Array -> ios.arrayValue()
LDValueType.Object -> ios.dictValue()
}
actual companion object {
actual val Empty: LDValue = LDValue(cocoapods.LaunchDarkly.LDValue.ofNull())
}
}
| 0 | Kotlin | 1 | 2 | b56adcfca78ef3636edc5ede05e8060f61f00c55 | 690 | launch-darkly-kotlin-sdk | MIT License |
app/src/main/java/com/example/attackontitanapp/data/local/dao/TitanRemoteKeysDao.kt | krishnachaitanya0107 | 451,893,029 | false | {"Kotlin": 102901} | package com.example.attackontitanapp.data.local.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.attackontitanapp.domain.model.TitanRemoteKeys
@Dao
interface TitanRemoteKeysDao {
@Query("SELECT * FROM titan_remote_keys_table WHERE id = :titanId")
suspend fun getRemoteKeys(titanId: Int): TitanRemoteKeys?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addAllRemoteKeys(titanRemoteKeys: List<TitanRemoteKeys>)
@Query("DELETE FROM titan_remote_keys_table")
suspend fun deleteAllRemoteKeys()
} | 0 | Kotlin | 0 | 3 | 4d3f22e7b79bb87e454bb30d2d0aab7c6a51a80b | 628 | AttackOnTitanApp | MIT License |
src/main/kotlin/Main.kt | sghill | 650,649,874 | false | null | import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToStream
import net.sghill.moderne.GroupsFactory
import net.sghill.moderne.PluginGroupSpec
import net.sghill.moderne.UpdateCenter
import net.sghill.moderne.UpdateCenterRepositoryLookup
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption.CREATE
import java.nio.file.StandardOpenOption.TRUNCATE_EXISTING
import kotlin.io.path.outputStream
@OptIn(ExperimentalSerializationApi::class)
suspend fun main() {
val plugins = Files.readAllLines(Paths.get(System.getenv("PLUGINS_INPUT_FILE"))).map { it.trim() }.filterNot { it.isBlank() }.toSet()
if (plugins.isEmpty()) {
throw IllegalStateException("No plugins found. Please define PLUGINS_INPUT_FILE to a file with one plugin id per line")
}
HttpClient(CIO) {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
})
}
}.use { client ->
val updateCenter: UpdateCenter = client.get("https://updates.jenkins.io/current/update-center.actual.json").body()
val factory = GroupsFactory(UpdateCenterRepositoryLookup(updateCenter))
val result = factory.create(PluginGroupSpec("my-plugins", plugins, "plugins from work"))
if (result.missing.isNotEmpty()) {
println("The following plugin ids are not in the update center:")
for (plugin in result.missing.map { it.id }.sorted()) {
println("\t${plugin}")
}
}
val json = Json { encodeDefaults = true }
val output = Paths.get("out.json")
if (Files.notExists(output)) {
Files.createFile(output)
}
output.outputStream(CREATE, TRUNCATE_EXISTING).use {
json.encodeToStream(result.pluginGroup, it)
}
}
}
| 0 | Kotlin | 0 | 0 | a46a42f1e0951ce5685e13e7ac0bb63525f0700b | 2,174 | moderne-repo-groups | Apache License 2.0 |
src/androidTest/java/com/example/navigation/deeplinks/BrowsableActivityTest.kt | vshpyrka | 754,325,488 | false | {"Kotlin": 192615} | package com.example.navigation.deeplinks
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.test.core.app.ApplicationProvider
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.navigation.R
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class BrowsableActivityTest {
@Test
fun testDeepLinkUri() {
val context: Context = ApplicationProvider.getApplicationContext()
val intent =
Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com/gizmos?status=200"))
.setPackage(context.packageName)
val scenario = launchActivity<BrowsableActivity>(intent)
onView(withId(R.id.text)).check(matches(withText("action=android.intent.action.VIEW, \ndata=http://www.example.com/gizmos?status=200, \ncode=200")))
scenario.close()
}
}
| 0 | Kotlin | 0 | 0 | bf0d3e6ca9c31116a5ebb77576dc01b62c896e13 | 1,182 | android-navigation-example | Apache License 2.0 |
app/src/main/java/io/aayush/relabs/network/data/common/DateTime.kt | theimpulson | 679,298,392 | false | {"Kotlin": 195396} | package io.aayush.relabs.network.data.common
import com.squareup.moshi.JsonClass
import java.text.SimpleDateFormat
import java.util.Locale
@JsonClass(generateAdapter = true)
data class DateTime(
val atomic: String = "1970-01-01T00:00:00+00:00",
val formatted: String = "January 1, 1970 at 0:00 AM"
) {
val long: Long
get() {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.getDefault())
return sdf.parse(atomic)!!.time
}
}
| 0 | Kotlin | 6 | 160 | f7b2829540d9bf9e34e0e13d7d120bffb9ca9354 | 493 | ReLabs | Apache License 2.0 |
core/src/main/java/com/abhat/core/model/Oembed.kt | AnirudhBhat | 257,323,871 | false | null | package com.abhat.core.model
import com.squareup.moshi.Json
/**
* Created by <NAME> on 04,May,2020
*/
data class Oembed(
@field:Json(name="thumbnail_url")
val thumbnailUrl:String?
) | 1 | null | 1 | 1 | 9036e653ed15d34241dcc5397efc687bae89328f | 193 | Reddit-client | Apache License 2.0 |
app/src/main/java/com/iamsdt/androidsketchpad/injection/module/RetrofitModule.kt | Iamsdt | 127,500,624 | false | null | package com.iamsdt.androidsketchpad.injection.module
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.iamsdt.androidsketchpad.data.retrofit.RetInterface
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
/**
* Created by <NAME> on 3/31/2018.
* at 12:00 PM
*/
@Module(includes = [NetworkModule::class])
class RetrofitModule {
@Provides
@Singleton
fun getRestInterface(retrofit: Retrofit): RetInterface =
retrofit.create(RetInterface::class.java)
@Provides
@Singleton
fun getRetrofit(okHttpClient: OkHttpClient,gson: Gson): Retrofit
= Retrofit.Builder()
.baseUrl("https://www.googleapis.com/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
@Provides
@Singleton
fun getGson():Gson = GsonBuilder().create()
} | 0 | Kotlin | 0 | 1 | 0954c720fb7e8202c98b1256a16a0df396474559 | 1,019 | AndroidSketchPad | Apache License 2.0 |
lcc-content/src/main/kotlin/com/joshmanisdabomb/lcc/world/feature/OilGeyserFeature.kt | joshmanisdabomb | 537,458,013 | false | {"Kotlin": 2724329, "Java": 138822} | package com.joshmanisdabomb.lcc.world.feature
import com.joshmanisdabomb.lcc.block.OilBlock.Companion.GEYSER
import com.joshmanisdabomb.lcc.directory.LCCBlocks
import com.joshmanisdabomb.lcc.extensions.transformInt
import com.joshmanisdabomb.lcc.world.GenUtils
import com.mojang.serialization.Codec
import net.minecraft.block.FluidBlock
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.world.gen.feature.DefaultFeatureConfig
import net.minecraft.world.gen.feature.Feature
import net.minecraft.world.gen.feature.util.FeatureContext
class OilGeyserFeature(configCodec: Codec<DefaultFeatureConfig>) : Feature<DefaultFeatureConfig>(configCodec) {
override fun generate(context: FeatureContext<DefaultFeatureConfig>): Boolean {
with (context) {
val height = 4 + random.nextInt(4)
if (!GenUtils.areaMatches(context.world::getBlockState, origin.x, origin.y, origin.z, height = height.minus(1)) { state, pos -> !world.isOutOfHeightLimit(pos.y) }) return false
if (!GenUtils.areaMatches(context.world::getBlockState, origin.x, origin.y - 2, origin.z, ex = 3, ez = 3, height = 1) { state, pos -> state.isOf(LCCBlocks.cracked_mud) }) return false
if (!GenUtils.areaMatches(context.world::getBlockState, origin.x, origin.y, origin.z, ex = 2, ez = 2, height = height.minus(1))) return false
val bp = BlockPos.Mutable()
for (i in height.minus(1) downTo -1) {
world.setBlockState(bp.set(context.origin).move(0, i, 0), LCCBlocks.oil.defaultState.with(FluidBlock.LEVEL, (i < height.minus(1) && i > -1).transformInt(8)).with(GEYSER, i > -1), 18)
for (j in 0..3) {
val direction = Direction.fromHorizontal(j)
world.setBlockState(bp.offset(direction), LCCBlocks.oil.defaultState.with(FluidBlock.LEVEL, (i == height.minus(1)).transformInt(7, (i == -1).transformInt(0, 8))).with(GEYSER, i > -1), 18)
if (i == 0) {
world.setBlockState(bp.offset(direction, 2), LCCBlocks.oil.defaultState.with(FluidBlock.LEVEL, 7), 18)
world.setBlockState(bp.add(if (j % 2 == 0) 1 else -1, 0, if (j / 2 == 0) 1 else -1), LCCBlocks.oil.defaultState.with(FluidBlock.LEVEL, 7), 18)
} else if (i == -1) {
if (random.nextInt(2) == 0) world.setBlockState(bp.offset(direction, 2), LCCBlocks.oil.defaultState.with(FluidBlock.LEVEL, 0), 18)
if (random.nextInt(2) == 0) world.setBlockState(bp.add(if (j % 2 == 0) 1 else -1, 0, if (j / 2 == 0) 1 else -1), LCCBlocks.oil.defaultState.with(FluidBlock.LEVEL, 0), 18)
}
}
}
for (x in -2..2) {
for (z in -2..2) {
if (random.nextInt(3) == 0) world.setBlockState(bp.set(context.origin).move(x, -1, z), LCCBlocks.oil.defaultState.with(FluidBlock.LEVEL, 0), 18)
}
}
}
return true
}
} | 0 | Kotlin | 0 | 0 | a836162eaf64a75ca97daffa02c1f9e66bdde1b4 | 3,068 | loosely-connected-concepts | Creative Commons Zero v1.0 Universal |
packages/mobile/android/app/src/main/java/co/audius/app/MainActivity.kt | AudiusProject | 201,821,771 | false | {"TypeScript": 12224874, "Python": 3591836, "JavaScript": 2647121, "PLpgSQL": 2636194, "CSS": 755714, "Go": 643358, "Rust": 555379, "Solidity": 383422, "HTML": 126866, "Shell": 97102, "MDX": 92735, "Mustache": 74017, "Ruby": 18128, "Lua": 15824, "Dockerfile": 12873, "Objective-C": 7094, "GLSL": 5911, "Objective-C++": 3516, "Kotlin": 3389, "Makefile": 2936, "Java": 1991, "Swift": 221, "Procfile": 180, "C": 104} | package co.audius.app
import android.os.Bundle
import com.bytedance.sdk.open.tiktok.TikTokOpenApiFactory
import com.bytedance.sdk.open.tiktok.TikTokOpenConfig
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
import com.google.android.gms.cast.framework.CastContext
import com.zoontek.rnbars.RNBars
import com.zoontek.rnbootsplash.RNBootSplash
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is
* used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "AudiusReactNative"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
override fun invokeDefaultOnBackPressed() {
// Not calling super. invokeDefaultOnBackPressed() b/c it will close the app.
// Instead, put the app in the backgroud to allow audio to keep playing.
moveTaskToBack(true)
}
override fun onCreate(savedInstanceState: Bundle?) {
RNBootSplash.init(this, R.style.BootTheme)
super.onCreate(null)
RNBars.init(this, "light-content")
TikTokOpenApiFactory.init(TikTokOpenConfig(BuildConfig.TIKTOK_APP_ID))
// lazy load Google Cast context
CastContext.getSharedInstance(this)
}
}
| 51 | TypeScript | 104 | 537 | 075f483b84e76a118f8838d6d048dae65f77d9fb | 1,694 | audius-protocol | Apache License 2.0 |
app/src/main/java/com/android/anonymous_02_22/domain/usercase/CountryInteraction.kt | ngothanhtuan1203 | 464,987,929 | false | {"Kotlin": 84145} | package com.android.anonymous_02_22.domain.usercase
import com.android.anonymous_02_22.domain.entities.CarInfo
import com.android.anonymous_02_22.domain.entities.CountryInfo
import com.android.anonymous_02_22.domain.entities.GitProfile
import com.android.anonymous_02_22.domain.mapper.CountryInfoMapper
import com.android.anonymous_02_22.domain.mapper.GitProfileMapper
import com.android.anonymous_02_22.domain.repository.LocalRepository
import com.android.anonymous_02_22.domain.repository.RemoteRepository
import com.android.anonymous_02_22.utility.Constant
import javax.inject.Inject
class CountryInteraction @Inject constructor(
private val remoteRepository: RemoteRepository,
private val localRepository: LocalRepository,
private val mapper: CountryInfoMapper
) : CountryUseCase {
override suspend fun fetchCountries(): List<CountryInfo> {
val model = localRepository.fetchCountries()
return mapper.toDomainList(model)
}
override suspend fun fetchCarInfo(countryCode: String): CarInfo {
val data = remoteRepository.fetchCountryCarInfo(Constant.CAR_INFO_MOCK_API)
return CarInfo("","","")
}
} | 0 | Kotlin | 0 | 0 | a6017683936fbe748a5424692893bd71ba23e518 | 1,158 | anonymous_02_22 | Apache License 2.0 |
framework/src/main/java/wulinpeng/com/framework/base/ui/BaseActivity.kt | 1014277960 | 79,416,483 | false | null | package wulinpeng.com.framework.base.ui
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import butterknife.ButterKnife
import butterknife.Unbinder
/**
*
* @author wulinpeng
* @datetime: 2019/4/6 8:58 PM
* @description:
*/
abstract class BaseActivity: AppCompatActivity() {
private var mUnBinder: Unbinder? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(getLayoutId())
mUnBinder = ButterKnife.bind(this)
initViews()
initData()
}
protected abstract fun getLayoutId(): Int
protected abstract fun initViews()
protected abstract fun initData()
override fun onDestroy() {
super.onDestroy()
mUnBinder?.unbind()
}
} | 1 | null | 1 | 1 | f8b3b271e5f84212bc31dff8383887bf15570660 | 796 | DailyReader | Apache License 2.0 |
app/src/main/kotlin/com/rayfantasy/icode/ui/layout/fragment/MainFragment.kt | AllenTom | 55,195,866 | true | {"Kotlin": 136983, "Java": 36175} | package com.rayfantasy.icode.ui.layout.fragment
import com.benny.library.kbinding.view.ViewBinderComponent
import com.rayfantasy.icode.R
import com.rayfantasy.icode.extension.generateViewId
import com.rayfantasy.icode.extension.lparams
import com.rayfantasy.icode.theme.colorPrimaryDark
import com.rayfantasy.icode.theme.observe
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.design.floatingActionButton
import org.jetbrains.anko.dip
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.relativeLayout
import org.jetbrains.anko.support.v4.swipeRefreshLayout
/**
* Created by Allen on 2016/4/3.
*/
class MainFragment : ViewBinderComponent<MainFragment> {
companion object{
val ID_SWIPE = generateViewId()
val ID_RECYCLER = generateViewId()
val ID_FAB = generateViewId()
}
override fun builder(): AnkoContext<*>.() -> Unit = {
relativeLayout {
swipeRefreshLayout {
id = ID_SWIPE
recyclerView {
id = ID_RECYCLER
}.lparams(matchParent, matchParent)
}.lparams(matchParent, matchParent)
floatingActionButton {
id = ID_FAB
setImageResource(R.mipmap.ic_create_new)
observe(colorPrimaryDark){setBackgroundColor(it)}
}.lparams(dip(40),dip(40)){}
}.lparams(matchParent, matchParent)
}
} | 0 | Kotlin | 0 | 0 | 63ece222e24cb3c8cc157b642c4374ec876f9d41 | 1,497 | iCode-Android-KBinding | Apache License 2.0 |
core/database/src/main/java/com/andannn/melodify/core/database/LyricDao.kt | andannn | 583,624,480 | false | {"Kotlin": 318245} | package com.andannn.melodify.core.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.andannn.melodify.core.database.entity.LyricColumns
import com.andannn.melodify.core.database.entity.LyricEntity
import com.andannn.melodify.core.database.entity.LyricWithAudioCrossRef
import com.andannn.melodify.core.database.entity.LyricWithAudioCrossRefColumns
import kotlinx.coroutines.flow.Flow
@Dao
interface LyricDao {
@Transaction
suspend fun insertLyricOfMedia(mediaStoreId: Long, lyric: LyricEntity) {
insertLyricEntities(listOf(lyric))
insertLyricWithMediaCrossRef(
listOf(
LyricWithAudioCrossRef(
mediaStoreId = mediaStoreId,
lyricId = lyric.id
)
)
)
}
@Insert(entity = LyricEntity::class, onConflict = OnConflictStrategy.IGNORE)
suspend fun insertLyricEntities(entities: List<LyricEntity>)
@Insert(entity = LyricWithAudioCrossRef::class, onConflict = OnConflictStrategy.IGNORE)
suspend fun insertLyricWithMediaCrossRef(crossRefs: List<LyricWithAudioCrossRef>)
@Query(
"""
select * from ${Tables.LYRIC_WITH_AUDIO_CROSS_REF}
left join ${Tables.LYRIC}
on ${LyricColumns.ID} = ${LyricWithAudioCrossRefColumns.LYRIC_ID}
where :mediaStoreId = ${LyricWithAudioCrossRefColumns.MEDIA_STORE_ID}
"""
)
fun getLyricByMediaStoreIdFlow(mediaStoreId: Long): Flow<LyricEntity?>
} | 5 | Kotlin | 0 | 0 | 128a2b2414b07dda5a14114fdb07ae858fedb35f | 1,596 | Melodify | Apache License 2.0 |
example/tbib_toast_example/android/app/src/main/kotlin/com/example/tbib_toast_example/MainActivity.kt | the-best-is-best | 399,160,962 | false | {"C++": 20301, "Dart": 11865, "CMake": 7978, "HTML": 3715, "C": 713, "Swift": 404, "Kotlin": 135, "Objective-C": 38} | package com.example.tbib_toast_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | C++ | 1 | 0 | d5bb6ddaf7636915ef85118988a8c891ae07ea7d | 135 | tbib_toast | MIT License |
app/src/main/java/com/blank/githubuser/ui/base/BaseFragment.kt | mbahgojol | 290,164,894 | false | {"Kotlin": 120927} | package com.blank.githubuser.ui.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
abstract class BaseFragment : Fragment() {
abstract fun layoutId(): Int
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(layoutId(), container, false)
}
} | 0 | Kotlin | 2 | 9 | a7845c51039bbf8c2e2d757c31328554f2e90a18 | 525 | GithubUsers-AndroidApp | Apache License 2.0 |
backend-common/src/main/kotlin/ru/otus/repositories/IRatingRepository.kt | otuskotlin | 327,223,991 | false | null | package ru.otus.repositories
import ru.otus.model.context.ExchangeContext
interface IRatingRepository {
suspend fun ExchangeContext.read()
suspend fun ExchangeContext.create()
suspend fun ExchangeContext.update()
suspend fun ExchangeContext.delete()
companion object {
val NONE = object : IRatingRepository {
override suspend fun ExchangeContext.read() {
TODO("Not yet implemented")
}
override suspend fun ExchangeContext.create() {
TODO("Not yet implemented")
}
override suspend fun ExchangeContext.update() {
TODO("Not yet implemented")
}
override suspend fun ExchangeContext.delete() {
TODO("Not yet implemented")
}
}
}
}
| 0 | Kotlin | 1 | 0 | 842fda56bf0bfbf0d80d85555792521b790037ed | 831 | otuskotlin-202012-rating-fs | MIT License |
app/src/main/java/com/development/clean/util/AESEncryption.kt | thangikcu | 515,687,582 | false | null | @file:Suppress("unused")
package com.development.clean.util
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import com.development.clean.BuildConfig
import com.development.clean.data.local.sharedprefs.AES_IV
import com.development.clean.data.local.sharedprefs.AppSharedPrefs
import com.development.clean.util.debug.Timber
import java.security.KeyStore
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
@Suppress("MemberVisibilityCanBePrivate")
object AESEncryption {
private const val PROVIDER = "AndroidKeyStore"
private const val KEY_STORE_ALIAS = "AES_${BuildConfig.APPLICATION_ID}"
private const val TRANSFORMATION = "AES/CBC/PKCS7Padding"
private const val KEY_SIZE = 256
private val keyStore: KeyStore = KeyStore.getInstance(PROVIDER).apply {
load(null)
}
private val iv: ByteArray = AppSharedPrefs.get<String?>(AES_IV, null)
.let { base64 ->
if (base64.isNullOrEmpty()) {
ByteArray(16).also {
SecureRandom().nextBytes(it)
AppSharedPrefs.put(AES_IV, Base64.encodeToString(it, Base64.DEFAULT))
}
} else {
Base64.decode(base64, Base64.DEFAULT)
}
}
init {
if (!keyStore.containsAlias(KEY_STORE_ALIAS)) {
val parameterSpec: KeyGenParameterSpec = KeyGenParameterSpec.Builder(
KEY_STORE_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).run {
setBlockModes(KeyProperties.BLOCK_MODE_CBC)
setKeySize(KEY_SIZE)
setRandomizedEncryptionRequired(false)
setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
build()
}
KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER)
.run {
init(parameterSpec)
generateKey()
}
}
}
fun encrypt(data: String): String? = try {
val cipher = Cipher.getInstance(TRANSFORMATION)
val secretKey = keyStore.getKey(KEY_STORE_ALIAS, null) as SecretKey
cipher.init(Cipher.ENCRYPT_MODE, secretKey, IvParameterSpec(iv))
val encrypt: ByteArray = cipher.doFinal(data.toByteArray(Charsets.UTF_8))
Base64.encodeToString(encrypt, Base64.DEFAULT)
} catch (e: Exception) {
Timber.e(e)
null
}
fun decrypt(encryptData: String): String? = try {
val cipher = Cipher.getInstance(TRANSFORMATION)
val secretKey = keyStore.getKey(KEY_STORE_ALIAS, null) as SecretKey
cipher.init(Cipher.DECRYPT_MODE, secretKey, IvParameterSpec(iv))
val decrypt: ByteArray = cipher.doFinal(Base64.decode(encryptData, Base64.DEFAULT))
decrypt.toString(Charsets.UTF_8)
} catch (e: Exception) {
Timber.e(e)
null
}
}
| 1 | null | 1 | 3 | 4c78d2f04e198831f4ad9d109b376c4586f5fcbf | 3,205 | Android-Kotlin-Clean-Architecture | Apache License 2.0 |
IndoorNavAndroid/nav-client/src/main/java/com/izhxx/navclient/domain/usecase/search/SearchUseCaseImpl.kt | ZhevlakovII | 507,916,442 | false | {"Kotlin": 97377} | package com.izhxx.navclient.domain.usecase.search
import com.izhxx.navcore.domain.model.SearchHistory
import com.izhxx.navcore.domain.repository.SearchRepository
import io.reactivex.Single
import javax.inject.Inject
internal class SearchUseCaseImpl @Inject constructor(
private val searchRepository: SearchRepository
) : SearchUseCase {
override fun insertRequest(request: SearchHistory) = searchRepository.insertRequest(request)
override fun getRequests(): Single<List<SearchHistory>> = searchRepository.getRequests()
} | 1 | Kotlin | 0 | 1 | bd26efb7ce87a5309a54a8e7ad929d8870ff2ec8 | 536 | IndoorNavigation | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.