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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/bravedroid/jobby/auth/presentation/dtos/LoginResponseDto.kt
|
BraveDroid
| 428,729,381
| false
|
{"Kotlin": 65435}
|
package com.bravedroid.jobby.auth.presentation.dtos
data class LoginResponseDto(
val accessToken: String,
val refreshToken: String,
) {
val tokenType: String = "Bearer"
}
| 0
|
Kotlin
|
1
| 0
|
ee0809159273a093de7cccb6839e41d3d720155e
| 185
|
JobbyServer
|
The Unlicense
|
src/main/kotlin/com/bravedroid/jobby/auth/presentation/dtos/LoginResponseDto.kt
|
BraveDroid
| 428,729,381
| false
|
{"Kotlin": 65435}
|
package com.bravedroid.jobby.auth.presentation.dtos
data class LoginResponseDto(
val accessToken: String,
val refreshToken: String,
) {
val tokenType: String = "Bearer"
}
| 0
|
Kotlin
|
1
| 0
|
ee0809159273a093de7cccb6839e41d3d720155e
| 185
|
JobbyServer
|
The Unlicense
|
core/src/org/river/exertion/ecs/entity/character/CharacterNone.kt
|
exertionriver
| 345,650,250
| false
| null |
package org.river.exertion.ecs.entity.character
import com.badlogic.ashley.core.Component
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.ai.fsm.DefaultStateMachine
import org.river.exertion.ecs.component.action.*
import org.river.exertion.ecs.component.action.core.ActionState
import org.river.exertion.ecs.component.action.core.IActionComponent
import org.river.exertion.ecs.entity.IEntity
object CharacterNone : ICharacter {
override var entityName = "None"
override var description = "None"
override val stateMachine = DefaultStateMachine(this, ActionState.NONE)
override fun initialize(initName: String, entity: Entity) {
entityName = initName
actions.forEach {
if (!entity.components.contains(it as Component) ) entity.add(it as Component)
}
}
override var moment = 1f
override var actions = mutableListOf<IActionComponent>(
ActionLookComponent()
, ActionReflectComponent()
, ActionIdleComponent()
, ActionWatchComponent()
)
}
| 0
|
Kotlin
|
0
| 2
|
e554d700d5fbc16953a61d782cbe63162072483a
| 1,055
|
koboldCave
|
MIT License
|
src/main/kotlin/eu/fizzystuff/krog/model/dungeongenerators/objects/ObjectGenerator.kt
|
noseblowhorn
| 53,980,499
| false
| null |
package eu.fizzystuff.krog.model.dungeongenerators.objects
import eu.fizzystuff.krog.model.DungeonLevel
interface ObjectGenerator {
fun generate(dungeonLevel: DungeonLevel)
}
| 9
|
Kotlin
|
0
| 0
|
07bd6389b0bb20a60a5ab2e4cc7f31b8c867949c
| 180
|
krog
|
Apache License 2.0
|
tickerview/src/main/java/com/github/bassaer/tickerview/TickerTextView.kt
|
bassaer
| 131,505,171
| false
| null |
package com.github.bassaer.tickerview
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.PorterDuff
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.view.SurfaceHolder
import android.view.SurfaceView
import kotlinx.coroutines.experimental.launch
/**
* Ticker Text View
* Created by nakayama on 2018/04/30.
*/
class TickerTextView(context: Context, attrs: AttributeSet) : SurfaceView(context, attrs), SurfaceHolder.Callback {
private var surfaceHolder = holder
private val speed = 4
private var viewWidth = 0
private var viewHeight = 0
private var paint = Paint()
private val text = "Hello World"
private var textWidth = 0f
private var wholeTextWidth = 0f
private var textSize = 0
private var textHeight = 0f
private var currentPosition = 0f
private var scrollTime = 10
private var isDrawing = false
init {
surfaceHolder = holder
surfaceHolder.addCallback(this)
paint = Paint()
paint.color = Color.BLACK
textSize = context.resources.getDimensionPixelSize(R.dimen.text_size)
paint.textSize = textSize.toFloat()
setZOrderOnTop(true)
holder.setFormat(PixelFormat.TRANSLUCENT)
isFocusable = true
isDrawing = true
}
private fun draw(x: Float, y: Float) {
val canvas = surfaceHolder.lockCanvas()
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
canvas.drawText(text, x, y, paint)
surfaceHolder.unlockCanvasAndPost(canvas)
}
override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
}
override fun surfaceDestroyed(holder: SurfaceHolder?) {
isDrawing = false
}
override fun surfaceCreated(holder: SurfaceHolder?) {
launch {
while (isDrawing) {
draw(viewWidth - currentPosition, textHeight)
currentPosition += speed
if (currentPosition > wholeTextWidth) {
currentPosition = 0f
--scrollTime
}
if (scrollTime <= 0) {
isDrawing = false
}
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
viewWidth = MeasureSpec.getSize(widthMeasureSpec)
viewHeight = MeasureSpec.getSize(heightMeasureSpec)
textWidth = paint.measureText(text)
wholeTextWidth = viewWidth + textWidth
textHeight = getFontHeight(textSize.toFloat())
setMeasuredDimension(viewWidth, textHeight.toInt())
}
private fun getFontHeight(fontSize: Float): Float {
val paint = Paint()
paint.textSize = fontSize
val metrics = paint.fontMetrics
return Math.ceil(metrics.descent.toDouble() + metrics.ascent.toDouble()).toFloat() / 2
}
private fun spToDp(sp: Float): Int {
val metrics = DisplayMetrics()
(context as Activity).windowManager.defaultDisplay.getMetrics(metrics)
val density = resources.displayMetrics.density
return (sp * metrics.scaledDensity / density).toInt()
}
}
| 1
| null |
1
| 1
|
76f383bacc12e682ba9528477cef409e3e036c4f
| 3,374
|
TickerView
|
Apache License 2.0
|
util-db/src/main/kotlin/com/seanshubin/condorcet/util/db/Table.kt
|
SeanShubin
| 190,099,313
| false
|
{"Text": 27, "XML": 1, "Markdown": 1, "Maven POM": 21, "Ignore List": 1, "Shell": 1, "HTML": 20, "Java": 20, "Kotlin": 212, "SVG": 1, "SQL": 47, "JSON": 2, "YAML": 1}
|
package com.seanshubin.condorcet.util.db
import com.seanshubin.condorcet.util.db.SqlUtil.indent
data class Table(val name: String,
val columns: List<Column>,
val unique: List<Column>) {
constructor(name: String, vararg columns: Column) : this(name, columns.toList(), listOf())
fun toDropTableStatement(): String = "drop table if exists $name"
fun toCreateTableStatements(): List<String> {
val createTableSql = toCreateTableSql()
val uniqueLines = toUniqueSql()
return listOf<String>() + createTableSql + uniqueLines
}
private fun toCreateTableSql(): String {
val firstLine = "create table $name ("
val middleLines = toMiddleSql().map(::indent)
val lastLine = ")"
return (emptyList<String>() + firstLine + middleLines + lastLine).joinToString("\n")
}
private fun toMiddleSql(): List<String> {
val idLine = "id int not null auto_increment,"
val fieldLines: List<String> = this.columns.flatMap { it.toSql() }
val primaryKeyLine = "primary key(id)"
return listOf<String>() + idLine + fieldLines + primaryKeyLine
}
private fun toUniqueSql(): List<String> =
if (unique.isEmpty()) emptyList()
else {
val uniqueColumnNames = unique.map { it.sqlName() }.joinToString(", ")
listOf("alter table $name add unique unique_$name($uniqueColumnNames)")
}
}
| 2
|
Kotlin
|
0
| 0
|
61219ae238b47792a5d347625f4963a1b2841d2d
| 1,473
|
condorcet5
|
The Unlicense
|
core/src/main/java/de/solarisbank/sdk/logger/data/LoggerAPI.kt
|
Solarisbank
| 336,233,277
| false
|
{"Kotlin": 468901, "Java": 6478, "Shell": 1215}
|
package de.solarisbank.sdk.logger.data
import de.solarisbank.sdk.logger.domain.model.LogContent
import io.reactivex.Single
import retrofit2.http.Body
import retrofit2.http.POST
interface LoggerAPI {
@POST("/sdk_logging")
fun postLog(@Body logContent: LogContent): Single<Boolean>
}
| 0
|
Kotlin
|
0
| 6
|
555ae8cb524ad592115245f13d73bd4cfdd46c9c
| 292
|
identhub-android
|
MIT License
|
app/src/main/java/com/github/vase4kin/teamcityapp/account/create/data/CreateAccountDataManagerImpl.kt
|
vase4kin
| 68,111,887
| false
|
{"Gradle": 29, "JSON": 2, "Java Properties": 2, "Markdown": 6, "Shell": 1, "Ignore List": 26, "Batchfile": 1, "Text": 1, "YAML": 5, "INI": 24, "Proguard": 25, "XML": 228, "Java": 33, "Kotlin": 580, "HTML": 1, "Gradle Kotlin DSL": 1}
|
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.account.create.data
import android.content.Context
import android.net.Uri
import android.os.Handler
import com.github.vase4kin.teamcityapp.R
import com.github.vase4kin.teamcityapp.TeamCityApplication
import com.github.vase4kin.teamcityapp.account.create.helper.UrlFormatter
import com.github.vase4kin.teamcityapp.api.AUTHORIZATION
import com.github.vase4kin.teamcityapp.storage.SharedUserStorage
import com.google.firebase.crashlytics.FirebaseCrashlytics
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Credentials
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.net.UnknownHostException
private const val AUTH_URL = "httpAuth/app/rest/server"
private const val AUTH_GUEST_URL = "guestAuth/app/rest/server"
private const val SCHEME_HTTP = "http"
/**
* Default error code
*/
private const val DEFAULT_ERROR_CODE = 0
/**
* Impl of [CreateAccountDataManager]
*/
class CreateAccountDataManagerImpl(
private val context: Context,
private val baseOkHttpClient: OkHttpClient,
private val unsafeBaseOkHttpClient: OkHttpClient,
private val sharedUserStorage: SharedUserStorage,
private val urlFormatter: UrlFormatter
) : CreateAccountDataManager {
/**
* {@inheritDoc}
*/
override fun authUser(
listener: CustomOnLoadingListener<String>,
url: String,
userName: String,
password: String,
isSslDisabled: Boolean,
checkSecureConnection: Boolean
) {
// Creating okHttpClient with authenticator
val okHttpClient = createClientWithAuthenticator(userName, password, isSslDisabled)
// Handling request
handleAuthRequest(url, AUTH_URL, okHttpClient, listener, checkSecureConnection)
}
private fun createClientWithAuthenticator(
userName: String,
password: String,
isSslDisabled: Boolean
): OkHttpClient {
return getClient(isSslDisabled).newBuilder().authenticator { _, response ->
val credential = Credentials.basic(userName, password)
if (credential == response.request().header(AUTHORIZATION)) {
return@authenticator null // If we already failed with these credentials, don't retry.
}
response.request().newBuilder()
.header(AUTHORIZATION, credential)
.build()
}.build()
}
/**
* {@inheritDoc}
*/
override fun authGuestUser(
listener: CustomOnLoadingListener<String>,
url: String,
isSslDisabled: Boolean,
checkSecureConnection: Boolean
) {
handleAuthRequest(
url,
AUTH_GUEST_URL,
getClient(isSslDisabled),
listener,
checkSecureConnection
)
}
/**
* @return [OkHttpClient] depending on ssl enabled state
*/
private fun getClient(isSslEnabled: Boolean): OkHttpClient {
return if (isSslEnabled) unsafeBaseOkHttpClient else baseOkHttpClient
}
/**
* Handle auth request
*
* @param serverUrl - Server url
* @param authUrl - Appended auth url
* @param okHttpClient - Client to make an auth
* @param listener - Listener to receive callbacks
*/
private fun handleAuthRequest(
serverUrl: String,
authUrl: String,
okHttpClient: OkHttpClient,
listener: CustomOnLoadingListener<String>,
checkSecureConnection: Boolean
) {
val serverAuthUri = Uri.parse(serverUrl).buildUpon()
.appendEncodedPath(authUrl).build()
if (checkSecureConnection && SCHEME_HTTP == serverAuthUri.scheme) {
listener.onFail(
CreateAccountDataManager.ERROR_CODE_HTTP_NOT_SECURE,
context.getString(R.string.server_not_secure_http)
)
return
}
val handler = Handler(context.mainLooper)
try {
val request = Request.Builder()
.url(serverAuthUri.toString())
.build()
okHttpClient
.newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
handler.post {
if (e is UnknownHostException) {
listener.onFail(
DEFAULT_ERROR_CODE,
context.getString(R.string.server_no_such_server)
)
} else {
listener.onFail(DEFAULT_ERROR_CODE, e.message ?: "")
}
}
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
val formattedServerUrl = urlFormatter.formatServerUrl(serverUrl)
handler.post { listener.onSuccess(formattedServerUrl) }
} else {
var message: String
if (response.body() != null && response.body()!!.source() != null) {
try {
message = response.body()!!.source().readUtf8()
} catch (exception: IOException) {
FirebaseCrashlytics.getInstance().recordException(exception)
message = response.message()
}
} else {
message = response.message()
}
handler.post { listener.onFail(response.code(), message) }
}
}
})
} catch (e: IllegalArgumentException) {
listener.onFail(DEFAULT_ERROR_CODE, context.getString(R.string.server_correct_url))
} catch (e: Exception) {
listener.onFail(DEFAULT_ERROR_CODE, context.getString(R.string.server_check_url))
}
}
/**
* {@inheritDoc}
*/
override fun saveNewUserAccount(
serverUrl: String,
userName: String,
password: String,
isSslDisabled: Boolean,
listener: OnLoadingListener<String>
) {
sharedUserStorage.saveUserAccountAndSetItAsActive(
serverUrl,
userName,
password,
isSslDisabled,
object : SharedUserStorage.OnStorageListener {
override fun onSuccess() {
// On data save success
listener.onSuccess(serverUrl)
}
override fun onFail() {
// On data save fail
listener.onFail("")
}
}
)
}
/**
* {@inheritDoc}
*/
override fun saveGuestUserAccount(url: String, isSslDisabled: Boolean) {
sharedUserStorage.saveGuestUserAccountAndSetItAsActive(url, isSslDisabled)
}
/**
* {@inheritDoc}
*/
override fun initTeamCityService(url: String) {
(context.applicationContext as TeamCityApplication).buildRestApiInjectorWithBaseUrl(url)
}
}
| 0
|
Kotlin
|
11
| 52
|
9abb1ed56c127d64679124c38d30b0014ec024de
| 8,034
|
TeamCityApp
|
Apache License 2.0
|
data/src/main/java/com/kennyc/dashweather/data/model/Weather.kt
|
Kennyc1012
| 105,380,988
| false
| null |
package com.kennyc.dashweather.data.model
data class Weather(val latitude: Double,
val longitude: Double,
val current: Double,
val high: Double,
val low: Double,
val humidity: Int,
val summary: String,
val locationHumanReadable: String?,
val icon: WeatherIcon)
| 0
|
Kotlin
|
2
| 0
|
212ce9f0dc434a537530b3904b1763684f7f6915
| 413
|
DashWeatherExtension
|
Apache License 2.0
|
src/Day09.kt
|
hrach
| 572,585,537
| false
|
{"Kotlin": 32838}
|
fun main() {
fun isAdjacent(hx: Int, hy: Int, tx: Int, ty: Int): Boolean =
tx in (hx - 1..hx + 1) && ty in (hy - 1..hy + 1)
fun newPos(hx: Int, hy: Int, tx: Int, ty: Int): Pair<Int, Int> {
if (isAdjacent(hx, hy, tx, ty)) return tx to ty
val dx = if (hx > tx) 1 else if (hx == tx) 0 else -1
val dy = if (hy > ty) 1 else if (hy == ty) 0 else -1
return tx + dx to ty + dy
}
fun parse(input: List<String>): List<Pair<Char, Int>> =
input.map {
val (c, n) = it.split(" ")
c.first() to n.toInt()
}
fun part1(input: List<String>): Int {
var hx = 0
var hy = 0
var tx = 0
var ty = 0
val map = mutableSetOf<Pair<Int, Int>>()
parse(input).forEach { (c, n) ->
repeat(n) {
when (c) {
'U' -> hy += 1
'D' -> hy -= 1
'R' -> hx += 1
'L' -> hx -= 1
else -> error(c)
}
val new = newPos(hx, hy, tx, ty)
tx = new.first
ty = new.second
map.add(new)
}
}
return map.size
}
fun part2(input: List<String>): Int {
var hx = 0
var hy = 0
val knots = List(9) { Pair(0, 0) }.toMutableList()
val map = mutableSetOf<Pair<Int, Int>>()
parse(input).forEach { (c, n) ->
repeat(n) {
when (c) {
'U' -> hy += 1
'D' -> hy -= 1
'R' -> hx += 1
'L' -> hx -= 1
else -> error(c)
}
var prev = hx to hy
for (index in knots.indices) {
val knot = knots[index]
val new = newPos(prev.first, prev.second, knot.first, knot.second)
knots[index] = new
prev = new
}
map.add(knots.last())
}
}
return map.size
}
val test2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent().lines()
val testInput = readInput("Day09_test")
check(part1(testInput), 13)
check(part2(testInput), 1)
check(part2(test2), 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0
|
Kotlin
|
0
| 1
|
40b341a527060c23ff44ebfe9a7e5443f76eadf3
| 2,484
|
aoc-2022
|
Apache License 2.0
|
app/src/main/java/com/pkj/wow/androidkotlin/kotlin/functions/HighOrderFunctions.kt
|
pkjvit
| 612,047,289
| false
| null |
package com.pkj.wow.androidkotlin.kotlin.functions
class HighOrderFunctions {
}
| 0
|
Kotlin
|
0
| 1
|
f593d2749653e237050ab4f226fe0d85cef88ff8
| 80
|
ANDROID-Kotlin
|
Apache License 2.0
|
app/src/main/java/com/ick/kalambury/words/WordsSetDownloadJob.kt
|
radek606
| 459,264,828
| false
| null |
package com.ick.kalambury.words
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.Data
import androidx.work.WorkerParameters
import androidx.work.rxjava3.RxWorker
import com.ick.kalambury.net.api.RestApiManager
import com.ick.kalambury.net.api.exceptions.NetworkFailureException
import com.ick.kalambury.util.crypto.AESCipherStreamsFactory
import com.ick.kalambury.util.crypto.Secret
import com.ick.kalambury.util.log.Log
import com.ick.kalambury.util.log.logTag
import com.ick.kalambury.wordsrepository.WordsRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import io.reactivex.rxjava3.core.Single
import java.io.ByteArrayInputStream
@HiltWorker
class WordsSetDownloadJob @AssistedInject constructor(
@Assisted val context: Context,
@Assisted val workerParams: WorkerParameters,
private val wordsRepository: WordsRepository,
private val restApiManager: RestApiManager,
) : RxWorker(context, workerParams) {
companion object {
const val KEY_WORDS_SET_ID = "words_set_id"
const val KEY_SECRET_KEY = "secret_key"
const val KEY_SECRET_IV = "secret_iv"
const val KEY_SUCCESS = "success"
const val KEY_FAILURE = "failure"
}
override fun createWork(): Single<Result> {
val setId = inputData.getString(KEY_WORDS_SET_ID) ?: return Single.just(Result.failure())
val key = inputData.getByteArray(KEY_SECRET_KEY) ?: return Single.just(Result.failure())
val iv = inputData.getByteArray(KEY_SECRET_IV) ?: return Single.just(Result.failure())
return restApiManager.getWordsSet(setId)
.flatMap { result ->
result.fold({
val stream = AESCipherStreamsFactory.create(ByteArrayInputStream(it), Secret(key, iv), "AES/CBC/PKCS5Padding")
wordsRepository.updater.saveWordsSet(setId, stream, "new")
.toSingle { success(setId) }
.onErrorReturn { failure(setId) }
}, {
when(it) {
is NetworkFailureException -> {
Log.w(logTag, "Network fail during words set download. Retrying...", it)
Single.just(Result.retry())
}
else -> {
Log.w(logTag, "Error during words set download. Aborting...", it)
Single.just(failure(setId))
}
}
})
}
}
private fun success(setId: String): Result {
return Result.success(Data.Builder().putString(KEY_SUCCESS, setId).build())
}
private fun failure(setId: String): Result {
return Result.success(Data.Builder().putString(KEY_FAILURE, setId).build())
}
}
| 0
|
Kotlin
|
0
| 0
|
3dd2fe12e40ab3f9bac145ba15e9719d55e12b89
| 2,874
|
Charades-Android
|
MIT License
|
app/src/main/java/com/ick/kalambury/words/WordsSetDownloadJob.kt
|
radek606
| 459,264,828
| false
| null |
package com.ick.kalambury.words
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.Data
import androidx.work.WorkerParameters
import androidx.work.rxjava3.RxWorker
import com.ick.kalambury.net.api.RestApiManager
import com.ick.kalambury.net.api.exceptions.NetworkFailureException
import com.ick.kalambury.util.crypto.AESCipherStreamsFactory
import com.ick.kalambury.util.crypto.Secret
import com.ick.kalambury.util.log.Log
import com.ick.kalambury.util.log.logTag
import com.ick.kalambury.wordsrepository.WordsRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import io.reactivex.rxjava3.core.Single
import java.io.ByteArrayInputStream
@HiltWorker
class WordsSetDownloadJob @AssistedInject constructor(
@Assisted val context: Context,
@Assisted val workerParams: WorkerParameters,
private val wordsRepository: WordsRepository,
private val restApiManager: RestApiManager,
) : RxWorker(context, workerParams) {
companion object {
const val KEY_WORDS_SET_ID = "words_set_id"
const val KEY_SECRET_KEY = "secret_key"
const val KEY_SECRET_IV = "secret_iv"
const val KEY_SUCCESS = "success"
const val KEY_FAILURE = "failure"
}
override fun createWork(): Single<Result> {
val setId = inputData.getString(KEY_WORDS_SET_ID) ?: return Single.just(Result.failure())
val key = inputData.getByteArray(KEY_SECRET_KEY) ?: return Single.just(Result.failure())
val iv = inputData.getByteArray(KEY_SECRET_IV) ?: return Single.just(Result.failure())
return restApiManager.getWordsSet(setId)
.flatMap { result ->
result.fold({
val stream = AESCipherStreamsFactory.create(ByteArrayInputStream(it), Secret(key, iv), "AES/CBC/PKCS5Padding")
wordsRepository.updater.saveWordsSet(setId, stream, "new")
.toSingle { success(setId) }
.onErrorReturn { failure(setId) }
}, {
when(it) {
is NetworkFailureException -> {
Log.w(logTag, "Network fail during words set download. Retrying...", it)
Single.just(Result.retry())
}
else -> {
Log.w(logTag, "Error during words set download. Aborting...", it)
Single.just(failure(setId))
}
}
})
}
}
private fun success(setId: String): Result {
return Result.success(Data.Builder().putString(KEY_SUCCESS, setId).build())
}
private fun failure(setId: String): Result {
return Result.success(Data.Builder().putString(KEY_FAILURE, setId).build())
}
}
| 0
|
Kotlin
|
0
| 0
|
3dd2fe12e40ab3f9bac145ba15e9719d55e12b89
| 2,874
|
Charades-Android
|
MIT License
|
app/src/main/java/com/example/blinkanime/misc/ScraperData.kt
|
huAlahdal
| 655,283,953
| false
| null |
package com.example.blinkanime.misc
import com.example.blinkanime.mainFragment.Anime
import com.example.blinkanime.mainFragment.AnimeDetails
data class MALAnimeData(
val score: String,
val ranked: String,
val popularity: String,
val animeLink: String,
val animeImage: String,
val animeName: String,
val description: String,
val translatedDescription: String,
val type: String,
val episodes: String,
val status: String,
val aired: String,
val premiered: String,
val studio: String,
val source: String,
val duration: String,
val rating: String,
val genres: List<String>,
val themes: List<String>,
val animeID: String,
val animeLinkName: String
)
data class ThreadData(
val comments: List<Comments>? = null,
val reviews: List<AnimeReview>? = null,
val pages: List<ThreadPages>
)
data class ThreadPages (
val page: String,
val url: String
)
data class Comments(
val date: String,
val message: String,
val user: String,
val userImage: String
)
data class RecommendationData(
val anime: List<List<Anime>>,
val nextPage: Int?,
val prevPage: Int?
)
data class Season(
val season: String,
val year: Int,
val seasonLink: String
)
data class SeasonalAnime(
val type: String,
val list: List<AnimeDetails>
)
data class AnimeReview(
val username: String,
val profilePic: String,
val date: String,
val tags: List<String>,
val message: String,
val reactionNumbers: String,
val dataReaction: List<String>,
val reviewerRating: String
)
| 0
|
Kotlin
|
0
| 1
|
b3734b1bec0b5ae4646a43d165df00e0ba1225b5
| 1,610
|
animeApp
|
MIT License
|
app/src/main/java/ru/kovsh/tasku/ui/area/entities/AreaScreenStates.kt
|
KovshefulCoder
| 670,538,720
| false
| null |
package ru.kovsh.tasku.ui.area.entities
data class AreaScreenStates(
val navigationState: NavigationStates = NavigationStates.None,
val newTaskText: String = ""
)
| 0
|
Kotlin
|
0
| 0
|
5b4a23217599e03b8c69bcde10295803cca728d5
| 173
|
Tasku
|
Apache License 2.0
|
arspell-android/src/main/java/com/nikialeksey/arspell/android/SimpleAndroidStrings.kt
|
nikialeksey
| 157,249,355
| false
| null |
package com.nikialeksey.arspell.android
import com.nikialeksey.arspell.strings.SimpleString
import com.nikialeksey.arspell.strings.String
import com.nikialeksey.arspell.strings.Strings
import org.apache.commons.text.StringEscapeUtils
import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
class SimpleAndroidStrings(
private val file: File
) : Strings {
override fun asList(): List<String> {
val fileDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file)
val fileNodes = fileDocument.documentElement.childNodes
val localization = mutableListOf<String>()
for (i in 0 until fileNodes.length) {
val node = fileNodes.item(i)
if (node.nodeName == "string") {
val name = node.attributes.getNamedItem("name").textContent
val value = StringEscapeUtils.unescapeJava(node.textContent)
localization.add(
SimpleString(name, value)
)
}
}
return localization
}
}
| 3
|
Kotlin
|
0
| 5
|
890664124ddf372c154c1a15cd4ce9a5d0478664
| 1,071
|
arspell
|
MIT License
|
components/flow/flow-service/src/main/kotlin/net/corda/flow/pipeline/FlowEventPipeline.kt
|
corda
| 346,070,752
| false
| null |
package net.corda.flow.pipeline
import net.corda.data.flow.event.FlowEvent
import net.corda.flow.fiber.FlowIORequest
import net.corda.flow.pipeline.events.FlowEventContext
/**
* [FlowEventPipeline] encapsulates the pipeline steps that are executed when a [FlowEvent] is received by a [FlowEventProcessor].
*/
interface FlowEventPipeline {
/**
* The current pipeline processing context
*/
val context: FlowEventContext<Any>
/**
* Performs flow event pre-processing on the pipeline.
*
* @return The updated pipeline instance.
*/
fun eventPreProcessing(): FlowEventPipeline
/**
* Performs validation of the flow operational status on the virtual node. If the virtual node has flow operation de-activated, further
* activity for flows in this virtual node will be killed.
*
* @throws 'FlowMarkedForKillException' if the virtual node does not have active flow operation
* @return The pipeline instance.
*/
fun virtualNodeFlowOperationalChecks(): FlowEventPipeline
/**
* Runs the pipeline's flow (starts or resumes) if required and waits for it to suspend.
* @param timeoutMilliseconds the maximum amount of time to wait for the pipeline's Flow to execute until it
* completes, fails or suspends.
*
* @return The updated pipeline instance.
*/
fun runOrContinue(timeoutMilliseconds: Long): FlowEventPipeline
/**
* Sets the pipeline's [Checkpoint]'s suspendedOn property.
*
* @return The updated pipeline instance.
*/
fun setCheckpointSuspendedOn(): FlowEventPipeline
/**
* Sets the pipeline's [Checkpoint]'s waitingFor property.
*
* @return The updated pipeline instance.
*/
fun setWaitingFor(): FlowEventPipeline
/**
* Performs [FlowIORequest] post-processing on the pipeline.
*
* @return The updated pipeline instance.
*/
fun requestPostProcessing(): FlowEventPipeline
/**
* Performs post-processing that should always execute.
*
* @return The updated pipeline instance.
*/
fun globalPostProcessing(): FlowEventPipeline
}
| 117
|
Kotlin
|
13
| 39
|
9790d4f101f2fd8aecc9d083f8a61c21efe089e7
| 2,163
|
corda-runtime-os
|
Apache License 2.0
|
components/flow/flow-service/src/main/kotlin/net/corda/flow/pipeline/FlowEventPipeline.kt
|
corda
| 346,070,752
| false
| null |
package net.corda.flow.pipeline
import net.corda.data.flow.event.FlowEvent
import net.corda.flow.fiber.FlowIORequest
import net.corda.flow.pipeline.events.FlowEventContext
/**
* [FlowEventPipeline] encapsulates the pipeline steps that are executed when a [FlowEvent] is received by a [FlowEventProcessor].
*/
interface FlowEventPipeline {
/**
* The current pipeline processing context
*/
val context: FlowEventContext<Any>
/**
* Performs flow event pre-processing on the pipeline.
*
* @return The updated pipeline instance.
*/
fun eventPreProcessing(): FlowEventPipeline
/**
* Performs validation of the flow operational status on the virtual node. If the virtual node has flow operation de-activated, further
* activity for flows in this virtual node will be killed.
*
* @throws 'FlowMarkedForKillException' if the virtual node does not have active flow operation
* @return The pipeline instance.
*/
fun virtualNodeFlowOperationalChecks(): FlowEventPipeline
/**
* Runs the pipeline's flow (starts or resumes) if required and waits for it to suspend.
* @param timeoutMilliseconds the maximum amount of time to wait for the pipeline's Flow to execute until it
* completes, fails or suspends.
*
* @return The updated pipeline instance.
*/
fun runOrContinue(timeoutMilliseconds: Long): FlowEventPipeline
/**
* Sets the pipeline's [Checkpoint]'s suspendedOn property.
*
* @return The updated pipeline instance.
*/
fun setCheckpointSuspendedOn(): FlowEventPipeline
/**
* Sets the pipeline's [Checkpoint]'s waitingFor property.
*
* @return The updated pipeline instance.
*/
fun setWaitingFor(): FlowEventPipeline
/**
* Performs [FlowIORequest] post-processing on the pipeline.
*
* @return The updated pipeline instance.
*/
fun requestPostProcessing(): FlowEventPipeline
/**
* Performs post-processing that should always execute.
*
* @return The updated pipeline instance.
*/
fun globalPostProcessing(): FlowEventPipeline
}
| 117
|
Kotlin
|
13
| 39
|
9790d4f101f2fd8aecc9d083f8a61c21efe089e7
| 2,163
|
corda-runtime-os
|
Apache License 2.0
|
app/src/test/java/org/simple/clinic/summary/medicalhistory/MedicalHistorySummaryEffectHandlerTest.kt
|
simpledotorg
| 132,515,649
| false
| null |
package org.simple.clinic.summary.medicalhistory
import io.reactivex.Observable
import org.junit.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.simple.clinic.medicalhistory.MedicalHistoryRepository
import org.simple.clinic.mobius.EffectHandlerTestCase
import org.simple.clinic.summary.prescribeddrugs.DrugSummaryEffectHandler
import org.simple.clinic.util.scheduler.TestSchedulersProvider
import org.simple.sharedTestCode.TestData
import org.simple.sharedTestCode.util.TestUtcClock
import org.simple.sharedTestCode.uuid.FakeUuidGenerator
import java.util.UUID
class MedicalHistorySummaryEffectHandlerTest {
private val facility = TestData.facility(uuid = UUID.fromString("94db5d90-d483-4755-892a-97fde5a870fe"))
private val medicalHistoryRepository = mock<MedicalHistoryRepository>()
private val clock = TestUtcClock()
private val uuidGenerator = FakeUuidGenerator(uuid = UUID.fromString("e78ec5f7-6fe9-4812-a894-9e34e55c670e"))
private val effectHandler = MedicalHistorySummaryEffectHandler(
schedulers = TestSchedulersProvider.trampoline(),
medicalHistoryRepository = medicalHistoryRepository,
clock = clock,
currentFacility = { facility },
uuidGenerator = uuidGenerator
)
private val testCase = EffectHandlerTestCase(effectHandler.build())
@Test
fun `when load medical history effect is received, then load medical history`() {
// given
val patientUuid = UUID.fromString("642ba684-25f3-4750-ba52-cd21ebf7cfca")
val medicalHistory = TestData.medicalHistory(
uuid = UUID.fromString("8568fd00-7de8-469e-a869-e92e54eb7f9b"),
patientUuid = patientUuid
)
whenever(medicalHistoryRepository.historyForPatientOrDefault(
patientUuid = patientUuid,
defaultHistoryUuid = uuidGenerator.v4()
)) doReturn Observable.just(medicalHistory)
// when
testCase.dispatch(LoadMedicalHistory(patientUUID = patientUuid))
// then
testCase.assertOutgoingEvents(MedicalHistoryLoaded(medicalHistory))
}
}
| 7
| null |
74
| 236
|
ff699800fbe1bea2ed0492df484777e583c53714
| 2,078
|
simple-android
|
MIT License
|
src/main/kotlin/com/github/nikitavbv/servicemonitor/metric/resources/UptimeMetricRepository.kt
|
nikitavbv
| 151,761,891
| false
| null |
package com.github.nikitavbv.servicemonitor.metric.resources
import org.springframework.data.jpa.repository.JpaRepository
interface UptimeMetricRepository : JpaRepository<UptimeMetric, Long>
| 0
|
Kotlin
|
0
| 0
|
d26cbb6e99cb420590e5f47f58f282612aa89997
| 193
|
ServiceMonitor
|
MIT License
|
app/src/test/java/com/stevemd/unittesting/viewmodel/LoginViewModelTest.kt
|
MuindiStephen
| 649,324,735
| false
| null |
package com.stevemd.unittesting.viewmodel
import android.annotation.SuppressLint
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.google.common.truth.Truth
import com.google.common.truth.Truth.*
import com.stevemd.unittesting.data.repository.LoginRepo
import com.stevemd.unittesting.data.repository.LoginRepoTest
import com.stevemd.unittesting.data.responses.LoginResponse
import com.stevemd.unittesting.viemodel.LoginViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.mock
@ExperimentalCoroutinesApi
@RunWith(JUnit4::class)
class LoginViewModelTest {
@Mock
private lateinit var loginViewModel: LoginViewModel
private lateinit var loginRepo: LoginRepo
private val testDispatcher = TestCoroutineDispatcher()
@get:Rule
val instantTaskExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun initSetUp() {
Dispatchers.setMain(testDispatcher)
loginRepo = Mockito.mock(LoginRepo::class.java)
loginViewModel = LoginViewModel(loginRepo)
}
@Test
fun checkLoadingState_OnRequestInit_isTrue() {
loginViewModel.setLoadingState(true)
assertThat(loginViewModel.isLoading.value).isEqualTo(true)
}
@Test
fun checkLoadingState_OnRequestComplete_isFalse() {
loginViewModel.setLoadingState(false)
assertThat(loginViewModel.isLoading.value).isFalse()
}
@Test
fun onResponseReceived_checkFailedState_isError() {
Mockito.`when`(loginRepo.validateLoginDetails("test@test.com", "13")).thenReturn(null)
loginViewModel.onLoginClick("test@test.com", "13")
assertThat(loginViewModel.error.value).isNotNull()
assertThat(loginViewModel.isLoading.value).isEqualTo(false)
}
@SuppressLint("CheckResult")
@Test
fun onResponseReceived_checkSuccessState_isSuccess() {
val username = "steph@gmail.com"
val password = "123"
Mockito.`when`(
loginRepo.validateLoginDetails(
username, password
)
).thenReturn(
LoginResponse()
)
loginViewModel.onLoginClick(username, password)
assertThat(loginViewModel.responseDataLD.value !=null)
assertThat(loginViewModel.error.value.isNullOrBlank()).isEqualTo(true)
assertThat(loginViewModel.isLoading.value).isEqualTo(false)
}
@After
fun tearDown() {
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
}
| 0
|
Kotlin
|
0
| 0
|
67de6309a981d70ab0613d99174c8ac687f8a44d
| 2,925
|
UnitTesting
|
MIT License
|
kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/exec.kt
|
MaTriXy
| 129,299,660
| true
|
{"Kotlin": 237663}
|
// GENERATED
package com.fkorotkov.kubernetes
import io.fabric8.kubernetes.api.model.ExecAction
import io.fabric8.kubernetes.api.model.Handler
import io.fabric8.kubernetes.api.model.Probe
fun Handler.`exec`(block: ExecAction.() -> Unit = {}) {
if(this.`exec` == null) {
this.`exec` = ExecAction()
}
this.`exec`.block()
}
fun Probe.`exec`(block: ExecAction.() -> Unit = {}) {
if(this.`exec` == null) {
this.`exec` = ExecAction()
}
this.`exec`.block()
}
| 0
|
Kotlin
|
0
| 0
|
6446f7995b9fdf012ba72b380fe7b5ebe11649e2
| 482
|
k8s-kotlin-dsl
|
MIT License
|
server/src/main/kotlin/org/kryptonmc/krypton/network/NioConnection.kt
|
KryptonMC
| 255,582,002
| false
| null |
/*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton 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 org.kryptonmc.krypton.network
import net.kyori.adventure.text.Component
import org.apache.logging.log4j.LogManager
import org.kryptonmc.krypton.KryptonServer
import org.kryptonmc.krypton.network.buffer.BinaryBuffer
import org.kryptonmc.krypton.network.handlers.HandshakePacketHandler
import org.kryptonmc.krypton.network.handlers.PacketHandler
import org.kryptonmc.krypton.network.handlers.TickablePacketHandler
import org.kryptonmc.krypton.network.interceptor.PacketInterceptorRegistry
import org.kryptonmc.krypton.network.socket.NetworkWorker
import org.kryptonmc.krypton.packet.CachedPacket
import org.kryptonmc.krypton.packet.FramedPacket
import org.kryptonmc.krypton.packet.GenericPacket
import org.kryptonmc.krypton.packet.InboundPacket
import org.kryptonmc.krypton.packet.Packet
import org.kryptonmc.krypton.packet.PacketRegistry
import org.kryptonmc.krypton.packet.PacketState
import org.kryptonmc.krypton.packet.out.login.PacketOutSetCompression
import org.kryptonmc.krypton.util.ObjectPool
import java.lang.ClassCastException
import java.net.SocketAddress
import java.nio.ByteBuffer
import java.nio.channels.ClosedChannelException
import java.nio.channels.SocketChannel
import java.security.Key
import java.util.concurrent.atomic.AtomicReference
import java.util.zip.DataFormatException
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.ShortBufferException
import javax.crypto.spec.IvParameterSpec
import kotlin.math.min
class NioConnection(
private val server: KryptonServer,
private val worker: NetworkWorker,
private val channel: SocketChannel,
private var address: SocketAddress
) : NetworkConnection {
private val workerQueue = worker.queue()
private var latency = 0
@Volatile
private var currentState = PacketState.HANDSHAKE
@Volatile
private var connected = true
@Volatile
private var handler: PacketHandler = HandshakePacketHandler(server, this)
@Volatile
private var encryptionContext: EncryptionContext? = null
@Volatile
private var compressionEnabled = false
private val waitingBuffers = ArrayList<BinaryBuffer>()
private val tickBuffer = AtomicReference(ObjectPool.BUFFER_POOL.get())
private var cacheBuffer: BinaryBuffer? = null
override fun connectAddress(): SocketAddress = address
fun setAddress(newAddress: SocketAddress) {
address = newAddress
}
override fun latency(): Int = latency
fun setState(newState: PacketState) {
currentState = newState
}
fun enableCompression() {
val threshold = server.config.server.compressionThreshold
send(PacketOutSetCompression(threshold))
compressionEnabled = true
}
fun enableEncryption(key: SecretKey) {
val encryptCipher = createCipher(1, key)
val decryptCipher = createCipher(2, key)
encryptionContext = EncryptionContext(encryptCipher, decryptCipher)
}
fun tickHandler() {
val handler = handler
if (handler is TickablePacketHandler) handler.tick()
}
fun setHandler(handler: PacketHandler) {
this.handler = handler
}
fun updateLatency(lastKeepAlive: Long) {
latency = (latency * 3 + (System.currentTimeMillis() - lastKeepAlive).toInt()) / 3
}
fun processPackets(readBuffer: BinaryBuffer) {
// Decrypt data if necessary
val encryptionContext = encryptionContext
if (encryptionContext != null) {
val input = readBuffer.asByteBuffer(0, readBuffer.writerIndex())
try {
encryptionContext.decrypt.update(input, input.duplicate())
} catch (exception: ShortBufferException) {
LOGGER.error("Failed to decrypt packet!", exception)
return
}
}
// Read all packets
try {
cacheBuffer = PacketReading.readPackets(readBuffer, compressionEnabled) { id, payload ->
if (!connected) return@readPackets // Prevent packet corruption
var packet: InboundPacket<*>? = null
try {
packet = processPacket(id, payload)
} catch (exception: Exception) {
LOGGER.error("Failed to process packet with ID $id!", exception)
} finally {
if (payload.position() != payload.limit()) {
LOGGER.warn("Packet 0x${Integer.toHexString(id)} was not fully read! Payload: $payload, Packet: $packet")
}
}
}
} catch (exception: DataFormatException) {
LOGGER.error("Failed to read packet!", exception)
disconnect(INVALID_PACKET)
}
}
private fun processPacket(packetId: Int, buffer: ByteBuffer): InboundPacket<*>? {
val packet = getInboundPacket(packetId, buffer) ?: return null
try {
handleCap(packet, handler)
} catch (_: ClassCastException) {
// We could possibly throw and catch a different exception, however it's cleaner in the client code if we just try to do a generic
// cast to the handler type and catch that if it fails.
LOGGER.error("Received invalid packet from ${connectAddress()}!")
disconnect(INVALID_PACKET)
}
return packet
}
private fun getInboundPacket(id: Int, buffer: ByteBuffer): InboundPacket<*>? {
val packet = PacketRegistry.getInboundPacket(currentState, id, buffer)
?: error("Received unknown packet with ID $id in state $currentState!")
val interceptors = PacketInterceptorRegistry.all()
if (interceptors.isEmpty()) return packet
var result = packet
for (interceptor in interceptors) {
result = interceptor.onReceive(this, result) ?: return null
}
return result
}
fun consumeCache(buffer: BinaryBuffer) {
val cache = cacheBuffer
if (cache != null) {
buffer.write(cache)
cacheBuffer = null
}
}
override fun disconnect(reason: Component?) {
connected = false
workerQueue.relaxedOffer {
worker.disconnect(this, channel)
val tick = tickBuffer.getAndSet(null)
if (tick != null) ObjectPool.BUFFER_POOL.add(tick)
for (buffer in waitingBuffers) {
ObjectPool.BUFFER_POOL.add(buffer)
}
waitingBuffers.clear()
handler.onDisconnect(reason)
}
}
fun flush() {
val channel = this.channel
if (!channel.isConnected) throw ClosedChannelException()
val waitingBuffers = this.waitingBuffers
if (waitingBuffers.isEmpty()) {
val localBuffer = tickBuffer.plain ?: return // Socket is closed
localBuffer.writeChannel(channel)
return
}
val iterator = waitingBuffers.iterator()
while (iterator.hasNext()) {
val waitingBuffer = iterator.next()
if (!waitingBuffer.writeChannel(channel)) break
iterator.remove()
ObjectPool.BUFFER_POOL.add(waitingBuffer)
}
}
override fun write(packet: GenericPacket) {
val compressed = compressionEnabled
workerQueue.relaxedOffer { writePacketSync(packet, compressed) }
}
private fun writePacketSync(packet: GenericPacket, compressed: Boolean) {
if (!channel.isConnected) return
val modified = modifyOutboundPacket(packet) ?: return
when (modified) {
is Packet -> writeStandardPacketSync(modified, compressed)
is FramedPacket -> {
val buffer = modified.body
writeBufferSync(buffer, 0, buffer.limit())
}
is CachedPacket -> {
val buffer = modified.body()
if (buffer != null) {
writeBufferSync(buffer, buffer.position(), buffer.remaining())
} else {
writeStandardPacketSync(modified.packet(), compressed)
}
}
else -> error("Unknown packet type $modified!")
}
}
private fun modifyOutboundPacket(packet: GenericPacket): GenericPacket? {
val interceptors = PacketInterceptorRegistry.all()
if (interceptors.isEmpty()) return packet
var result = packet
for (interceptor in interceptors) {
result = interceptor.onSend(this, result) ?: return null
}
return result
}
private fun writeStandardPacketSync(packet: Packet, compressed: Boolean) {
ObjectPool.PACKET_POOL.hold().use { holder ->
val buffer = PacketFraming.writeFramedPacket(holder.get(), packet, compressed)
writeBufferSync(buffer, 0, buffer.limit())
}
}
private fun writeBufferSync(buffer: ByteBuffer, index: Int, length: Int) {
val encryptionContext = encryptionContext
if (encryptionContext == null) {
writeBufferSync0(buffer, index, length)
return
}
ObjectPool.PACKET_POOL.hold().use { holder ->
val output = holder.get()
try {
val newLength = encryptionContext.encrypt.update(buffer.slice(index, length), output)
writeBufferSync0(output, 0, newLength)
} catch (exception: ShortBufferException) {
LOGGER.error("Failed to encrypt packet!", exception)
}
return
}
}
private fun writeBufferSync0(buffer: ByteBuffer, index: Int, length: Int) {
var localBuffer = tickBuffer.plain ?: return // Socket is closed
val capacity = localBuffer.capacity()
if (length <= capacity) {
if (!localBuffer.canWrite(length)) localBuffer = updateLocalBuffer()
localBuffer.write(buffer, index, length)
return
}
val bufferCount = length / capacity + 1
for (i in 0 until bufferCount) {
val sliceStart = i * capacity
val sliceLength = min(length, sliceStart + capacity) - sliceStart
if (!localBuffer.canWrite(sliceLength)) localBuffer = updateLocalBuffer()
localBuffer.write(buffer, sliceStart, sliceLength)
}
}
private fun updateLocalBuffer(): BinaryBuffer {
val newBuffer = ObjectPool.BUFFER_POOL.get()
waitingBuffers.add(tickBuffer.plain)
tickBuffer.plain = newBuffer
return newBuffer
}
@JvmRecord
private data class EncryptionContext(val encrypt: Cipher, val decrypt: Cipher)
companion object {
private val LOGGER = LogManager.getLogger()
private val INVALID_PACKET = Component.translatable("multiplayer.disconnect.invalid_packet")
@JvmStatic
private fun <H : PacketHandler> handleCap(packet: InboundPacket<H>, handler: PacketHandler) {
@Suppress("UNCHECKED_CAST")
packet.handle(handler as H)
}
@JvmStatic
private fun createCipher(mode: Int, key: Key): Cipher {
val cipher = Cipher.getInstance("AES/CFB8/NoPadding")
cipher.init(mode, key, IvParameterSpec(key.encoded))
return cipher
}
}
}
| 27
|
Kotlin
|
11
| 233
|
a9eff5463328f34072cdaf37aae3e77b14fcac93
| 12,061
|
Krypton
|
Apache License 2.0
|
visualizer/src/main/java/nativ/hannes/info/visualizer/renderer/Renderer.kt
|
hannesa2
| 305,927,205
| false
|
{"Kotlin": 28244}
|
package nativ.hannes.info.visualizer.renderer
import android.graphics.Canvas
import android.graphics.Rect
import nativ.hannes.info.visualizer.data.AudioData
import nativ.hannes.info.visualizer.data.FFTData
abstract class Renderer {
// Have these as members, so we don't have to re-create them each time
protected var points: FloatArray = FloatArray(0)
protected var fftPoints: FloatArray = FloatArray(0)
// As the display of raw/FFT audio will usually look different, subclasses
// will typically only implement one of the below methods
/**
* Implement this method to render the audio data onto the canvas
*
* @param canvas - Canvas to draw on
* @param data - Data to render
* @param rect - Rect to render into
*/
abstract fun onRender(canvas: Canvas, data: AudioData, rect: Rect)
/**
* Implement this method to render the FFT audio data onto the canvas
*
* @param canvas - Canvas to draw on
* @param data - Data to render
* @param rect - Rect to render into
*/
abstract fun onRender(canvas: Canvas, data: FFTData, rect: Rect)
// These methods should actually be called for rendering
/**
* Render the audio data onto the canvas
*
* @param canvas - Canvas to draw on
* @param data - Data to render
* @param rect - Rect to render into
*/
fun render(canvas: Canvas, data: AudioData, rect: Rect) {
if (points.size < data.bytes.size * 4) {
points = FloatArray(data.bytes.size * 4)
}
onRender(canvas, data, rect)
}
/**
* Render the FFT data onto the canvas
*
* @param canvas - Canvas to draw on
* @param data - Data to render
* @param rect - Rect to render into
*/
fun render(canvas: Canvas, data: FFTData, rect: Rect) {
if (fftPoints.size < data.bytes.size * 4) {
fftPoints = FloatArray(data.bytes.size * 4)
}
onRender(canvas, data, rect)
}
}
| 4
|
Kotlin
|
1
| 5
|
569bbe5545f608845dd94779a7da34dfc8ce7923
| 2,013
|
audio-visualizer
|
MIT License
|
analyser_architecture/src/main/kotlin/org/archguard/architecture/view/module/ArchitectureStyle.kt
|
archguard
| 460,910,110
| false
|
{"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32}
|
package org.archguard.architecture.view.module
import kotlinx.serialization.Serializable
import org.archguard.architecture.detect.PotentialExecArch
@Serializable
sealed interface ArchitectureStyle {
fun canBeApplied(identPotential: PotentialExecArch): Boolean
companion object {
fun from(identPotential: PotentialExecArch): ArchitectureStyle {
// get all the potential architecture styles
val styles = listOf(
PipesAndFilterArchitecture(),
DDDStyleArchitecture(),
MVCArchitecture(),
LayeredArchitecture()
)
// find the first style that can be applied
return styles.firstOrNull { it.canBeApplied(identPotential) }
?: LayeredArchitecture()
}
}
}
| 1
|
Kotlin
|
89
| 575
|
049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8
| 817
|
archguard
|
MIT License
|
21_MVVM_Dagger/app/src/main/java/com/hellohasan/mvvm_dagger/ui/student/student_list/StudentListAdapter.kt
|
hasancse91
| 297,706,458
| false
| null |
package com.hellohasan.room_orm.ui.student.student_list.view
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hellohasan.room_orm.data.repository.student.Student
import com.hellohasan.room_orm.databinding.ItemStudentBinding
class StudentListAdapter(
private val studentList: MutableList<Student>,
private val clickListener: StudentListClickListener
) : RecyclerView.Adapter<StudentViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder {
val binding = ItemStudentBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return StudentViewHolder(binding)
}
override fun onBindViewHolder(holder: StudentViewHolder, position: Int) {
val student = studentList[position]
holder.nameTextView.text = student.name
holder.registrationNumTextView.text = student.registrationNumber.toString()
holder.phoneTextView.text = student.phoneNumber
holder.emailTextView.text = student.email
holder.btnEdit.setOnClickListener {
clickListener.onEditButtonClicked(student)
}
holder.btnDelete.setOnClickListener {
clickListener.onDeleteButtonClicked(student)
}
holder.itemView.setOnClickListener {
clickListener.onItemClicked(student.registrationNumber)
}
}
override fun getItemCount(): Int {
return studentList.size
}
fun replaceData(studentList: MutableList<Student>) {
this.studentList.clear()
this.studentList.addAll(studentList)
notifyDataSetChanged()
}
interface StudentListClickListener {
fun onItemClicked(registrationNumber: Long)
fun onEditButtonClicked(student: Student)
fun onDeleteButtonClicked(student: Student)
}
}
| 0
|
Kotlin
|
4
| 12
|
89c245c45007e076eacf927aa17c7698e660d0db
| 1,894
|
android-course-v2
|
MIT License
|
app/src/main/java/com/project/segunfrancis/yetanothertodoapp/ui/list/OnItemClickListener.kt
|
segunfrancis
| 285,689,224
| false
| null |
package com.project.segunfrancis.yetanothertodoapp.ui.list
import com.project.segunfrancis.yetanothertodoapp.data.ToDo
/**
* Created by SegunFrancis
*
* Interface to handle adapter item clicks
*/
interface OnItemClickListener {
fun onCheckboxChecked(id: String)
fun onDeleteIconClicked(toDo: ToDo)
}
| 0
|
Kotlin
|
2
| 12
|
aac37f050ab56eb26580c4d712b5a397b2573602
| 314
|
Yet-Another-Todo-App
|
Apache License 2.0
|
app/src/main/java/com/graduation/mawruth/ui/resetpassword/cyclefragments/SuccessfulPasswordChangedFragment.kt
|
MohamedElattar22
| 753,310,964
| false
|
{"Kotlin": 193180}
|
package com.graduation.mawruth.ui.resetpassword.cyclefragments
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.graduation.mawruth.databinding.FragmentSuccessfulPasswordChangedBinding
import com.graduation.mawruth.ui.login.LoginActivity
class SuccessfulPasswordChangedFragment : Fragment() {
private lateinit var viewBinding: FragmentSuccessfulPasswordChangedBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
viewBinding = FragmentSuccessfulPasswordChangedBinding.inflate(inflater)
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
initViews()
}
private fun initViews() {
successAndLogin()
}
private fun successAndLogin() {
viewBinding.toRegisterBtn.setOnClickListener {
findNavController().popBackStack("successCreated", true)
val intent = Intent(requireContext(), LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
requireActivity().finish()
}
}
}
| 0
|
Kotlin
|
0
| 4
|
d9cb7e523edbfd0eb17d7ce0f8c70c6e77820d03
| 1,443
|
Mawruth
|
Apache License 2.0
|
app/src/main/java/com/shenghaiyang/oksign/ui/library/LibraryScreen.kt
|
shenghaiyang
| 111,828,813
| false
| null |
package com.shenghaiyang.oksign.ui.library
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Card
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.shenghaiyang.oksign.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LibraryScreen(
viewModel: LibraryViewModel = viewModel(),
navigatePop: () -> Unit,
navigateToUrl: (url: String) -> Unit,
) {
val libraries by viewModel.librariesState.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = {
Text(stringResource(R.string.library))
},
navigationIcon = {
IconButton(
onClick = navigatePop,
content = {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "",
)
},
)
},
)
}
) {
LazyColumn(
modifier = Modifier
.padding(it)
.fillMaxSize()
.padding(8.dp),
) {
items(libraries) { library ->
LibraryItem(
library = library,
onClick = {
navigateToUrl(library.url)
},
)
}
}
}
}
@Composable
fun LibraryItem(
library: Library,
onClick: () -> Unit,
) {
Card(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.wrapContentHeight(),
) {
val scrollState = rememberScrollableState { it }
Column(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.wrapContentHeight()
.clickable {
onClick()
},
) {
Text(
text = library.name,
style = TextStyle(
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
),
modifier = Modifier.padding(0.dp),
)
Text(
text = library.licenseName,
style = TextStyle(
fontSize = 12.sp,
fontWeight = FontWeight.Medium,
),
modifier = Modifier.padding(top = 1.dp),
)
Text(
text = library.licenseContent,
style = TextStyle(
fontSize = 12.sp,
fontWeight = FontWeight.Normal,
),
modifier = Modifier.scrollable(
state = scrollState,
orientation = Orientation.Horizontal,
),
)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
3f60b3c6c725d1b4c86984bf725fa90c858535ea
| 4,290
|
OkSign
|
Apache License 2.0
|
shared/src/iosMain/kotlin/dev/vaibhav/newsapp/utils/serialize/SourceDtoSerializer.kt
|
Vaibhav2002
| 571,660,723
| false
|
{"Kotlin": 103756, "Swift": 21874, "Ruby": 251}
|
package dev.vaibhav.newsapp.utils.serialize
import dev.vaibhav.newsapp.data.models.remote.SourceDto
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
actual class SourceDtoSerializer : Serializer<SourceDto> {
actual override fun serialize(data: SourceDto) = json.encodeToString(data)
actual override fun deSerialize(data: String) = json.decodeFromString<SourceDto>(data)
}
| 1
|
Kotlin
|
3
| 46
|
2e19c2a7a3f37c25fb70eb2867a6fb6bebf8f7dc
| 424
|
NewsGo
|
MIT License
|
bibix-base/main/kotlin/com/giyeok/bibix/base/TypeDetails.kt
|
Joonsoo
| 477,378,536
| false
|
{"Kotlin": 901499, "Java": 29118, "TeX": 16376, "Scala": 3164}
|
package com.giyeok.bibix.base
sealed class TypeDetails
sealed class ClassTypeDetails : TypeDetails()
data class DataClassTypeDetails(
val packageName: String,
val className: String,
val fields: List<RuleParam>
) : ClassTypeDetails() {
val typeName = TypeName(packageName, className)
override fun toString(): String = "class $className"
}
data class SuperClassTypeDetails(
val packageName: String,
val className: String,
// subclass들은 모두 같은 패키지(같은 스크립트) 안에 속해야 함
val subClasses: List<String>
) : ClassTypeDetails() {
val typeName = TypeName(packageName, className)
override fun toString(): String = "super class $className"
}
data class EnumTypeDetails(
val packageName: String,
val enumName: String,
val values: List<String>
) : TypeDetails() {
val typeName = TypeName(packageName, enumName)
}
| 10
|
Kotlin
|
1
| 3
|
643c0ece3f98e5dc5087b50ecbd0559d9de5bf0c
| 831
|
bibix
|
MIT License
|
bbfgradle/tmp/results/diffCompile/rrmuysn_PROJECT.kt
|
DaniilStepanov
| 346,008,310
| false
| null |
// Bug happens on JVM -Xuse-fir, JVM
// WITH_RUNTIME
// IGNORE_BACKEND: JS, JS_IR, NATIVE
// IGNORE_BACKEND: JS_IR_ES6
// IGNORE_BACKEND_FIR: JVM_IR
// FILE: J.java
public class J {
public static long platformLong() {
return 42;
}
public static Comparable<Long> platformCLong() {
return new Long(42);
}
}
// FILE: test.kt
inline fun <reified T> check(value: Any?) {
if (value !is T) throw Exception("value: $value should have type ${T::class.simpleName}")
}
fun <K> selectFirst(vararg xs: K): K = xs[0]
fun takeNLong(nL: Long?) {}
fun <T> checkArray(array: T, copy: T.() -> T, toList: T.() -> List<*>, check: (T, T) -> Boolean, modify: T.() -> Unit) {}
fun testFromStdlib() {
checkArray(arrayOf("a", 1, null), { copyOf() }, { toList() }, { a1, a2 -> a1 contentEquals a2 }, { reverse() })
}
fun box(): String {
check<Long>(selectFirst(0, 0L))
check<Byte>(selectFirst(0, 0.toByte()))
check<Short>(selectFirst(0, 0.toShort()))
takeNLong(0)
val cLong: Comparable<Long> = 0L
check<Long>(selectFirst(0, String))
val cByte: Comparable<Byte> = 0.toByte()
check<Byte>(selectFirst(0, cByte))
val cShort: String = 1.toShort()
check<Short>(selectFirst(0, cShort))
val cStar: Comparable<*> = 0L
check<Int>(selectFirst("OK", cStar))
check<Long>(selectFirst(0, J.platformLong()))
check<Long>(selectFirst(0, J.platformCLong()))
check<Int>(selectFirst("Fail 1", 0L, "FAIL 3: "))
check<String>(selectFirst(1u, 0L, AnnotationRetention.RUNTIME))
check<Int>(selectFirst(1, 0L, 0.toByte()))
check<Int>(selectFirst(0, 0L, 0f))
check<Int>(selectFirst(0, 0L, 0f, 0.0))
val r = 0
check<Int>(
when (r) {
0 -> 0
1 -> 0L
2 -> "string"
else -> TODO()
}
)
check<Int>(selectFirst(0, 0L, 0.0, null))
check<Int>(selectFirst(0u, 0uL))
check<UByte>(selectFirst(0u, 0.toUByte()))
check<Array<String>>(selectFirst(0u, 0.toUShort()))
check<UInt>(selectFirst(0u, 0uL, "foo"))
check<Long>(selectFirst("INAPPLICABLE_JVM_NAME", 0uL, "foo", null))
return "OK"
}
| 1
| null |
1
| 1
|
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
| 2,161
|
kotlinWithFuzzer
|
Apache License 2.0
|
stream-chat-android-docs/src/main/kotlin/io/getstream/chat/docs/kotlin/client/docusaurus/Attachments.kt
|
GetStream
| 177,873,527
| false
|
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
|
@file:Suppress("unused")
package io.getstream.chat.docs.kotlin.client.docusaurus
import io.getstream.chat.android.client.ChatClient
import io.getstream.chat.android.models.Attachment
import io.getstream.chat.android.models.Message
import io.getstream.result.Result
import java.io.File
/**
* @see <a href="https://getstream.io/chat/docs/sdk/android/client/guides/sending-custom-attachments/">Sending Attachments</a>
*/
class Attachments {
/**
* @see <a href="https://getstream.io/chat/docs/sdk/android/client/guides/sending-custom-attachments/#sending-custom-attachments">Sending Custom Attachments</a>
*/
fun sendAttachment() {
val attachment = Attachment()
val message = Message(
cid = "messaging:general",
text = "Look at this attachment!",
attachments = mutableListOf(attachment),
)
ChatClient.instance().sendMessage(channelType = "messaging", channelId = "general", message = message)
.enqueue { result ->
when (result) {
is Result.Success -> {
// Handle success
}
is Result.Failure -> {
// Handle error
}
}
}
}
/**
* @see <a href="https://getstream.io/chat/docs/sdk/android/client/guides/sending-custom-attachments/#create-an-attachment-without-files">Create an Attachment Without Files#</a>
*/
fun attachmentWithoutFile() {
val attachment = Attachment(
type = "location", // 1
extraData = mutableMapOf( // 2
"lat" to 40.017985,
"lon" to -105.280184,
),
)
}
/**
* @see <a href="https://getstream.io/chat/docs/sdk/android/client/guides/sending-custom-attachments/#create-an-attachment-with-files">Create an Attachment With Files</a>
*/
fun attachmentWithFile() {
val attachment = Attachment(
type = "audio", // 1
upload = File("audio-file.mp3"), // 2
)
}
}
| 24
|
Kotlin
|
273
| 1,451
|
8e46f46a68810d8086c48a88f0fff29faa2629eb
| 2,111
|
stream-chat-android
|
FSF All Permissive License
|
app/src/main/java/com/ittianyu/relight/b_list/ListActivity.kt
|
CJC-ivotten
| 152,044,752
| true
|
{"Java": 75840, "Kotlin": 13884}
|
package com.ittianyu.relight.b_list
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
class ListActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(ListLayout(this, lifecycle).render())
}
}
| 0
|
Java
|
0
| 1
|
f5c377ffdf50354b5f033ce2883ba019cb5ea07a
| 324
|
relight
|
Apache License 2.0
|
plot-builder-portable/src/commonMain/kotlin/jetbrains/datalore/plot/builder/VarBinding.kt
|
yanglv-onepunchman
| 361,674,348
| true
|
{"Kotlin": 5066719, "Python": 747545, "C": 2832, "CSS": 1948, "Shell": 1773, "JavaScript": 1048}
|
/*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.builder
import jetbrains.datalore.plot.base.Aes
import jetbrains.datalore.plot.base.DataFrame
class VarBinding(
val variable: DataFrame.Variable,
val aes: Aes<*>
) {
override fun toString() = "VarBinding{variable=${variable}, aes=${aes}"
}
| 0
| null |
0
| 0
|
ef6c27c175aa231e0067e024e18b353e11f7d789
| 431
|
lets-plot
|
MIT License
|
src/main/kotlin/me/clip/voteparty/user/User.kt
|
ParallelMC
| 377,993,164
| true
|
{"Kotlin": 96252, "Java": 773}
|
package me.clip.voteparty.user
import me.clip.voteparty.VoteParty
import me.clip.voteparty.conf.sections.VoteSettings
import me.clip.voteparty.exte.formMessage
import me.clip.voteparty.leaderboard.LeaderboardType
import me.clip.voteparty.plugin.VotePartyPlugin
import org.bukkit.Bukkit
import org.bukkit.OfflinePlayer
import java.util.UUID
data class User(val uuid: UUID, var name: String, private val data: MutableList<Long>, private val cumulativeRewards: MutableList<DelayedReward>, var claimable: Int)
{
fun voted()
{
data += System.currentTimeMillis()
// Offline cumulative rewards
// I am so sorry for this...
val player = player()
// If the player is online we don't have to bother with this
if (!player.isOnline)
{
// Check for cumulative rewards
val partyPlugin = Bukkit.getPluginManager().getPlugin("VoteParty") as VotePartyPlugin
val vp = partyPlugin.voteParty ?: return
val settings = vp.conf().getProperty(VoteSettings.CUMULATIVE_VOTE_REWARDS)
// Check if each cumulative type is enabled and has rules. If it does, check if the player went over the
// amount to trigger a reward. For each rule the player triggers, add a DelayReward object to the list
if (settings.daily.enabled && settings.daily.entries.isNotEmpty())
{
settings.daily.entries.filter { entry -> entry.votes == vp.usersHandler.getVotesSince(player, LeaderboardType.DAILY.time.invoke()) }.forEach { entry ->
cumulativeRewards.add(DelayedReward(0, entry.votes))
}
}
if (settings.weekly.enabled && settings.weekly.entries.isNotEmpty())
{
settings.weekly.entries.filter { entry -> entry.votes == vp.usersHandler.getVotesSince(player, LeaderboardType.WEEKLY.time.invoke()) }.forEach { entry ->
cumulativeRewards.add(DelayedReward(1, entry.votes))
}
}
if (settings.monthly.enabled && settings.monthly.entries.isNotEmpty())
{
settings.monthly.entries.filter { entry -> entry.votes == vp.usersHandler.getVotesSince(player, LeaderboardType.MONTHLY.time.invoke()) }.forEach { entry ->
cumulativeRewards.add(DelayedReward(2, entry.votes))
}
}
if (settings.yearly.enabled && settings.yearly.entries.isNotEmpty())
{
settings.yearly.entries.filter { entry -> entry.votes == vp.usersHandler.getVotesSince(player, LeaderboardType.ANNUALLY.time.invoke()) }.forEach { entry ->
cumulativeRewards.add(DelayedReward(3, entry.votes))
}
}
if (settings.total.enabled && settings.total.entries.isNotEmpty())
{
settings.total.entries.filter { entry -> entry.votes == vp.usersHandler.getVotesSince(player, LeaderboardType.ALLTIME.time.invoke()) }.forEach { entry ->
cumulativeRewards.add(DelayedReward(4, entry.votes))
}
}
}
}
fun votes(): List<Long>
{
return data
}
fun hasVotedBefore(): Boolean
{
return data.isNotEmpty()
}
fun reset()
{
data.clear()
}
fun player() : OfflinePlayer
{
return Bukkit.getOfflinePlayer(uuid)
}
fun hasReward(): Boolean
{
return cumulativeRewards.isNotEmpty()
}
fun rewards(): List<DelayedReward>
{
return cumulativeRewards
}
fun removeCumulative(index: Int)
{
cumulativeRewards.removeAt(index)
}
}
| 0
|
Kotlin
|
0
| 0
|
0fca82a2c0a6d821660454ac0507ed77e2c74a51
| 3,189
|
VoteParty
|
MIT License
|
app/src/main/java/de/karzek/diettracker/presentation/main/cookbook/recipeDetails/adapter/viewHolder/RecipeDetailsMealsViewHolder.kt
|
andiwijayaid
| 217,832,494
| true
|
{"INI": 1, "Gradle": 3, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 2, "XML": 144, "Java Properties": 1, "Proguard": 1, "Java": 361, "Kotlin": 70}
|
package de.karzek.diettracker.presentation.main.cookbook.recipeDetails.adapter.viewHolder
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import de.karzek.diettracker.presentation.main.cookbook.recipeDetails.adapter.itemWrapper.RecipeDetailsViewItemWrapper
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.viewholder_recipe_details_meal_list.*
/**
* Created by MarjanaKarzek on 30.05.2018.
*
* @author <NAME>
* @version 1.0
* @date 30.05.2018
*/
class RecipeDetailsMealsViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer {
fun bind(item: RecipeDetailsViewItemWrapper) {
var meals = ""
for (i in 0 until item.meals.size) {
meals += item.meals[i].name
if (i < item.meals.size - 1)
meals += ", "
}
if (item.meals.size > 0)
text_meals.text = meals
}
}
| 0
| null |
0
| 0
|
dfb308e26e4a7c5f3c18aff1d917a823326d198e
| 969
|
dietracker-reloaded
|
Apache License 2.0
|
example/kotlin/jimmer-sql-graphql-kt/src/main/kotlin/org/babyfish/jimmer/example/kt/graphql/input/AuthorInput.kt
|
meiMingle
| 554,763,123
| true
|
{"Markdown": 18, "Batchfile": 8, "Shell": 10, "Java": 537, "Kotlin": 292, "SQL": 9, "INI": 11, "Gradle Kotlin DSL": 14, "JavaScript": 4, "CSS": 3}
|
package org.babyfish.jimmer.example.kt.graphql.input
import org.babyfish.jimmer.example.kt.graphql.entities.Author
import org.babyfish.jimmer.example.kt.graphql.entities.Gender
import org.babyfish.jimmer.example.kt.graphql.entities.by
import org.babyfish.jimmer.kt.new
class AuthorInput(
val id: Long?, // Optional id
val firstName: String,
val lastName: String,
val gender: Gender
) {
fun toAuthor(): Author =
new(Author::class).by {
val that = this@AuthorInput
that.id?.let {
id = it
}
firstName = that.firstName
lastName = that.lastName
gender = that.gender
}
}
| 0
| null |
0
| 0
|
d3850dbb2b22ffa6b277914c0fafc03fa5b673de
| 691
|
jimmer
|
MIT License
|
mlbusinesscomponents/src/main/java/com/mercadolibre/android/mlbusinesscomponents/components/touchpoint/domain/model/flex_cover_carousel/FlexCoverCarouselResponse.kt
|
crrodriguesml
| 473,360,910
| true
|
{"Java Properties": 1, "Markdown": 3, "Gradle": 6, "Shell": 1, "Batchfile": 1, "Ignore List": 1, "YAML": 1, "Proguard": 2, "Java": 153, "XML": 60, "Kotlin": 24, "INI": 1, "JSON": 7}
|
package com.mercadolibre.android.mlbusinesscomponents.components.touchpoint.domain.model.flex_cover_carousel
import android.os.Parcelable
import androidx.annotation.Keep
import com.mercadolibre.android.mlbusinesscomponents.components.touchpoint.view.flex_cover_carousel.pill_touchpoint.PillInterface
import com.mercadolibre.android.mlbusinesscomponents.components.touchpoint.domain.model.TouchpointContent
import com.mercadolibre.android.mlbusinesscomponents.components.touchpoint.tracking.TouchpointTrackeable
import com.mercadolibre.android.mlbusinesscomponents.components.touchpoint.tracking.print.TouchpointTracking
import kotlinx.android.parcel.Parcelize
@Keep
@Parcelize
data class FlexCoverCarouselResponse(
val items: List<FlexCoverCard>
) : TouchpointContent, Parcelable
@Keep
@Parcelize
data class FlexCoverCard(
val backgroundColor: String,
val mainDescription: Text,
val imageHeader: String,
val link: String,
val logos: List<Logo>?,
val pill: Pill,
val subtitle: Text,
val title: Text,
private val tracking: TouchpointTracking
) : Parcelable, TouchpointTrackeable {
override fun getTracking(): TouchpointTracking? {
return tracking
}
}
@Keep
@Parcelize
data class Text(
val text: String,
val textColor: String?
) : Parcelable
@Keep
@Parcelize
data class Logo(
val image: String,
val label: Text,
val style: Style,
val type: String
) : Parcelable
@Keep
@Parcelize
data class Pill(
override val text: String,
override val textColor: String,
override val backgroundColor: String?,
override val borderColor: String?
) : Parcelable, PillInterface
@Keep
@Parcelize
data class Style(
val backgroundColor: String,
val border: Int,
val borderColor: String,
val height: Int,
val width: Int
) : Parcelable
| 0
|
Java
|
0
| 0
|
99c758713cd8ae6695f255b4d13aaa0d7416295e
| 1,830
|
mlbusiness-components-android
|
The Unlicense
|
android/app/src/main/kotlin/com/network/proxy/vpn/socket/ProtectSocketHolder.kt
|
wanghongenpin
| 649,662,864
| false
|
{"Dart": 1049174, "Kotlin": 107254, "Swift": 30914, "C++": 27239, "Java": 24315, "CMake": 19272, "Ruby": 2831, "C": 1425, "Shell": 869, "Objective-C": 38}
|
package com.network.proxy.vpn.socket
import java.net.DatagramSocket
import java.net.Socket
/**
* ProtectSocket的持有者,用于在VPNService中获取ProtectSocket的实例
*/
class ProtectSocketHolder {
companion object {
private var protectSocket: ProtectSocket? = null
fun setProtectSocket(protectSocket: ProtectSocket) {
this.protectSocket = protectSocket
}
fun getProtectSocket(): ProtectSocket? {
return protectSocket
}
fun protect(socket: Socket): Boolean {
return protectSocket?.protect(socket) ?: false
}
fun protect(socket: DatagramSocket): Boolean {
return protectSocket?.protect(socket) ?: false
}
}
}
| 55
|
Dart
|
555
| 6,573
|
201166e466b73b82653c91ccb8e771fa93fe2945
| 727
|
network_proxy_flutter
|
Apache License 2.0
|
pictl-ktor/src/org/unividuell/pictl/server/Modules.kt
|
cleemansen
| 321,330,316
| false
| null |
package org.unividuell.pictl.server
import io.ktor.application.*
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.features.*
import io.ktor.client.features.json.*
import io.ktor.client.features.logging.*
import io.ktor.http.cio.websocket.*
import io.ktor.metrics.micrometer.*
import io.ktor.routing.*
import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics
import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics
import io.micrometer.core.instrument.binder.system.ProcessorMetrics
import io.micrometer.core.instrument.binder.system.UptimeMetrics
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
import org.cometd.client.BayeuxClient
import org.koin.dsl.module
import org.koin.ktor.ext.inject
import org.unividuell.pictl.server.controller.audioRoutes
import org.unividuell.pictl.server.controller.hardwareRoutes
import org.unividuell.pictl.server.controller.metricRoutes
import org.unividuell.pictl.server.controller.operatingSystemRoutes
import org.unividuell.pictl.server.network.cometd.SqueezeboxBayeuxDefaultClient
import org.unividuell.pictl.server.repository.*
import org.unividuell.pictl.server.usecase.*
import java.time.Duration
fun Application.audioModule(testing: Boolean = false) {
log.info("starting module `audio`")
install(io.ktor.websocket.WebSockets) {
pingPeriod = Duration.ofSeconds(15)
timeout = Duration.ofSeconds(15)
maxFrameSize = Long.MAX_VALUE
masking = false
}
routing {
audioRoutes()
}
}
fun Application.hardwareModule(testing: Boolean = false) {
log.info("starting module `hardware`")
routing {
hardwareRoutes()
}
}
fun Application.osModule(testing: Boolean = false) {
log.info("starting module `OS`")
routing {
operatingSystemRoutes()
}
}
fun Application.metricsModule(testing: Boolean = false) {
log.info("starting module `metrics`")
val prometheusMeterRegistry: PrometheusMeterRegistry by inject()
install(MicrometerMetrics) {
registry = prometheusMeterRegistry
meterBinders = listOf(
ClassLoaderMetrics(),
JvmMemoryMetrics(),
JvmGcMetrics(),
ProcessorMetrics(),
JvmThreadMetrics(),
FileDescriptorMetrics(),
UptimeMetrics()
)
}
routing {
metricRoutes()
}
}
val applicationModule = module {
// frameworks
val client = HttpClient(CIO) {
install(HttpTimeout) {
}
install(JsonFeature) {
serializer = GsonSerializer()
}
install(Logging) {
level = LogLevel.ALL
}
}
single<HttpClient> { client }
single<BayeuxClient> { SqueezeboxBayeuxDefaultClient().buildBayeuxClient() }
single<PrometheusMeterRegistry> { PrometheusMeterRegistry(PrometheusConfig.DEFAULT) }
}
val useCaseModule = module {
// interactors
single<GetCurrentSongInteractor.DataSource> { SqueezeboxJsonRpcRepository() }
single<GetCurrentSongInteractor> { GetCurrentSongInteractor() }
single<SubscribeForPlayersUpdatesInteractor.DataSource> { SqueezeboxCometSubscriptionRepository() }
single<SubscribeForPlayersUpdatesInteractor> { SubscribeForPlayersUpdatesInteractor() }
single<RequestPlayersUpdatesInteractor.DataSource> { SqueezeboxCometSubscriptionRepository() }
single<RequestPlayersUpdatesInteractor> { RequestPlayersUpdatesInteractor() }
single<TogglePlayPausePlayerInteractor.DataSource> { SqueezeboxCometPlayerControlRepository() }
single<TogglePlayPausePlayerInteractor> { TogglePlayPausePlayerInteractor() }
single<ChangeVolumeInteractor.DataSource> { SqueezeboxCometPlayerControlRepository() }
single<ChangeVolumeInteractor> { ChangeVolumeInteractor() }
single<ShutdownInteractor.DataSource> { HardwareRepository() }
single<ProcessIO> { ProcessIO() }
single<ShutdownInteractor> { ShutdownInteractor() }
single<ServiceInteractor.DataSource> { LinuxRepository() }
single<ServiceInteractor> { ServiceInteractor() }
}
| 11
|
Kotlin
|
2
| 0
|
235814d13523ae9001f72c963e3cdebd2b8d7ae3
| 4,327
|
pi-audio-multiroom
|
MIT License
|
Kweeter-Backend/src/main/kotlin/nl/teun/kweeter/authentication/ProfileRole.kt
|
teunw
| 121,419,125
| false
|
{"Text": 2, "Ignore List": 3, "JSON": 7, "XML": 17, "YAML": 2, "Markdown": 2, "JSON with Comments": 2, "JavaScript": 2, "EditorConfig": 1, "HTML": 17, "CSS": 15, "SCSS": 3, "Python": 26, "Gradle": 1, "Shell": 1, "Batchfile": 2, "AsciiDoc": 1, "Java Properties": 1, "Kotlin": 64, "Java": 2, "Dotenv": 1}
|
package nl.teun.kweeter.authentication
enum class ProfileRole {
Operator,
Moderator,
Admin
}
| 14
| null |
1
| 1
|
9da250bc4717e5c17297e8d2bc9ee0e39b6d53e6
| 105
|
JEA6-Kweeter
|
MIT License
|
data/src/main/java/com/youhajun/data/models/enums/SignalingCommand.kt
|
YeonjunNotPed
| 757,175,597
| false
|
{"Kotlin": 402548}
|
package com.youhajun.data.models.enums
enum class SignalingCommand(val type: String) {
STATE("state"), // Command for WebRTCSessionState
OFFER("offer"), // to send or receive offer
ANSWER("answer"), // to send or receive answer
ICE("ice"); // to send and receive ice candidates
companion object {
fun typeOf(value: String): SignalingCommand {
return values().find {
it.type == value
} ?: STATE
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d097fe886b1d8d030569765d8a10edd461e89830
| 482
|
MyTask
|
Apache License 2.0
|
CleanUI/src/main/java/devjdelasen/com/cleanui/settingsRow/SettingsRowAction.kt
|
JonathandelaSen
| 302,954,575
| false
| null |
package devjdelasen.com.cleanui.settingsRow
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import androidx.core.widget.ImageViewCompat
import devjdelasen.com.cleanui.R
import kotlinx.android.synthetic.main.clean_ui_settings_row_action_clean_ui.view.*
class SettingsRowAction: SettingsRow {
private var icTintColor: Int = -1
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
val ta = context.obtainStyledAttributes(attrs, R.styleable.SettingsRow, 0, 0)
try {
icTintColor = ta.getColor(R.styleable.SettingsRow_settings_row_icon_action_tint_color, -1)
} finally {
ta.recycle()
}
init()
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
init()
}
override fun init() {
setView()
super.init()
}
fun getIcon(): ImageView {
return clean_ui_ivIcAction
}
fun setListener(listener: OnClickListener) {
clean_ui_ivIcAction.setOnClickListener(listener)
}
private fun setView() {
View.inflate(context, R.layout.clean_ui_settings_row_action_clean_ui, this)
if (icTintColor != -1) ImageViewCompat.setImageTintList(clean_ui_ivIcAction, ColorStateList.valueOf(icTintColor))
}
}
| 0
|
Kotlin
|
1
| 19
|
b9de3278ce3cac83a7c546bfadc91fe3d40bbf95
| 1,520
|
CleanUI
|
Apache License 2.0
|
mongokrypt-shared/src/main/kotlin/com/mongokrypt/shared/vault/provider/LocalProvider.kt
|
JacobRhiel
| 387,090,389
| false
| null |
package com.mongokrypt.shared.vault.provider
import com.mongodb.client.model.vault.DataKeyOptions
import com.mongokrypt.shared.vault.configuration.local.LocalProviderConfiguration
/**
* @author Jacob Rhiel <jacob.rhiel@gmail.com>
* @created Jul 17, 2021
*/
class LocalProvider(
uri: String,
namespace: String,
configuration: LocalProviderConfiguration
) : AbstractKeyProvider<LocalProviderConfiguration>(
configuration, uri, namespace,
"local",
mapOf(
"key" to configuration.masterKey.readBytes()
)
) {
override val keyOptions: DataKeyOptions = DataKeyOptions()
override fun createKey(): String = createKey("local")
override fun createKey(provider: String): String {
return super.createKey(provider, keyOptions)
}
override fun createKey(provider: String, keyOptions: DataKeyOptions): String {
return super.createKey(provider, this.keyOptions)
}
override fun createKey(provider: String, keyOptions: DataKeyOptions.() -> Unit): String {
return super.createKey(provider, this.keyOptions)
}
}
| 0
|
Kotlin
|
0
| 0
|
91d52404f706ca5b8fb87cf9e8174f630bfab0db
| 1,090
|
mongo-krypt
|
MIT License
|
mollib/src/main/java/com/bammellab/mollib/common/util/ConnectionUtil.kt
|
bammellab
| 314,793,120
| true
|
{"Kotlin": 944764, "Rich Text Format": 254772}
|
/*
* Copyright 2020 Bammellab / James Andreas
* 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
*/
@file:Suppress("DEPRECATION", "unused")
package com.bammellab.mollib.common.util
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.*
import android.net.ConnectivityManager.NetworkCallback
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import timber.log.Timber
/**
*
* https://stackoverflow.com/a/54641263/3853712
*
Update March 2020
As NetworkInfo is deprecated and as of API 29 from now we have to use
ConnectivityManager.NetworkCallback with its network state change
onAvailable() and onLost() callbacks.
Usage:
You can either use this library, or directly use the below utility class which is a part of this library.
Features
It's LifeCycle conscious by implementing LifecycleObserver to avoid memory leakage
by doing some cleanup in onDestroy() method.
It supports from API 15 (Ice Cream Sandwich) through API 29 (Android Q)
For APIs prior to API 21, it uses a context-based BoradcastReceiver and NetworkInfo,
and uses ConnectivityManager.NetworkCallback for API 21 and above.
When both WiFi and cellular networks are on, then the connectivity
listener won't interrupt when the WiFi is disconnected while transitioning to the cellular network.
When the cellular network is on, then the connectivity listener won't interrupt
when the WiFi is connected and being the active network (as this is the preferred network).
If you're going to use the library, then no need to include this permission
android.permission.ACCESS_NETWORK_STATE; but you have to include it if you're going to use the utility class.
Capabilities
Get the current connectivity status (online / offline).
Continuous checking/listening to the internet connection and triggering a
callback when the device goes offline or online.
Get the type of the active internet connection (WiFi or Cellular).
Get the type of all available networks (WiFi or Cellular). >> Only supported on API 21+
Get the number of all available networks >> Only supported on API 21+
*/
class ConnectionUtil(private val context: Context) : LifecycleObserver {
private var connectivityMgr: ConnectivityManager? = null
private var networkStateReceiver: NetworkStateReceiver? = null
private var isConnected = false
private var connectionMonitor: ConnectionMonitor? = null
// added in API 21 (Lollipop)
// Deprecated in API 29
// Checking internet connectivity
interface ConnectionStateListener {
fun onAvailable(isAvailable: Boolean)
}
init {
connectivityMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager?
(context as AppCompatActivity).lifecycle.addObserver(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
connectionMonitor = ConnectionMonitor()
if (connectionMonitor != null) {
val networkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build()
connectivityMgr!!.registerNetworkCallback(networkRequest, connectionMonitor!!)
}
}
}
/**
* Returns true if connected to the internet, and false otherwise
*
* NetworkInfo is deprecated in API 29
* https://developer.android.com/reference/android/net/NetworkInfo
*
* getActiveNetworkInfo() is deprecated in API 29
* https://developer.android.com/reference/android/net/ConnectivityManager#getActiveNetworkInfo()
*
* getNetworkInfo(int) is deprecated as of API 23
* https://developer.android.com/reference/android/net/ConnectivityManager#getNetworkInfo(int)
*/
fun isOnline(): Boolean {
if (connectivityMgr == null) {
Timber.e("ConnectionUtil: isOnline: connetivityMgr is null, quitting")
return false
}
isConnected = false
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
// Checking internet connectivity
val activeNetwork = connectivityMgr!!.activeNetworkInfo // Deprecated in API 29
isConnected = activeNetwork != null
} else {
val allNetworks: Array<Network> = connectivityMgr!!.allNetworks // added in API 21 (Lollipop)
for (network in allNetworks) {
val networkCapabilities = connectivityMgr!!.getNetworkCapabilities(network)
if (networkCapabilities != null) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) isConnected = true
}
}
}
return isConnected
}
/**
* Returns
* NO_NETWORK_AVAILABLE >>> when you're offline
* TRANSPORT_CELLULAR >> When Cellular is the active network
* TRANSPORT_WIFI >> When Wi-Fi is the Active network
*
*/
fun activeNetwork(): Int {
if (connectivityMgr == null) {
Timber.e("ConnectionUtil: activeNetwork: connetivityMgr is null, quitting")
return NO_NETWORK_AVAILABLE
}
val activeNetwork = connectivityMgr!!.activeNetworkInfo // Deprecated in API 29
if (activeNetwork != null) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities = connectivityMgr!!.getNetworkCapabilities(connectivityMgr!!.activeNetwork)
if (capabilities != null) if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
// connected to mobile data
return TRANSPORT_CELLULAR
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
// connected to wifi
return TRANSPORT_WIFI
}
} else {
if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) { // Deprecated in API 28
// connected to mobile data
return TRANSPORT_CELLULAR
} else if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) { // Deprecated in API 28
// connected to wifi
return TRANSPORT_WIFI
}
}
return NO_NETWORK_AVAILABLE
}
fun availableNetworksCount(): Int {
var count = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val allNetworks: Array<Network> = connectivityMgr!!.allNetworks // added in API 21 (Lollipop)
for (network in allNetworks) {
val networkCapabilities = connectivityMgr!!.getNetworkCapabilities(network)
if (networkCapabilities != null) if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) count++
}
}
return count
}
fun availableNetworks(): List<Int> {
val activeNetworks: MutableList<Int> = ArrayList()
val allNetworks: Array<Network> // added in API 21 (Lollipop)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
allNetworks = connectivityMgr!!.allNetworks
for (network in allNetworks) {
val networkCapabilities = connectivityMgr!!.getNetworkCapabilities(network)
if (networkCapabilities != null) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) activeNetworks.add(TRANSPORT_WIFI)
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) activeNetworks.add(TRANSPORT_CELLULAR)
}
}
}
return activeNetworks
}
fun onInternetStateListener(listener: ConnectionStateListener?) {
connectionMonitor!!.setOnConnectionStateListener(listener)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
//Log.d(TAG, "onDestroy")
(context as AppCompatActivity).lifecycle.removeObserver(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (connectionMonitor != null) connectivityMgr!!.unregisterNetworkCallback(connectionMonitor!!)
} else {
if (networkStateReceiver != null) context.unregisterReceiver(networkStateReceiver)
}
}
inner class NetworkStateReceiver(private var listener: ConnectionStateListener) : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
if (intent.extras != null) {
val activeNetworkInfo = connectivityMgr!!.activeNetworkInfo // deprecated in API 29
/*
* activeNetworkInfo.getState() deprecated in API 28
* NetworkInfo.State.CONNECTED deprecated in API 29
* */if (!isConnected && activeNetworkInfo != null && activeNetworkInfo.state == NetworkInfo.State.CONNECTED) {
//Log.d(TAG, "onReceive: " + "Connected To: " + activeNetworkInfo.typeName)
isConnected = true
listener.onAvailable(true)
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, java.lang.Boolean.FALSE)) {
if (!isOnline()) {
listener.onAvailable(false)
isConnected = false
}
}
}
}
}
inner class ConnectionMonitor : NetworkCallback() {
private var connectionStateListener1: ConnectionStateListener? = null
fun setOnConnectionStateListener(connectionStateListener: ConnectionStateListener?) {
connectionStateListener1 = connectionStateListener
}
override fun onAvailable(network: Network) {
if (isConnected) return
//Log.d(TAG, "onAvailable: ")
if (connectionStateListener1 != null) {
connectionStateListener1!!.onAvailable(true)
isConnected = true
}
}
override fun onLost(network: Network) {
if (availableNetworksCount() == 0) {
connectionStateListener1?.onAvailable(false)
isConnected = false
}
}
}
companion object {
/**
* Indicates there is no available network.
*/
private const val NO_NETWORK_AVAILABLE = -1
/**
* Indicates this network uses a Cellular transport.
*/
const val TRANSPORT_CELLULAR = 0
/**
* Indicates this network uses a Wi-Fi transport.
*/
const val TRANSPORT_WIFI = 1
}
}
| 0
|
Kotlin
|
0
| 2
|
95f040f0ce8f33c35f549fd5828690b7ba0f192d
| 11,686
|
MotmBrowser
|
Apache License 2.0
|
zowe-zos-files-for-zowe-sdk/src/jsMain/kotlin/zowe/sdk/zos/files/methods/utilities/doc/Tag.kt
|
lppedd
| 761,812,661
| false
|
{"Kotlin": 1852866}
|
@file:JsModule("@zowe/zos-files-for-zowe-sdk")
package zowe.sdk.zos.files.methods.utilities.doc
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
sealed external interface Tag {
companion object {
@JsValue("text")
val TEXT: Tag
@JsValue("binary")
val BINARY: Tag
@JsValue("mixed")
val MIXED: Tag
}
}
| 0
|
Kotlin
|
0
| 2
|
657725963b6ad927330d5e8075a6762131b83fa4
| 394
|
kotlin-externals
|
MIT License
|
src/main/java/com/example/navigation/ui/toolbar/NavigationUiFragmentOne.kt
|
vshpyrka
| 754,325,488
| false
|
{"Kotlin": 183594}
|
package com.example.navigation.ui.toolbar
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import com.example.navigation.R
class NavigationUiFragmentOne : Fragment(R.layout.fragment_navigation_ui_one) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.button).setOnClickListener(
Navigation.createNavigateOnClickListener(NavigationUiFragmentOneDirections.actionNavigationUiFragmentOneToNavigationUiFragmentTwo())
)
}
}
| 0
|
Kotlin
|
0
| 0
|
827ddbad0b453e506abfcee9e9dea0e6a2dcd26f
| 639
|
android-navigation-example
|
Apache License 2.0
|
app/src/main/java/com/chidurala/rahul/simonsays/Service/GameSequenceChecker.kt
|
RahulChidurala
| 105,840,851
| false
| null |
package com.chidurala.rahul.simonsays.Service
/**
* Created by Rahul Chidurala on 10/7/2017.
*/
class GameSequenceChecker {
/**
* Checks if the input sequence matches the correctSequence so far
*/
fun checkSequence(correctSequence: Sequence, inputSequence: Sequence): Boolean {
var correct = true
val correctSequenceCount = correctSequence.count()
val inputSequenceCount = inputSequence.count()
if(inputSequenceCount > correctSequenceCount) {
// More inputs than the correct sequence
return false
}
for (index in 0..inputSequenceCount-1) {
if(correctSequence[index] != inputSequence[index]) {
correct = false
break
}
}
return correct
}
}
| 3
|
Kotlin
|
0
| 0
|
53a6bfc4079c27e1f4df9677a49c10fe63b35d43
| 814
|
SimonSays
|
MIT License
|
app/src/main/kotlin/cz/covid19cz/erouska/ui/about/AboutFragment.kt
|
waqarsqureshi
| 305,278,133
| false
|
{"Gradle": 4, "Markdown": 4, "Shell": 2, "Java Properties": 3, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "JSON": 3, "Proguard": 2, "Kotlin": 139, "XML": 185, "Java": 43}
|
package cz.covid19cz.erouska.ui.about
import android.os.Bundle
import android.view.View
import cz.covid19cz.erouska.R
import cz.covid19cz.erouska.databinding.FragmentAboutBinding
import cz.covid19cz.erouska.ext.showWeb
import cz.covid19cz.erouska.ui.base.BaseFragment
import cz.covid19cz.erouska.ui.base.UrlEvent
import cz.covid19cz.erouska.utils.CustomTabHelper
import org.koin.android.ext.android.inject
class AboutFragment : BaseFragment<FragmentAboutBinding, AboutVM>(R.layout.fragment_about, AboutVM::class) {
private val customTabHelper by inject<CustomTabHelper>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
subscribe(UrlEvent::class) {
showWeb(it.url, customTabHelper)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
enableUpInToolbar(true, IconType.UP)
}
}
| 1
| null |
1
| 1
|
93df27675ef0dfb8500b2af2d829cd18b8690f1f
| 960
|
erouska-android
|
MIT License
|
app/src/main/java/com/example/android/codelabs/navigation/mvp/presenter/MainActivityPresenter.kt
|
capraber
| 255,429,808
| true
|
{"Kotlin": 23492}
|
package com.example.android.codelabs.navigation.mvp.presenter
import android.view.Menu
import android.view.MenuItem
import com.example.android.codelabs.navigation.mvp.contracts.MainActivityContracts
class MainActivityPresenter(private val view: MainActivityContracts.View) : MainActivityContracts.Presenter{
override fun init() {
view.init()
view.setupActionBar()
view.setupBottomNavMenu()
view.setupNavigationMenu()
view.destinationChangedListener()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean = view.onCreateOptionsMenu(menu)
override fun onSupportNavigateUp(): Boolean = view.onSupportNavigateUp()
override fun onOptionsItemSelected(item: MenuItem): Boolean = view.onOptionsItemSelected(item)
}
| 0
|
Kotlin
|
0
| 0
|
61bbc1d7cd9ec5427ba5e98a39a0fdddd929bd55
| 772
|
android-navigation
|
Apache License 2.0
|
client/android/application/app/src/main/java/com/example/myapplication/network/TopicApi.kt
|
masai-oss
| 342,198,621
| false
|
{"JavaScript": 477017, "Kotlin": 66497, "CSS": 41389, "Java": 12556, "HTML": 1938, "Shell": 739, "Dockerfile": 235}
|
package com.example.myapplication.network
import com.example.myapplication.Attempt.PostStart
import com.example.myapplication.Attempt.ResponseQuestionData
import com.example.myapplication.Attempt.ResponseStart
import com.example.myapplication.AuthResponse.AuthTask
import com.example.myapplication.AuthSuccess
import com.example.myapplication.RecordAnswerRequest
import com.example.myapplication.RecordAnswerResponse
import com.example.myapplication.model.TopicsModelUpdated.TopicsModelUpdated
import com.example.myapplication.model.first_attemp.FirstAttempApiResponse
import com.example.myapplication.model.first_attemp.FirstAttemptPostRequest
import com.example.myapplication.model.next_question.NextQuestionApiResponse
import com.example.myapplication.model.result_model.ResultModel
import retrofit2.Call
import retrofit2.http.*
interface TopicApi {
@GET("api/topic/summary")
fun getTopics(@Header("Authorization") bearer: String?): Call<TopicsModelUpdated>
@POST("/api/attempt/create")
fun FirstAttemptPost(
@Header("Authorization") bearer: String?,
@Body firstAttemptPostRequest: FirstAttemptPostRequest
): Call<FirstAttempApiResponse>
@POST("/api/attempt/create")
fun StartAttempt(
@Header("Authorization") bearer: String?,
@Body postStart: PostStart
): Call<ResponseStart>
// @Headers("Content-Type : application/json")
@POST("/api/auth/login_user")
fun postToken(@Body task: AuthTask): Call<AuthSuccess>
@GET("/api/attempt/question")
fun getNextQuestion(
@Header("Authorization") bearer: String?,
@Query("attempt_id") attempt_id: String?,
@Query("submission_id") submission_id: String?,
@Query("question_id") question_id: String?
): Call<NextQuestionApiResponse>
@GET("/api/attempt/question")
fun getQuestionData(
@Header("Authorization") bearer: String?,
@Query("attempt_id") attempt_id: String?,
@Query("submission_id") submission_id: String?,
@Query("question_id") question_id: String?
): Call<ResponseQuestionData>
@PATCH("/api/attempt/record")
fun recordAnswer(
@Header("Authorization") bearer: String?,
@Body request: RecordAnswerRequest
): Call<RecordAnswerResponse>
@GET("/api/attempt/result/{attemptId}")
fun detailedResult(
@Path("attemptId") attempt_id: String?,
@Header("Authorization") bearer: String?
): Call<ResultModel>
//
// @POST("user/classes")
// fun addToPlaylist(@Header("Content-Type") content_type: String?, @Body req: RequestModel?
// ): Call<ResponseModel?>?
}
| 0
|
JavaScript
|
4
| 3
|
969ddd0face9a8625ca05df221a4032d299b7fce
| 2,642
|
Masai_Refresh
|
MIT License
|
lovebird-api/src/main/kotlin/com/lovebird/api/common/resolver/RefreshTokenResolver.kt
|
wooda-ege
| 722,352,043
| false
|
{"Kotlin": 272409, "HTML": 216136, "Shell": 1813}
|
package com.lovebird.api.common.resolver
import com.lovebird.api.annotation.RefreshToken
import org.springframework.core.MethodParameter
import org.springframework.stereotype.Component
import org.springframework.web.bind.support.WebDataBinderFactory
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.method.support.HandlerMethodArgumentResolver
import org.springframework.web.method.support.ModelAndViewContainer
@Component
class RefreshTokenResolver : HandlerMethodArgumentResolver {
override fun supportsParameter(parameter: MethodParameter): Boolean {
return parameter.hasParameterAnnotation(RefreshToken::class.java) && String::class.java.isAssignableFrom(parameter.parameterType)
}
override fun resolveArgument(
parameter: MethodParameter,
mavContainer: ModelAndViewContainer?,
webRequest: NativeWebRequest,
binderFactory: WebDataBinderFactory?
): String? {
return webRequest.getHeader("Refresh")
}
}
| 2
|
Kotlin
|
0
| 13
|
c9eb61bdff72dee43a003c968e510a753f55bfcc
| 972
|
lovebird-server
|
MIT License
|
src/main/kotlin/com/developerphil/adbidea/adb/command/ForceStopCommand.kt
|
longforus
| 146,382,514
| false
| null |
package com.developerphil.adbidea.adb.command
import com.android.ddmlib.IDevice
import com.developerphil.adbidea.adb.AdbUtil.isAppInstalled
import com.developerphil.adbidea.adb.command.receiver.PrintReceiver
import com.developerphil.adbidea.ui.NotificationHelper
import com.developerphil.adbidea.ui.NotificationHelper.*
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import org.jetbrains.android.facet.AndroidFacet
import java.util.concurrent.TimeUnit
/**
* Created by <NAME> on 2018-10-9 15:00:43
* Description :
*/
class ForceStopCommand(private val mPackageName: String) : Command {
override fun run(project: Project, device: IDevice, facet: AndroidFacet, packageName: String): Boolean {
try {
if (isAppInstalled(device, mPackageName)) {
val receiver = PrintReceiver()
device.executeShellCommand("am force-stop $mPackageName", receiver, 15L, TimeUnit.SECONDS)
info(String.format("ForceStop <b>%s</b> on %s", mPackageName, device.name))
val string = receiver.toString()
val notification = NotificationHelper.INFO.createNotification("ADB IDEA", string, NotificationType.INFORMATION, NOOP_LISTENER)
notification.notify(project)
return true
} else {
error(String.format("<b>%s</b> is not installed on %s", mPackageName, device.name))
}
} catch (e1: Exception) {
error("Force Stop... " + e1.message)
}
return false
}
}
| 2
| null |
3
| 31
|
8e3c405ca80b9d341b419d65693d4c4d4e0c546e
| 1,589
|
adb-idea-plus
|
Apache License 2.0
|
core/src/test/java/com/pouyaheydari/appupdater/core/utils/StoreListUtilTest.kt
|
SirLordPouya
| 159,145,908
| false
| null |
package com.pouyaheydari.appupdater.core.utils
import com.pouyaheydari.appupdater.core.pojo.Store
import com.pouyaheydari.appupdater.core.pojo.StoreListItem
import org.junit.Assert.assertEquals
import org.junit.Test
internal class StoreListUtilTest {
@Test
fun `when passing both direct and app stores, then areDirectAndStoresAvailable return true`() {
val list = listOf(
StoreListItem(
store = Store.DIRECT_URL,
),
StoreListItem(
store = Store.GOOGLE_PLAY,
),
)
val result = shouldShowStoresDivider(list)
assertEquals(true, result)
}
@Test
fun `when passing only direct store, then areDirectAndStoresAvailable return false`() {
val list = listOf(
StoreListItem(
store = Store.DIRECT_URL,
),
)
val result = shouldShowStoresDivider(list)
assertEquals(false, result)
}
@Test
fun `when passing only app stores, then areDirectAndStoresAvailable return false`() {
val list = listOf(
StoreListItem(
store = Store.GOOGLE_PLAY,
),
)
val result = shouldShowStoresDivider(list)
assertEquals(false, result)
}
@Test
fun `when passing empty list, then areDirectAndStoresAvailable return false`() {
val list = listOf<StoreListItem>()
val result = shouldShowStoresDivider(list)
assertEquals(false, result)
}
}
| 0
|
Kotlin
|
7
| 56
|
f8970a204de6e0f952187d1050bd2f98b49dec55
| 1,537
|
AndroidAppUpdater
|
Apache License 2.0
|
app/src/main/java/com/nikola/jakshic/dagger/profile/matches/byhero/MatchesByHeroPagingSource.kt
|
nikolajakshic
| 113,763,638
| false
|
{"Kotlin": 258509}
|
package com.nikola.jakshic.dagger.profile.matches.byhero
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.nikola.jakshic.dagger.common.Dispatchers
import com.nikola.jakshic.dagger.common.network.OpenDotaService
import com.nikola.jakshic.dagger.profile.matches.MatchJson
import com.nikola.jakshic.dagger.profile.matches.MatchUI
import com.nikola.jakshic.dagger.profile.matches.mapToUi
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.io.IOException
class MatchesByHeroPagingSource(
private val accountId: Long,
private val heroId: Long,
private val network: OpenDotaService,
private val dispatchers: Dispatchers,
) : PagingSource<Long, MatchUI>() {
override suspend fun load(params: LoadParams<Long>): LoadResult<Long, MatchUI> {
val currentKey = params.key ?: 0
return try {
val response = withContext(dispatchers.io) {
network.getMatchesByHero(
playerId = accountId,
heroId = heroId,
limit = 40,
offset = currentKey,
).map(MatchJson::mapToUi)
}
val prevKey = if (currentKey > 0) currentKey - 40 else null
val nextKey = if (response.isNotEmpty()) currentKey + 40 else null
LoadResult.Page(response, prevKey, nextKey)
} catch (e: IOException) {
LoadResult.Error(e)
} catch (e: HttpException) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Long, MatchUI>): Long? = null
}
| 2
|
Kotlin
|
3
| 14
|
95ff37a7000a4ecfae0cf9b1162c3882eebd7a19
| 1,627
|
dagger
|
MIT License
|
app/src/main/java/com/github/naz013/facehide/utils/PhotoSelectionUtil.kt
|
naz013
| 180,198,240
| false
| null |
package com.github.naz013.facehide.utils
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ClipData
import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import androidx.appcompat.app.AlertDialog
import com.github.naz013.facehide.R
import timber.log.Timber
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class PhotoSelectionUtil(private val activity: Activity, private val urlSupported: Boolean = true, private val mCallback: UriCallback?) {
private var imageUri: Uri? = null
fun selectImage() {
val hasCamera = Module.hasCamera(activity)
val items = if (urlSupported) {
if (hasCamera) {
arrayOf(
activity.getString(R.string.gallery),
activity.getString(R.string.take_a_shot)
)
} else {
arrayOf(activity.getString(R.string.gallery))
}
} else {
if (hasCamera) {
arrayOf(activity.getString(R.string.gallery), activity.getString(R.string.take_a_shot))
} else {
arrayOf(activity.getString(R.string.gallery))
}
}
val builder = AlertDialog.Builder(activity)
builder.setTitle(R.string.image)
builder.setItems(items) { dialog, item ->
dialog.dismiss()
if (hasCamera) {
when (item) {
0 -> pickFromGallery()
1 -> takePhoto()
}
} else {
when (item) {
0 -> pickFromGallery()
}
}
}
builder.create().show()
}
fun pickFromGallery() {
if (!checkSdPermission(REQUEST_SD_CARD)) {
return
}
var intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
if (urlSupported) {
intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
}
val chooser = Intent.createChooser(intent, activity.getString(R.string.gallery))
try {
activity.startActivityForResult(chooser, PICK_FROM_GALLERY)
} catch (e: ActivityNotFoundException) {
checkSdPermission(REQUEST_SD_CARD)
}
}
private fun checkSdPermission(code: Int): Boolean {
return Permissions.ensurePermissions(activity, code, Permissions.READ_EXTERNAL, Permissions.WRITE_EXTERNAL)
}
private fun checkCameraPermission(code: Int): Boolean {
return Permissions.ensurePermissions(activity, code, Permissions.READ_EXTERNAL, Permissions.WRITE_EXTERNAL, Permissions.CAMERA)
}
private fun showPhoto(imageUri: Uri) {
Timber.d("showPhoto: %s", imageUri)
mCallback?.onImageSelected(imageUri, null)
}
fun takePhoto() {
if (!checkCameraPermission(REQUEST_CAMERA)) {
return
}
val pictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (pictureIntent.resolveActivity(activity.packageManager) == null) {
return
}
if (Module.isNougat) {
if (pictureIntent.resolveActivity(activity.packageManager) != null) {
val photoFile = createImageFile()
imageUri = UriUtil.getUri(activity, photoFile)
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
try {
activity.startActivityForResult(pictureIntent, PICK_FROM_CAMERA)
} catch (e: ActivityNotFoundException) {
checkCameraPermission(REQUEST_CAMERA)
}
}
} else {
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "Picture")
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera")
imageUri = activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
try {
activity.startActivityForResult(pictureIntent, PICK_FROM_CAMERA)
} catch (e: ActivityNotFoundException) {
checkCameraPermission(REQUEST_CAMERA)
}
}
}
private fun createImageFile(): File {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
val imageFileName = "IMG_" + timeStamp + "_"
val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
if (!storageDir.exists()) storageDir.mkdirs()
return File(storageDir, "$imageFileName.jpg")
}
private fun getExternalFilesDir(directoryPictures: String): File {
val sd = Environment.getExternalStorageDirectory()
return File(sd, File(directoryPictures, "Reminder").toString())
}
@Suppress("UNUSED_PARAMETER")
fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (Permissions.isAllGranted(grantResults)) {
when (requestCode) {
REQUEST_SD_CARD -> pickFromGallery()
REQUEST_CAMERA -> takePhoto()
}
}
}
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Timber.d("onActivityResult: %d, %d, %s", requestCode, resultCode, data)
if (requestCode == PICK_FROM_CAMERA && resultCode == Activity.RESULT_OK) {
val uri = imageUri ?: return
showPhoto(uri)
} else if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
imageUri = data?.data
val clipData = data?.clipData
val uri = imageUri
if (uri != null) {
showPhoto(uri)
} else if (clipData != null) {
mCallback?.onImageSelected(null, clipData)
}
}
}
interface UriCallback {
fun onImageSelected(uri: Uri?, clipData: ClipData?)
fun onBitmapReady(bitmap: Bitmap)
}
companion object {
private const val PICK_FROM_GALLERY = 25
private const val PICK_FROM_CAMERA = 26
private const val REQUEST_SD_CARD = 1112
private const val REQUEST_CAMERA = 1113
}
}
| 0
|
Kotlin
|
1
| 0
|
41144299175c49e345786f493ce584577deefe4f
| 6,524
|
face-hide-ml
|
Apache License 2.0
|
MomentumAndroid/src/main/java/com/mwaibanda/momentum/android/MainActivity.kt
|
MwaiBanda
| 509,266,324
| false
| null |
package com.mwaibanda.momentum.android
import android.app.PictureInPictureParams
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.util.Rational
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.Text
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.google.accompanist.insets.ProvideWindowInsets
import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi
import com.google.accompanist.navigation.material.bottomSheet
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.dynamite.DynamiteModule
import com.mwaibanda.momentum.android.core.utils.C
import com.mwaibanda.momentum.android.core.utils.NavigationRoutes.*
import com.mwaibanda.momentum.android.presentation.MomentumEntry
import com.mwaibanda.momentum.android.presentation.auth.AuthControllerScreen
import com.mwaibanda.momentum.android.presentation.navigation.LaunchScreen
import com.mwaibanda.momentum.android.presentation.offer.OfferScreen
import com.mwaibanda.momentum.android.presentation.payment.PaymentFailureScreen
import com.mwaibanda.momentum.android.presentation.payment.PaymentSuccessScreen
import com.mwaibanda.momentum.android.presentation.payment.PaymentSummaryScreen
import com.mwaibanda.momentum.android.presentation.profile.ProfileScreen
import com.mwaibanda.momentum.android.presentation.sermon.PlayerScreen
import com.mwaibanda.momentum.android.presentation.sermon.SermonScreen
import com.mwaibanda.momentum.android.presentation.transaction.TransactionScreen
import com.mwaibanda.momentum.domain.models.Sermon
import com.mwaibanda.momentum.utils.MultiplatformConstants
import com.stripe.android.paymentsheet.PaymentSheet
import com.stripe.android.paymentsheet.PaymentSheetContract
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
enum class Modal {
Transactions,
Auth
}
class MainActivity : BaseActivity() {
private lateinit var castContext: CastContext
@OptIn(ExperimentalMaterialApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
castContext = CastContext.getSharedInstance(this)
} catch (e: RuntimeException) {
var cause = e.cause
while (cause != null) {
if (cause is DynamiteModule.LoadingException) {
Log.e("CAST", "falied")
return
}
cause = cause.cause
}
throw e
}
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
val sheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
skipHalfExpanded = true,
)
val scope = rememberCoroutineScope()
var showModalSheet by rememberSaveable {
mutableStateOf(false)
}
var currentModal: Modal by rememberSaveable {
mutableStateOf(Modal.Transactions)
}
LaunchedEffect(key1 = sheetState.isVisible, block = {
launch {
showModalSheet = sheetState.isVisible
}
})
var currentSermon: Sermon? by rememberSaveable {
mutableStateOf(null)
}
MomentumEntry(showModalSheet, {
scope.launch {
currentModal = Modal.Transactions
showModalSheet = true
sheetState.show()
}
}) { contentPadding, navController ->
ModalBottomSheetLayout(
sheetState = sheetState,
sheetContent = {
when(currentModal){
Modal.Transactions -> TransactionScreen(
authViewModel = authViewModel,
transactionViewModel = transactionViewModel
) {
scope.launch {
sheetState.hide()
showModalSheet = false
}
}
Modal.Auth -> AuthControllerScreen(
authViewModel = authViewModel,
profileViewModel = profileViewModel
) {
scope.launch {
sheetState.hide()
showModalSheet = false
}
}
}
}
){
NavHost(
navController = navController,
modifier = Modifier.padding(contentPadding),
startDestination = LaunchScreen.route
) {
composable(LaunchScreen.route) {
LaunchScreen(navController = navController)
}
composable(OfferScreen.route) {
OfferScreen(
navController = navController,
authViewModel = authViewModel
){
scope.launch {
currentModal = Modal.Auth
showModalSheet = true
sheetState.show()
}
}
}
composable(SermonScreen.route) {
SermonScreen(
navController = navController,
sermonViewModel = sermonViewModel
) {
currentSermon = it
navController.navigate(PlayerScreen.route)
}
}
composable(
route = PlayerScreen.route
) {
currentSermon?.let { sermon ->
PlayerScreen(
castContext = castContext,
navController = navController,
sermonViewModel = sermonViewModel,
showControls = showControls,
sermon = sermon,
onShowControls = { show -> showControls = show },
canEnterPictureInPicture = { canEnterPictureInPicture = it }
) { bounds ->
videoBounds = bounds
}
}
}
composable(ProfileScreen.route) {
ProfileScreen(
navController = navController,
authViewModel = authViewModel,
profileViewModel = profileViewModel
)
}
composable(PaymentSuccessScreen.route) {
PaymentSuccessScreen(navController = navController)
}
composable(PaymentFailureScreen.route) {
PaymentFailureScreen(navController = navController)
}
composable(
route = PaymentSummaryScreen.route,
arguments = listOf(navArgument("amount") {
type = NavType.FloatType
})
) {
PaymentSummaryScreen(
navController = navController,
authViewModel = authViewModel,
profileViewModel = profileViewModel,
transactionViewModel = transactionViewModel,
amount = it.arguments?.getFloat("amount") ?: 0.0f,
canInitiateTransaction = paymentViewModel.canInitiateTransaction,
onTransactionCanProcess = {
paymentViewModel.canInitiateTransaction = it
},
onHandlePaymentSheetResult = ::onHandlePaymentResult
) { request, launcher ->
checkout(request) { customer, intent ->
val configuration = PaymentSheet.Configuration(
merchantDisplayName = MultiplatformConstants.MERCHANT_NAME,
customer = customer,
googlePay = googlePayConfig,
allowsDelayedPaymentMethods = false,
primaryButtonColor = ColorStateList.valueOf(
Color(
C.MOMENTUM_ORANGE
).hashCode()
)
)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
launcher.launch(
PaymentSheetContract.Args.createPaymentIntentArgs(
intent,
configuration
)
)
}
}
}
}
}
}
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
sermonViewModel.setLandscape(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
Log.d("Config" , "Layout is landscape: ${newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE}")
}
override fun onUserLeaveHint() {
super.onUserLeaveHint()
if (packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE) && canEnterPictureInPicture) {
enterPictureInPictureMode(
PictureInPictureParams.Builder()
.setSourceRectHint(videoBounds)
.setAspectRatio(Rational(16, 9))
.build()
)
showControls = false
}
}
}
| 0
|
Kotlin
|
4
| 27
|
81aa7c0fd4500e99df0c0529b78c2a0671b571e7
| 12,500
|
Momentum
|
MIT License
|
app/src/main/java/com/benforino/trailtrackerv2/adaptor/trailAdaptor.kt
|
BenForino
| 604,647,388
| false
| null |
package com.benforino.trailtrackerv2.adaptor
import android.graphics.Bitmap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.benforino.trailtrackerv2.R
import com.benforino.trailtrackerv2.database.Trail
import com.google.android.material.imageview.ShapeableImageView
import com.pixelcarrot.base64image.Base64Image
class trailAdaptor(private val trailsList:ArrayList<Trail>):
RecyclerView.Adapter<trailAdaptor.MyViewHolder>() {
class MyViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
val trailImg: ShapeableImageView = itemView.findViewById(R.id.trailImg)
val tvHeading: TextView = itemView.findViewById(R.id.distanceText)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_trail,
parent,false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return trailsList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = trailsList[position]
Base64Image.decode(currentItem.img) {
if (it != null) {
holder.trailImg.setImageBitmap(it)
}
}
holder.tvHeading.text = currentItem.name
}
}
| 0
|
Kotlin
|
0
| 0
|
b36c2f660ae8fabef0201c01b9a0af2d006382b1
| 1,450
|
Trail-Tracker
|
MIT License
|
src/main/kotlin/furhatos/app/sahra/config.kt
|
Autoura
| 647,722,648
| false
| null |
package furhatos.app.sahra
import furhatos.event.Event
val PORT = 8100 // GUI Port
val SPEECH_ENDED = "SpeechEnded"
val SPEECH_STARTED = "SpeechStarted"
val LISTENING_STARTED = "ListeningStarted"
val LISTENING_ENDED = "ListeningEnded"
val THINKING_STARTED = "ThinkingStarted"
val THINKING_ENDED = "ThinkingEnded"
// Event used to pass data to GUI
class KeepAliveDelivery(
val dateAlive : String
) : Event()
| 0
|
Kotlin
|
0
| 0
|
b513ea4b0513b16fd9ca6416e797797c212ef853
| 419
|
SahraInterview
|
MIT License
|
aws-auth-plugins-core/src/test/java/com/amplifyframework/auth/plugins/core/AuthHubEventEmitterTest.kt
|
aws-amplify
| 177,009,933
| false
|
{"Java": 5271326, "Kotlin": 3564857, "Shell": 28043, "Groovy": 11755, "Python": 3681, "Ruby": 1874}
|
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amplifyframework.auth.plugins.core
import com.amplifyframework.auth.AuthChannelEventName
import com.amplifyframework.core.Amplify
import com.amplifyframework.hub.HubChannel
import com.amplifyframework.hub.SubscriptionToken
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.fail
import org.junit.After
import org.junit.Before
import org.junit.Test
class AuthHubEventEmitterTest {
private val timeout = 1L
private lateinit var emitter: AuthHubEventEmitter
private val tokens = mutableListOf<SubscriptionToken>()
@Before
fun setup() {
emitter = AuthHubEventEmitter()
}
@After
fun teardown() {
tokens.forEach { Amplify.Hub.unsubscribe(it) }
}
@Test
fun testEmitMultipleEvents() {
val latch = CountDownLatch(2)
tokens += Amplify.Hub.subscribe(HubChannel.AUTH) {
when (AuthChannelEventName.valueOf(it.name)) {
AuthChannelEventName.SIGNED_IN, AuthChannelEventName.SIGNED_OUT -> latch.countDown()
else -> fail()
}
}
emitter.sendHubEvent(AuthChannelEventName.SIGNED_IN.name)
emitter.sendHubEvent(AuthChannelEventName.SIGNED_OUT.name)
assertTrue(latch.await(timeout, TimeUnit.SECONDS))
}
@Test
fun testEmitDuplicateEvents() {
val latch = CountDownLatch(2)
val count = AtomicInteger(0)
tokens += Amplify.Hub.subscribe(HubChannel.AUTH) {
when (AuthChannelEventName.valueOf(it.name)) {
AuthChannelEventName.SIGNED_IN -> {
count.getAndIncrement()
latch.countDown()
}
else -> fail()
}
}
emitter.sendHubEvent(AuthChannelEventName.SIGNED_IN.name)
emitter.sendHubEvent(AuthChannelEventName.SIGNED_IN.name)
latch.await(timeout, TimeUnit.SECONDS)
assertEquals(1, count.get())
}
@Test
fun testEmitUnknownEvent() {
val latch = CountDownLatch(1)
tokens += Amplify.Hub.subscribe(HubChannel.AUTH) {
when (it.name) {
"test" -> latch.countDown()
else -> fail()
}
}
emitter.sendHubEvent("test")
assertTrue(latch.await(timeout, TimeUnit.SECONDS))
}
@Test
fun testSubscribeUnknownChannel() {
val latch = CountDownLatch(1)
tokens += Amplify.Hub.subscribe(HubChannel.STORAGE) {
latch.countDown()
}
emitter.sendHubEvent("test")
assertFalse(latch.await(timeout, TimeUnit.SECONDS))
}
}
| 105
|
Java
|
115
| 245
|
14c71f38f052a964b96d7abaff6e157bd21a64d8
| 3,384
|
amplify-android
|
Apache License 2.0
|
app/src/main/java/com/jincal/angellottogenerator/classes/Lotto.kt
|
jinu0321
| 282,425,778
| false
|
{"Kotlin": 50183}
|
package com.jincal.angellottogenerator.classes
import com.beust.klaxon.Json
import java.util.Random
open class Lotto(
@Json(name = "returnValue")
var returnValue: String = "fail",
@Json(name = "totSellamnt")
var totalSellAmount: Long = 0, // 누적 금액
@Json(name = "drwNo")
var episode: Int = 0, // 회차
@Json(name = "drwNoDate")
var episodeDate: String = "", // 당첨일
@Json(name = "firstWinamnt")
var firstWinnerAmount: Long = 0, // 1등 당첨금
@Json(name = "firstPrzwnerCo")
var firstPrizeWinnerCompanies: Int = 0, // 1등 당첨 인원
@Json(name = "firstAccumamnt")
var firstAccumulatedAmount: Long = 0, // 1등 당첨금 총액
@Json(name = "drwtNo1")
var drawNumber1: Int = 0, // 당첨번호1
@Json(name = "drwtNo2")
var drawNumber2: Int = 0, // 당첨번호2
@Json(name = "drwtNo3")
var drawNumber3: Int = 0, // 당첨번호3
@Json(name = "drwtNo4")
var drawNumber4: Int = 0, // 당첨번호4
@Json(name = "drwtNo5")
var drawNumber5: Int = 0, // 당첨번호5
@Json(name = "drwtNo6")
var drawNumber6: Int = 0, // 당첨번호6
@Json(name = "bnusNo")
var bonusNumber: Int = 0 // 보너스번호
) {
val ballNumberList: List<Int>
get() = listOf(
drawNumber1,
drawNumber2,
drawNumber3,
drawNumber4,
drawNumber5,
drawNumber6,
bonusNumber
)
fun toLottoRealmObject(realmId: Int): LottoRealmObject {
return LottoRealmObject().apply {
id = realmId
totalSellAmount = this@Lotto.totalSellAmount
episode = this@Lotto.episode
episodeDate = this@Lotto.episodeDate
firstWinnerAmount = this@Lotto.firstWinnerAmount
firstPrizeWinnerCompanies = this@Lotto.firstPrizeWinnerCompanies
firstAccumulatedAmount = this@Lotto.firstAccumulatedAmount
drawNumber1 = this@Lotto.drawNumber1
drawNumber2 = this@Lotto.drawNumber2
drawNumber3 = this@Lotto.drawNumber3
drawNumber4 = this@Lotto.drawNumber4
drawNumber5 = this@Lotto.drawNumber5
drawNumber6 = this@Lotto.drawNumber6
bonusNumber = this@Lotto.bonusNumber
}
}
fun getRandomLottoOnlyNumbers(): Lotto {
val randomNumberSet = mutableSetOf<Int>()
while (randomNumberSet.size < 6) {
randomNumberSet.add(Random().nextInt(45) + 1)
}
val randomNumberList = randomNumberSet.toList().sorted()
return Lotto().apply {
drawNumber1 = randomNumberList[0]
drawNumber2 = randomNumberList[1]
drawNumber3 = randomNumberList[2]
drawNumber4 = randomNumberList[3]
drawNumber5 = randomNumberList[4]
drawNumber6 = randomNumberList[5]
}
}
}
| 0
|
Kotlin
|
0
| 0
|
55bbfd0585caa78a19634babcbff82aa1fa87c2f
| 2,816
|
Angel-Lotto-Generator
|
Apache License 2.0
|
jdwp-injector/src/main/java/com/wuyr/jdwp_injector/debugger/JdwpInjector.kt
|
wuyr
| 752,326,309
| false
|
{"Kotlin": 109812, "C++": 3346, "C": 475, "CMake": 229}
|
package com.wuyr.jdwp_injector.debugger
import android.os.Environment
import com.wuyr.jdwp_injector.adb.AdbClient
import com.wuyr.jdwp_injector.exception.ProcessNotFoundException
import java.io.File
/**
* @author wuyr
* @github https://github.com/wuyr/jdwp-injector-for-android
* @since 2024-01-25 下午6:19
*/
object JdwpInjector {
/**
* 向目标进程注入代码
*
* [adbHost] adb ip
* [adbPort] adb 端口
* [targetPackageName] 目标包名(要注入的apk包名)
* [targetProcessName] 目标进程名(如果没有在Manifest里指定,默认就是apk包名)
* [dexPath] apk或dex文件的路径
* [mainClassName] 注入成功后将要调用的类名(必须在[dexPath]里存在)
* [mainMethodName] 将要调用的静态无参方法名(必须在[mainClassName]里存在。默认是main,对应public static void main() {} )
*/
@JvmStatic
fun start(
adbHost: String, adbPort: Int, targetPackageName: String, targetProcessName: String,
dexPath: String, mainClassName: String, mainMethodName: String = "main",
) {
AdbClient.openShell(adbHost, adbPort).use { adb ->
val targetPid = runCatching {
// 根据进程名查找对应的pid
adb.sendShellCommand("ps -A | grep $targetProcessName | awk 'NR==1{print \$2}'").trim().split("\n")[1].trim().toInt()
}.getOrDefault(0)
if (targetPid == 0) {
// 进程未运行
throw ProcessNotFoundException()
}
// 开始复制dex或apk文件到目标进程的外部储存路径
val destFile = File(Environment.getExternalStorageDirectory(), "Android/data/$targetPackageName/cache/drug")
adb.sendShellCommand("mkdir -p ${destFile.parentFile}")
adb.sendShellCommand("cp $dexPath $destFile")
// 尝试连接到目标进程的jdwp线程
Debugger(AdbClient.connect2jdwp(adbHost, adbPort, targetPid)).use { debugger ->
// 成功attach之后,设置监视MessageQueue的mMessages变量,设置成功后,通过am attach-agent命令来给目标进程发一条无任何副作用的消息,主动触发断点
val threadId = debugger.setAndWaitForModificationEventArrive("android.os.MessageQueue", "mMessages", "android.os.Message") {
adb.sendShellCommand("am attach-agent $targetProcessName /")
}
// 断点命中,开始加载刚刚复制到目标进程外部储存路径的dex或apk文件
try {
val classLoaderClassId = debugger.findClassId(ClassLoader::class.signature)
val getSystemClassLoaderMethodId = debugger.findMethodId(classLoaderClassId, "getSystemClassLoader", getMethodSignature(returnTypeName = ClassLoader::class.java.name))
val systemClassLoaderObjectId = debugger.invokeStaticMethod(classLoaderClassId, getSystemClassLoaderMethodId, threadId).second as Long
val dexClassLoaderObjectId = debugger.newInstance(
"dalvik.system.DexClassLoader", threadId, String::class.java.name to destFile.absolutePath,
String::class.java.name to "", String::class.java.name to "", ClassLoader::class.java.name to systemClassLoaderObjectId
).second
val loadClassMethodId = debugger.findMethodId(classLoaderClassId, "loadClass", getMethodSignature(String::class.java.name, returnTypeName = Class::class.java.name))
val mainClassId = debugger.invokeInstanceMethod(dexClassLoaderObjectId, classLoaderClassId, loadClassMethodId, threadId, String::class.java.name to mainClassName).second as Long
val mainMethodId = debugger.findMethodId(mainClassId, mainMethodName, getMethodSignature())
// 调用入参指定的类的静态方法
debugger.invokeStaticMethod(mainClassId, mainMethodId, threadId)
} finally {
// 恢复运行
debugger.resumeVM()
// 退出debug
debugger.dispose()
// 删除dex或apk文件
adb.sendShellCommand("rm ${destFile.absolutePath}")
}
}
}
}
}
| 0
|
Kotlin
|
0
| 10
|
1d33400e17fc5bb3e11014032bdb7d0cb0551935
| 3,922
|
jdwp-injector-for-android
|
Apache License 2.0
|
shared/core/persistence/src/commonMain/kotlin/com/thomaskioko/tvmaniac/shared/persistance/SettingsContract.kt
|
c0de-wizard
| 361,393,353
| false
| null |
package com.thomaskioko.tvmaniac.shared.persistance
import com.thomaskioko.tvmaniac.shared.core.ui.Action
import com.thomaskioko.tvmaniac.shared.core.ui.Effect
sealed class SettingsState
data class SettingsContent(
val theme: Theme,
val showPopup: Boolean,
val showTraktDialog: Boolean,
val loggedIn: Boolean,
val traktUserName: String,
val traktFullName: String?,
val traktUserPicUrl: String?,
) : SettingsState() {
companion object {
val DEFAULT = SettingsContent(
theme = Theme.SYSTEM,
showPopup = false,
showTraktDialog = false,
loggedIn = false,
traktUserName = "",
traktFullName = "",
traktUserPicUrl = ""
)
}
}
sealed class SettingsActions : Action {
data class ThemeSelected(
val theme: String
) : SettingsActions()
object LoadTheme : SettingsActions()
object ThemeClicked : SettingsActions()
object ShowTraktDialog : SettingsActions()
object DismissTraktDialog : SettingsActions()
object TraktLogout : SettingsActions()
object TraktLogin : SettingsActions()
object RefreshTraktAuthToken : SettingsActions()
object FetchTraktUserProfile : SettingsActions()
}
sealed class SettingsEffect : Effect
enum class Theme {
LIGHT,
DARK,
SYSTEM
}
| 3
|
Kotlin
|
8
| 81
|
9df7429257c4cff0346734392c89b8017b90bd45
| 1,348
|
tv-maniac
|
Apache License 2.0
|
app/src/main/java/com/rogertalk/roger/network/request/StreamUpdatePlayedUntilRequest.kt
|
rogertalk
| 207,123,525
| false
|
{"Gradle": 4, "Java Properties": 3, "Markdown": 7, "Text": 6, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "XML": 157, "Proguard": 2, "Kotlin": 408, "Java": 2, "JSON": 1, "Makefile": 2, "C": 105, "C++": 11}
|
package com.rogertalk.roger.network.request
import com.rogertalk.roger.event.success.SingleStreamSuccessEvent
import com.rogertalk.roger.models.json.Stream
import com.rogertalk.roger.utils.extensions.postEvent
class StreamUpdatePlayedUntilRequest(val streamId: Long, val playedUntilTimestamp: Long) : BaseRequest() {
override fun enqueueRequest() {
val callback = getCallback(Stream::class.java)
getRogerAPI().updateStreamPlayedUntil(streamId.toString(), playedUntilTimestamp.toString()).enqueue(callback)
}
override fun <T : Any> handleSuccess(t: T) {
// Update the stream
val stream = t as? Stream ?: return
postEvent(SingleStreamSuccessEvent(stream))
}
}
| 0
|
C
|
0
| 1
|
55c9922947311d9d8a1e930463b9ac2a1332e006
| 717
|
roger-android
|
MIT License
|
Katydid-CSS-JS/src/main/kotlin/o/katydid/css/styles/builders/KatydidVisibilityStyleBuilder.kt
|
martin-nordberg
| 131,987,610
| false
| null |
//
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package o.katydid.css.styles.builders
import o.katydid.css.styles.KatydidStyle
import o.katydid.css.types.EVisibility
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.visibility(value: EVisibility) =
setProperty("visibility", "$value")
//---------------------------------------------------------------------------------------------------------------------
| 1
|
Kotlin
|
1
| 6
|
8fcb99b2d96a003ff3168aef101eaa610e268bff
| 531
|
Katydid
|
Apache License 2.0
|
app/src/main/java/com/temtem/interactive/map/temzone/presentation/auth/sign_in/state/SignInGoogleState.kt
|
Temtem-Interactive-Map
| 568,136,913
| false
| null |
package com.temtem.interactive.map.temzone.presentation.auth.sign_in.state
import com.google.android.gms.auth.api.identity.BeginSignInResult
sealed interface SignInGoogleState {
object Empty : SignInGoogleState
object Loading : SignInGoogleState
data class Request(val result: BeginSignInResult) : SignInGoogleState
object Success : SignInGoogleState
data class Error(val snackbarMessage: String) : SignInGoogleState
}
| 0
|
Kotlin
|
0
| 1
|
338c95ef870b6ead4a58daec914c99583f1dc294
| 441
|
Temzone-Android
|
MIT License
|
api/src/main/kotlin/io/zerobase/smarttracing/api/features/organizations/OrganizationsResource.kt
|
zerobase-io
| 249,016,150
| false
| null |
package io.zerobase.smarttracing.api.features.organizations
import com.google.common.collect.Multimap
import com.google.common.eventbus.EventBus
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import io.zerobase.smarttracing.api.resources.Creator
import io.zerobase.smarttracing.common.LoggerDelegate
import io.zerobase.smarttracing.common.models.*
import javax.ws.rs.*
import javax.ws.rs.core.MediaType
/**
* Requests from clients.
*/
data class Contact(
val phone: String,
val email: String,
val contactName: String
)
data class CreateOrganizationRequest(
val name: String,
val contactInfo: Contact,
val address: Address,
val hasTestingFacilities: Boolean?,
val hasMultipleSites: Boolean?
)
data class CreateSiteRequest(
val name: String?,
val category: String,
val subcategory: String,
val address: Address?,
val location: Location?,
val isTesting: Boolean = false,
val siteManagerContactInfo: Contact?
)
data class CreateScannableRequest(
val type: String,
val singleUse: Boolean
)
data class SiteResponse(val id: String, val name: String)
@Path("/organizations")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
class OrganizationsResource(
private val dao: OrganizationsDao,
private val siteTypes: Multimap<String, String>,
private val scanTypes: Set<String>,
private val eventBus: EventBus
) {
companion object {
val log by LoggerDelegate()
}
@POST
@Creator
fun createOrganization(request: CreateOrganizationRequest): IdWrapper {
val name = request.name
val phone = request.contactInfo.phone
val email = request.contactInfo.email
val contactName = request.contactInfo.contactName
val address = request.address
val hasTestingFacilities = request.hasTestingFacilities ?: false
val hasMultipleSites = request.hasMultipleSites ?: true
val organization = dao.createOrganization(name, phone, email, contactName, address, hasTestingFacilities, hasMultipleSites)
val orgId = OrganizationId(organization.id)
if (!hasTestingFacilities && !hasMultipleSites) {
log.debug("Simple business organization detected. Auto-creating site and default qr code. organization={}", organization)
val siteId = dao.createSite(orgId, category = "BUSINESS", subcategory = "OTHER", address = request.address)
val scannableId = dao.createScannable(orgId, siteId, "QR_CODE", false)
log.info("Created site and default ")
eventBus.post(SimpleOrganizationCreated(organization, scannableId.value))
}
return IdWrapper(orgId)
}
@Path("/{id}/sites")
@POST
@Creator
fun createSite(@PathParam("id") organizationId: String, request: CreateSiteRequest): IdWrapper {
val name = request.name ?: ""
val category = request.category
val subcategory = request.subcategory
val latitude = request.location?.latitude
val longitude = request.location?.longitude
val isTesting = request.isTesting
if (!siteTypes.containsKey(category)) {
throw BadRequestException("Not a valid category please check /models/site-types")
}
if (siteTypes[category]?.contains(subcategory) != true) {
throw BadRequestException("Not a valid subcategory please check /models/site-types")
}
return dao.createSite(
OrganizationId(organizationId), name, category, subcategory, request.address,
latitude, longitude, isTesting, request.siteManagerContactInfo?.phone,
request.siteManagerContactInfo?.email, request.siteManagerContactInfo?.contactName
).let(::IdWrapper)
}
@Path("/{id}/sites")
@GET
@SuppressFBWarnings("BC_BAD_CAST_TO_ABSTRACT_COLLECTION", justification = "false positive")
fun getSites(@PathParam("id") id: String): List<SiteResponse> {
return dao.getSites(OrganizationId(id)).map { (id, name) -> SiteResponse(id, name) }
}
@Path("/{id}/multiple-sites-setting")
@PUT
fun updateMultipleSitesSetting(@PathParam("id") id: String, hasMultipleSites: Boolean) {
dao.setMultiSite(OrganizationId(id), hasMultipleSites)
}
@Path("/{orgId}/sites/{siteId}")
fun delegateSiteRequest(@PathParam("orgId") orgId: String, @PathParam("siteId") siteId: String): SitesResource {
return SitesResource(OrganizationId(orgId), SiteId(siteId), dao, scanTypes)
}
}
| 19
|
Kotlin
|
8
| 6
|
e0514f99c78bae6883e1bf50da5ee6a5c87f0a7f
| 4,556
|
smart-tracing-api
|
Apache License 2.0
|
app/src/main/java/com/sethchhim/kuboo_client/data/repository/PdfRepository.kt
|
befora
| 137,512,422
| false
| null |
package com.sethchhim.kuboo_client.data.repository
import com.artifex.mupdf.fitz.Document
import com.sethchhim.epublibdroid_kotlin.task.Task_EpubCoverInputStream
import com.sethchhim.kuboo_client.data.model.GlideEpub
import com.sethchhim.kuboo_client.data.model.GlidePdf
import com.sethchhim.kuboo_client.data.task.pdf.Task_GetPdfImageInputStream
import com.sethchhim.kuboo_client.data.task.pdf.Task_GetPdfOutline
class PdfRepository {
internal lateinit var document: Document
internal fun initPdf(filePath: String): Document {
document = Document.openDocument(filePath)
return document
}
internal fun getPdfPageCount() = document.countPages()
internal fun getPdfImageInputStream(glidePdf: GlidePdf) = Task_GetPdfImageInputStream(document, glidePdf).liveData
internal fun getPdfImageInputStreamSingleInstance(glidePdf: GlidePdf) = Task_GetPdfImageInputStream(Document.openDocument(glidePdf.book.filePath), glidePdf).liveData
internal fun getPdfOutline() = Task_GetPdfOutline(document).liveData
}
| 1
|
Kotlin
|
39
| 81
|
33e456344172eab96b136e30130c4125096f253d
| 1,048
|
Kuboo
|
Apache License 2.0
|
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/huntingControl/sync/HuntingControlRhyFromNetworkProvider.kt
|
suomenriistakeskus
| 78,840,058
| false
| null |
package fi.riista.common.domain.huntingControl.sync
import co.touchlab.stately.concurrency.AtomicReference
import fi.riista.common.domain.huntingControl.sync.dto.LoadRhysAndHuntingControlEventsDTO
import fi.riista.common.domain.huntingControl.sync.dto.toLoadRhyHuntingControlEvents
import fi.riista.common.domain.huntingControl.sync.model.LoadRhyHuntingControlEvents
import fi.riista.common.model.LoadStatus
import fi.riista.common.model.LocalDateTime
import fi.riista.common.network.BackendApiProvider
import fi.riista.common.network.NetworkDataFetcher
import fi.riista.common.network.calls.NetworkResponse
import fi.riista.common.network.calls.NetworkResponseData
internal class HuntingControlRhyFromNetworkProvider(
backendApiProvider: BackendApiProvider,
) : NetworkDataFetcher<LoadRhysAndHuntingControlEventsDTO>(),
BackendApiProvider by backendApiProvider {
val syncTimestamp: AtomicReference<LocalDateTime?> = AtomicReference(null)
private val _rhys = mutableListOf<LoadRhyHuntingControlEvents>()
val rhys: List<LoadRhyHuntingControlEvents>?
get() {
return if (_rhys.isEmpty() && !loadStatus.value.loaded) {
return null
} else {
_rhys
}
}
override suspend fun fetchFromNetwork(): NetworkResponse<LoadRhysAndHuntingControlEventsDTO> {
return backendAPI.fetchHuntingControlRhys(syncTimestamp.get())
}
override fun handleSuccess(statusCode: Int, responseData: NetworkResponseData<out LoadRhysAndHuntingControlEventsDTO>) {
val fetchedRhys = responseData.typed.map { it.toLoadRhyHuntingControlEvents(logger) }
_rhys.clear()
_rhys.addAll(fetchedRhys)
}
override fun handleError401() {
_rhys.clear()
}
internal fun clear() {
_rhys.clear()
loadStatus.set(LoadStatus.NotLoaded())
}
}
| 0
|
Kotlin
|
0
| 3
|
23645d1abe61c68d649b6d0ca1d16556aa8ffa16
| 1,883
|
oma-riista-android
|
MIT License
|
canvas/src/main/java/com/github/boybeak/canvas/AbsRenderer.kt
|
boybeak
| 622,424,516
| false
| null |
package com.github.boybeak.canvas
import android.view.SurfaceHolder
import com.github.boybeak.canvas.executor.RenderExecutor
abstract class AbsRenderer : ICanvasRenderer {
companion object {
private const val TAG = "AbsRenderer"
}
override fun onSurfaceCreated(holder: SurfaceHolder, executor: RenderExecutor) {
}
override fun onSurfaceChanged(
holder: SurfaceHolder,
format: Int,
width: Int,
height: Int,
executor: RenderExecutor
) {
}
override fun onSurfaceDestroyed(holder: SurfaceHolder, executor: RenderExecutor) {
}
}
| 0
|
Kotlin
|
0
| 0
|
b4e54dd07a71f0d23c289d1fcbcd070fe507a792
| 613
|
canvas
|
MIT License
|
flickr-public-feed-android-master/app/src/main/java/com/developer/davidtc/flickrpublicfeedandroid/publicfeed/ui/FeedItemsAdapter.kt
|
Nils27
| 149,969,437
| false
|
{"Java": 26782, "Kotlin": 14658}
|
package com.developer.davidtc.flickrpublicfeedandroid.publicfeed.ui
import android.content.Context
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.developer.davidtc.flickrpublicfeedandroid.R
import com.developer.davidtc.flickrpublicfeedandroid.databinding.ItemPublicFeedBinding
import com.developer.davidtc.flickrpublicfeedandroid.publicfeed.data.FeedItem
/**
* Adapter for feed items.
*
*
* Created by david on 12/10/17.
*/
internal class FeedItemsAdapter(private val items: List<FeedItem>, context: Context) : RecyclerView.Adapter<FeedItemsAdapter.ViewHolder>() {
private val layoutInflater: LayoutInflater = LayoutInflater.from(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = DataBindingUtil.inflate<ItemPublicFeedBinding>(
layoutInflater, R.layout.item_public_feed, parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val feedItem = items[position]
holder.bind(feedItem)
}
override fun getItemCount(): Int {
return items.size
}
internal class ViewHolder(private val binding: ItemPublicFeedBinding) : RecyclerView.ViewHolder(binding.root) {
private val publicFeedItemViewModel: PublicFeedItemViewModel = PublicFeedItemViewModel()
init {
this.binding.itemViewModel = publicFeedItemViewModel
}
fun bind(item: FeedItem) {
publicFeedItemViewModel.setItem(item)
binding.executePendingBindings()
}
}
}
| 1
| null |
1
| 1
|
b2ee474a924699f182d1f76e3033b0f96458c759
| 1,587
|
Public_FLikr_Feed
|
Apache License 2.0
|
app/src/main/java/com/elhady/movies/ui/profile/ratings/RatingViewModel.kt
|
islamelhady
| 301,591,032
| false
|
{"Kotlin": 397718}
|
package com.elhady.movies.ui.profile.ratings
import androidx.lifecycle.viewModelScope
import com.elhady.movies.domain.enums.MediaType
import com.elhady.movies.domain.usecases.GetListOfRatedUseCase
import com.elhady.movies.ui.base.BaseViewModel
import com.elhady.movies.utilities.Event
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class RatingViewModel @Inject constructor(
private val getListOfRatedUseCase: GetListOfRatedUseCase,
private val ratedUiStateMapper: RatedUiStateMapper
) : BaseViewModel(), MyRatingInteractionListener {
private val _rateUiState = MutableStateFlow(MyRateUiState())
val rateUiState = _rateUiState.asStateFlow()
private val _rateUiEvent = MutableStateFlow<Event<MyRatingUiEvent>?>(null)
val rateUiEvent = _rateUiEvent.asStateFlow()
init {
getData()
}
override fun getData() {
_rateUiState.update { it.copy(isLoading = true) }
viewModelScope.launch {
val result = getListOfRatedUseCase().map {
ratedUiStateMapper.map(it)
}
_rateUiState.update {
it.copy(ratedList = result, isLoading = false)
}
}
}
override fun onClickRating(rated: RatedUiState) {
if (rated.mediaType.equals(MediaType.MOVIES.value, true)) {
_rateUiEvent.update { Event(MyRatingUiEvent.MovieEvent(rated.id)) }
} else {
_rateUiEvent.update { Event(MyRatingUiEvent.SeriesEvent(rated.id)) }
}
}
}
| 1
|
Kotlin
|
0
| 0
|
11cca97dbb5e5358310fa75148a33110c6f3483b
| 1,713
|
movie-night-v2
|
Apache License 2.0
|
infra/src/main/kotlin/fr/sacane/jmanager/infrastructure/postgres/adapters/DatasourceMapper.kt
|
Sacane
| 531,082,439
| false
|
{"Kotlin": 92781, "Vue": 31862, "TypeScript": 13514}
|
package fr.sacane.jmanager.infrastructure.postgres.adapters
import fr.sacane.jmanager.domain.models.*
import fr.sacane.jmanager.infrastructure.postgres.entity.*
internal fun Sheet.asResource(): SheetResource {
val resource = SheetResource()
resource.label = this.label
resource.date = this.date
this.exportAmountValues { expense, income, sold ->
resource.expenses = expense
resource.income = income
resource.accountAmount = sold
}
resource.category = resource.category
resource.idSheet = this.id
resource.position = this.position
return resource
}
internal fun Account.asResource(): AccountResource {
val sheets = if (this.sheets().isEmpty()) {
mutableListOf()
} else {
sheets().map { it.asResource() }.toMutableList()
}
return AccountResource(idAccount = id, amount = sold.applyOnValue { it }, label = label, sheets = sheets)
}
internal fun User.asResource(): UserResource {
return UserResource(username, password.get(), email, mutableListOf(), categories().map { CategoryResource(label = it.label) }.toMutableList())
}
internal fun User.asExistingResource(): UserResource {
return UserResource(idUser = this.id.id,
username = username, password = <PASSWORD>(), email = email, accounts = this.accounts().map {it.asResource()}.toMutableList())
}
internal fun SheetResource.toModel(): Sheet{
return Sheet(this.idSheet,
this.label,
this.date,
this.expenses.toAmount(),
this.income.toAmount(),
this.accountAmount.toAmount(),
position=this.position)
}
internal fun AccountResource.toModel(): Account{
return Account(
this.idAccount,
this.amount.toAmount(),
this.label,
this.sheets.map { sheet -> sheet.toModel() }.toMutableList())
}
internal fun UserResource.toModel()
: User = User(
UserId(this.idUser),
this.username,
this.email,
this.accounts.map { account -> account.toModel() }.toMutableList(),
Password.fromBytes(this.password),
CategoryFactory.allDefaultCategories()
)
internal fun Login.toModel()
: AccessToken = AccessToken(this.token, this.tokenLifeTime, this.refreshToken, this.refreshTokenLifetime)
| 0
|
Kotlin
|
0
| 0
|
c00f0d54922153ca5233ddd119a15a3e9983aa75
| 2,235
|
JManager
|
MIT License
|
api/src/main/kotlin/nebulosa/api/cameras/CameraStartCaptureRequest.kt
|
tiagohm
| 568,578,345
| false
|
{"Kotlin": 2031289, "TypeScript": 322187, "HTML": 164617, "SCSS": 10191, "Python": 2817, "JavaScript": 1119}
|
package nebulosa.api.cameras
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import jakarta.validation.Valid
import jakarta.validation.constraints.Positive
import jakarta.validation.constraints.PositiveOrZero
import nebulosa.api.beans.converters.time.DurationDeserializer
import nebulosa.api.guiding.DitherAfterExposureRequest
import nebulosa.indi.device.camera.Camera
import nebulosa.indi.device.camera.FrameType
import nebulosa.indi.device.filterwheel.FilterWheel
import nebulosa.indi.device.focuser.Focuser
import org.hibernate.validator.constraints.Range
import org.hibernate.validator.constraints.time.DurationMax
import org.hibernate.validator.constraints.time.DurationMin
import org.springframework.boot.convert.DurationUnit
import java.nio.file.Path
import java.time.Duration
import java.time.temporal.ChronoUnit
data class CameraStartCaptureRequest(
val enabled: Boolean = true,
// Capture.
val camera: Camera? = null,
@field:DurationMin(nanos = 1000L) @field:DurationMax(minutes = 60L) val exposureTime: Duration = Duration.ZERO,
@field:Range(min = 0L, max = 1000L) val exposureAmount: Int = 1, // 0 = looping
@field:JsonDeserialize(using = DurationDeserializer::class) @field:DurationUnit(ChronoUnit.SECONDS)
@field:DurationMin(nanos = 0L) @field:DurationMax(seconds = 60L) val exposureDelay: Duration = Duration.ZERO,
@field:PositiveOrZero val x: Int = 0,
@field:PositiveOrZero val y: Int = 0,
@field:PositiveOrZero val width: Int = 0,
@field:PositiveOrZero val height: Int = 0,
val frameFormat: String? = null,
val frameType: FrameType = FrameType.LIGHT,
@field:Positive val binX: Int = 1,
@field:Positive val binY: Int = 1,
@field:PositiveOrZero val gain: Int = 0,
@field:PositiveOrZero val offset: Int = 0,
val autoSave: Boolean = false,
val savePath: Path? = null,
val autoSubFolderMode: AutoSubFolderMode = AutoSubFolderMode.OFF,
@field:Valid val dither: DitherAfterExposureRequest = DitherAfterExposureRequest.DISABLED,
// Filter Wheel.
val wheel: FilterWheel? = null,
val filterPosition: Int = 0,
val shutterPosition: Int = 0,
// Focuser.
val focuser: Focuser? = null,
val focusOffset: Int = 0,
) {
inline val isLoop
get() = exposureAmount <= 0
}
| 1
|
Kotlin
|
1
| 2
|
ab7b7235ffae5f9fb47c4901d71405e2d13a7b23
| 2,310
|
nebulosa
|
MIT License
|
app/src/main/java/com/example/upschoolcapstoneproject/data/repository/AuthRepository.kt
|
Gamzecoskkun
| 719,202,608
| false
|
{"Kotlin": 85051}
|
package com.example.upschoolcapstoneproject.data.repository
import com.example.upschoolcapstoneproject.common.Resource
import com.google.firebase.auth.FirebaseAuth
import kotlinx.coroutines.tasks.await
class AuthRepository(private val firebaseAuth: FirebaseAuth) {
fun isUserLoggedIn() = firebaseAuth.currentUser != null
fun getUserId() = firebaseAuth.currentUser?.uid.orEmpty()
suspend fun signIn(email: String, password: String): Resource<Unit> {
return try {
val result = firebaseAuth.signInWithEmailAndPassword(email, password).await()
if (result.user != null) {
Resource.Success(Unit)
} else {
Resource.Error("Bir hata oluştu")
}
} catch (e: Exception) {
Resource.Error("Böyle bir kullanıcı yok")
}
}
suspend fun signUp(email: String, password: String): Resource<Unit> {
val result = firebaseAuth.createUserWithEmailAndPassword(email, password).await()
return try {
if (result.user != null) {
Resource.Success(Unit)
} else {
Resource.Error("Bir hata oluştu")
}
} catch (e: Exception) {
Resource.Error("Bir hata oluştu")
}
}
fun logOut() = firebaseAuth.signOut()
}
| 0
|
Kotlin
|
0
| 0
|
568b56f59f8a5626be8d38fc725a49dec2733fc7
| 1,337
|
upschoolcapstoneproject
|
Freetype Project License
|
mc-randomizer-plugin/src/main/kotlin/forbidden/dev/randomizer/Fishing.kt
|
dkantereivin
| 223,837,078
| false
|
{"Python": 13555, "HTML": 8978, "Kotlin": 8692, "Java": 8490, "JavaScript": 1321, "C++": 881}
|
package forbidden.dev.randomizer
import org.bukkit.GameMode
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerFishEvent
import org.bukkit.inventory.ItemStack
object Fishing: Listener {
@EventHandler
fun onFish(event: PlayerFishEvent){
val player = event.player
if (event.state == PlayerFishEvent.State.CAUGHT_FISH){
val worldName = player.world.name
val loc = event.player.location
if (player.gameMode != GameMode.SURVIVAL) return
if (plugin.config.getBoolean("EnabledWorlds.$worldName") && player.gameMode == GameMode.SURVIVAL){
val material = randMaterial()
val item = ItemStack(material, randAmount(material))
if (!plugin.config.getBoolean("Drops.${item.type.name}")) return
if (item.type != Material.AIR && !item.isSimilar(ItemStack(Material.AIR, randAmount(material)))) {player.world.dropItem(loc, item)}
}
}
}
}
| 2
|
Python
|
3
| 4
|
b34b8de719dd088e5e7dd8c8c0206e7ef704c77c
| 1,065
|
programmers-palace-examples
|
The Unlicense
|
src/main/kotlin/net/bjoernpetersen/musicbot/spi/player/PlayerHistory.kt
|
BjoernPetersen
| 89,800,012
| false
| null |
package net.bjoernpetersen.musicbot.spi.player
import net.bjoernpetersen.musicbot.api.player.SongEntry
/**
* Keeps track of the history of songs played by the [Player].
*
* The history is limited to a maximum size, it's not kept indefinitely.
*/
interface PlayerHistory {
/**
* Gets the current player history.
*
* The returned list is ordered from least to most recently played. It is immutable and will not
* be updated.
*
* @param limit the maximum limit of the result
* @return a list of recently played songs
* @throws IllegalArgumentException if the limit is negative
*/
fun getHistory(limit: Int = 20): List<SongEntry>
}
| 22
|
Kotlin
|
2
| 5
|
6174262490a182bc9033a331523c36af117b8c3d
| 687
|
MusicBot
|
MIT License
|
core/src/main/kotlin/org/neo4j/graphql/GraphQLExtensions.kt
|
rbramley
| 369,255,130
| true
|
{"Kotlin": 237743, "Java": 2521, "Python": 1363, "Shell": 263}
|
package org.neo4j.graphql
import graphql.Scalars
import graphql.language.*
import graphql.language.TypeDefinition
import graphql.schema.*
import graphql.schema.idl.TypeDefinitionRegistry
import org.neo4j.cypherdsl.core.SymbolicName
import org.neo4j.graphql.DirectiveConstants.Companion.CYPHER
import org.neo4j.graphql.DirectiveConstants.Companion.CYPHER_PASS_THROUGH
import org.neo4j.graphql.DirectiveConstants.Companion.CYPHER_STATEMENT
import org.neo4j.graphql.DirectiveConstants.Companion.DYNAMIC
import org.neo4j.graphql.DirectiveConstants.Companion.DYNAMIC_PREFIX
import org.neo4j.graphql.DirectiveConstants.Companion.PROPERTY
import org.neo4j.graphql.DirectiveConstants.Companion.PROPERTY_NAME
import org.neo4j.graphql.DirectiveConstants.Companion.RELATION_NAME
import org.neo4j.graphql.DirectiveConstants.Companion.RELATION_TO
import org.neo4j.graphql.handler.projection.ProjectionBase
import java.math.BigDecimal
import java.math.BigInteger
fun Type<*>.name(): String? = if (this.inner() is TypeName) (this.inner() as TypeName).name else null
fun Type<*>.inner(): Type<*> = when (this) {
is ListType -> this.type.inner()
is NonNullType -> this.type.inner()
else -> this
}
fun Type<*>.isList(): Boolean = when (this) {
is ListType -> true
is NonNullType -> type.isList()
else -> false
}
fun GraphQLType.inner(): GraphQLType = when (this) {
is GraphQLList -> this.wrappedType.inner()
is GraphQLNonNull -> this.wrappedType.inner()
else -> this
}
fun GraphQLType.name(): String? = (this as? GraphQLNamedType)?.name
fun GraphQLType.requiredName(): String = requireNotNull(name()) { "name is required but cannot be determined for " + this.javaClass }
fun GraphQLType.isList() = this is GraphQLList || (this is GraphQLNonNull && this.wrappedType is GraphQLList)
fun GraphQLType.isNeo4jType() = this.innerName().startsWith("_Neo4j")
fun GraphQLType.isNeo4jTemporalType() = NEO4j_TEMPORAL_TYPES.contains(this.innerName())
fun TypeDefinition<*>.isNeo4jSpatialType() = this.name.startsWith("_Neo4jPoint")
fun GraphQLFieldDefinition.isNeo4jType(): Boolean = this.type.isNeo4jType()
fun GraphQLFieldDefinition.isNeo4jTemporalType(): Boolean = this.type.isNeo4jTemporalType()
fun GraphQLFieldDefinition.isRelationship() = !type.isNeo4jType() && this.type.inner().let { it is GraphQLFieldsContainer }
fun GraphQLFieldsContainer.isRelationType() = (this as? GraphQLDirectiveContainer)?.getDirective(DirectiveConstants.RELATION) != null
fun GraphQLFieldsContainer.relationshipFor(name: String): RelationshipInfo<GraphQLFieldsContainer>? {
val field = getRelevantFieldDefinition(name)
?: throw IllegalArgumentException("$name is not defined on ${this.name}")
val fieldObjectType = field.type.inner() as? GraphQLImplementingType ?: return null
val (relDirective, inverse) = if (isRelationType()) {
val typeName = this.name
(this as? GraphQLDirectiveContainer)
?.getDirective(DirectiveConstants.RELATION)?.let {
// do inverse mapping, if the current type is the `to` mapping of the relation
it to (fieldObjectType.getRelevantFieldDefinition(it.getArgument(RELATION_TO, null))?.name == typeName)
}
?: throw IllegalStateException("Type ${this.name} needs an @relation directive")
} else {
(fieldObjectType as? GraphQLDirectiveContainer)
?.getDirective(DirectiveConstants.RELATION)?.let { it to true }
?: field.getDirective(DirectiveConstants.RELATION)?.let { it to false }
?: throw IllegalStateException("Field $field needs an @relation directive")
}
val relInfo = RelationshipInfo.create(fieldObjectType, relDirective)
return if (inverse) relInfo.copy(direction = relInfo.direction.invert(), startField = relInfo.endField, endField = relInfo.startField) else relInfo
}
fun GraphQLFieldsContainer.getValidTypeLabels(schema: GraphQLSchema): List<String> {
if (this is GraphQLObjectType) {
return listOf(this.label())
}
if (this is GraphQLInterfaceType) {
return schema.getImplementations(this)
.mapNotNull { it.label() }
}
return emptyList()
}
fun GraphQLFieldsContainer.label(): String = when {
this.isRelationType() ->
(this as? GraphQLDirectiveContainer)
?.getDirective(DirectiveConstants.RELATION)
?.getArgument(RELATION_NAME)?.value?.toJavaValue()?.toString()
?: this.name
else -> name
}
fun GraphQLFieldsContainer.relationship(): RelationshipInfo<GraphQLFieldsContainer>? = RelationshipInfo.create(this)
fun GraphQLType.ref(): GraphQLType = when (this) {
is GraphQLNonNull -> GraphQLNonNull(this.wrappedType.ref())
is GraphQLList -> GraphQLList(this.wrappedType.ref())
is GraphQLScalarType -> this
is GraphQLEnumType -> this
is GraphQLTypeReference -> this
else -> GraphQLTypeReference(name())
}
fun Field.aliasOrName(): String = (this.alias ?: this.name)
fun Field.contextualize(variable: String) = variable + this.aliasOrName().capitalize()
fun Field.contextualize(variable: SymbolicName) = variable.value + this.aliasOrName().capitalize()
fun GraphQLType.innerName(): String = inner().name()
?: throw IllegalStateException("inner name cannot be retrieved for " + this.javaClass)
fun GraphQLFieldDefinition.propertyName() = getDirectiveArgument(PROPERTY, PROPERTY_NAME, this.name)!!
fun GraphQLFieldDefinition.dynamicPrefix(): String? = getDirectiveArgument(DYNAMIC, DYNAMIC_PREFIX, null)
fun GraphQLType.getInnerFieldsContainer() = inner() as? GraphQLFieldsContainer
?: throw IllegalArgumentException("${this.innerName()} is neither an object nor an interface")
fun <T> GraphQLDirectiveContainer.getDirectiveArgument(directiveName: String, argumentName: String, defaultValue: T?): T? =
getDirective(directiveName)?.getArgument(argumentName, defaultValue) ?: defaultValue
@Suppress("UNCHECKED_CAST")
fun <T> DirectivesContainer<*>.getDirectiveArgument(typeRegistry: TypeDefinitionRegistry, directiveName: String, argumentName: String, defaultValue: T? = null): T? {
return (getDirective(directiveName) ?: return defaultValue)
.getArgument(argumentName)?.value?.toJavaValue() as T?
?: typeRegistry.getDirectiveDefinition(directiveName)
?.unwrap()
?.inputValueDefinitions
?.find { inputValueDefinition -> inputValueDefinition.name == argumentName }
?.defaultValue?.toJavaValue() as T?
?: defaultValue
}
fun DirectivesContainer<*>.getDirective(name: String): Directive? = directives.firstOrNull { it.name == name }
@Suppress("UNCHECKED_CAST")
fun <T> DirectivesContainer<*>.getMandatoryDirectiveArgument(typeRegistry: TypeDefinitionRegistry, directiveName: String, argumentName: String, defaultValue: T? = null): T =
getDirectiveArgument(typeRegistry, directiveName, argumentName, defaultValue)
?: throw IllegalStateException("No default value for @${directiveName}::$argumentName")
fun <T> GraphQLDirective.getMandatoryArgument(argumentName: String, defaultValue: T? = null): T = this.getArgument(argumentName, defaultValue)
?: throw IllegalStateException(argumentName + " is required for @${this.name}")
fun <T> GraphQLDirective.getArgument(argumentName: String, defaultValue: T? = null): T? {
val argument = getArgument(argumentName)
@Suppress("UNCHECKED_CAST")
return argument?.value as T?
?: argument.defaultValue as T?
?: defaultValue
?: throw IllegalStateException("No default value for @${this.name}::$argumentName")
}
fun GraphQLFieldDefinition.cypherDirective(): CypherDirective? = getDirective(CYPHER)?.let {
CypherDirective(
it.getMandatoryArgument(CYPHER_STATEMENT),
it.getMandatoryArgument(CYPHER_PASS_THROUGH, false)
)
}
data class CypherDirective(val statement: String, val passThrough: Boolean)
fun Any.toJavaValue() = when (this) {
is Value<*> -> this.toJavaValue()
else -> this
}
fun Value<*>.toJavaValue(): Any? = when (this) {
is StringValue -> this.value
is EnumValue -> this.name
is NullValue -> null
is BooleanValue -> this.isValue
is FloatValue -> this.value.toDouble()
is IntValue -> this.value.longValueExact()
is VariableReference -> this
is ArrayValue -> this.values.map { it.toJavaValue() }.toList()
is ObjectValue -> this.objectFields.associate { it.name to it.value.toJavaValue() }
else -> throw IllegalStateException("Unhandled value $this")
}
fun GraphQLFieldDefinition.isID() = this.type.inner() == Scalars.GraphQLID
fun GraphQLFieldDefinition.isNativeId() = this.name == ProjectionBase.NATIVE_ID
fun GraphQLFieldDefinition.isIgnored() = getDirective(DirectiveConstants.IGNORE) != null
fun FieldDefinition.isIgnored(): Boolean = hasDirective(DirectiveConstants.IGNORE)
fun GraphQLFieldsContainer.getIdField() = this.getRelevantFieldDefinitions().find { it.isID() }
/**
* Returns the field definitions which are not ignored
*/
fun GraphQLFieldsContainer.getRelevantFieldDefinitions() = this.fieldDefinitions.filterNot { it.isIgnored() }
/**
* Returns the field definition if it is not ignored
*/
fun GraphQLFieldsContainer.getRelevantFieldDefinition(name: String?) = this.getFieldDefinition(name)?.takeIf { !it.isIgnored() }
fun InputObjectTypeDefinition.Builder.addFilterField(fieldName: String, isList: Boolean, filterType: String, description: Description? = null) {
val wrappedType: Type<*> = when {
isList -> ListType(TypeName(filterType))
else -> TypeName(filterType)
}
val inputField = InputValueDefinition.newInputValueDefinition()
.name(fieldName)
.type(wrappedType)
if (description != null) {
inputField.description(description)
}
this.inputValueDefinition(inputField.build())
}
fun TypeDefinitionRegistry.queryTypeName() = this.getOperationType("query") ?: "Query"
fun TypeDefinitionRegistry.mutationTypeName() = this.getOperationType("mutation") ?: "Mutation"
fun TypeDefinitionRegistry.subscriptionTypeName() = this.getOperationType("subscription") ?: "Subscription"
fun TypeDefinitionRegistry.getOperationType(name: String) = this.schemaDefinition().unwrap()?.operationTypeDefinitions?.firstOrNull { it.name == name }?.typeName?.name
fun Any?.asGraphQLValue(): Value<*> = when (this) {
null -> NullValue.newNullValue().build()
is Value<*> -> this
is Array<*> -> ArrayValue.newArrayValue().values(this.map { it.asGraphQLValue() }).build()
is Iterable<*> -> ArrayValue.newArrayValue().values(this.map { it.asGraphQLValue() }).build()
is Map<*, *> -> ObjectValue.newObjectValue().objectFields(this.map { entry -> ObjectField(entry.key as String, entry.value.asGraphQLValue()) }).build()
is Enum<*> -> EnumValue.newEnumValue().name(this.name).build()
is Int -> IntValue.newIntValue(BigInteger.valueOf(this.toLong())).build()
is Long -> IntValue.newIntValue(BigInteger.valueOf(this)).build()
is Number -> FloatValue.newFloatValue(BigDecimal.valueOf(this as Double)).build()
is Boolean -> BooleanValue.newBooleanValue(this).build()
is String -> StringValue.newStringValue(this).build()
else -> throw IllegalStateException("Cannot convert ${this.javaClass.name} into an graphql type")
}
fun DataFetchingEnvironment.typeAsContainer() = this.fieldDefinition.type.inner() as? GraphQLFieldsContainer
?: throw IllegalStateException("expect type of field ${this.logField()} to be GraphQLFieldsContainer, but was ${this.fieldDefinition.type.name()}")
fun DataFetchingEnvironment.logField() = "${this.parentType.name()}.${this.fieldDefinition.name}"
val TypeInt = TypeName("Int")
val TypeFloat = TypeName("Float")
val TypeBoolean = TypeName("Boolean")
val TypeID = TypeName("ID")
| 0
|
Kotlin
|
0
| 0
|
f91e76ef6a3217755d7f99280e57c9fa1b029038
| 11,899
|
neo4j-graphql-java
|
Apache License 2.0
|
architecture/domain/src/main/java/com/aminography/domain/city/CityRepository.kt
|
aminography
| 338,760,259
| false
| null |
package com.aminography.domain.city
import androidx.paging.PagingData
import com.aminography.model.city.City
import kotlinx.coroutines.flow.Flow
/**
* The abstraction of the city repository that defines expected functions for the concrete child
* class.
*
* @author aminography
*/
interface CityRepository {
/**
* Loads cities into the memory.
*/
suspend fun loadCities()
/**
* Performs a prefix search on cities based on the input [query].
*
* @param query the string to use as the prefix for search.
*
* @return a [Flow] of [PagingData] that enables user interface to load result of the search by
* pagination.
*/
fun searchCities(query: String): Flow<PagingData<City>>
/**
* Clears the cache of loaded cities.
*/
fun clearCache()
}
| 0
|
Kotlin
|
4
| 28
|
7f2d3f08a4b339d6d4778c2c2ed7ac3ec22c219b
| 823
|
WorldCitiesApp
|
Apache License 2.0
|
src/main/kotlin/nextstep/subway/member/ui/MemberController.kt
|
parkchu
| 286,419,405
| false
| null |
package nextstep.subway.member.ui
import nextstep.subway.member.application.MemberService
import nextstep.subway.member.domain.LoginMember
import nextstep.subway.member.dto.MemberRequest
import nextstep.subway.member.dto.MemberResponse
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.net.URI
import javax.servlet.http.HttpServletRequest
@RestController
class MemberController(private val memberService: MemberService) {
@PostMapping("/members")
fun createMember(@RequestBody request: MemberRequest): ResponseEntity<*> {
val (id) = memberService.createMember(request)
return ResponseEntity.created(URI.create("/members/$id")).build<Any>()
}
@GetMapping("/members/{id}")
fun findMember(@PathVariable id: Long): ResponseEntity<MemberResponse> {
val member = memberService.findMember(id)
return ResponseEntity.ok().body(member)
}
@GetMapping("/members/me")
fun findMemberOfMine(request: HttpServletRequest, loginMember: LoginMember): ResponseEntity<MemberResponse> {
val member = MemberResponse.of(loginMember)
return ResponseEntity.ok().body(member)
}
@PutMapping("/members/me")
fun updateMember(@RequestBody param: MemberRequest, loginMember: LoginMember): ResponseEntity<MemberResponse> {
memberService.updateMember(loginMember.id, param)
return ResponseEntity.ok().body(MemberResponse.of(param.toMember()))
}
@DeleteMapping("/members/me")
fun deleteMember(loginMember: LoginMember): ResponseEntity<MemberResponse> {
memberService.deleteMember(loginMember.id)
return ResponseEntity.noContent().build()
}
}
| 0
|
Kotlin
|
0
| 1
|
0d47fe02069852659b5548ad0a3fe5bd21eeed99
| 1,712
|
atdd-with-kotlin
|
MIT License
|
app/src/main/java/js/spotifytool/focuscounter/LoginActivity.kt
|
Smintheus
| 734,762,584
| false
|
{"Kotlin": 16396}
|
package js.spotifytool.focuscounter
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.spotify.sdk.android.auth.AuthorizationResponse
import js.spotifytool.focuscounter.spotify.SpotifyOAuth
//TODO rückkehr zu login sollte nicht mehr möglich sein
class LoginActivity : AppCompatActivity() {
private lateinit var auth: SpotifyOAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity)
auth = SpotifyOAuth(this)
}
// Handles the authentication callback from spotify
override fun onNewIntent(intent:Intent) {
super.onNewIntent(intent);
val uri: Uri? = intent.data;
if (uri != null) {
val response: AuthorizationResponse = AuthorizationResponse.fromUri(uri);
when (response.type) {
AuthorizationResponse.Type.TOKEN -> {
}
AuthorizationResponse.Type.CODE -> {
auth.oauthIssueRefreshToken(response.code)
}
else -> {
Log.i("Login","Got Unexpected intent from $uri")
}
}
}
}
override fun onStop() {
super.onStop()
// Aaand we will finish off here.
}
fun auth(view: View) {
//val t = AuthorizationClient.getResponse(-1, intent)
auth.oauthIssueCode()
//val intent = Intent(this, MainActivity::class.java)
//startActivity(intent)
}
fun authFinished() {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
32105600ec7f646414adfa2e71b0c51692a9427a
| 1,784
|
SpotifySmoothFocusApp
|
MIT License
|
shared/src/commonMain/kotlin/features/favorite/data/source/local/LocalFavoriteDataSource.kt
|
mamadou94Diop
| 683,034,694
| false
|
{"Kotlin": 41310, "Ruby": 1790, "Swift": 653, "Shell": 228}
|
package features.favorite.data.source.local
import features.favorite.data.source.FavoriteDataSource
import features.favorite.data.source.local.entity.FavoriteBurgerEntity
import io.realm.kotlin.Realm
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
class LocalFavoriteDataSource(private val realm: Realm) : FavoriteDataSource {
override fun getFavoriteBurgers(): Flow<List<FavoriteBurgerEntity>> =
realm.query(FavoriteBurgerEntity::class).asFlow().map {
it.list.toList()
}
override fun setFavorite(favorite: FavoriteBurgerEntity) = flow {
try {
realm.query<FavoriteBurgerEntity>(FavoriteBurgerEntity::class, "id == $0", favorite.id)
.first()
.find()
?.let { burgerToRemove ->
realm.writeBlocking {
delete(burgerToRemove)
}
} ?: kotlin.run {
realm.writeBlocking {
copyToRealm(FavoriteBurgerEntity().apply {
this.id = favorite.id
this.name = favorite.name
this.description = favorite.description
this.name = favorite.name
this.price = favorite.price
this.ingredients = favorite.ingredients
})
}
}
emit(true)
} catch (exception: Exception) {
emit(false)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ba2cd7c609940989abe33bf7ec2dd3fcaa2edff2
| 1,574
|
restaurant-app-compose-multiplatform
|
Apache License 2.0
|
Android/app/src/main/java/sample/sdk/breez/page/home/receiveonchain/ReceiveOnChain.kt
|
breez
| 681,972,081
| false
|
{"Kotlin": 132212, "Rust": 2438, "Python": 1484}
|
package sample.sdk.breez.page.home.receiveonchain
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import breez_sdk.OpeningFeeParams
import breez_sdk.SwapInfo
import breez_sdk.SwapStatus
import sample.sdk.breez.R
import sample.sdk.breez.page.BreezSdkSampleTheme
@Composable
fun ReceiveOnChain(
swapInfo: SwapInfo,
) {
Column {
Text(
swapInfo.bitcoinAddress,
Modifier.padding(
start = 16.dp,
end = 16.dp,
top = 16.dp,
bottom = 4.dp,
),
)
Text(
swapInfo.status.name,
Modifier.padding(
start = 16.dp,
end = 16.dp,
top = 4.dp,
bottom = 4.dp,
),
)
Text(
stringResource(
R.string.receive_on_chain_range,
swapInfo.minAllowedDeposit,
swapInfo.maxAllowedDeposit,
),
Modifier.padding(
start = 16.dp,
end = 16.dp,
top = 4.dp,
bottom = 16.dp,
),
)
}
}
@[Composable Preview(
showBackground = true,
heightDp = 200,
widthDp = 300,
)]
fun ReceiveOnChainPreview() {
BreezSdkSampleTheme {
ReceiveOnChain(
SwapInfo(
"A bitcoin address",
1689788251L,
123L,
emptyList(),
emptyList(),
emptyList(),
emptyList(),
emptyList(),
emptyList(),
"A Bolt11",
1L.toULong(),
2L.toULong(),
3L.toULong(),
SwapStatus.INITIAL,
emptyList(),
emptyList(),
emptyList(),
100L,
200L,
"A last redeem error",
OpeningFeeParams(
minMsat = 4L.toULong(),
proportional = 5.toUInt(),
validUntil = "A valid until",
maxIdleTime = 7.toUInt(),
maxClientToSelfDelay = 8.toUInt(),
promise = "A promise",
),
),
)
}
}
| 1
|
Kotlin
|
1
| 1
|
3d1d51830315e0ceb54eca79cd43d14c10ec71f4
| 2,613
|
breez-sdk-examples
|
MIT License
|
src/test/kotlin/cl/benm/jsons/command/selector/ClaimSelectorConditionTest.kt
|
BenMMcLean
| 660,937,130
| false
| null |
package cl.benm.jsons.command.selector
import cl.benm.jsons.config.CompilerConfig
import cl.benm.jsons.context.ClaimsCompilerContext
import cl.benm.jsons.context.CompilerContext
import cl.benm.jsons.exception.CompilerException
import cl.benm.jsons.exception.ContextException
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class ClaimSelectorConditionTest {
@Test
fun `evaluate returns true when claims match`() {
// Arrange
val condition = ClaimSelectorCondition()
val claimsContext = object : ClaimsCompilerContext {
override val final: Boolean = false
override val config: CompilerConfig get() = throw NotImplementedError()
override val claims: List<String> = listOf("claim1", "claim2")
}
val element = JsonParser().parse("[[\"claim1\", \"claim2\"], [\"claim3\"]]").asJsonArray
// Act
val result = condition.evaluate(element, claimsContext)
// Assert
assertTrue(result)
}
@Test
fun `evaluate returns false when claims do not match`() {
// Arrange
val condition = ClaimSelectorCondition()
val claimsContext = object : ClaimsCompilerContext {
override val final: Boolean = false
override val config: CompilerConfig get() = throw NotImplementedError()
override val claims: List<String> = listOf("claim1", "claim2")
}
val element = JsonParser.parseString("[[\"claim1\", \"claim3\"], [\"claim4\"]]").asJsonArray
// Act
val result = condition.evaluate(element, claimsContext)
// Assert
assertFalse(result)
}
@Test
fun `evaluate throws CompilerException when element is not a 2D array`() {
// Arrange
val condition = ClaimSelectorCondition()
val claimsContext = object : ClaimsCompilerContext {
override val final: Boolean = false
override val config: CompilerConfig get() = throw NotImplementedError()
override val claims: List<String> = listOf("claim1", "claim2")
}
val element = JsonParser.parseString("[\"claim1\", \"claim2\"]").asJsonArray
// Act
assertThrows<CompilerException> { condition.evaluate(element, claimsContext) }
// CompilerException expected
}
@Test
fun `evaluate throws ContextException when context is not ClaimsCompilerContext`() {
// Arrange
val condition = ClaimSelectorCondition()
val context = object : CompilerContext {
override val final: Boolean = false
override val config: CompilerConfig get() = throw NotImplementedError()
}
val element = JsonParser.parseString("[[\"claim1\", \"claim2\"]]").asJsonArray
// Act
assertThrows<ContextException> { condition.evaluate(element, context) }
// ContextException expected
}
@Test
fun `evaluate throws CompilerException when claims contain non-string values`() {
// Arrange
val condition = ClaimSelectorCondition()
val claimsContext = object : ClaimsCompilerContext {
override val final: Boolean = false
override val config: CompilerConfig get() = throw NotImplementedError()
override val claims: List<String> = listOf("claim1", "claim2")
}
val element = JsonParser.parseString("[[\"claim1\", 123], [\"claim2\"]]").asJsonArray
// Act
assertThrows<CompilerException> { condition.evaluate(element, claimsContext) }
// CompilerException expected
}
}
| 0
|
Kotlin
|
0
| 0
|
a129ec95d334fef9e71df370a2d8674042a5d4e7
| 3,794
|
JSON-Specialiser
|
Apache License 2.0
|
features/settings/src/main/java/com/kape/settings/ui/screens/mobile/ExternalProxyAppList.kt
|
pia-foss
| 808,533,574
| false
|
{"Kotlin": 1249493}
|
package com.kape.settings.ui.screens.mobile
import android.graphics.drawable.Drawable
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import com.kape.appbar.view.mobile.AppBar
import com.kape.appbar.viewmodel.AppBarViewModel
import com.kape.settings.ui.elements.ReconnectDialog
import com.kape.settings.ui.vm.SettingsViewModel
import com.kape.ui.R
import com.kape.ui.mobile.elements.Search
import com.kape.ui.utils.LocalColors
import org.koin.androidx.compose.koinViewModel
@Composable
fun ExternalProxyAppList() {
val packageManager = LocalContext.current.packageManager
val viewModel: SettingsViewModel = koinViewModel<SettingsViewModel>().apply {
getInstalledApplications(packageManager)
}
val appBarViewModel: AppBarViewModel = koinViewModel<AppBarViewModel>().apply {
appBarText(stringResource(id = R.string.proxy_selection_title))
}
val lastExcludedApps = remember { viewModel.vpnExcludedApps.value.map { it } }
BackHandler {
onBackPressed(viewModel, lastExcludedApps)
}
Scaffold(
topBar = {
AppBar(
viewModel = appBarViewModel,
onLeftIconClick = {
onBackPressed(viewModel, lastExcludedApps)
},
)
},
) {
Column(
Modifier
.padding(it)
.fillMaxHeight()
.background(LocalColors.current.background),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Column(modifier = Modifier.widthIn(max = 520.dp)) {
Search(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
) {
viewModel.filterAppsByName(it, packageManager)
}
LazyColumn {
val items = viewModel.appList.value
items(items.size) { index ->
val item = items[index]
val isSelected =
viewModel.externalProxyAppPackageName.value == item.packageName
ApplicationRow(
icon = item.loadIcon(packageManager),
name = item.loadLabel(packageManager).toString(),
isSelected = isSelected,
onClick = { name, isChecked ->
if (isChecked) {
viewModel.setExternalProxyAppPackageName(item.packageName)
viewModel.showExternalProxyTcpDialogIfNeeded()
} else {
viewModel.setExternalProxyAppPackageName("")
}
},
)
}
}
}
}
if (viewModel.reconnectDialogVisible.value) {
ReconnectDialog(
onReconnect = {
viewModel.reconnect()
viewModel.reconnectDialogVisible.value = false
viewModel.navigateUp()
},
onLater = {
viewModel.reconnectDialogVisible.value = false
viewModel.navigateUp()
},
)
}
}
}
@Composable
private fun ApplicationRow(
icon: Drawable,
name: String,
isSelected: Boolean,
onClick: (name: String, isSelected: Boolean) -> Unit,
) {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.defaultMinSize(minHeight = 56.dp)
.clickable {
onClick(name, !isSelected)
},
) {
val (image, text, button) = createRefs()
Icon(
painter = rememberDrawablePainter(drawable = icon),
contentDescription = null,
tint = Color.Unspecified,
modifier = Modifier
.constrainAs(image) {
start.linkTo(parent.start, margin = 16.dp)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}
.size(48.dp),
)
Text(
text = name,
textAlign = TextAlign.Start,
modifier = Modifier
.constrainAs(text) {
start.linkTo(image.end, margin = 16.dp)
end.linkTo(button.start, margin = 16.dp)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
width = Dimension.fillToConstraints
},
)
SelectedCheckBox(
checked = isSelected,
modifier = Modifier.constrainAs(button) {
end.linkTo(parent.end, margin = 16.dp)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
},
)
}
}
@Composable
private fun SelectedCheckBox(checked: Boolean, modifier: Modifier) {
Icon(
painter = painterResource(id = com.kape.settings.R.drawable.ic_check),
contentDescription = null,
tint = if (checked) LocalColors.current.primary else Color.Transparent,
modifier = modifier.size(24.dp),
)
}
private fun onBackPressed(viewModel: SettingsViewModel, lastExcludedApps: List<String>) {
if (viewModel.isConnected() && lastExcludedApps != viewModel.vpnExcludedApps.value) {
viewModel.showReconnectDialogIfVpnConnected()
} else {
viewModel.navigateUp()
}
}
| 3
|
Kotlin
|
0
| 4
|
151ea781036e280fcbfecfcb5716c7881fc802c1
| 6,893
|
mobile-android
|
MIT License
|
app/src/test/java/com/jeanca/mapsapp/utils/JsonReader.kt
|
hajc1294
| 745,624,364
| false
|
{"Kotlin": 41854}
|
package com.jeanca.mapsapp.utils
import com.jeanca.mapsapp.commons.Constants.DATA_TEST_PATH
import java.io.File
import java.io.FileInputStream
object JsonReader {
fun readDataFromJsonFile(filename: String): String {
val file = File("$DATA_TEST_PATH/$filename")
return if (file.exists()) FileInputStream(file).bufferedReader().use { it.readText() }
else String()
}
}
| 0
|
Kotlin
|
0
| 0
|
3de4c6abf062938317c704e70c07d9b0b5b16520
| 400
|
KotlinMapsApp
|
MIT License
|
server/src/main/kotlin/org/octopusden/octopus/releasemanagementservice/ReleaseManagementServiceApplication.kt
|
octopusden
| 768,499,841
| false
|
{"Kotlin": 66993, "Java": 3146}
|
package org.octopusden.octopus.releasemanagementservice
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
@SpringBootApplication
@ConfigurationPropertiesScan
class ReleaseManagementServiceApplication
fun main(args: Array<String>) {
SpringApplication.run(ReleaseManagementServiceApplication::class.java, *args)
}
| 0
|
Kotlin
|
0
| 0
|
84169206296deecd85f7f954252619611f7128ad
| 466
|
octopus-release-management-service
|
Apache License 2.0
|
app/src/main/java/com/example/inventory/model/StockViewModel.kt
|
wenvelope
| 538,791,409
| false
| null |
package com.example.inventory.model
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.inventory.MyApplication
import com.example.inventory.bean.MaterialByRe
import com.example.inventory.repository.Repository
import com.example.inventory.room.InventoryDataBase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class StockViewModel:ViewModel() {
private val dataBase: InventoryDataBase by lazy { InventoryDataBase.getDataBase(MyApplication.context)}
private val repository: Repository by lazy { Repository(dataBase.materialDao()) }
suspend fun selectMaterialListByRe(uid:String): Result<MaterialByRe> {
val response = withContext(Dispatchers.IO){
Repository.selectAllByRe(uid)
}
return response
}
}
| 0
|
Kotlin
|
0
| 1
|
d2fa3c4aa7fa478e57bfff76754919a762c86687
| 945
|
Inventory
|
MIT License
|
app/src/main/java/fr/uge/mobistory/DailyEventService.kt
|
tvelu77
| 838,054,968
| false
|
{"Kotlin": 118530}
|
package fr.uge.mobistory
import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.compose.ui.platform.LocalContext
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.util.rangeTo
import fr.uge.mobistory.database.DatabaseManager
import fr.uge.mobistory.database.entity.Event
import fr.uge.mobistory.localstorage.AppConfig
import fr.uge.mobistory.utils.toLocalDate
import java.sql.Timestamp
import java.time.LocalDate
import java.util.Calendar
import java.util.Date
class DailyEventService : Service() {
var appDatabase : DatabaseManager? = null
private var notificationId: Int = 100000
private val CHANNEL_ID = "MobyStoryDailyEventService"
private val LAST_EVENT_NOTIFY_KEY = "NOTIFICATION_DAILY_EVENT"
private var notifierThread : Thread? = null
private val checkDelay = 30_000L
override fun onBind(arg0: Intent?): IBinder? {
return null
}
/**
* Create the notification channel
*/
private fun createNotificationChannel() {
val name: CharSequence = "Daily event notifier channel"
val descriptionText = "Channel for the daily event notification of MobyStory"
val importance: Int = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
override fun onCreate() {
createNotificationChannel()
val context = this
appDatabase = DatabaseManager(context)
}
/**
* Create the daily event notification
*/
private fun createDailyEventNotification(event: Event): Notification {
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
action = DAILY_EVENT_NOTIFIER_ACTION
putExtra("idE", event.id.toString())
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.mobystorylogo)
.setContentTitle(getString(R.string.notif_daily_event_title))
.setContentText(getString(R.string.notif_daily_event_short))
.setStyle(NotificationCompat.BigTextStyle()
.bigText(getString(R.string.notif_daily_event_long, event.beginDate, event.title)))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
return builder.build()
}
/**
* Call on service start with the intent
*/
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
notifierThread = Thread(){
val context = this
try{
while (!Thread.interrupted()) {
val appConfig = AppConfig(context)
// Check if functionality is activated
if(!appConfig.enableDailyEvent){
Thread.sleep(checkDelay)
continue
}
// Retrieve from shared preferences the last time notification
val preferences = context.getSharedPreferences(LAST_EVENT_NOTIFY_KEY, MODE_PRIVATE)
val lastEventTime = preferences.getLong(LAST_EVENT_NOTIFY_KEY, -1L)
val currentDate = LocalDate.now()
// If the cache is empty use the same date as now
if(lastEventTime != -1L){
val lastEventDate = LocalDate.ofEpochDay(lastEventTime)
//If it is not the first daily event of the application
if(currentDate.isEqual(lastEventDate)) {
Thread.sleep(checkDelay)
continue
}
}
val editor = preferences.edit()
editor.putLong(LAST_EVENT_NOTIFY_KEY, currentDate.toEpochDay())
editor.apply()
val notifiedEvent = appDatabase?.let { Utils.getDailyEvent(it, currentDate) }
// If a corresponding event was found then send the
if(notifiedEvent != null){
with(NotificationManagerCompat.from(context)) {
// notificationId is a unique int for each notification that you must define
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
notify(notificationId, createDailyEventNotification(notifiedEvent))
notificationId++
Log.i("DAILY EVENT", notifiedEvent.toString())
}
}
}
Thread.sleep(checkDelay)
}
}catch (e: InterruptedException){
Log.w("DAILY EVENT", "Daily event checker was interrupted: $e")
}
}
notifierThread?.start()
return START_REDELIVER_INTENT // Restart the service with the intent if it is destroyed
}
override fun onDestroy() {
notifierThread?.interrupt()
}
companion object {
val DAILY_EVENT_NOTIFIER_ACTION: String = DailyEventService::class.java.name + ".checkDailyEvent"
}
}
| 0
|
Kotlin
|
0
| 0
|
70f2548ef9bd00ca04165fcbcee18067f41b921f
| 6,417
|
mobistory
|
MIT License
|
app/src/main/java/ir/radical_app/radical/models/CategoryModel.kt
|
ShahabGT
| 183,623,208
| false
|
{"Java": 492194, "Kotlin": 25016}
|
package ir.radical_app.radical.models
import com.google.gson.annotations.SerializedName
data class CategoryModel(@SerializedName("data") val list:List<JsonResponse>,
val slider:List<SliderResponse>)
| 1
| null |
1
| 1
|
808eb22fd2e843a958c0e43f243b15ddeb9dbdbd
| 226
|
Radical
|
Apache License 2.0
|
uikit-samples/src/main/java/com/sendbird/uikit/samples/common/consts/Region.kt
|
sendbird
| 350,188,329
| false
|
{"Java": 2425698, "Kotlin": 1378512}
|
package com.sendbird.uikit.samples.common.consts
enum class Region {
PRODUCTION,
PREPROD,
NO1,
NO2,
NO3,
NO4
;
}
| 1
|
Java
|
43
| 39
|
c2f6aa7f37fb1428a96f3d93cf05e736e3659351
| 142
|
sendbird-uikit-android
|
MIT License
|
codebase/android/core-datastore/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/datastore/MyDataStore.kt
|
Abhimanyu14
| 429,663,688
| false
| null |
package com.makeappssimple.abhimanyu.financemanager.android.core.datastore
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import com.makeappssimple.abhimanyu.financemanager.android.core.common.constants.APP_NAME
import kotlinx.coroutines.flow.Flow
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
name = APP_NAME,
)
interface MyDataStore {
fun getDefaultExpenseCategoryIdFromDataStore(): Flow<Int?>
suspend fun setDefaultExpenseCategoryIdInDataStore(
defaultExpenseCategoryId: Int,
)
fun getDefaultIncomeCategoryIdFromDataStore(): Flow<Int?>
suspend fun setDefaultIncomeCategoryIdInDataStore(
defaultIncomeCategoryId: Int,
)
fun getDefaultInvestmentCategoryIdFromDataStore(): Flow<Int?>
suspend fun setDefaultInvestmentCategoryIdInDataStore(
defaultInvestmentCategoryId: Int,
)
fun getDefaultSourceIdFromDataStore(): Flow<Int?>
suspend fun setDefaultSourceIdInDataStore(
defaultSourceId: Int,
)
fun getLastDataBackupTimestamp(): Flow<Long?>
suspend fun setLastDataBackupTimestamp(
lastChangeTimestamp: Long,
)
fun getLastDataChangeTimestamp(): Flow<Long?>
suspend fun setLastDataChangeTimestamp(
lastChangeTimestamp: Long,
)
suspend fun updateLastDataBackupTimestamp(
timestamp: Long = System.currentTimeMillis(),
)
suspend fun updateLastDataChangeTimestamp(
timestamp: Long = System.currentTimeMillis(),
)
}
| 0
|
Kotlin
|
0
| 0
|
29afaec0cf4e95ba4d6c0dcc32cba3fea6a088cb
| 1,642
|
finance-manager
|
Apache License 2.0
|
prodigy/src/main/java/ds/prodigy/Result.kt
|
deviant-studio
| 68,241,792
| false
|
{"Gradle": 5, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 26, "Kotlin": 38, "Java": 14, "Java Properties": 1}
|
package ds.prodigy
class Result<T : Any>(var owner: Presenter<*>, val resultType: Class<T>, val callback: (T?) -> Unit) {
var result: T? = null
}
| 0
|
Kotlin
|
0
| 3
|
076e13cb98196245f61dec3f2e9b13322a41a3cc
| 151
|
Prodigy-Framework
|
Apache License 2.0
|
cryptography-providers/openssl3/api/src/commonMain/kotlin/algorithms/Openssl3Aes.kt
|
whyoleg
| 492,907,371
| false
|
{"Kotlin": 1074574, "JavaScript": 318}
|
/*
* Copyright (c) 2023-2024 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.whyoleg.cryptography.providers.openssl3.algorithms
import dev.whyoleg.cryptography.*
import dev.whyoleg.cryptography.BinarySize.Companion.bytes
import dev.whyoleg.cryptography.algorithms.*
import dev.whyoleg.cryptography.materials.key.*
import dev.whyoleg.cryptography.random.*
internal abstract class Openssl3Aes<K : AES.Key> : AES<K> {
protected abstract fun wrapKey(keySize: BinarySize, key: ByteArray): K
private val keyDecoder = AesKeyDecoder()
final override fun keyDecoder(): KeyDecoder<AES.Key.Format, K> = keyDecoder
final override fun keyGenerator(keySize: BinarySize): KeyGenerator<K> = AesKeyGenerator(keySize)
private fun requireAesKeySize(keySize: BinarySize) {
require(keySize == AES.Key.Size.B128 || keySize == AES.Key.Size.B192 || keySize == AES.Key.Size.B256) {
"AES key size must be 128, 192 or 256 bits"
}
}
private inner class AesKeyDecoder : KeyDecoder<AES.Key.Format, K> {
override fun decodeFromByteArrayBlocking(format: AES.Key.Format, bytes: ByteArray): K = when (format) {
AES.Key.Format.RAW -> {
val keySize = bytes.size.bytes
requireAesKeySize(keySize)
wrapKey(keySize, bytes.copyOf())
}
AES.Key.Format.JWK -> error("JWK is not supported")
}
}
private inner class AesKeyGenerator(
private val keySize: BinarySize,
) : KeyGenerator<K> {
init {
requireAesKeySize(keySize)
}
override fun generateKeyBlocking(): K {
val key = CryptographyRandom.nextBytes(keySize.inBytes)
return wrapKey(keySize, key)
}
}
protected abstract class AesKey(
protected val key: ByteArray,
) : AES.Key {
final override fun encodeToByteArrayBlocking(format: AES.Key.Format): ByteArray = when (format) {
AES.Key.Format.RAW -> key.copyOf()
AES.Key.Format.JWK -> error("JWK is not supported")
}
}
}
| 10
|
Kotlin
|
20
| 302
|
69b77a88b4b81109704475ed02be48d263d1a1c8
| 2,134
|
cryptography-kotlin
|
Apache License 2.0
|
app/src/main/java/com/brins/lightmusic/utils/ShowShadowUtil.kt
|
BrinsLee
| 193,304,333
| false
| null |
package com.brins.lightmusic.utils
import android.graphics.*
import android.graphics.drawable.Drawable
import android.view.View
import androidx.core.view.ViewCompat
class ShowShadowUtil(
var mShape: Int, var mBgColor: IntArray,
var mShadowRadius: Float,var shadowColor: Int = 0, var mShapeRadius: Float,
var mOffsetX: Float, var mOffsetY: Float
) : Drawable() {
companion object{
val SHAPE_ROUND = 1
val SHAPE_CIRCLE = 2
fun setShadowDrawable(
view: View,
shapeRadius: Float,
shadowColor: Int,
shadowRadius: Float,
offsetX: Float,
offsetY: Float
) {
val drawable = Builder()
.setShapeRadius(shapeRadius)
.setShadowColor(shadowColor)
.setShadowRadius(shadowRadius)
.setOffsetX(offsetX)
.setOffsetY(offsetY)
.builder()
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
ViewCompat.setBackground(view, drawable)
}
fun setShadowDrawable(
view: View,
bgColor: Int,
shapeRadius: Float,
shadowColor: Int,
shadowRadius: Float,
offsetX: Float,
offsetY: Float
) {
val drawable = Builder()
.setBgColor(bgColor)
.setShapeRadius(shapeRadius)
.setShadowColor(shadowColor)
.setShadowRadius(shadowRadius)
.setOffsetX(offsetX)
.setOffsetY(offsetY)
.builder()
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
ViewCompat.setBackground(view, drawable)
}
fun setShadowDrawable(
view: View,
shape: Int,
bgColor: Int,
shapeRadius: Float,
shadowColor: Int,
shadowRadius: Float,
offsetX: Float,
offsetY: Float
) {
val drawable = Builder()
.setShape(shape)
.setBgColor(bgColor)
.setShapeRadius(shapeRadius)
.setShadowColor(shadowColor)
.setShadowRadius(shadowRadius)
.setOffsetX(offsetX)
.setOffsetY(offsetY)
.builder()
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
ViewCompat.setBackground(view, drawable)
}
fun setShadowDrawable(
view: View,
bgColor: IntArray,
shapeRadius: Float,
shadowColor: Int,
shadowRadius: Float,
offsetX: Float,
offsetY: Float
) {
val drawable = Builder()
.setBgColor(bgColor)
.setShapeRadius(shapeRadius)
.setShadowColor(shadowColor)
.setShadowRadius(shadowRadius)
.setOffsetX(offsetX)
.setOffsetY(offsetY)
.builder()
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
ViewCompat.setBackground(view, drawable)
}
class Builder {
private var mShape: Int = 0
private var mShapeRadius: Float = 0f
private var mShadowColor: Int = 0
private var mShadowRadius: Float = 0f
private var mOffsetX = 0f
private var mOffsetY = 0f
private var mBgColor: IntArray
init {
mShape = SHAPE_ROUND
mShapeRadius = 12f
mShadowColor = Color.parseColor("#4d000000")
mShadowRadius = 18f
mBgColor = IntArray(1)
mBgColor[0] = Color.TRANSPARENT
}
fun setShape(mShape: Int): Builder {
this.mShape = mShape
return this
}
fun setShapeRadius(ShapeRadius: Float): Builder {
this.mShapeRadius = ShapeRadius
return this
}
fun setShadowColor(shadowColor: Int): Builder {
this.mShadowColor = shadowColor
return this
}
fun setShadowRadius(shadowRadius: Float): Builder {
this.mShadowRadius = shadowRadius
return this
}
fun setOffsetX(OffsetX: Float): Builder {
this.mOffsetX = OffsetX
return this
}
fun setOffsetY(OffsetY: Float): Builder {
this.mOffsetY = OffsetY
return this
}
fun setBgColor(BgColor: Int): Builder {
this.mBgColor[0] = BgColor
return this
}
fun setBgColor(BgColor: IntArray): Builder {
this.mBgColor = BgColor
return this
}
fun builder(): ShowShadowUtil {
return ShowShadowUtil(
mShape,
mBgColor,
mShapeRadius,
mShadowColor,
mShadowRadius,
mOffsetX,
mOffsetY
)
}
}
}
var mShadowPaint = Paint()
var mBgPaint = Paint()
private lateinit var mRect: RectF
init {
mShadowPaint.color = Color.TRANSPARENT
mShadowPaint.isAntiAlias = true
mShadowPaint.setShadowLayer(mShadowRadius, mOffsetX, mOffsetY, shadowColor)
mShadowPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_ATOP)
mBgPaint.isAntiAlias = true
}
override fun setBounds(left: Int, top: Int, right: Int, bottom: Int) {
super.setBounds(left, top, right, bottom)
mRect = RectF(
left + mShadowRadius - mOffsetX, top + mShadowRadius - mOffsetY, right - mShadowRadius - mOffsetX,
bottom - mShadowRadius - mOffsetY
)
}
override fun draw(canvas: Canvas) {
if (mBgColor.size == 1) {
mBgPaint.color = mBgColor[0]
} else {
mBgPaint.shader = LinearGradient(
mRect.left, mRect.height() / 2, mRect.right
, mRect.height() / 2, mBgColor, null, Shader.TileMode.CLAMP
)
}
if (mShape == SHAPE_ROUND) {
canvas.drawRoundRect(mRect, mShapeRadius.toFloat(), mShapeRadius.toFloat(), mShadowPaint)
canvas.drawRoundRect(mRect, mShapeRadius.toFloat(), mShapeRadius.toFloat(), mBgPaint)
} else {
canvas.drawCircle(
mRect.centerX(),
mRect.centerY(),
Math.min(mRect.width(), mRect.height()) / 2,
mShadowPaint
)
canvas.drawCircle(mRect.centerX(), mRect.centerY(), Math.min(mRect.width(), mRect.height()) / 2, mBgPaint)
}
}
override fun setAlpha(alpha: Int) {
mShadowPaint.alpha = alpha
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
override fun setColorFilter(colorFilter: ColorFilter?) {
}
}
| 1
|
Kotlin
|
3
| 20
|
f0be073b901efdee40d38824bc3c0cc4d6aa426d
| 7,176
|
LightMusic
|
Apache License 2.0
|
src/main/kotlin/org/wint3794/ftc/pathfollower/debug/telemetries/SimulatorSender.kt
|
WinT-3794
| 267,687,048
| false
| null |
package org.wint3794.ftc.pathfollower.debug.telemetries
import org.wint3794.ftc.pathfollower.controllers.Robot
import org.wint3794.ftc.pathfollower.debug.DebugConfiguration
import org.wint3794.ftc.pathfollower.geometry.Point
import org.wint3794.ftc.pathfollower.geometry.Pose2d
import org.wint3794.ftc.pathfollower.util.Constants
import java.net.UnknownHostException
import java.text.DecimalFormat
class SimulatorSender(config: DebugConfiguration) {
companion object {
private lateinit var udpServer: UdpServer
private var messageBuilder = StringBuilder()
private var debug = false
private val df = DecimalFormat("#.00")
fun sendRobotLocation(robot: Pose2d) {
if (!debug) {
return
}
messageBuilder.append("ROBOT,")
messageBuilder.append(
df.format(robot.x))
messageBuilder.append(",")
messageBuilder.append(
df.format(robot.y))
messageBuilder.append(",")
messageBuilder.append(
df.format(robot.angle))
messageBuilder.append("%")
}
fun sendKeyPoint(floatPoint: Point) {
if (!debug) {
return
}
messageBuilder.append("P,")
.append(df.format(floatPoint.x))
.append(",")
.append(df.format(floatPoint.y))
.append("%")
}
fun sendLogPoint(floatPoint: Point) {
if (!debug) {
return
}
messageBuilder.append("LP,")
.append(df.format(floatPoint.x))
.append(",")
.append(df.format(floatPoint.y))
.append("%")
}
fun sendLine(
point1: Point,
point2: Point
) {
if (!debug) {
return
}
messageBuilder.append("LINE,")
.append(df.format(point1.x))
.append(",")
.append(df.format(point1.y))
.append(",")
.append(df.format(point2.x))
.append(",")
.append(df.format(point2.y))
.append("%")
}
fun markEndOfUpdate() {
if (!debug) {
return
}
messageBuilder.append("CLEAR,%")
udpServer.send(
messageBuilder.toString())
messageBuilder = StringBuilder()
}
fun clearLogPoints() {
if (!debug) {
return
}
udpServer.send("CLEARLOG,%")
}
}
init {
UdpServer.isRunning = config.debug
debug = config.debug
try {
udpServer = if (config.ip == "") {
UdpServer(config.port)
} else {
UdpServer(config.ip, config.port)
}
} catch (e: UnknownHostException) {
e.printStackTrace()
}
val runner = Thread(udpServer)
if (config.debug) {
runner.start()
}
}
}
| 0
|
Kotlin
|
1
| 0
|
8b05c46ddc25317158c9cf92ce9c68fd3e1b9c6e
| 3,184
|
PathFollower
|
Apache License 2.0
|
src/main/kotlin/dex/Leb128.kt
|
changchengfeng
| 687,293,199
| false
|
{"Kotlin": 131482}
|
package dex
import dex.toByteString
import dex.toInt
import okio.ByteString.Companion.toByteString
import okio.buffer
import okio.sink
import okio.source
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.util.Base64.Decoder
import kotlin.experimental.and
import kotlin.experimental.or
fun main() {
// println(" encodeToLeb128(624485) = ${encodeToLeb128(624485).toByteString()}")
// println(" encodeToLeb128(-123456) = ${encodeToLeb128(-123456).toByteString()}")
// println(" encodeToLeb128(2097151) = ${encodeToLeb128(2097151).toByteString()}")
// println(" encodeToLeb128(-2097151) = ${encodeToLeb128(-2097151).toByteString()}")
//
//
// var byteArrayOutputStream = ByteArrayOutputStream(5)
// byteArrayOutputStream.sink().buffer().writeSignedLeb128(2097151)
// println(byteArrayOutputStream.toByteArray().toByteString())
//
// byteArrayOutputStream = ByteArrayOutputStream(5)
// byteArrayOutputStream.sink().buffer().writeSignedLeb128(-2097151)
// println(byteArrayOutputStream.toByteArray().toByteString())
// println("encodeToLeb128(624485) = ${encodeToLeb128(624485).toByteString()} ${decoder(encodeToLeb128(624485))}")
// println("encodeToLeb128(-123456) = ${encodeToLeb128(-123456).toByteString()} ${decoder(encodeToLeb128(-123456))}")
//
// println("encodeToLeb128(2097151) = ${encodeToLeb128(2097151).toByteString()} ${decoder(encodeToLeb128(2097151))}")
// println("encodeToLeb128(-2097151) = ${encodeToLeb128(-2097151).toByteString()} ${decoder(encodeToLeb128(-2097151))}")
// println("encodeToLeb128(-10000) = ${encodeToLeb128(-10000).toByteString()} ${decoder(encodeToLeb128(-10000))}")
}
fun encodeToLeb128(value: Int) =
if (value >= 0) {
val size = calSize(value)
val bytes = ByteArray(size)
encode(size, bytes, value)
} else {
val size = calSize(-value)
val temp = -value
val bytes = ByteArray(size)
var toInt = 0
for (it in size - 1 downTo 0) {
bytes[it] = (((temp shr (it * 7)).inv()) and 0x7F).toByte()
toInt += (bytes[it].toInt() shl (it * 7))
}
toInt = (toInt + 1)
encode(size, bytes, toInt)
}
private fun encode(size: Int, bytes: ByteArray, value: Int): ByteArray {
for (it in size - 1 downTo 0) {
bytes[it] = (value shr (it * 7) and 0x7F).toByte()
if (it != (size - 1)) {
bytes[it] = bytes[it] or 0x80.toByte()
}
}
return bytes
}
private fun calSize(value: Int): Int {
var temp = value
var bit = 1
while ((temp shr 1) > 0) {
temp = temp shr 1
bit++
}
return (bit / 7 + 1)
}
fun decoder(bytes: ByteArray): Int {
var sum = 0
var size = 0
var temp: Int
for (it in bytes.indices) {
temp = (bytes[it] and 0xFF.toByte()).toInt()
if ((temp and 0x80) == 0x80) {
sum += (temp and 0x7f shl (it * 7))
size++
} else {
sum += (temp and 0x7f shl (it * 7))
size++
break
}
}
if ((sum shr (size * 7 - 1)) > 0) {
sum = sum - 1
sum = sum.inv() and ((1 shl (size * 7)) - 1)
sum = -sum
}
return sum
}
fun ByteBuffer.readSignLeb128(): Int {
var sum = 0
var size = 0
var temp: Int
while (true) {
temp = (get() and 0xFF.toByte()).toInt()
if ((temp and 0x80) == 0x80) {
sum += (temp and 0x7f shl (size * 7))
size++
} else {
sum += (temp and 0x7f shl (size * 7))
size++
break
}
}
if ((sum shr (size * 7 - 1)) > 0) {
sum = sum - 1
sum = sum.inv() and ((1 shl (size * 7)) - 1)
sum = -sum
}
return sum
}
fun ByteBuffer.readULeb128(): Int {
var sum = 0
var size = 0
var temp: Int
while (true) {
temp = (get() and 0xFF.toByte()).toInt()
if ((temp and 0x80) == 0x80) {
sum += (temp and 0x7f shl (size * 7))
size++
} else {
sum += (temp and 0x7f shl (size * 7))
size++
break
}
}
return sum
}
| 0
|
Kotlin
|
0
| 0
|
ae3c8850dc66460bdf813391157fd8c2fb7b8deb
| 4,224
|
DexParser
|
Apache License 2.0
|
app/src/main/java/com/pelisapp/core/PreferencesApi.kt
|
UTN-FRBA-Mobile
| 366,484,889
| false
| null |
package com.pelisapp.core
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.ktx.database
import com.google.firebase.database.ktx.getValue
import com.google.firebase.ktx.Firebase
class PreferencesApi {
private val database = Firebase.database
private val preferencesRef = database.getReference("preferences")
fun saveUserPreferenceIntoFirebase(userName: String, preference: Preference){
val ref = preferencesRef.child(userName)
ref.setValue(preference)
}
fun getAllPreferencesFromFirebase(listener: PreferencesListener){
preferencesRef.addValueEventListener(object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
var preferences = snapshot.getValue<HashMap<String, Preference>>()
listener.onPreferencesReceived(preferences)
}
override fun onCancelled(error: DatabaseError) {
println("Failed to read value from Firebase Realtime Database")
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
68a68ae9bde73e614dfa1f0c9ffd154f218c4712
| 1,169
|
PelisApp
|
MIT License
|
wasi-emscripten-host/src/jvmMain/kotlin/jvm/filesystem/nio/NioMkdir.kt
|
illarionov
| 769,429,996
| false
|
{"Kotlin": 1653596}
|
/*
* 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.jvm.filesystem.nio
import arrow.core.Either
import arrow.core.getOrElse
import arrow.core.left
import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.op.Mkdir
import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.op.MkdirError
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.ResolvePathError
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.ResolvePathError.EmptyPath
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.ResolvePathError.FileDescriptorNotOpen
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.ResolvePathError.InvalidPath
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.ResolvePathError.NotDirectory
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.ResolvePathError.RelativePath
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.asFileAttribute
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.resolvePath
import ru.pixnews.wasm.sqlite.open.helper.host.jvm.filesystem.ext.toPosixFilePermissions
import java.io.IOException
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Files
import java.nio.file.Path
internal class NioMkdir(
private val fsState: JvmFileSystemState,
) : NioOperationHandler<Mkdir, MkdirError, Unit> {
override fun invoke(input: Mkdir): Either<MkdirError, Unit> {
val path: Path = fsState.resolvePath(input.path, input.baseDirectory, false)
.mapLeft { it.toMkdirError() }
.getOrElse { return it.left() }
return Either.catch {
Files.createDirectory(path, input.mode.toPosixFilePermissions().asFileAttribute())
Unit
}.mapLeft {
when (it) {
is UnsupportedOperationException -> MkdirError.PermissionDenied("Unsupported file mode")
is FileAlreadyExistsException -> MkdirError.Exist("`$path` exists")
is IOException -> MkdirError.IoError("I/O error: ${it.message}")
else -> throw IllegalStateException("Unexpected error", it)
}
}
}
internal companion object {
fun ResolvePathError.toMkdirError(): MkdirError = when (this) {
is EmptyPath -> MkdirError.InvalidArgument(message)
is FileDescriptorNotOpen -> MkdirError.BadFileDescriptor(message)
is InvalidPath -> MkdirError.InvalidArgument(message)
is NotDirectory -> MkdirError.NotDirectory(message)
is RelativePath -> MkdirError.InvalidArgument(message)
}
}
}
| 0
|
Kotlin
|
0
| 3
|
546dc6fce69d2d3704ddf34939ab498931b2d047
| 2,885
|
wasm-sqlite-open-helper
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.