path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/swiftbargain/ui/composable/ContentLoading.kt
|
ahmedfikry24
| 814,676,783
| false
|
{"Kotlin": 480967}
|
package com.example.swiftbargain.ui.composable
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition
import com.example.swiftbargain.R
@Composable
fun ContentLoading(isVisible: Boolean) {
val size = (LocalConfiguration.current.screenWidthDp / 2).dp
AnimatedVisibility(
modifier = Modifier.fillMaxSize(),
visible = isVisible,
enter = fadeIn(tween(500)) + scaleIn(tween(500)),
exit = fadeOut(tween(500)) + scaleOut(tween(500)),
) {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.lottie_loading))
LottieAnimation(
modifier = Modifier.size(size),
composition = composition,
iterations = LottieConstants.IterateForever
)
}
}
| 0
|
Kotlin
|
0
| 0
|
c83e040911380b9f75e35007fff4d04433da7e1e
| 1,497
|
SwiftBargain
|
MIT License
|
src/main/kotlin/cn/lkgc/jjl/framework/utils/PageResultUtils.kt
|
mirrorb
| 862,651,819
| false
|
{"Kotlin": 144419, "Java": 24940, "Batchfile": 123}
|
package cn.lkgc.jjl.framework.utils
import cn.lkgc.jjl.framework.pojo.PageResult
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
object PageResultUtils {
fun <T> empty(): PageResult<T> {
return PageResult(emptyList(), 0L)
}
fun <T> empty(total: Long): PageResult<T> {
return PageResult(emptyList(), total)
}
fun <T> from(page: Page<T>): PageResult<T> {
return PageResult(page.records, page.total)
}
}
| 0
|
Kotlin
|
0
| 1
|
8b2d574c2cfb97a01e6f9868ab80c77f444d7924
| 470
|
jjl-housekeeping
|
Apache License 2.0
|
plugins-dev/src/main/java/org/runestar/client/plugins/dev/PrayerDebug.kt
|
forsco
| 246,016,204
| true
|
{"Kotlin": 1368739, "Java": 984619}
|
package org.runestar.client.plugins.dev
import org.runestar.client.api.util.DisposablePlugin
import org.runestar.client.api.Fonts
import org.runestar.client.game.api.Prayer
import org.runestar.client.game.api.live.LiveCanvas
import org.runestar.client.game.api.live.Prayers
import org.runestar.client.plugins.spi.PluginSettings
import java.awt.Color
class PrayerDebug : DisposablePlugin<PluginSettings>() {
override val defaultSettings = PluginSettings()
override fun onStart() {
add(LiveCanvas.repaints.subscribe { g ->
val x = 5
var y = 40
g.font = Fonts.PLAIN_12
g.color = Color.WHITE
val strings = ArrayList<String>()
Prayer.values().filter { Prayers.isEnabled(it) }.mapTo(strings) { it.toString() }
strings.forEach { s ->
g.drawString(s, x, y)
y += g.font.size + 5
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
b15c07570af82377bcd2be48b00a5e9708be08ab
| 938
|
client
|
MIT License
|
domain-access/src/main/java/pl/kamilszustak/read/domain/access/usecase/user/GetUserUseCase.kt
|
swistak7171
| 289,985,013
| false
| null |
package pl.kamilszustak.read.domain.access.usecase.user
import pl.kamilszustak.read.domain.access.usecase.UseCase
import pl.kamilszustak.read.model.domain.user.User
interface GetUserUseCase : UseCase<User>
| 2
|
Kotlin
|
0
| 1
|
70d7be58042410bdb969035413b726126426e3d3
| 207
|
read
|
Apache License 2.0
|
net/src/main/java/com/tans/tfiletransporter/transferproto/p2pconn/P2pConnectionState.kt
|
Tans5
| 329,625,887
| false
|
{"Kotlin": 485795, "Java": 29868}
|
package com.tans.tfiletransporter.transferproto.p2pconn
import java.net.InetSocketAddress
sealed class P2pConnectionState {
object NoConnection : P2pConnectionState()
object Requesting : P2pConnectionState()
class Active(
val localAddress: InetSocketAddress?,
val remoteAddress: InetSocketAddress?
) : P2pConnectionState()
data class Handshake(
val localAddress: InetSocketAddress,
val remoteAddress: InetSocketAddress,
val remoteDeviceName: String
) : P2pConnectionState()
}
| 0
|
Kotlin
|
14
| 78
|
1734b4c556f425fabc0df6c69292366df37073b6
| 545
|
tFileTransporter
|
Apache License 2.0
|
src/main/kotlin/io/github/clivelewis/assistant/tts/TtsService.kt
|
clivelewis
| 781,393,282
| false
|
{"Kotlin": 78719}
|
package io.github.clivelewis.assistant.tts
interface TtsService {
fun generateTts(text: String): ByteArray?
}
| 0
|
Kotlin
|
0
| 0
|
26eb6405e781f51531099e5c6f5728c5459483c4
| 115
|
sam
|
Apache License 2.0
|
app/src/main/java/com/smparkworld/hiltbinderexample/sample/intomap/hiltdefault/stringkey/MapStringKeySampleModelImpl3.kt
|
Park-SM
| 502,595,266
| false
| null |
package com.smparkworld.hiltbinderexample.sample.intomap.hiltdefault.stringkey
import android.util.Log
import com.smparkworld.hiltbinder.HiltMapBinds
import dagger.multibindings.StringKey
import javax.inject.Inject
@HiltMapBinds
@StringKey("model3")
class MapStringKeySampleModelImpl3 @Inject constructor(
private val testString: String
) : MapStringKeySampleModel {
override fun printTestString() {
Log.d("Test!!", "TestString is `$testString` in MapStringKeySampleModelImpl3 class.")
}
}
| 0
|
Kotlin
|
0
| 5
|
cdb20e8bf340384c1a5ec6917d86d5cde74dc49b
| 512
|
HiltBinder
|
Apache License 2.0
|
app/src/main/java/br/com/joaovq/mydailypet/MainActivity.kt
|
joaovq
| 650,739,082
| false
|
{"Kotlin": 326547, "Ruby": 1076}
|
package br.com.joaovq.mydailypet
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.lifecycleScope
import br.com.joaovq.core.data.datastore.DARKMODE_PREFERENCE_KEY
import br.com.joaovq.core.data.datastore.PreferencesManager
import br.com.joaovq.core.data.datastore.setNightThemeApp
import br.com.joaovq.mydailypet.databinding.ActivityMainBinding
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.appupdate.AppUpdateOptions
import com.google.android.play.core.install.InstallStateUpdatedListener
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability
import com.google.android.play.core.ktx.isFlexibleUpdateAllowed
import com.google.android.play.core.ktx.isImmediateUpdateAllowed
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
import com.google.android.play.core.install.model.ActivityResult as PlayActivityResult
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val log = Timber.tag(this::class.java.simpleName)
private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
private val viewModel by viewModels<MainViewModel>()
private var updateType: Int = AppUpdateType.FLEXIBLE
private val appUpdateManager by lazy {
AppUpdateManagerFactory.create(applicationContext).apply {
if (updateType == AppUpdateType.FLEXIBLE) {
registerListener(installUpdateStateListener)
}
}
}
private val updateResultLauncher = registerForActivityResult(
ActivityResultContracts.StartIntentSenderForResult()
) { result: ActivityResult ->
when {
result.resultCode == PlayActivityResult.RESULT_IN_APP_UPDATE_FAILED -> {}
result.resultCode != RESULT_OK -> {
log.e("Update flow failed! Result code: %s", result.resultCode);
// If the update is canceled or fails,
// you can request to start the update again.
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
super.onCreate(savedInstanceState)
setContentView(binding.root)
lifecycleScope.launch {
viewModel.isNewUser.collectLatest { isNewUser ->
splashScreen.setKeepOnScreenCondition { isNewUser == null }
}
}
lifecycleScope.launch { setNightTheme() }
checkUpdateAvailable()
}
private suspend fun setNightTheme() {
viewModel.isDarkPreference.collectLatest {
setNightThemeApp(it)
}
}
private val installUpdateStateListener = InstallStateUpdatedListener { installState ->
if (installState.totalBytesToDownload().toInt() == InstallStatus.DOWNLOADED) {
Toast.makeText(applicationContext, "Upload completed", Toast.LENGTH_SHORT).show()
}
}
private fun checkUpdateAvailable() {
val appUpdateInfoTask = appUpdateManager.appUpdateInfo
appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
val isUpdateAvailable =
appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
val isUpdateTypeAllowed = when (updateType) {
AppUpdateType.FLEXIBLE -> appUpdateInfo.isFlexibleUpdateAllowed
AppUpdateType.IMMEDIATE -> appUpdateInfo.isImmediateUpdateAllowed
else -> false
}
if (isUpdateAvailable && isUpdateTypeAllowed) {
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
updateResultLauncher,
AppUpdateOptions.newBuilder(updateType).build()
)
}
}
}
override fun onDestroy() {
super.onDestroy()
if (updateType == AppUpdateType.FLEXIBLE) {
appUpdateManager.unregisterListener(installUpdateStateListener)
}
}
}
| 1
|
Kotlin
|
0
| 0
|
ce80c4b481c996fc02c0f22689954edf8154d588
| 4,558
|
MyDailyPet
|
MIT License
|
Kotlin/lib/src/main/java/com/wolt/blurhashkt/BlurHashDecoder.kt
|
Darking360
| 196,459,756
| true
|
{"C": 255658, "Swift": 39551, "CSS": 24715, "TypeScript": 10682, "JavaScript": 8081, "HTML": 7883, "Shell": 6452, "Kotlin": 6028, "Java": 1094, "Makefile": 156}
|
package com.wolt.blurhashkt
import android.graphics.Bitmap
import android.graphics.Color
import kotlin.math.*
/**
* Created by mike on 31/07/2017.
*/
object BlurHashDecoder {
val MAX_SIZE = 20
private val digitCharacters = arrayOf(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '#', '$', '%', '*', '+', ',', '-', '.',
':', ';', '=', '?', '@', '[', ']', '^', '_', '{',
'|', '}', '~'
)
fun decode(blurHash: String?, width: Int, height: Int, punch: Float): Bitmap? {
if (blurHash == null || blurHash.length < 6) {
return null
}
val sizeFlag = blurHash[0].toString().decode83()
val numY = (sizeFlag / 9) + 1
val numX = (sizeFlag % 9) + 1
if (blurHash.length != 4 + 2 * numX * numY) {
return null
}
val quantisedMaximumValue = blurHash[1].toString().decode83()
val maximumValue = (quantisedMaximumValue + 1) / 166f
val colors = (0 until numX * numY).map { i ->
if (i == 0) {
val value = blurHash.substring(2, 6).decode83()
decodeDc(value)
} else {
val startIndex = 4 + i * 2
val value = blurHash.substring(startIndex, startIndex + 2).decode83()
decodeAc(value, maximumValue * punch)
}
}
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
for (y in 0 until height) {
for (x in 0 until width) {
var r = 0f
var g = 0f
var b = 0f
for (j in 0 until numY) {
for (i in 0 until numX) {
val basis = (cos(PI * x * i / width) * cos(PI * y * j / height)).toFloat()
val color = colors[i + j * numX]
r += color[0] * basis
g += color[1] * basis
b += color[2] * basis
}
}
bitmap.setPixel(x, y, Color.rgb(linearToSRgb(r), linearToSRgb(g), linearToSRgb(b)))
}
}
return bitmap
}
private fun String.decode83(): Int {
var value = 0
for (i in 0 until this.length) {
val digit = digitCharacters.indexOf(this[i])
if (digit != -1) {
value = value * 83 + digit
}
}
return value
}
private fun decodeDc(value: Int): Array<Float> {
val intR = value shr 16
val intG = (value shr 8) and 255
val intB = value and 255
return arrayOf(sRgbToLinear(intR), sRgbToLinear(intG), sRgbToLinear(intB))
}
private fun sRgbToLinear(value: Int): Float {
val v = value / 255f
return if (v <= 0.04045) (v / 12.92f) else ((v + 0.055) / 1.055).pow(2.4).toFloat()
}
private fun decodeAc(value: Int, maximumValue: Float): Array<Float> {
val quantR = value / (19 * 19)
val quantG = (value / 19) % 19
val quantB = value % 19
return arrayOf(
signPow((quantR - 9) / 9.0f, 2.0f) * maximumValue,
signPow((quantG - 9) / 9.0f, 2.0f) * maximumValue,
signPow((quantB - 9) / 9.0f, 2.0f) * maximumValue
)
}
private fun signPow(value: Float, exp: Float) = value.pow(exp).withSign(value)
private fun linearToSRgb(value: Float): Int {
val v = value.coerceIn(0f, 1f)
return if (v <= 0.0031308f) {
(v * 12.92f * 255 + 0.5f).toInt()
} else {
((1.055f * v.toDouble().pow( 1 / 2.4) - 0.055f) * 255 + 0.5f).toInt()
}
}
}
| 0
|
C
|
0
| 1
|
9ea6105a0a9e06f46919708fce6075a6d9dbb93d
| 4,004
|
blurhash
|
The Unlicense
|
app/src/main/java/com/naufalprakoso/superheroapp/ui/detail/HeroDetailTabsAdapter.kt
|
naufalprakoso
| 264,489,858
| false
| null |
package com.naufalprakoso.superheroapp.ui.detail
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.naufalprakoso.superheroapp.database.relation.Superhero
import com.naufalprakoso.superheroapp.ui.detail.appearance.AppearanceFragment
import com.naufalprakoso.superheroapp.ui.detail.biography.BiographyFragment
import com.naufalprakoso.superheroapp.ui.detail.powerstats.PowerStatsFragment
import com.naufalprakoso.superheroapp.ui.detail.work.WorkFragment
import com.naufalprakoso.superheroapp.ui.detail.connection.ConnectionFragment
class HeroDetailTabsAdapter(
fa: FragmentActivity,
var superhero: Superhero,
private var mNumOfTabs: Int
) : FragmentStateAdapter(fa) {
override fun getItemCount(): Int = mNumOfTabs
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> BiographyFragment.getInstance(superhero.biography)
1 -> PowerStatsFragment.getInstance(superhero.powerStat)
2 -> AppearanceFragment.getInstance(superhero.appearance)
3 -> WorkFragment.getInstance(superhero.work)
else -> ConnectionFragment.getInstance(superhero.connection)
}
}
}
| 1
|
Kotlin
|
1
| 27
|
c4eff01819529d1091dcfc2334346d1c419f3d79
| 1,280
|
Superhero-App
|
MIT License
|
console/src/main/kotlin/com/caoccao/javet/shell/modules/javet/BaseJavetPackage.kt
|
caoccao
| 421,317,146
| false
|
{"Kotlin": 48362, "Java": 12593, "Dockerfile": 1769}
|
/*
* Copyright (c) 2023-2024. caoccao.com <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.caoccao.javet.shell.modules.javet
import com.caoccao.javet.interfaces.IJavetUniFunction
import com.caoccao.javet.interop.V8Runtime
import com.caoccao.javet.interop.callback.IJavetDirectCallable
import com.caoccao.javet.interop.callback.JavetCallbackContext
import com.caoccao.javet.interop.callback.JavetCallbackType
import com.caoccao.javet.shell.constants.Constants
import com.caoccao.javet.shell.modules.BaseDirectProxyHandler
import com.caoccao.javet.values.V8Value
import com.caoccao.javet.values.primitive.V8ValueString
abstract class BaseJavetPackage(private val v8Runtime: V8Runtime) : BaseDirectProxyHandler(v8Runtime) {
abstract fun getName(): String
abstract fun isValid(): Boolean
override fun proxyGet(target: V8Value?, property: V8Value, receiver: V8Value?): V8Value {
var v8Value = super.proxyGet(target, property, receiver)
if (v8Value.isUndefined) {
if (property is V8ValueString) {
val childName = property.value
if (childName.isNotBlank()) {
val name = if (getName().isBlank()) childName else "${getName()}.$childName"
try {
val clazz = Class.forName(name)
v8Value = Constants.Javet.JAVET_PROXY_CONVERTER.toV8Value(v8Runtime, clazz)
} catch (_: Throwable) {
@Suppress("DEPRECATION")
val namedPackage = Package.getPackage(name)
if (namedPackage != null) {
v8Value = JavetPackage(v8Runtime, namedPackage).toV8Value()
} else {
v8Value = JavetVirtualPackage(v8Runtime, name).toV8Value()
}
}
}
}
}
return v8Value
}
override fun proxyGetStringGetterMap(): Map<String, IJavetUniFunction<String, out V8Value, Exception>> {
if (stringGetterMap == null) {
stringGetterMap = mapOf(
".getPackages" to IJavetUniFunction<String, V8Value, Exception> { propertyName: String ->
v8Runtime.createV8ValueFunction(
JavetCallbackContext(
propertyName,
this, JavetCallbackType.DirectCallNoThisAndResult,
IJavetDirectCallable.NoThisAndResult<Exception> { _: Array<V8Value>? ->
val prefix = "${getName()}."
val v8ValueArray = v8Runtime.createV8ValueArray()
Package.getPackages()
.filter { it.name.startsWith(prefix) }
.filter { !it.name.substring(prefix.length).contains(".") }
.map { JavetPackage(v8Runtime, it).toV8Value() }
.forEach {
v8ValueArray.push(it)
}
v8ValueArray
},
)
)
},
".name" to IJavetUniFunction<String, V8Value, Exception> { _: String ->
v8Runtime.createV8ValueString(getName())
},
".valid" to IJavetUniFunction<String, V8Value, Exception> { _: String ->
v8Runtime.createV8ValueBoolean(isValid())
},
)
}
return stringGetterMap!!
}
}
| 0
|
Kotlin
|
0
| 2
|
7322d90b251f3fcc66ee60b25a5fda3c4dd90684
| 4,239
|
JavetShell
|
Apache License 2.0
|
apps/etterlatte-oppdater-behandling/src/main/kotlin/migrering/AvbrytBehandlingHvisMigreringFeila.kt
|
navikt
| 417,041,535
| false
|
{"Kotlin": 3977041, "TypeScript": 855520, "Handlebars": 19431, "Shell": 9939, "HTML": 1776, "CSS": 598, "Dockerfile": 520}
|
package no.nav.etterlatte.migrering
import no.nav.etterlatte.BehandlingService
import no.nav.etterlatte.libs.common.rapidsandrivers.correlationId
import no.nav.etterlatte.libs.common.rapidsandrivers.eventName
import no.nav.etterlatte.rapidsandrivers.migrering.Migreringshendelser
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.MessageContext
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.River
import org.slf4j.LoggerFactory
import rapidsandrivers.BEHANDLING_ID_KEY
import rapidsandrivers.behandlingId
import rapidsandrivers.migrering.ListenerMedLoggingOgFeilhaandtering
internal class AvbrytBehandlingHvisMigreringFeila(
rapidsConnection: RapidsConnection,
private val behandlingService: BehandlingService,
) :
ListenerMedLoggingOgFeilhaandtering(Migreringshendelser.AVBRYT_BEHANDLING) {
private val logger = LoggerFactory.getLogger(this::class.java)
init {
logger.info("initierer rapid for ${this.javaClass.name}")
River(rapidsConnection).apply {
eventName(hendelsestype)
correlationId()
validate { it.requireKey(BEHANDLING_ID_KEY) }
}.register(this)
}
override fun haandterPakke(
packet: JsonMessage,
context: MessageContext,
) {
logger.info("Avbryter behandling ${packet.behandlingId} fordi den feila under migrering")
behandlingService.avbryt(packet.behandlingId)
logger.info("Har avbrutt behandling ${packet.behandlingId} fordi den feila under migrering")
}
}
| 13
|
Kotlin
|
0
| 5
|
d0b42ff1df660904897d6869868f440747ce74d5
| 1,578
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
test_runner/src/main/kotlin/ftl/ios/Parse.kt
|
miguelslemos
| 146,530,624
| false
| null |
package ftl.ios
import ftl.util.Bash
import java.io.File
object Parse {
private fun validateFile(path: String) {
val file = File(path)
if (!file.exists()) {
throw RuntimeException("File $path does not exist!")
}
if (file.isDirectory) throw RuntimeException("$path is a directory!")
}
private fun methodName(matcher: MatchResult): String {
return matcher.groupValues.last()
.replace('.', '/')
.replace(' ', '/')
}
internal fun parseObjcTests(binary: String): List<String> {
validateFile(binary)
val results = mutableListOf<String>()
// https://github.com/linkedin/bluepill/blob/37e7efa42472222b81adaa0e88f2bd82aa289b44/Source/Shared/BPXCTestFile.m#L18
val output = Bash.execute("nm -U $binary")
output.lines().forEach { line ->
// 000089b0 t -[EarlGreyExampleTests testLayout]
// 00008330 t -[EarlGreyExampleTests testCustomAction]
val pattern = """.+\st\s-\[(.+\stest.+)]""".toRegex()
val matcher = pattern.find(line)
if (matcher != null && matcher.groupValues.size == 2) {
results.add(methodName(matcher))
}
}
return results.distinct()
}
internal fun parseSwiftTests(binary: String): List<String> {
validateFile(binary)
val results = mutableListOf<String>()
// The OS limits the list of arguments to ARG_MAX. Setting the xargs limit avoids a fatal
// 'argument too long' error. xargs will split the args and run the command for each chunk.
val argMax = Bash.execute("getconf ARG_MAX")
// https://github.com/linkedin/bluepill/blob/37e7efa42472222b81adaa0e88f2bd82aa289b44/Source/Shared/BPXCTestFile.m#L17-18
val demangledOutput = Bash.execute("nm -gU $binary | xargs -s $argMax xcrun swift-demangle")
demangledOutput.lines().forEach { line ->
// _T025EarlGreyExampleTestsSwift0abceD0C10testLayoutyyF ---> EarlGreyExampleTestsSwift.EarlGreyExampleSwiftTests.testLayout() -> ()
// _T025EarlGreyExampleTestsSwift0abceD0C16testCustomActionyyF ---> EarlGreyExampleTestsSwift.EarlGreyExampleSwiftTests.testCustomAction() -> ()
val pattern = """.+\s--->\s.+\.(.+\.test.+)\(\)\s->\s\(\)""".toRegex()
val matcher = pattern.find(line)
if (matcher != null && matcher.groupValues.size == 2) {
results.add(methodName(matcher))
}
}
return results.distinct()
}
@JvmStatic
fun main(args: Array<String>) {
// TODO: Replace hardcoded file with args
val objcBinary = "./src/test/kotlin/xctest/fixtures/objc/EarlGreyExampleTests"
parseObjcTests(objcBinary)
val swiftBinary = "./src/test/kotlin/xctest/fixtures/swift/EarlGreyExampleSwiftTests"
parseSwiftTests(swiftBinary)
}
}
| 1
| null |
1
| 1
|
2fc5c82244fedf9260ba2b5c38c859286390552a
| 2,948
|
flank
|
MIT License
|
utbot-python/src/main/kotlin/org/utbot/python/fuzzing/provider/TupleValueProvider.kt
|
UnitTestBot
| 480,810,501
| false
| null |
package org.utbot.python.fuzzing.provider
import org.utbot.fuzzing.Routine
import org.utbot.fuzzing.Seed
import org.utbot.fuzzing.ValueProvider
import org.utbot.python.framework.api.python.PythonTree
import org.utbot.python.framework.api.python.util.pythonTupleClassId
import org.utbot.python.fuzzing.PythonFuzzedValue
import org.utbot.python.fuzzing.PythonMethodDescription
import org.utbot.python.fuzzing.provider.utils.getSuitableConstantsFromCode
import org.utbot.python.newtyping.*
import org.utbot.python.newtyping.general.UtType
object TupleValueProvider : ValueProvider<UtType, PythonFuzzedValue, PythonMethodDescription> {
override fun accept(type: UtType): Boolean {
return type.pythonTypeName() == pythonTupleClassId.canonicalName
}
override fun generate(description: PythonMethodDescription, type: UtType) = sequence {
yieldAll(getConstants(description, type))
val param = type.pythonAnnotationParameters()
yield(
Seed.Collection(
construct = Routine.Collection {
PythonFuzzedValue(
PythonTree.TupleNode(
emptyMap<Int, PythonTree.PythonTreeNode>().toMutableMap(),
),
"%var% = ${type.pythonTypeRepresentation()}"
)
},
modify = Routine.ForEach(param) { self, i, values ->
(self.tree as PythonTree.TupleNode).items[i] = values.first().tree
}
))
}
private fun getConstants(description: PythonMethodDescription, type: UtType): List<Seed<UtType, PythonFuzzedValue>> {
if (!typesAreEqual(type.parameters.first(), pythonAnyType))
return getSuitableConstantsFromCode(description, type)
return emptyList()
}
}
| 397
|
Kotlin
|
32
| 91
|
f9c95348acb59c1b4fc212ecb36e6b2968e9ac5a
| 1,847
|
UTBotJava
|
Apache License 2.0
|
runtime/src/test/java/com/instana/android/instrumentation/HTTPMarkerShould.kt
|
instana
| 81,942,955
| false
| null |
/*
* (c) Copyright IBM Corp. 2021
* (c) Copyright Instana Inc. and contributors 2021
*/
package com.instana.android.instrumentation
import com.instana.android.BaseTest
import com.instana.android.Instana
import com.instana.android.core.InstanaConfig
import com.instana.android.core.InstanaWorkManager
import com.nhaarman.mockitokotlin2.*
import org.junit.Assert.assertNotNull
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import org.junit.Before
import org.junit.Test
import java.io.IOException
import java.net.HttpURLConnection
class HTTPMarkerShould : BaseTest() {
private val mockManager = mock<InstanaWorkManager>()
private val config = InstanaConfig(API_KEY, SERVER_URL)
@Before
fun setUp() {
Instana.setup(app, config)
Instana.sessionId = "sessionId"
}
@Test
fun createMarker() {
val remoteCallMarker = HTTPMarker(URL, METHOD, emptyMap(), app, mockManager, config)
assertNotNull(remoteCallMarker)
assert(remoteCallMarker.headerValue().isNotBlank())
}
@Test
fun endedWithThrowableAndHttpUrlConnection() {
val mockConnection = mock<HttpURLConnection> {
on { requestMethod } doReturn METHOD
}
val remoteCallMarker = HTTPMarker(URL, METHOD, emptyMap(), app, mockManager, config)
remoteCallMarker.finish(mockConnection, IOException("error"))
verify(mockManager).queue(any())
}
@Test
fun endedWithSuccessAndHttpUrlConnection() {
val mockConnection = mock<HttpURLConnection> {
on { requestMethod } doReturn METHOD
on { responseCode } doReturn 200
on { contentLengthLong } doReturn 10
on { contentLength } doReturn 10
}
val remoteCallMarker = HTTPMarker(URL, METHOD, emptyMap(), app, mockManager, config)
remoteCallMarker.finish(mockConnection)
verify(mockManager).queue(any())
}
@Test
fun endedWithOkHttpResponse() {
val response = Response.Builder().protocol(Protocol.HTTP_1_1)
.message("blah").request(Request.Builder().url(URL).get().build()).code(200).build()
val remoteCallMarker = HTTPMarker(URL, METHOD, emptyMap(), app, mockManager, config)
remoteCallMarker.finish(response)
verify(mockManager).queue(any())
}
@Test
fun canceled() {
val remoteCallMarker = HTTPMarker(URL, METHOD, emptyMap(), app, mockManager, config)
assertNotNull(remoteCallMarker)
remoteCallMarker.cancel()
verify(mockManager).queue(any())
}
@Test
fun getHeaders() {
val remoteCallMarker = HTTPMarker(URL, METHOD, emptyMap(), app, mockManager, config)
assertNotNull(remoteCallMarker)
assertNotNull(remoteCallMarker.headerValue())
assert(remoteCallMarker.headerValue().isNotBlank())
verifyNoMoreInteractions(mockManager)
}
companion object {
const val METHOD = "GET"
const val URL = "https://www.google.com/"
const val API_KEY = "<KEY>"
const val SERVER_URL = "https://www.google.com"
}
}
| 1
|
Kotlin
|
4
| 19
|
ec1133cc48c8da4b43658be2be7a31610c05308f
| 3,130
|
android-agent
|
MIT License
|
compose/foundation/foundation/src/androidInstrumentedTest/kotlin/androidx/compose/foundation/text/input/BasicTextFieldHandwritingTest.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 99565022, "Java": 63440543, "C++": 9126850, "AIDL": 592008, "Python": 308602, "Shell": 186862, "TypeScript": 40586, "HTML": 32277, "Groovy": 24103, "Svelte": 20307, "ANTLR": 19860, "CMake": 15482, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text.input
import android.view.KeyEvent.ACTION_DOWN
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_CANCEL
import android.view.MotionEvent.ACTION_MOVE
import android.view.MotionEvent.ACTION_UP
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.platform.ViewRootForTest
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.SemanticsNode
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.SemanticsNodeInteraction
import androidx.compose.ui.test.TouchInjectionScope
import androidx.compose.ui.test.invokeGlobalAssertions
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.requestFocus
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.center
import androidx.compose.ui.unit.toOffset
import androidx.core.view.InputDeviceCompat
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import kotlin.math.roundToInt
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalFoundationApi::class, ExperimentalTestApi::class)
@LargeTest
@RunWith(AndroidJUnit4::class)
internal class BasicTextFieldHandwritingTest {
@get:Rule
val rule = createComposeRule()
@get:Rule
val immRule = ComposeInputMethodManagerTestRule()
private val inputMethodInterceptor = InputMethodInterceptor(rule)
private val Tag = "BasicTextField2"
private val imm = FakeInputMethodManager()
@Test
fun textField_startStylusHandwriting_unfocused() {
testStylusHandwriting(stylusHandwritingStarted = true) {
performStylusHandwriting()
}
}
@Test
fun textField_startStylusHandwriting_focused() {
testStylusHandwriting(stylusHandwritingStarted = true) {
requestFocus()
performStylusHandwriting()
}
}
@Test
fun textField_click_notStartStylusHandwriting() {
testStylusHandwriting(stylusHandwritingStarted = false) {
performStylusInput {
down(visibleSize.center.toOffset())
move()
up()
}
}
}
@Test
fun textField_longClick_notStartStylusHandwriting() {
testStylusHandwriting(stylusHandwritingStarted = false) {
performStylusInput {
down(visibleSize.center.toOffset())
move(viewConfiguration.longPressTimeoutMillis + 1)
up()
}
}
}
@Test
fun textField_longPressAndDrag_notStartStylusHandwriting() {
testStylusHandwriting(stylusHandwritingStarted = false) {
performStylusInput {
val startPosition = visibleSize.center.toOffset()
down(visibleSize.center.toOffset())
val position = startPosition + Offset(viewConfiguration.handwritingSlop * 2, 0f)
moveTo(
position = position,
delayMillis = viewConfiguration.longPressTimeoutMillis + 1
)
up()
}
}
}
@Test
fun textField_disabled_notStartStylusHandwriting() {
immRule.setFactory { imm }
inputMethodInterceptor.setTextFieldTestContent {
val state = remember { TextFieldState() }
BasicTextField(
state = state,
modifier = Modifier.fillMaxSize().testTag(Tag),
enabled = false
)
}
rule.onNodeWithTag(Tag).performStylusHandwriting()
rule.runOnIdle {
imm.expectNoMoreCalls()
}
}
@Test
fun textField_readOnly_notStartStylusHandwriting() {
immRule.setFactory { imm }
inputMethodInterceptor.setTextFieldTestContent {
val state = remember { TextFieldState() }
BasicTextField(
state = state,
modifier = Modifier.fillMaxSize().testTag(Tag),
readOnly = true
)
}
rule.onNodeWithTag(Tag).performStylusHandwriting()
rule.runOnIdle {
imm.expectNoMoreCalls()
}
}
private fun testStylusHandwriting(
stylusHandwritingStarted: Boolean,
interaction: SemanticsNodeInteraction.() -> Unit
) {
immRule.setFactory { imm }
inputMethodInterceptor.setTextFieldTestContent {
val state = remember { TextFieldState() }
BasicTextField(
state = state,
modifier = Modifier.fillMaxSize().testTag(Tag)
)
}
interaction.invoke(rule.onNodeWithTag(Tag))
rule.runOnIdle {
if (stylusHandwritingStarted) {
imm.expectCall("startStylusHandwriting")
}
imm.expectNoMoreCalls()
}
}
/** Start stylus handwriting on the target element. */
private fun SemanticsNodeInteraction.performStylusHandwriting() {
performStylusInput {
val startPosition = visibleSize.center.toOffset()
down(startPosition)
moveTo(startPosition + Offset(viewConfiguration.handwritingSlop * 2, 0f))
up()
}
}
private fun SemanticsNodeInteraction.performStylusInput(
block: TouchInjectionScope.() -> Unit
): SemanticsNodeInteraction {
@OptIn(ExperimentalTestApi::class)
invokeGlobalAssertions()
val node = fetchSemanticsNode("Failed to inject stylus input.")
val stylusInjectionScope = StylusInjectionScope(node)
block.invoke(stylusInjectionScope)
return this
}
// We don't have StylusInjectionScope at the moment. This is a simplified implementation for
// the basic use cases in this test. It only supports single stylus pointer, and the pointerId
// is totally ignored.
private inner class StylusInjectionScope(
semanticsNode: SemanticsNode
) : TouchInjectionScope, Density by semanticsNode.layoutInfo.density {
private val root = semanticsNode.root as ViewRootForTest
private val downTime: Long = System.currentTimeMillis()
private var lastPosition: Offset = Offset.Unspecified
private var currentTime: Long = System.currentTimeMillis()
private val boundsInRoot = semanticsNode.boundsInRoot
override val visibleSize: IntSize =
IntSize(boundsInRoot.width.roundToInt(), boundsInRoot.height.roundToInt())
override val viewConfiguration: ViewConfiguration =
semanticsNode.layoutInfo.viewConfiguration
private fun localToRoot(position: Offset): Offset {
return position + boundsInRoot.topLeft
}
override fun advanceEventTime(durationMillis: Long) {
require(durationMillis >= 0) {
"duration of a delay can only be positive, not $durationMillis"
}
currentTime += durationMillis
}
override fun currentPosition(pointerId: Int): Offset? {
return lastPosition
}
override fun down(pointerId: Int, position: Offset) {
val rootPosition = localToRoot(position)
lastPosition = rootPosition
sendTouchEvent(ACTION_DOWN)
}
override fun updatePointerTo(pointerId: Int, position: Offset) {
lastPosition = localToRoot(position)
}
override fun move(delayMillis: Long) {
advanceEventTime(delayMillis)
sendTouchEvent(ACTION_MOVE)
}
@ExperimentalTestApi
override fun moveWithHistoryMultiPointer(
relativeHistoricalTimes: List<Long>,
historicalCoordinates: List<List<Offset>>,
delayMillis: Long
) {
// Not needed for this test because Android only support one stylus pointer.
}
override fun up(pointerId: Int) {
sendTouchEvent(ACTION_UP)
}
override fun cancel(delayMillis: Long) {
sendTouchEvent(ACTION_CANCEL)
}
private fun sendTouchEvent(action: Int) {
val positionInScreen = run {
val array = intArrayOf(0, 0)
root.view.getLocationOnScreen(array)
Offset(array[0].toFloat(), array[1].toFloat())
}
val motionEvent = MotionEvent.obtain(
/* downTime = */ downTime,
/* eventTime = */ currentTime,
/* action = */ action,
/* pointerCount = */ 1,
/* pointerProperties = */ arrayOf(
MotionEvent.PointerProperties().apply {
id = 0
toolType = MotionEvent.TOOL_TYPE_STYLUS
}
),
/* pointerCoords = */ arrayOf(
MotionEvent.PointerCoords().apply {
val startOffset = lastPosition
// Allows for non-valid numbers/Offsets to be passed along to Compose to
// test if it handles them properly (versus breaking here and we not knowing
// if Compose properly handles these values).
x = if (startOffset.isValid()) {
positionInScreen.x + startOffset.x
} else {
Float.NaN
}
y = if (startOffset.isValid()) {
positionInScreen.y + startOffset.y
} else {
Float.NaN
}
}
),
/* metaState = */ 0,
/* buttonState = */ 0,
/* xPrecision = */ 1f,
/* yPrecision = */ 1f,
/* deviceId = */ 0,
/* edgeFlags = */ 0,
/* source = */ InputDeviceCompat.SOURCE_TOUCHSCREEN,
/* flags = */ 0
)
rule.runOnUiThread {
root.view.dispatchTouchEvent(motionEvent)
}
}
}
}
| 25
|
Kotlin
|
905
| 4,995
|
824114c787e8be1b5a81e589f81827c9121c36e6
| 11,264
|
androidx
|
Apache License 2.0
|
libraries/tools/binary-compatibility-validator/src/test/kotlin/cases/nestedClasses/publicInterface.kt
|
JakeWharton
| 99,388,807
| false
| null |
package cases.nestedClasses
public interface PublicInterface {
public object ObjPublic
private object ObjPrivate
public class NestedPublic
private class NestedPrivate
public interface NestedPublicInterface
private interface NestedPrivateInterface
}
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 278
|
kotlin
|
Apache License 2.0
|
app/src/main/java/dgca/verifier/app/android/verification/model/RuleValidationResultCard.kt
|
eu-digital-green-certificates
| 355,126,967
| false
| null |
/*
* ---license-start
* eu-digital-green-certificates / dgca-wallet-app-android
* ---
* Copyright (C) 2021 T-Systems International GmbH and all other contributors
* ---
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ---license-end
*
* Created by osarapulov on 6/18/21 8:59 AM
*/
package dgca.wallet.app.android.dcc.ui.wallet.certificates.view.validity.rules
import dgca.verifier.app.engine.Result
data class DccRuleValidationResultCard(
val description: String,
val result: Result,
val current: String,
val countryIsoCode: String
)
| 4
|
Kotlin
|
19
| 99
|
540abc57dcd0dc94c127053bdd73706984ba741d
| 1,086
|
dgca-verifier-app-android
|
Apache License 2.0
|
app/src/main/java/com/wavesplatform/wallet/v2/ui/widget/MarketPulseAppWidgetProvider.kt
|
wavesplatform
| 98,419,999
| false
| null |
/*
* Created by <NAME> on 18/7/2019
* Copyright © 2019 Waves Platform. All rights reserved.
*/
package com.wavesplatform.wallet.v2.ui.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.v4.content.ContextCompat
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.RemoteViews
import com.wavesplatform.wallet.R
import com.wavesplatform.wallet.v2.data.analytics.AnalyticEvents
import com.wavesplatform.wallet.v2.data.analytics.analytics
import com.wavesplatform.wallet.v2.data.manager.MarketWidgetDataManager
import com.wavesplatform.wallet.v2.data.model.local.widget.MarketWidgetProgressState
import com.wavesplatform.wallet.v2.data.model.local.widget.MarketWidgetSettings
import com.wavesplatform.wallet.v2.data.model.local.widget.MarketWidgetStyle
import com.wavesplatform.wallet.v2.ui.widget.configuration.MarketWidgetConfigureActivity
import com.wavesplatform.wallet.v2.util.ACTION_AUTO_UPDATE_WIDGET
import com.wavesplatform.wallet.v2.util.EnvironmentManager
import com.wavesplatform.wallet.v2.util.getLocalizedString
import com.wavesplatform.wallet.v2.util.startAlarmUpdate
import dagger.android.AndroidInjection
import pers.victor.ext.isNetworkConnected
import java.util.*
import javax.inject.Inject
/**
* Implementation of App Widget functionality.
* App Widget Configuration implemented in [MarketWidgetConfigureActivity]
*/
class MarketPulseAppWidgetProvider : AppWidgetProvider() {
@Inject
lateinit var marketWidgetDataManager: MarketWidgetDataManager
private var onUpdateCompleteListener: EnvironmentManager.Companion.OnUpdateCompleteListener? = null
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateWidget(context, appWidgetManager, appWidgetId)
loadPrice(context, appWidgetId)
context.startAlarmUpdate<MarketPulseAppWidgetProvider>(appWidgetId)
}
}
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
// When the user deletes the widget, delete the preference associated with it.
for (appWidgetId in appWidgetIds) {
MarketWidgetSettings.clearSettings(context, appWidgetId)
}
}
override fun onEnabled(context: Context) {
analytics.trackEvent(AnalyticEvents.MarketPulseAddedEvent)
// Enter relevant functionality for when the first widget is created
}
override fun onDisabled(context: Context) {
marketWidgetDataManager.clearSubscription()
analytics.trackEvent(AnalyticEvents.MarketPulseRemovedEvent)
// Enter relevant functionality for when the last widget is disabled
}
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
super.onReceive(context, intent)
val widgetId = intent.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
?: AppWidgetManager.INVALID_APPWIDGET_ID
if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
when (intent.action) {
ACTION_CURRENCY_CHANGE -> {
MarketWidgetSettings.currencySettings().switchCurrency(context, widgetId)
updateWidget(context, AppWidgetManager.getInstance(context), widgetId)
analytics.trackEvent(AnalyticEvents.MarketPulseActiveEvent)
}
ACTION_UPDATE -> {
loadPrice(context, widgetId)
analytics.trackEvent(AnalyticEvents.MarketPulseActiveEvent)
}
ACTION_AUTO_UPDATE_WIDGET -> {
loadPrice(context, widgetId)
}
}
}
}
private fun loadPrice(context: Context, widgetId: Int) {
if (isNetworkConnected()) {
updateWidgetProgress(context, widgetId, MarketWidgetProgressState.PROGRESS)
if (EnvironmentManager.isUpdateCompleted()) {
marketWidgetDataManager.loadMarketsPrices(context, widgetId, successListener = {
updateWidget(context, AppWidgetManager.getInstance(context), widgetId, MarketWidgetProgressState.IDLE)
}, errorListener = {
updateWidgetProgress(context, widgetId, MarketWidgetProgressState.IDLE)
})
} else {
EnvironmentManager.update()
onUpdateCompleteListener = object : EnvironmentManager.Companion.OnUpdateCompleteListener {
override fun onComplete() {
EnvironmentManager.removeOnUpdateCompleteListener(onUpdateCompleteListener!!)
loadPrice(context, widgetId)
}
override fun onError() {
EnvironmentManager.removeOnUpdateCompleteListener(onUpdateCompleteListener!!)
updateWidgetProgress(context, widgetId, MarketWidgetProgressState.IDLE)
}
}
EnvironmentManager.addOnUpdateCompleteListener(onUpdateCompleteListener!!)
}
}
}
companion object {
const val PREFS_NAME = "com.wavesplatform.wallet.v2.ui.widget.MarketWidget"
const val ACTION_CURRENCY_CHANGE = "currency_change_action"
const val ACTION_UPDATE = "update_action"
internal fun updateWidget(context: Context, appWidgetManager: AppWidgetManager,
appWidgetId: Int, progressState: MarketWidgetProgressState = MarketWidgetProgressState.NONE) {
// Construct the RemoteViews object
val theme = MarketWidgetSettings.themeSettings().getTheme(context, appWidgetId)
val views = RemoteViews(context.packageName, theme.themeLayout)
configureClicks(context, appWidgetId, views)
configureProgressState(context, appWidgetId, progressState, views)
configureMarketList(context, appWidgetId, views)
views.setTextViewText(R.id.text_currency, highLightCurrency(context, theme, appWidgetId))
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.list_markets)
}
internal fun updateWidgetProgress(context: Context, appWidgetId: Int,
progressState: MarketWidgetProgressState = MarketWidgetProgressState.NONE) {
val appWidgetManager = AppWidgetManager.getInstance(context)
val theme = MarketWidgetSettings.themeSettings().getTheme(context, appWidgetId)
val views = RemoteViews(context.packageName, theme.themeLayout)
configureProgressState(context, appWidgetId, progressState, views)
appWidgetManager.partiallyUpdateAppWidget(appWidgetId, views)
}
fun updateAllWidgetsByBroadcast(context: Context) {
val intent = Intent(context, MarketPulseAppWidgetProvider::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val widgetManager = AppWidgetManager.getInstance(context)
val ids = widgetManager.getAppWidgetIds(ComponentName(context, MarketPulseAppWidgetProvider::class.java))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
context.sendBroadcast(intent)
}
fun updateWidgetByBroadcast(context: Context, widgetId: Int) {
val intent = Intent(context, MarketPulseAppWidgetProvider::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids = intArrayOf(widgetId)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
context.sendBroadcast(intent)
}
private fun configureMarketList(context: Context, appWidgetId: Int, views: RemoteViews) {
val adapter = Intent(context, MarketWidgetAdapterService::class.java)
adapter.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
adapter.data = Uri.parse(adapter.toUri(Intent.URI_INTENT_SCHEME))
views.setRemoteAdapter(R.id.list_markets, adapter)
}
private fun configureProgressState(context: Context, appWidgetId: Int,
progressState: MarketWidgetProgressState, views: RemoteViews,
locale: Locale = Locale.getDefault()) {
when (progressState) {
MarketWidgetProgressState.IDLE -> {
views.setViewVisibility(R.id.image_update, View.VISIBLE)
views.setViewVisibility(R.id.progress_updating, View.GONE)
views.setTextViewText(R.id.text_update, context.getLocalizedString(R.string.market_widget_update, locale))
configureClicks(context, appWidgetId, views)
}
MarketWidgetProgressState.PROGRESS -> {
views.setViewVisibility(R.id.image_update, View.GONE)
views.setViewVisibility(R.id.progress_updating, View.VISIBLE)
views.setTextViewText(R.id.text_update, context.getLocalizedString(R.string.market_widget_updating, locale))
views.setOnClickPendingIntent(R.id.linear_update, null)
}
else -> {
// nothing
}
}
}
private fun highLightCurrency(context: Context, theme: MarketWidgetStyle, appWidgetId: Int): SpannableString {
val currency = MarketWidgetSettings.currencySettings().getCurrency(context, appWidgetId).name
val highLightString = SpannableString(context.getString(R.string.market_widget_currency_text))
val activeSpan = ForegroundColorSpan(ContextCompat.getColor(context, theme.colors.currencyActiveColor))
val inActiveSpan = ForegroundColorSpan(ContextCompat.getColor(context, theme.colors.currencyInactiveColor))
highLightString.setSpan(inActiveSpan, 0, highLightString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
highLightString.setSpan(activeSpan, highLightString.indexOf(currency),
highLightString.indexOf(currency) + currency.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
return highLightString
}
private fun configureClicks(context: Context, appWidgetId: Int, views: RemoteViews) {
// set on click intent to 'setting' button
val configIntent = Intent(context, MarketWidgetConfigureActivity::class.java)
configIntent.action = AppWidgetManager.ACTION_APPWIDGET_CONFIGURE
configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
configIntent.putExtra(MarketWidgetConfigureActivity.EXTRA_APPWIDGET_CHANGE, true)
var pIntent = PendingIntent.getActivity(context, appWidgetId,
configIntent, 0)
views.setOnClickPendingIntent(R.id.image_configuration, pIntent)
// set on click intent to 'currency switch' button
val currencySwitcherIntent = Intent(context, MarketPulseAppWidgetProvider::class.java)
currencySwitcherIntent.action = ACTION_CURRENCY_CHANGE
currencySwitcherIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
pIntent = PendingIntent.getBroadcast(context, appWidgetId, currencySwitcherIntent, 0)
views.setOnClickPendingIntent(R.id.text_currency, pIntent)
// set on click intent to 'update' button
val updateIntent = Intent(context, MarketPulseAppWidgetProvider::class.java)
updateIntent.action = ACTION_UPDATE
updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
pIntent = PendingIntent.getBroadcast(context, appWidgetId, updateIntent, 0)
views.setOnClickPendingIntent(R.id.linear_update, pIntent)
}
}
}
| 2
| null |
52
| 55
|
5f4106576dc4fe377a355d045f638e7469cd6abe
| 12,507
|
WavesWallet-android
|
MIT License
|
core-db/src/main/java/io/novafoundation/nova/core_db/model/BrowserHostSettingsLocal.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 8137060, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.core_db.model
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import io.novafoundation.nova.common.utils.Identifiable
@Entity(tableName = "browser_host_settings")
data class BrowserHostSettingsLocal(
@PrimaryKey
val hostUrl: String,
val isDesktopModeEnabled: Boolean
) : Identifiable {
@Ignore
override val identifier: String = hostUrl
}
| 12
|
Kotlin
|
6
| 9
|
618357859a4b7af95391fc0991339b78aff1be82
| 431
|
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/example/newsapp/network/NewsApiService.kt
|
cikalmaulana
| 647,096,125
| false
| null |
package com.example.newsapp.network
import com.example.newsapp.NewsItem
import com.example.newsapp.NewsResponse
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface NewsApiService {
// https://newsapi.org/v2/everything?q=keyword&apiKey=f84d5717585f4b6a9a4ba3acab6d1ce5
@GET("everything")
suspend fun getAllNews(
@Query("q") keyword: String,
@Query("apiKey") apiKey: String
): Response<NewsResponse>
// https://newsapi.org/v2/top-headlines?country=id&apiKey=f84d5717585f4b6a9a4ba3acab6d1ce5
@GET("top-headlines")
suspend fun getNewsByCountry(
@Query("country") keyword: String,
@Query("apiKey") apiKey: String
): Response<NewsResponse>
}
| 0
|
Kotlin
|
0
| 0
|
178be027d316de732e58d5c6b0e095f7809e17cf
| 739
|
NewsApp
|
MIT License
|
app/src/main/java/com/whitelotusapps/chime/adapter/FileBrowserAdapter.kt
|
Aky97567
| 137,248,264
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 2, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "YAML": 2, "Proguard": 1, "Java": 2, "XML": 14, "Kotlin": 15}
|
package com.whitelotusapps.chime.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.whitelotusapps.chime.R
import com.whitelotusapps.chime.callback.BaseListener
import com.whitelotusapps.chime.utilities.BaseEvents
import java.io.File
import java.util.*
class FileBrowserAdapter(private val baseDir: File, private val context: Context, private val mBaseListener: BaseListener) : RecyclerView.Adapter<RecyclerView.ViewHolder?>() {
private var currentDir: File? = null
private var subdirList: Array<File>? = null
private var fileList: Array<File>? = null
private var subDirCount = 0
private var fileCount = 0
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): FileViewHolder {
return FileViewHolder(LayoutInflater.from(context).inflate(R.layout.file_browser_directory_item, viewGroup, false))
}
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, i: Int) {
(viewHolder as FileViewHolder).pos = i
if (i == 0 && currentDir!!.name != baseDir.name) {
viewHolder.name.text = ".."
viewHolder.name.setTextColor(ContextCompat.getColor(context, R.color.secondary_text))
viewHolder.RLFile.setOnClickListener { updateDir(currentDir!!.parentFile) }
} else if (currentDir!!.name == baseDir.name) {
if (i < subDirCount) {
viewHolder.name.text = subdirList!![i].name
viewHolder.name.setTextColor(ContextCompat.getColor(context, R.color.secondary_text))
val fileItem = subdirList!![viewHolder.position]
viewHolder.RLFile.setOnClickListener {
if (fileItem.isDirectory) {
updateDir(fileItem)
} else {
Toast.makeText(context, "Not a Directory", Toast.LENGTH_SHORT).show()
}
}
} else {
viewHolder.name.text = fileList!![i - subDirCount].name
viewHolder.name.setTextColor(ContextCompat.getColor(context, R.color.cyan_text))
val fileItem = fileList!![viewHolder.position - subDirCount]
viewHolder.RLFile.setOnClickListener {
if (fileItem.isDirectory) {
updateDir(fileItem)
} else {
Toast.makeText(context, "Not a Directory", Toast.LENGTH_SHORT).show()
}
}
}
} else if (i != 0 && currentDir!!.name != baseDir.name) {
if (i <= subDirCount) {
viewHolder.name.text = subdirList!![i - 1].name
viewHolder.name.setTextColor(ContextCompat.getColor(context, R.color.secondary_text))
val fileItem = subdirList!![viewHolder.position - 1]
viewHolder.RLFile.setOnClickListener {
if (fileItem.isDirectory) {
updateDir(fileItem)
} else {
Toast.makeText(context, "Not a Directory", Toast.LENGTH_SHORT).show()
}
}
} else {
viewHolder.name.text = fileList!![i - (subDirCount + 1)].name
viewHolder.name.setTextColor(ContextCompat.getColor(context, R.color.cyan_text))
val fileItem = fileList!![viewHolder.position - (subDirCount + 1)]
viewHolder.RLFile.setOnClickListener {
if (fileItem.isDirectory) {
updateDir(fileItem)
} else {
Toast.makeText(context, "Not a Directory", Toast.LENGTH_SHORT).show()
}
}
}
}
}
fun updateDir(fileItem: File?) {
Toast.makeText(context, "Directory", Toast.LENGTH_SHORT).show()
currentDir = fileItem
files
notifyDataSetChanged()
mBaseListener.onEvent(BaseEvents.DIRECTORY_CHANGED, 0, currentDir)
}
override fun getItemCount(): Int {
return if (currentDir!!.name == baseDir.name) {
subDirCount + fileCount
} else {
subDirCount + fileCount
}
}
inner class FileViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var name: TextView
var RLFile: RelativeLayout
var pos = 0
init {
// get the reference of item views
name = itemView.findViewById(R.id.fileName)
RLFile = itemView.findViewById(R.id.RLFile)
}
}
val files: Unit
get() {
subdirList = currentDir!!.listFiles { file -> file.isDirectory }
subDirCount = if (subdirList != null) subdirList!!.size else 0
fileList = currentDir!!.listFiles { file ->
(file.path.endsWith(".mp3")
|| file.path.endsWith(".flac") || file.path.endsWith(".wav")
|| file.path.endsWith(".ogg"))
}
fileCount = if (fileList != null) fileList!!.size else 0
}
fun sortByName(fileset: Array<File>?) {
Arrays.sort(fileset) { f1, f2 ->
if (f1 == null || f2 == null) {
0
} else 0
}
}
init {
updateDir(baseDir)
}
}
| 0
|
Kotlin
|
0
| 0
|
848725fccaa2cce2478f3aa1696f1262a011df8a
| 5,597
|
Chime
|
Apache License 2.0
|
app/src/main/java/com/odhiambopaul/movie/data/response/NowPlayingResponse.kt
|
paulodhiambo
| 259,288,146
| false
| null |
package com.odhiambopaul.movie.data.response
import com.odhiambopaul.movie.data.entity.Dates
import com.odhiambopaul.movie.data.entity.Movie
data class NowPlayingResponse(
val dates: Dates,
val page: Int, // 1
val results: List<Movie>,
val total_pages: Int, // 44
val total_results: Int // 861
)
| 1
|
Kotlin
|
3
| 4
|
006a2bbe5fd1e128ca34c660d41fbab63b826013
| 317
|
MovieApp
|
The Unlicense
|
plugins/kotlin/idea/tests/testData/intentions/branched/elvisToIfThen/safeCastUnstable.kt
|
ingokegel
| 72,937,917
| true
| null |
// AFTER-WARNING: Variable 'y' is never used
class My(var z: Any, val x: Int) {
fun foo() {
val y = (z as? My)?.x <caret>?: 42
}
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 146
|
intellij-community
|
Apache License 2.0
|
frontend/web/src/main/kotlin/com/jakewharton/sdksearch/ui/Index.kt
|
JakeWharton
| 114,199,331
| false
| null |
package com.jakewharton.sdksearch.ui
import com.jakewharton.sdksearch.api.dac.FetchDocumentationService
import com.jakewharton.sdksearch.search.presenter.SearchPresenter
import com.jakewharton.sdksearch.search.presenter.SearchPresenter.Event
import com.jakewharton.sdksearch.store.item.Item
import com.jakewharton.sdksearch.store.item.ItemStore
import com.jakewharton.sdksearch.sync.ItemSynchronizer
import kotlin.browser.document
import kotlin.dom.clear
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import org.w3c.dom.HTMLAnchorElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.HTMLLIElement
import org.w3c.dom.HTMLSpanElement
import org.w3c.dom.HTMLUListElement
import timber.log.ConsoleTree
import timber.log.Timber
import timber.log.debug
fun main() {
Timber.plant(ConsoleTree())
val count = document.getElementById("count") as HTMLSpanElement
val state = document.getElementById("state") as HTMLSpanElement
val query = document.getElementById("query") as HTMLInputElement
val items = document.getElementById("items") as HTMLUListElement
val store = InMemoryItemStore()
val synchronizer = ItemSynchronizer(store, FetchDocumentationService)
val presenter = SearchPresenter(store, synchronizer)
GlobalScope.launch {
presenter.start()
}
GlobalScope.launch(Dispatchers.Unconfined) {
for (model in presenter.models) {
Timber.debug { model.toString() }
count.textContent = model.count.toString()
state.textContent = model.syncStatus.name
items.clear()
model.queryResults.items.forEach { item ->
val link = document.createElement("a") as HTMLAnchorElement
link.textContent = "${item.packageName}.${item.className}"
link.href = item.link
val listItem = document.createElement("li") as HTMLLIElement
listItem.appendChild(link)
items.appendChild(listItem)
}
}
}
query.addEventListener("input", {
presenter.events.offer(Event.QueryChanged(query.value))
})
}
class InMemoryItemStore : ItemStore {
private val itemsSink: SendChannel<List<Item>>
private val itemsFlow: Flow<List<Item>>
init {
val itemsChannel = ConflatedBroadcastChannel(emptyList<Item>())
itemsSink = itemsChannel
itemsFlow = itemsChannel.asFlow()
}
override fun count() = itemsFlow.map { it.size.toLong() }
override suspend fun updateItems(items: List<Item>) {
Timber.debug { "Updating ${items.size} items" }
itemsSink.offer(items)
}
override fun queryItems(term: String): Flow<List<Item>> {
return itemsFlow.map { items ->
items.filter { it.className.contains(term, ignoreCase = true) }
.sortedWith(compareBy {
val name = it.className
when {
name.equals(term, ignoreCase = true) -> 1
name.startsWith(term, ignoreCase = true) && name.indexOf('.') == -1 -> 2
name.endsWith(".$term", ignoreCase = true) -> 3
name.startsWith(term, ignoreCase = true) -> 4
name.contains(".$term", ignoreCase = true) -> 5
else -> 6
}
})
}
}
}
| 38
|
Kotlin
|
187
| 2,044
|
33e4b60af539aef108d1d3193f99ae151ce14733
| 3,409
|
SdkSearch
|
Apache License 2.0
|
libp2p/src/main/kotlin/io/libp2p/pubsub/PubsubCrypto.kt
|
libp2p
| 189,293,403
| false
| null |
package io.libp2p.pubsub
import io.libp2p.core.crypto.PrivKey
import io.libp2p.core.crypto.marshalPublicKey
import io.libp2p.core.crypto.unmarshalPublicKey
import io.libp2p.etc.types.toProtobuf
import pubsub.pb.Rpc
val SignPrefix = "libp2p-pubsub:".toByteArray()
fun pubsubSign(msg: Rpc.Message, key: PrivKey): Rpc.Message {
if (msg.hasKey() || msg.hasSignature()) throw IllegalArgumentException("Message to sign should not contain 'key' or 'signature' fields")
val signature = key.sign(SignPrefix + msg.toByteArray())
return Rpc.Message.newBuilder(msg)
.setSignature(signature.toProtobuf())
.setKey(marshalPublicKey(key.publicKey()).toProtobuf())
.build()
}
fun pubsubValidate(msg: Rpc.Message): Boolean {
val msgToSign = Rpc.Message.newBuilder(msg)
.clearSignature()
.clearKey()
.build()
return unmarshalPublicKey(msg.key.toByteArray()).verify(
SignPrefix + msgToSign.toByteArray(),
msg.signature.toByteArray()
)
}
| 33
| null |
76
| 272
|
1cde874089d45f90e2f6ca20f39a77b69cd7e66e
| 1,008
|
jvm-libp2p
|
Apache License 2.0
|
src/jvmMain/kotlin/view/View.kt
|
Belgrak
| 498,621,205
| false
|
{"Kotlin": 14101}
|
package view
import Screen
import ViewModel
import androidx.compose.runtime.Composable
@Composable
fun View(viewModel: ViewModel) {
when (viewModel.state.screen) {
Screen.MainView -> MainView(viewModel::singlePlayMode, viewModel::multiplayerLocalMode)
Screen.GameView -> GameView(viewModel::backToMain, viewModel.state.gameMode)
}
}
| 0
|
Kotlin
|
1
| 0
|
24f75103b6f75103de1574e9a8b23e7366e6a73f
| 359
|
TicTacToe
|
MIT License
|
src/test/kotlin/com/pkulak/memo/storage/BlockStorageTest.kt
|
pkulak
| 375,744,026
| false
| null |
package com.pkulak.memo.storage
import com.pkulak.memo.ACCOUNT
import com.pkulak.memo.BLOCK_ID
import com.pkulak.memo.init
import com.pkulak.memo.initDb
import com.pkulak.memo.inject
import io.kotest.matchers.shouldBe
import io.ktor.application.Application
import io.ktor.server.testing.withTestApplication
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class BlockStorageTest {
@BeforeAll
fun setup() = withTestApplication(Application::init) {
initDb()
}
@Test
fun insertAndSelect() = withTestApplication(Application::init) {
val blockStorage: BlockStorage by inject()
blockStorage.insertBlock(BLOCK_ID, ACCOUNT, ACCOUNT, "Pizza! \uD83C\uDF55")
blockStorage.selectBlock(BLOCK_ID)?.memo shouldBe "Pizza! \uD83C\uDF55"
}
}
| 0
|
Kotlin
|
0
| 2
|
aa7a8b4bebde4553e45a61b3981aae74f8606fa7
| 897
|
nanomemo
|
MIT License
|
explosion-gradle-plugin/src/main/kotlin/lol/bai/explosion/gradle/internal/Explosion.kt
|
badasintended
| 697,683,788
| false
|
{"Kotlin": 23609}
|
package lol.bai.explosion.gradle.internal
import lol.bai.explosion.gradle.ExplosionExt
import lol.bai.explosion.gradle.ExplosionPlatformConfig
import org.gradle.api.Project
import java.nio.file.Path
open class Explosion(project: Project, outputDir: Path) : ExplosionExt {
override val fabric = Platform(project, "fabric", outputDir, null)
override val forge = Platform(project, "forge", outputDir, null)
override val neoforge = Platform(project, "neoforge", outputDir, null)
}
| 1
|
Kotlin
|
0
| 2
|
97909605dcbb4856951c3b72f087bc4ab22dfdf7
| 493
|
explosion
|
MIT License
|
app/src/main/java/com/example/inventory/DateTypeConverter.kt
|
YapChenLeong
| 635,729,977
| false
| null |
package com.example.inventory
import androidx.room.TypeConverter
import java.text.SimpleDateFormat
import java.util.*
class DateTypeConverter {
/**
* Suppose you need to persist instances of Date in your Room database.
* Room doesn't know how to persist Date objects, so you need to define type converters:
*
* This example defines two type converter methods:
* one that converts a Date object to a Long object,
* one that performs the inverse conversion from Long to Date
* */
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
return value?.let { Date(it) }
}
@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
return date?.time?.toLong()
}
// @TypeConverter
// fun fromTimestamp(timeStamp: Long?): String? {
// return timeStamp?.let { FORMATTER.format(timeStamp) }
// }
//
// @TypeConverter
// fun dateToTimestamp(timeStamp: String?): Long? {
// return timeStamp?.let { FORMATTER.parse(it)?.time }
// }
//
// companion object{
// val FORMATTER = SimpleDateFormat("dd-MM-yyyy")
// }
}
| 0
|
Kotlin
|
0
| 1
|
6aa3c692b56badfcd43e8cf70f7efcd7e1bb70bc
| 1,124
|
Inventoray-App
|
Apache License 2.0
|
app/src/main/java/uk/co/richyhbm/monochromatic/Utilities/Permissions.kt
|
Vistaus
| 173,779,457
| true
|
{"Kotlin": 66370}
|
package uk.co.richyhbm.monochromatic.Utilities
import android.app.AppOpsManager
import android.content.Context
import android.content.pm.PackageManager
import uk.co.richyhbm.monochromatic.R
object Permissions {
fun hasSecureSettingsPermission(context: Context): Boolean {
return context.checkCallingOrSelfPermission(context.getString(R.string.write_secure_settings_permission)) == PackageManager.PERMISSION_GRANTED
}
fun hasUsageStatsPermission(context: Context): Boolean {
val appOps = context
.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
val mode = appOps.checkOpNoThrow(
AppOpsManager.OPSTR_GET_USAGE_STATS,
android.os.Process.myUid(), context.packageName
)
return if (mode == AppOpsManager.MODE_DEFAULT) {
context.checkCallingOrSelfPermission("android.permission.PACKAGE_USAGE_STATS") == PackageManager.PERMISSION_GRANTED
} else {
mode == AppOpsManager.MODE_ALLOWED
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1d423c72a7e3115235bfdf7008746bf4804b909d
| 1,027
|
Monochromatic
|
Apache License 2.0
|
src/222/main/kotlin/org/rust/lang/core/psi/ext/IntentionPreview.kt
|
t-kameyama
| 117,343,211
| true
|
{"Kotlin": 9922160, "Rust": 158709, "Python": 103835, "HTML": 21219, "Lex": 12335, "ANTLR": 3096, "Java": 688, "Shell": 377, "RenderScript": 120}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.psi.PsiElement
val PsiElement.isIntentionPreviewElement: Boolean get() = false
| 10
|
Kotlin
|
0
| 0
|
33a679cf18314c93dce5b85595a39dd108edeaf7
| 244
|
intellij-rust
|
MIT License
|
src/main/kotlin/scheduler/ScheduleMessage.kt
|
Vikl5
| 826,286,748
| false
| null |
package org.vikl5.scheduler
import com.slack.api.methods.SlackApiException
import org.slf4j.LoggerFactory
import org.vikl5.config.DateTimeToUnixConverter
import org.vikl5.config.SlackConnectionInfo
import org.vikl5.util.UserScore
import java.io.IOException
class ScheduleMessage {
private val slackConnectionInfo = SlackConnectionInfo()
fun postOnSchedule(userScores: List<UserScore>) {
val text = buildMessageText(userScores)
val logger = LoggerFactory.getLogger("my-awesome-slack-app")
val timeToPost = DateTimeToUnixConverter().unixTimeStampForPostingMessages().epochSeconds.toInt()
logger.info("Value of timeToPost is: $timeToPost")
try {
val postMessage = slackConnectionInfo.client.methods(slackConnectionInfo.token).chatScheduleMessage { r ->
r
.channel(slackConnectionInfo.channelId)
.text(text)
.postAt(timeToPost)
}
logger.info("The bot is posting this message: {}", postMessage.message.text)
} catch (e: IOException) {
logger.error("error: {}", e.message, e)
} catch (e: SlackApiException) {
logger.error("error: {}", e.message, e)
}
}
private fun buildMessageText(userScores: List<UserScore>): String {
val topScores = userScores.withIndex().joinToString("\n") { (index, userScore) ->
"${index + 1}. ${userScore.username}, Score: ${userScore.score}/1000"
}
val highestScoreUserId = userScores.firstOrNull()?.userId?.let { "<@$it>" } ?: "No user"
return """The highscore for today is here!!:star-struck: Thank you all for participating!:sparkles: :earth_africa:
|Top Scores:
|$topScores
|
|:flowersmile:Congratulations to the top scorer of today: $highestScoreUserId! :tada: :tada: """.trimMargin()
}
}
| 0
| null |
0
| 2
|
d1c5e0ee0f6594d21aad3191e98c0d26d6ebec40
| 1,933
|
WhenTakenSlackBot
|
MIT License
|
src/android/libs/mobile_sdk/libs/test/SalesforceSDKTest/src/com/salesforce/androidsdk/auth/idp/IDPSPManagerTestCase.kt
|
forcedotcom
| 23,411,868
| false
| null |
package com.salesforce.androidsdk.auth.idp
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.test.platform.app.InstrumentationRegistry
import com.salesforce.androidsdk.accounts.UserAccount
import com.salesforce.androidsdk.util.LogUtil
import org.junit.Assert
import java.lang.RuntimeException
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import java.util.concurrent.TimeUnit
internal open class IDPSPManagerTestCase {
companion object {
const val MAX_EVENTS = 16
const val TIMEOUT_MS: Long = 500 // we don't go to the server so async operations should complete quickly
}
lateinit var context: Context
lateinit var recordedEvents: BlockingQueue<String>
fun recordEvent(event: String) {
Log.i(this::class.java.simpleName, "recording event [$event]")
recordedEvents.add(event)
}
open fun setup() {
context = InstrumentationRegistry.getInstrumentation().targetContext
recordedEvents = ArrayBlockingQueue(MAX_EVENTS)
}
fun sendBroadcast(context:Context, intent: Intent) {
recordEvent("sendBroadcast ${LogUtil.intentToString(intent)}")
}
open fun startActivity(context:Context, intent: Intent) {
recordEvent("startActivity ${LogUtil.intentToString(intent)}")
}
fun throwOnSend(context: Context, intent: Intent) {
throw RuntimeException()
}
fun waitForEvent(expectedEvent: String) {
Log.i(this::class.java.simpleName, "waiting for event [$expectedEvent]")
val actualEvent = recordedEvents.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS)
if (actualEvent == null) {
Assert.fail("received no event")
} else {
Log.i(this::class.java.simpleName, "received event [$actualEvent]")
Assert.assertTrue(actualEvent.startsWith(expectedEvent))
}
}
fun expectNoEvent() {
Assert.assertNull(recordedEvents.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS))
}
fun buildUser(orgId: String, userId:String):UserAccount {
return UserAccount(Bundle().apply {
putString("orgId", orgId)
putString("userId", userId)
})
}
fun checkActiveFlow(idpSpManager: IDPSPManager,
expectedAction: String,
expectedMessageIndex: Int):IDPSPMessage? {
val activeFlow = idpSpManager.getActiveFlow()
Assert.assertNotNull("Active flow not expected to be null", activeFlow)
activeFlow?.let {
Assert.assertTrue("Not enough messages in active flow",
it.messages.size > expectedMessageIndex)
Assert.assertEquals(
"Wrong message type at index $expectedMessageIndex",
expectedAction, it.messages[expectedMessageIndex].action
)
}
return activeFlow?.messages?.get(expectedMessageIndex)
}
fun checkActiveFlow(idpSpManager: IDPSPManager,
expectedMessage: IDPSPMessage,
expectedMessageIndex: Int) {
val activeFlow = idpSpManager.getActiveFlow()
Assert.assertNotNull("Active flow not expected to be null", activeFlow)
activeFlow?.let {
Assert.assertTrue("Not enough messages in active flow",
it.messages.size > expectedMessageIndex)
Assert.assertEquals(
"Wrong message at index $expectedMessageIndex",
expectedMessage.toString(), it.messages[expectedMessageIndex].toString()
)
}
}
}
| 1
| null |
114
| 48
|
9eb11893bf43ca3ba6da736739a61b9c1a45da2e
| 3,667
|
SalesforceMobileSDK-CordovaPlugin
|
Apache License 2.0
|
knowledgebase-gui/src/main/java/ru/usedesk/knowledgebase_gui/screen/IUsedeskOnSupportClickListener.kt
|
usedesk
| 127,645,126
| false
|
{"Kotlin": 713304}
|
package ru.usedesk.knowledgebase_gui.screen
interface IUsedeskOnSupportClickListener {
fun onSupportClick()
}
| 0
|
Kotlin
|
6
| 3
|
06ddd407029a9fc7002642bcf67a7269cf0b8353
| 115
|
Android_SDK
|
MIT License
|
app/src/main/java/com/example/vehiclecontacting/Activity/MainActivity.kt
|
Bngel
| 366,048,859
| false
| null |
package com.example.vehiclecontacting.Activity
import android.os.Bundle
import android.widget.ImageView
import androidx.viewpager2.widget.ViewPager2
import com.example.vehiclecontacting.Adapter.MainViewPagerFragmentStateAdapter
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.view_tab.*
import com.example.vehiclecontacting.Repository.AnimRepository.playTabBtnClickAnim
import com.example.vehiclecontacting.Repository.InfoRepository
import com.example.vehiclecontacting.R
import com.example.vehiclecontacting.Repository.StatusRepository
import com.example.vehiclecontacting.Repository.StatusRepository.PAGE_COMMUNITY
import com.example.vehiclecontacting.Repository.StatusRepository.PAGE_HOME
import com.example.vehiclecontacting.Repository.StatusRepository.PAGE_USER
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
InfoRepository.DOWNLOAD_PATH = applicationContext.filesDir.absolutePath + "/Vc_Download"
InfoRepository.PORTRAIT_PATH = applicationContext.filesDir.absolutePath + "/Vc_Avt"
// 用户状态设置
initUser()
// 控件设置
initWidget()
}
private fun initWidget() {
// viewpager控件属性设置
vpEvent()
// Tab控件单击事件绑定
tabEvent()
}
private fun initUser() {
InfoRepository.initStatus(this)
}
private fun tabEvent() {
tab_home.setOnClickListener {
if (StatusRepository.homeTabStatus != StatusRepository.HomeTab.HOME) {
playTabBtnClickAnim(it as ImageView, R.drawable.yw_home)
StatusRepository.homeTabStatus = StatusRepository.HomeTab.HOME
tab_community.setImageResource(R.drawable.gw_community)
tab_user.setImageResource(R.drawable.gw_user)
main_viewpager.currentItem = PAGE_HOME
}
}
tab_community.setOnClickListener {
if (StatusRepository.homeTabStatus != StatusRepository.HomeTab.COMMUNITY) {
playTabBtnClickAnim(it as ImageView, R.drawable.yw_community)
StatusRepository.homeTabStatus = StatusRepository.HomeTab.COMMUNITY
tab_home.setImageResource(R.drawable.gw_home)
tab_user.setImageResource(R.drawable.gw_user)
main_viewpager.currentItem = PAGE_COMMUNITY
}
}
tab_user.setOnClickListener {
if (StatusRepository.homeTabStatus != StatusRepository.HomeTab.USER) {
playTabBtnClickAnim(it as ImageView, R.drawable.yw_user)
StatusRepository.homeTabStatus = StatusRepository.HomeTab.USER
tab_home.setImageResource(R.drawable.gw_home)
tab_community.setImageResource(R.drawable.gw_community)
main_viewpager.currentItem = PAGE_USER
}
}
// 默认启动选择首页
tab_home.setImageResource(R.drawable.yw_home)
StatusRepository.homeTabStatus = StatusRepository.HomeTab.HOME
}
private fun vpEvent() {
val adapter = MainViewPagerFragmentStateAdapter(this, 3)
main_viewpager.adapter = adapter
main_viewpager.isUserInputEnabled = false
main_viewpager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
when (position) {
PAGE_HOME -> {
playTabBtnClickAnim(tab_home, R.drawable.yw_home)
StatusRepository.homeTabStatus = StatusRepository.HomeTab.HOME
tab_community.setImageResource(R.drawable.gw_community)
tab_user.setImageResource(R.drawable.gw_user)
main_viewpager.currentItem = PAGE_HOME
}
PAGE_COMMUNITY -> {
playTabBtnClickAnim(tab_community, R.drawable.yw_community)
StatusRepository.homeTabStatus = StatusRepository.HomeTab.COMMUNITY
tab_community.setImageResource(R.drawable.gw_community)
tab_home.setImageResource(R.drawable.gw_home)
main_viewpager.currentItem = PAGE_COMMUNITY
}
PAGE_USER -> {
playTabBtnClickAnim(tab_user, R.drawable.yw_user)
StatusRepository.homeTabStatus = StatusRepository.HomeTab.USER
tab_community.setImageResource(R.drawable.gw_community)
tab_home.setImageResource(R.drawable.gw_home)
main_viewpager.currentItem = PAGE_USER
}
}
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
759ffa90c487d4472a79e20bf51ca35454cc7e65
| 4,908
|
VehicleContacting
|
Apache License 2.0
|
src/test/kotlin/g1701_1800/s1786_number_of_restricted_paths_from_first_to_last_node/SolutionTest.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g1701_1800.s1786_number_of_restricted_paths_from_first_to_last_node
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun countRestrictedPaths() {
assertThat(
Solution()
.countRestrictedPaths(
5,
arrayOf(
intArrayOf(1, 2, 3), intArrayOf(1, 3, 3),
intArrayOf(2, 3, 1), intArrayOf(1, 4, 2), intArrayOf(5, 2, 2),
intArrayOf(3, 5, 1), intArrayOf(5, 4, 10)
)
),
equalTo(3)
)
}
@Test
fun countRestrictedPaths2() {
assertThat(
Solution()
.countRestrictedPaths(
7,
arrayOf(
intArrayOf(1, 3, 1), intArrayOf(4, 1, 2), intArrayOf(7, 3, 4),
intArrayOf(2, 5, 3), intArrayOf(5, 6, 1), intArrayOf(6, 7, 2), intArrayOf(7, 5, 3),
intArrayOf(2, 6, 4)
)
),
equalTo(1)
)
}
}
| 0
|
Kotlin
|
20
| 43
|
e8b08d4a512f037e40e358b078c0a091e691d88f
| 1,204
|
LeetCode-in-Kotlin
|
MIT License
|
app/src/test/java/com/example/project2mygrocery/dataentry.kt
|
smartinternz02
| 514,138,962
| false
|
{"Kotlin": 11972}
|
package com.example.project2mygrocery
private val item = listOf("tomatoes","apple")
object dataentry {
fun validate(
itemName: String,
itemQuantity : Int,
itemPrice : Double
):Boolean{
return true
}
}
| 0
|
Kotlin
|
1
| 0
|
2be2c4617895eee3638be4400ec3f4f7e56099ab
| 246
|
SPSGP-88032-Virtual-Internship---Android-Application-Development-Using-Kotlin
|
Apache License 2.0
|
kool-physics/src/jsMain/kotlin/de/fabmax/kool/physics/articulations/Articulation.js.kt
|
kool-engine
| 81,503,047
| false
| null |
package de.fabmax.kool.physics.articulations
import de.fabmax.kool.math.PoseF
import de.fabmax.kool.physics.MemoryStack
import de.fabmax.kool.physics.PhysicsImpl
import de.fabmax.kool.physics.SupportFunctions
import de.fabmax.kool.physics.toPxTransform
import physx.PxArticulationFlagEnum
import physx.PxArticulationLink
import physx.PxArticulationReducedCoordinate
actual fun Articulation(isFixedBase: Boolean): Articulation = ArticulationImpl(isFixedBase)
class ArticulationImpl(val isFixedBase: Boolean) : Articulation() {
val pxArticulation: PxArticulationReducedCoordinate
override var minPositionIterations: Int
get() = SupportFunctions.PxArticulationReducedCoordinate_getMinSolverPositionIterations(pxArticulation)
set(value) {
pxArticulation.setSolverIterationCounts(value, minVelocityIterations)
}
override var minVelocityIterations: Int
get() = SupportFunctions.PxArticulationReducedCoordinate_getMinSolverVelocityIterations(pxArticulation)
set(value) {
pxArticulation.setSolverIterationCounts(minPositionIterations, value)
}
init {
PhysicsImpl.checkIsLoaded()
pxArticulation = PhysicsImpl.physics.createArticulationReducedCoordinate()
if (isFixedBase) {
pxArticulation.setArticulationFlag(PxArticulationFlagEnum.eFIX_BASE, true)
}
}
override fun createLink(parent: ArticulationLink?, pose: PoseF): ArticulationLink {
parent as ArticulationLinkImpl?
return MemoryStack.stackPush().use { mem ->
@Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE")
val parentLink = parent?.holder?.px as PxArticulationLink?
val pxPose = pose.toPxTransform(mem.createPxTransform())
val pxLink = pxArticulation.createLink(parentLink, pxPose)
val link = ArticulationLinkImpl(pxLink, parent)
_links += link
link
}
}
override fun wakeUp() {
pxArticulation.wakeUp()
}
override fun putToSleep() {
pxArticulation.putToSleep()
}
override fun release() {
pxArticulation.release()
}
}
| 9
| null |
20
| 303
|
8d05acd3e72ff2fc115d0939bf021a5f421469a5
| 2,173
|
kool
|
Apache License 2.0
|
nativeprojects/drill-kni/src/kjniMain/kotlin/com/epam/kjni/core/util/CallJavaShortMethod.kt
|
disfogeN
| 174,986,456
| true
|
{"Kotlin": 822313, "HTML": 17724, "CSS": 8583, "Shell": 532}
|
package com.epam.kjni.core.util
import com.epam.kjni.core.GlobState
import jvmapi.jchar
import jvmapi.jclass
import jvmapi.jdouble
import jvmapi.jint
import jvmapi.jobject
import jvmapi.jshort
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.free
import kotlinx.cinterop.invoke
import kotlinx.cinterop.nativeHeap
import kotlinx.cinterop.pointed
import kotlinx.cinterop.value
class CallJavaShortMethod(
jO: jobject?,
javaClass: jclass?,
methodName: CPointer<ByteVar>,
methodSignature: CPointer<ByteVar>
) : JavaMethod(jO, javaClass, methodName, methodSignature) {
override fun invoke(vararg raw: X): jshort {
val arguments = toJObjectArray(raw)
val jniEnv = GlobState.env?.pointed?.value?.pointed
val value = jniEnv!!.CallShortMethodA!!(GlobState.env, jO, getMethod(), arguments)
nativeHeap.free(arguments)
return value
}
}
| 0
|
Kotlin
|
0
| 0
|
c2a6002caab163d1fdb836dd77e4a8966c5d9ce2
| 930
|
Drill4J
|
Apache License 2.0
|
dd-sdk-android/src/main/kotlin/com/datadog/android/core/internal/thread/LoggingThreadPoolExecutor.kt
|
DataDog
| 219,536,756
| false
| null |
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.core.internal.thread
import com.datadog.android.v2.api.InternalLogger
import java.util.concurrent.BlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
/**
* [ThreadPoolExecutor] with a [ThreadPoolExecutor.afterExecute] hook, which will log any unhandled
* exception raised.
*/
internal class LoggingThreadPoolExecutor(
corePoolSize: Int,
maximumPoolSize: Int,
keepAliveTime: Long,
unit: TimeUnit?,
workQueue: BlockingQueue<Runnable>?,
private val logger: InternalLogger
) : ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue) {
override fun afterExecute(r: Runnable?, t: Throwable?) {
@Suppress("UnsafeThirdPartyFunctionCall") // we just call super
super.afterExecute(r, t)
loggingAfterExecute(r, t, logger)
}
}
| 55
| null |
53
| 86
|
bcf0d12fd978df4e28848b007d5fcce9cb97df1c
| 1,128
|
dd-sdk-android
|
Apache License 2.0
|
app/src/main/java/com/codrutursache/casey/data/remote/service/SpoonacularService.kt
|
ursachecodrut
| 739,025,706
| false
|
{"Kotlin": 173858}
|
package com.codrutursache.casey.data.data_source
import com.codrutursache.casey.data.response.RandomFoodTriviaResponse
import com.codrutursache.casey.data.response.RecipeInformationResponse
import com.codrutursache.casey.data.response.RecipeListResponse
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface SpoonacularService {
@GET("/recipes/complexSearch")
suspend fun complexSearch(
@Query("number") number: Int = 10,
@Query("offset") offset: Int = 0,
): RecipeListResponse
@GET("/recipes/{id}/information")
suspend fun getRecipeInformation(
@Path("id") id: Int,
@Query("includeNutrition") includeNutrition: Boolean = false,
): RecipeInformationResponse
@GET("/recipes/informationBulk")
suspend fun getRecipeInformationBulk(
@Path("ids") ids: List<Int>,
@Query("includeNutrition") includeNutrition: Boolean = false,
): List<RecipeInformationResponse>
@GET("/food/trivia/random")
suspend fun getRandomFoodTrivia(): RandomFoodTriviaResponse
companion object {
enum class ImageSize(val size: String) {
SMALL("100x100"),
MEDIUM("250x250"),
LARGE("500x500"),
}
enum class CdnItem(val item: String) {
INGREDIENTS("ingredients"),
EQUIPMENT("equipment"),
}
const val BASE_URL = "https://api.spoonacular.com"
const val RAPID_API_HOST = "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com"
const val RAPID_API_URL = "https://$RAPID_API_HOST"
const val CDN_URL = "https://spoonacular.com/cdn"
inline fun getFromCdn(item: CdnItem, size: ImageSize, name: String) =
"$CDN_URL/${item.item}_${size.size}/$name"
}
}
| 0
|
Kotlin
|
0
| 1
|
f47a35989af88b37f81f4d9705fff4d6ac61a5ef
| 1,798
|
casey
|
MIT License
|
shared/src/main/java/xyz/klinker/messenger/shared/service/HeadlessSmsSendService.kt
|
zacharee
| 295,825,167
| false
| null |
/*
* Copyright (C) 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 xyz.klinker.messenger.shared.service
import android.app.Service
import android.content.Intent
import android.net.Uri
import android.os.IBinder
import xyz.klinker.messenger.shared.data.DataSource
import xyz.klinker.messenger.shared.data.MimeType
import xyz.klinker.messenger.shared.data.model.Conversation
import xyz.klinker.messenger.shared.util.PhoneNumberUtils
import xyz.klinker.messenger.shared.util.SendUtils
/**
* Service for sending messages to a conversation without a UI present. These messages could come
* from something like Phone.
*/
class HeadlessSmsSendService : Service() {
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
try {
if (intent == null) {
return Service.START_NOT_STICKY
}
val addresses = PhoneNumberUtils.parseAddress(Uri.decode(intent.dataString))
val text = getText(intent)
val phoneNumbers = StringBuilder()
for (i in addresses.indices) {
phoneNumbers.append(addresses[i])
if (i != addresses.size - 1) {
phoneNumbers.append(", ")
}
}
val source = DataSource
val conversationId = source.insertSentMessage(phoneNumbers.toString(), text, MimeType.TEXT_PLAIN, this)
val conversation = source.getConversation(this, conversationId)
SendUtils(conversation?.simSubscriptionId)
.send(this, text, addresses)
} catch (e: Exception) {
}
return super.onStartCommand(intent, flags, startId)
}
private fun getText(intent: Intent): String {
val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)
return text?.toString() ?: intent.getStringExtra(Intent.EXTRA_TEXT)!!
}
}
| 1
| null |
7
| 4
|
f957421823801b617194cd68e31ba31b96e6100b
| 2,511
|
pulse-sms-android
|
Apache License 2.0
|
node-kotlin/src/jsMain/kotlin/node/vm/SyntheticModuleOptions.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 7083457}
|
// Automatically generated - do not modify!
package node.vm
sealed external interface SyntheticModuleOptions {
/**
* String used in stack traces.
* @default 'vm:module(i)' where i is a context-specific ascending index.
*/
var identifier: String?
/**
* The contextified object as returned by the `vm.createContext()` method, to compile and evaluate this module in.
*/
var context: Context?
}
| 0
|
Kotlin
|
6
| 26
|
3ca49a8f44fc8b46e393ffe66fbd81f8b4943c18
| 435
|
types-kotlin
|
Apache License 2.0
|
packages/datadog_flutter_plugin/android/src/main/kotlin/com/datadoghq/flutter/DatadogLogsPlugin.kt
|
DataDog
| 436,020,465
| false
| null |
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadoghq.flutter
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.datadog.android.Datadog
import com.datadog.android.event.EventMapper
import com.datadog.android.log.Logger
import com.datadog.android.log.Logs
import com.datadog.android.log.LogsConfiguration
import com.datadog.android.log.model.LogEvent
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.lang.ClassCastException
import java.lang.NullPointerException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.json.JSONArray
import org.json.JSONObject
class DatadogLogsPlugin internal constructor() : MethodChannel.MethodCallHandler {
companion object LogParameterNames {
const val LOG_LEVEL = "logLevel"
const val LOG_MESSAGE = "message"
const val LOG_CONTEXT = "context"
const val LOG_ERROR_MESSAGE = "errorMessage"
const val LOG_ERROR_KIND = "errorKind"
const val LOG_STACK_TRACE = "stackTrace"
const val LOG_KEY = "key"
const val LOG_TAG = "tag"
const val LOG_VALUE = "value"
// See DatadogSdkPlugin's description of this same member
private var previousConfiguration: Map<String, Any?>? = null
val instance: DatadogLogsPlugin by lazy {
DatadogLogsPlugin()
}
// For testing purposes only
internal fun resetConfig() {
previousConfiguration = null
}
}
private lateinit var channel: MethodChannel
private lateinit var binding: FlutterPlugin.FlutterPluginBinding
private val loggerRegistry: MutableMap<String, Logger> = mutableMapOf()
fun attachToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "datadog_sdk_flutter.logs")
channel.setMethodCallHandler(this)
binding = flutterPluginBinding
}
fun detachFromEngine() {
channel.setMethodCallHandler(null)
}
internal fun addLogger(loggerHandle: String, logger: Logger) {
loggerRegistry[loggerHandle] = logger
}
fun getLogger(loggerHandle: String): Logger? {
return loggerRegistry[loggerHandle]
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (handleGlobalMethod(call, result)) {
return
}
val loggerHandle = call.argument<String>("loggerHandle")
if (loggerHandle == null) {
result.missingParameter(call.method)
return
}
if (call.method == "createLogger") {
val encodedConfig = call.argument<Map<String, Any?>>("configuration")
if (encodedConfig != null) {
createLogger(loggerHandle, encodedConfig)
result.success(null)
} else {
result.invalidOperation("Bad logging configuration creating a logger")
}
return
}
getLogger(loggerHandle)?.let { logger ->
try {
if (call.method == "destroyLogger") {
loggerRegistry.remove(loggerHandle)
result.success(null)
} else {
callLoggerMethod(logger, call, result)
}
} catch (e: ClassCastException) {
result.error(
DatadogSdkPlugin.CONTRACT_VIOLATION,
e.toString(),
mapOf(
"methodName" to call.method
)
)
}
}
}
private fun handleGlobalMethod(call: MethodCall, result: MethodChannel.Result): Boolean {
if (call.method == "enable") {
enable(call, result)
return true
} else if (call.method == "deinitialize") {
deinitialize(call, result)
return true
} else if (call.method == "addGlobalAttribute") {
val key = call.argument<String>(LOG_KEY)
val value = call.argument<Any>(LOG_VALUE)
if (key != null && value != null) {
Logs.addAttribute(key, value)
result.success(null)
} else {
result.missingParameter(call.method)
}
return true
} else if (call.method == "removeGlobalAttribute") {
val key = call.argument<String>(LOG_KEY)
if (key != null) {
Logs.removeAttribute(key)
result.success(null)
} else {
result.missingParameter(call.method)
}
return true
}
return false
}
private fun enable(call: MethodCall, result: MethodChannel.Result) {
val encodedConfig = call.argument<Map<String, Any?>>("configuration")
if (previousConfiguration == null) {
if (encodedConfig != null) {
val config = LogsConfiguration.Builder()
.withEncoded(encodedConfig)
val attachLogMeapper = (encodedConfig["attachLogMapper"] as? Boolean) ?: false
if (attachLogMeapper) {
config.setEventMapper(
object : EventMapper<LogEvent> {
override fun map(event: LogEvent): LogEvent? {
return mapLogEvent(event)
}
}
)
}
Logs.enable(config.build())
previousConfiguration = encodedConfig
result.success(null)
} else {
result.invalidOperation("Bad configuration when enabling logging feature")
}
} else if (previousConfiguration != encodedConfig) {
// Maybe use DevLogger instead?
Log.e(DATADOG_FLUTTER_TAG, MESSAGE_INVALID_LOGGER_REINITIALIZATION)
}
}
private fun deinitialize(call: MethodCall, result: MethodChannel.Result) {
previousConfiguration = null
result.success(null)
}
@Suppress("LongMethod", "ComplexMethod", "NestedBlockDepth")
private fun callLoggerMethod(logger: Logger, call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"log" -> {
internalLog(logger, call, result)
}
"addAttribute" -> {
val key = call.argument<String>(LOG_KEY)
val value = call.argument<Any>(LOG_VALUE)
if (key != null && value != null) {
addAttributeInternal(logger, key, value)
result.success(null)
} else {
result.missingParameter(call.method)
}
}
"addTag" -> {
val tag = call.argument<String>(LOG_TAG)
if (tag != null) {
val value = call.argument<String>(LOG_VALUE)
if (value != null) {
logger.addTag(tag, value)
} else {
logger.addTag(tag)
}
result.success(null)
} else {
result.missingParameter(call.method)
}
}
"removeAttribute" -> {
val key = call.argument<String>(LOG_KEY)
if (key != null) {
logger.removeAttribute(key)
result.success(null)
} else {
result.missingParameter(call.method)
}
}
"removeTag" -> {
val tag = call.argument<String>(LOG_TAG)
if (tag != null) {
logger.removeTag(tag)
result.success(null)
} else {
result.missingParameter(call.method)
}
}
"removeTagWithKey" -> {
val key = call.argument<String>(LOG_KEY)
if (key != null) {
logger.removeTagsWithKey(key)
result.success(null)
} else {
result.missingParameter(call.method)
}
}
else -> {
result.notImplemented()
}
}
}
private fun createLogger(loggerHandle: String, configuration: Map<String, Any?>) {
val logBuilder = Logger.Builder()
.withEncoded(configuration)
val logger = logBuilder.build()
loggerRegistry[loggerHandle] = logger
}
@Suppress("TooGenericExceptionCaught")
private fun internalLog(
logger: Logger,
call: MethodCall,
result: MethodChannel.Result
) {
try {
val message = call.argument<String>(LOG_MESSAGE)!!
val level = parseLogLevel(call.argument<String>(LOG_LEVEL)!!)
val context = call.argument<Map<String, Any?>>(LOG_CONTEXT)!!
// Optional parameters
val errorKind = call.argument<String>(LOG_ERROR_KIND)
val errorMessage = call.argument<String>(LOG_ERROR_MESSAGE)
val stackTrace = call.argument<String>(LOG_STACK_TRACE)
logger.log(level, message, errorKind, errorMessage, stackTrace, context)
result.success(null)
} catch (e: ClassCastException) {
result.error(DatadogSdkPlugin.CONTRACT_VIOLATION, e.stackTraceToString(), null)
} catch (e: NullPointerException) {
result.error(DatadogSdkPlugin.CONTRACT_VIOLATION, e.stackTraceToString(), null)
}
}
private fun addAttributeInternal(logger: Logger, key: String, value: Any) {
when (value) {
is Boolean -> logger.addAttribute(key, value)
is Int -> logger.addAttribute(key, value)
is Long -> logger.addAttribute(key, value)
is String -> logger.addAttribute(key, value)
is Double -> logger.addAttribute(key, value)
is List<*> -> {
val jsonList = JSONArray(value)
logger.addAttribute(key, jsonList)
}
is Map<*, *> -> {
val jsonObject = JSONObject(value)
logger.addAttribute(key, jsonObject)
}
}
}
@Suppress("TooGenericExceptionCaught")
internal fun mapLogEvent(event: LogEvent): LogEvent? {
val jsonEvent = event.toJson().asFlutterMap()
var modifiedJson: Map<String, Any?>? = null
val latch = CountDownLatch(1)
val handler = Handler(Looper.getMainLooper())
handler.post {
try {
channel.invokeMethod(
"mapLogEvent",
mapOf(
"event" to jsonEvent
),
object : MethodChannel.Result {
override fun success(result: Any?) {
@Suppress("UNCHECKED_CAST")
modifiedJson = result as? Map<String, Any?>
latch.countDown()
}
override fun error(
errorCode: String,
errorMessage: String?,
errorDetails: Any?
) {
// No telemetry needed, this is likely an issue in user code
latch.countDown()
}
override fun notImplemented() {
Datadog._internalProxy()._telemetry.error(
"mapLogEvent returned notImplemented."
)
latch.countDown()
}
}
)
} catch (e: Exception) {
Datadog._internalProxy()._telemetry.error("Attempting call mapLogEvent failed.", e)
latch.countDown()
}
}
try {
// Stalls until the method channel finishes
if (!latch.await(1, TimeUnit.SECONDS)) {
Datadog._internalProxy()._telemetry.debug("logMapper timed out")
return event
}
return modifiedJson?.let {
if (!it.containsKey("_dd.mapper_error")) {
val modifiedEvent = LogEvent.fromJsonObject(modifiedJson!!.toJsonObject())
event.status = modifiedEvent.status
event.message = modifiedEvent.message
event.ddtags = modifiedEvent.ddtags
event.logger.name = modifiedEvent.logger.name
event.error?.fingerprint = modifiedEvent.error?.fingerprint
event.additionalProperties.clear()
event.additionalProperties.putAll(modifiedEvent.additionalProperties)
}
event
}
} catch (e: Exception) {
Datadog._internalProxy()._telemetry.error(
"Attempt to deserialize mapped log event failed, or latch await was interrupted." +
" Returning unmodified event.",
e
)
return event
}
}
}
fun LogsConfiguration.Builder.withEncoded(encoded: Map<String, Any?>): LogsConfiguration.Builder {
var builder = this
(encoded["customEndpoint"] as? String)?.let {
builder = builder.useCustomEndpoint(it)
}
return builder
}
fun Logger.Builder.withEncoded(encoded: Map<String, Any?>): Logger.Builder {
var builder = this
(encoded["service"] as? String)?.let {
builder = builder.setService(it)
}
(encoded["name"] as? String)?.let {
builder = builder.setName(it)
}
(encoded["networkInfoEnabled"] as? Boolean)?.let {
builder = builder.setNetworkInfoEnabled(it)
}
(encoded["bundleWithRumEnabled"] as? Boolean)?.let {
builder = builder.setBundleWithRumEnabled(it)
}
(encoded["bundleWithTraceEnabled"] as? Boolean)?.let {
builder = builder.setBundleWithTraceEnabled(it)
}
return builder
}
internal fun parseLogLevel(logLevel: String): Int {
return when (logLevel) {
"LogLevel.debug" -> Log.DEBUG
"LogLevel.info" -> Log.INFO
"LogLevel.notice" -> Log.WARN
"LogLevel.warning" -> Log.WARN
"LogLevel.error" -> Log.ERROR
"LogLevel.critical" -> Log.ASSERT
"LogLevel.alert" -> Log.ASSERT
"LogLevel.emergency" -> Log.ASSERT
else -> Log.INFO
}
}
internal const val MESSAGE_INVALID_LOGGER_REINITIALIZATION =
"🔥 Re-enabling the Datadog Logging with different options is not supported, even after a" +
" hot restart. Cold restart your application to change your current configuration."
| 18
| null |
38
| 42
|
a5657fe3aa7a944b2849de9f93be4936d5689833
| 15,367
|
dd-sdk-flutter
|
Apache License 2.0
|
matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/pushers/DefaultPusherService.kt
|
saad100104006
| 212,864,777
| true
|
{"Kotlin": 3623105, "Java": 26427, "HTML": 22563, "Shell": 20524}
|
/*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.matrix.android.internal.session.pushers
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.work.BackoffPolicy
import androidx.work.WorkManager
import com.zhuinden.monarchy.Monarchy
import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.api.auth.data.SessionParams
import im.vector.matrix.android.api.session.pushers.Pusher
import im.vector.matrix.android.api.session.pushers.PushersService
import im.vector.matrix.android.internal.database.mapper.asDomain
import im.vector.matrix.android.internal.database.model.PusherEntity
import im.vector.matrix.android.internal.database.query.where
import im.vector.matrix.android.internal.task.TaskExecutor
import im.vector.matrix.android.internal.task.configureWith
import im.vector.matrix.android.internal.task.toConfigurableTask
import im.vector.matrix.android.internal.worker.WorkManagerUtil
import im.vector.matrix.android.internal.worker.WorkManagerUtil.matrixOneTimeWorkRequestBuilder
import im.vector.matrix.android.internal.worker.WorkerParamsFactory
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
internal class DefaultPusherService @Inject constructor(
private val context: Context,
private val monarchy: Monarchy,
private val sessionParam: SessionParams,
private val getPusherTask: GetPushersTask,
private val removePusherTask: RemovePusherTask,
private val taskExecutor: TaskExecutor
) : PushersService {
override fun refreshPushers() {
getPusherTask
.toConfigurableTask()
.executeBy(taskExecutor)
}
override fun addHttpPusher(pushkey: String, appId: String, profileTag: String,
lang: String, appDisplayName: String, deviceDisplayName: String,
url: String, append: Boolean, withEventIdOnly: Boolean)
: UUID {
val pusher = JsonPusher(
pushKey = pushkey,
kind = "http",
appId = appId,
appDisplayName = appDisplayName,
deviceDisplayName = deviceDisplayName,
profileTag = profileTag,
lang = lang,
data = JsonPusherData(url, if (withEventIdOnly) PushersService.EVENT_ID_ONLY else null),
append = append)
val params = AddHttpPusherWorker.Params(pusher, sessionParam.credentials.userId)
val request = matrixOneTimeWorkRequestBuilder<AddHttpPusherWorker>()
.setConstraints(WorkManagerUtil.workConstraints)
.setInputData(WorkerParamsFactory.toData(params))
.setBackoffCriteria(BackoffPolicy.LINEAR, 10_000L, TimeUnit.MILLISECONDS)
.build()
WorkManager.getInstance(context).enqueue(request)
return request.id
}
override fun removeHttpPusher(pushkey: String, appId: String, callback: MatrixCallback<Unit>) {
val params = RemovePusherTask.Params(sessionParam.credentials.userId, pushkey, appId)
removePusherTask
.configureWith(params)
.dispatchTo(callback)
//.enableRetry() ??
.executeBy(taskExecutor)
}
override fun livePushers(): LiveData<List<Pusher>> {
return monarchy.findAllMappedWithChanges(
{ realm -> PusherEntity.where(realm, sessionParam.credentials.userId) },
{ it.asDomain() }
)
}
override fun pushers(): List<Pusher> {
return monarchy.fetchAllCopiedSync { PusherEntity.where(it, sessionParam.credentials.userId) }.map { it.asDomain() }
}
}
| 2
| null |
0
| 2
|
588e5d6e63ecfee9d93ef3da5987b8deb59f412f
| 4,299
|
NovaChat
|
Apache License 2.0
|
rx_activity_result/src/main/kotlin/rx_activity_result3/OnResult.kt
|
vickyleu
| 437,791,262
| true
|
{"Kotlin": 16485}
|
package rx_activity_result3
import android.content.Intent
import java.io.Serializable
interface OnResult : Serializable {
fun response(requestCode: Int, resultCode: Int, data: Intent?)
fun error(throwable: Throwable?)
}
| 0
|
Kotlin
|
0
| 0
|
29d02371dfef744aa6ad15bffb2ca73e7261b3eb
| 229
|
RxActivityResult
|
Apache License 2.0
|
src/main/kotlin/no/nav/k9brukerdialogapi/oppslag/arbeidsgiver/Arbeidsgivere.kt
|
navikt
| 460,765,798
| false
| null |
package no.nav.helse.arbeidsgiver
import java.time.LocalDate
data class ArbeidsgivereOppslagRespons (
val arbeidsgivere: Arbeidsgivere
)
data class Arbeidsgivere (
val organisasjoner: List<Organisasjon>,
val privateArbeidsgivere: List<PrivatArbeidsgiver>?
)
class Organisasjon (
val organisasjonsnummer: String,
val navn: String?
)
data class PrivatArbeidsgiver (
val offentligIdent: String,
val ansattFom: LocalDate? = null,
val ansattTom: LocalDate? = null
)
| 9
|
Kotlin
|
0
| 0
|
f218e4420e5b39d209fe3d92148dbe3ffe095d48
| 497
|
pleiepengesoknad-api
|
MIT License
|
backend/data/src/test/kotlin/io/tolgee/unit/service/dataImport/processors/processors/xliff/Xliff12FileProcessorTest.kt
|
tolgee
| 303,766,501
| false
| null |
package io.tolgee.unit.service.dataImport.processors.processors.xliff
import io.tolgee.dtos.dataImport.ImportFileDto
import io.tolgee.model.dataImport.Import
import io.tolgee.model.dataImport.ImportFile
import io.tolgee.model.dataImport.issues.issueTypes.FileIssueType
import io.tolgee.model.dataImport.issues.paramTypes.FileIssueParamType
import io.tolgee.service.dataImport.processors.FileProcessorContext
import io.tolgee.service.dataImport.processors.xliff.Xliff12FileProcessor
import org.assertj.core.api.Assertions.assertThat
import org.mockito.kotlin.mock
import org.testng.annotations.BeforeMethod
import org.testng.annotations.Test
import java.io.File
import javax.xml.stream.XMLEventReader
import javax.xml.stream.XMLInputFactory
class Xliff12FileProcessorTest {
private lateinit var importMock: Import
private lateinit var importFile: ImportFile
private lateinit var importFileDto: ImportFileDto
private lateinit var fileProcessorContext: FileProcessorContext
private val inputFactory: XMLInputFactory = XMLInputFactory.newInstance()
private lateinit var xmlStreamReader: XMLEventReader
@BeforeMethod
fun setup() {
importMock = mock()
importFile = ImportFile("exmample.xliff", importMock)
importFileDto = ImportFileDto(
"exmample.xliff",
File("src/test/resources/import/xliff/example.xliff")
.inputStream()
)
xmlStreamReader = inputFactory.createXMLEventReader(importFileDto.inputStream)
fileProcessorContext = FileProcessorContext(importFileDto, importFile, mock())
}
@Test
fun `processes xliff 12 file correctly`() {
Xliff12FileProcessor(fileProcessorContext, xmlStreamReader).process()
assertThat(fileProcessorContext.languages).hasSize(2)
assertThat(fileProcessorContext.translations).hasSize(176)
assertThat(fileProcessorContext.translations["vpn.devices.removeA11Y"]!![0].text).isEqualTo("Remove %1")
assertThat(fileProcessorContext.translations["vpn.devices.removeA11Y"]!![0].language.name).isEqualTo("en")
assertThat(fileProcessorContext.translations["vpn.devices.removeA11Y"]!![1].text).isEqualTo("Eliminar %1")
assertThat(fileProcessorContext.translations["vpn.devices.removeA11Y"]!![1].language.name).isEqualTo("es-MX")
val keyMeta = fileProcessorContext.keys["vpn.aboutUs.releaseVersion"]!!.keyMeta!!
assertThat(keyMeta.comments).hasSize(1)
assertThat(keyMeta.comments[0].text).isEqualTo(
"Refers to the installed version." +
" For example: \"Release Version: 1.23\""
)
assertThat(keyMeta.codeReferences).hasSize(1)
assertThat(keyMeta.codeReferences[0].path).isEqualTo("../src/ui/components/VPNAboutUs.qml")
assertThat(fileProcessorContext.translations["systray.quit"]!![0].text).isEqualTo(
"<x equiv-text=\"{{ favorite ? 'Remove from favorites' :" +
" 'Add to favorites'}}\" id=\"INTERPOLATION\"></x>"
)
assertThat(fileProcessorContext.translations["systray.quit"]!![1].text)
.isEqualTo(
"<x equiv-text=\"{{ favorite ? 'Remove from favorites' :" +
" 'Add to favorites'}}\" id=\"INTERPOLATION\"></x>"
)
}
@Test
fun `processes xliff 12 fast enough`() {
importFileDto = ImportFileDto(
"exmample.xliff",
File("src/test/resources/import/xliff/larger.xlf")
.inputStream()
)
fileProcessorContext = FileProcessorContext(importFileDto, importFile, mock())
xmlStreamReader = inputFactory.createXMLEventReader(importFileDto.inputStream)
val start = System.currentTimeMillis()
Xliff12FileProcessor(fileProcessorContext, xmlStreamReader).process()
assertThat(System.currentTimeMillis() - start).isLessThan(4000)
}
@Test
fun `handles errors correctly`() {
importFileDto = ImportFileDto(
"exmample.xliff",
File("src/test/resources/import/xliff/error_example.xliff")
.inputStream()
)
xmlStreamReader = inputFactory.createXMLEventReader(importFileDto.inputStream)
fileProcessorContext = FileProcessorContext(importFileDto, importFile, mock())
Xliff12FileProcessor(fileProcessorContext, xmlStreamReader).process()
assertThat(fileProcessorContext.translations).hasSize(2)
fileProcessorContext.fileEntity.issues.let { issues ->
assertThat(issues).hasSize(4)
assertThat(issues[0].type).isEqualTo(FileIssueType.TARGET_NOT_PROVIDED)
assertThat(issues[0].params!![0].type).isEqualTo(FileIssueParamType.KEY_NAME)
assertThat(issues[0].params!![0].value).isEqualTo("vpn.main.back")
assertThat(issues[1].type).isEqualTo(FileIssueType.ID_ATTRIBUTE_NOT_PROVIDED)
assertThat(issues[1].params!![0].type).isEqualTo(FileIssueParamType.FILE_NODE_ORIGINAL)
assertThat(issues[1].params!![0].value).isEqualTo("../src/platforms/android/androidauthenticationview.qml")
}
}
}
| 50
| null |
81
| 666
|
38c1064783f3ec5d60d0502ec0420698395af539
| 4,812
|
tolgee-platform
|
Apache License 2.0
|
epoxy-processor/src/main/java/com/airbnb/epoxy/DataBindingModelInfo.kt
|
CPLASF1925
| 126,679,184
| true
|
{"Java Properties": 2, "YAML": 1, "Markdown": 5, "Gradle": 17, "Shell": 1, "Batchfile": 1, "Text": 1, "Ruby": 1, "Ignore List": 13, "XML": 66, "Proguard": 8, "Kotlin": 41, "INI": 6, "Java": 374, "JSON": 2}
|
package com.airbnb.epoxy
import com.airbnb.epoxy.ClassNames.*
import com.airbnb.epoxy.Utils.*
import com.squareup.javapoet.*
import javax.lang.model.element.*
import javax.lang.model.util.*
internal class DataBindingModelInfo(
private val typeUtils: Types,
private val elementUtils: Elements,
val layoutResource: ResourceValue,
val moduleName: String,
private val layoutPrefix: String = ""
) : GeneratedModelInfo() {
private val dataBindingClassName: ClassName
val dataBindingClassElement: Element?
get() = getElementByName(dataBindingClassName, elementUtils, typeUtils)
init {
dataBindingClassName = getDataBindingClassNameForResource(layoutResource, moduleName)
superClassElement = Utils.getElementByName(EPOXY_DATA_BINDING_MODEL,
elementUtils, typeUtils) as TypeElement
superClassName = EPOXY_DATA_BINDING_MODEL
generatedClassName = buildGeneratedModelName()
parametrizedClassName = generatedClassName
boundObjectTypeName = EPOXY_DATA_BINDING_HOLDER
shouldGenerateModel = true
collectMethodsReturningClassType(superClassElement, typeUtils)
}
/**
* Look up the DataBinding class generated for this model's layout file and parse the attributes
* for it.
*/
fun parseDataBindingClass() {
// This databinding class won't exist until the second round of annotation processing since
// it is generated in the first round.
val hashCodeValidator = HashCodeValidator(typeUtils, elementUtils)
dataBindingClassElement!!.enclosedElements
.filter { Utils.isSetterMethod(it) }
.forEach {
addAttribute(
DataBindingAttributeInfo(this, it as ExecutableElement,
hashCodeValidator))
}
}
private fun getDataBindingClassNameForResource(
layoutResource: ResourceValue,
moduleName: String
): ClassName {
val modelName = layoutResource.resourceName!!.toUpperCamelCase().plus(BINDING_SUFFIX)
return ClassName.get(moduleName + ".databinding", modelName)
}
private fun buildGeneratedModelName(): ClassName {
val modelName = layoutResource.resourceName!!
.removePrefix(layoutPrefix)
.toUpperCamelCase()
.plus(BINDING_SUFFIX)
.plus(GeneratedModelInfo.GENERATED_MODEL_SUFFIX)
return ClassName.get(moduleName, modelName)
}
companion object {
val BINDING_SUFFIX = "Binding"
}
}
| 0
|
Java
|
0
| 1
|
d1da6fbc5775c24927bde4e9ea3335234ce44e81
| 2,707
|
epoxy
|
Apache License 2.0
|
DSL/com.larsreimann.safeds/src/main/kotlin/com/larsreimann/safeds/constant/SdsProtocolTokenClassValue.kt
|
lars-reimann
| 499,036,565
| false
| null |
package com.larsreimann.safeds.constant
import com.larsreimann.safeds.safeDS.SdsProtocolTokenClass
import com.larsreimann.safeds.utils.ExperimentalSdsApi
/**
* The possible values for an [SdsProtocolTokenClass].
*/
@ExperimentalSdsApi
enum class SdsProtocolTokenClassValue(val value: String) {
/**
* Matches any attribute or function.
*/
Anything("."),
/**
* Matches any attribute.
*/
AnyAttribute("\\a"),
/**
* Matches any function.
*/
AnyFunction("\\f");
override fun toString(): String {
return value
}
}
/**
* Returns the [SdsProtocolTokenClassValue] of this [SdsProtocolTokenClass].
*
* @throws IllegalArgumentException If the value is unknown.
*/
@ExperimentalSdsApi
fun SdsProtocolTokenClass.value(): SdsProtocolTokenClassValue {
return SdsProtocolTokenClassValue.values().firstOrNull { it.value == this.value }
?: throw IllegalArgumentException("Unknown token class value value '$value'.")
}
| 47
|
Kotlin
|
0
| 9
|
db8c0d1e33ff177b48fc0d118291628d29f7a865
| 995
|
Safe-DS
|
MIT License
|
ktoml-core/src/commonTest/kotlin/com/akuleshov7/ktoml/encoders/PrimitiveEncoderTest.kt
|
orchestr7
| 330,720,838
| false
| null |
package com.akuleshov7.ktoml.encoders
import com.akuleshov7.ktoml.annotations.TomlLiteral
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlin.test.Test
class PrimitiveEncoderTest {
@Serializable
enum class Greeting {
@SerialName("hello") Hello
}
@Test
fun primitivesTest() {
@Serializable
data class File(
val enabled: Boolean = true,
val pi: Double = 3.14,
val count: Long = 3,
val port: Int = 8080,
val greeting: String = "hello",
val enumGreeting: Greeting = Greeting.Hello,
@TomlLiteral
val path: String = """C:\some\path\"""
)
assertEncodedEquals(
value = File(),
expectedToml = """
enabled = true
pi = 3.14
count = 3
port = 8080
greeting = "hello"
enumGreeting = "hello"
path = 'C:\some\path\'
""".trimIndent()
)
}
@Test
fun stringEscapeTest() {
@Serializable
data class File(
val escapeString: String? = null,
@TomlLiteral
val literalEscapeString: String? = null
)
val tab = '\t'
assertEncodedEquals(
value = File("\"hello world\""),
expectedToml = """escapeString = "\"hello world\"""""
)
assertEncodedEquals(
value = File("hello \b\t\n\u000C\r world"),
expectedToml = """escapeString = "hello \b$tab\n\f\r world""""
)
assertEncodedEquals(
value = File("hello \u0000 world"),
expectedToml = """escapeString = "hello \u0000 world""""
)
assertEncodedEquals(
value = File("""hello\world"""),
expectedToml = """escapeString = "hello\\world""""
)
assertEncodedEquals(
value = File("""hello \Uffffffff world"""),
expectedToml = """escapeString = "hello \Uffffffff world""""
)
assertEncodedEquals(
value = File(literalEscapeString = "'quotes'"),
expectedToml = """literalEscapeString = '\'quotes\''"""
)
}
@Test
fun jsWholeDoubleRegression() {
@Serializable
data class File(
val wholeNumberDouble: Double = 3.0
)
assertEncodedEquals(
value = File(),
expectedToml = "wholeNumberDouble = 3.0"
)
}
}
| 36
| null |
23
| 450
|
b22969a093d3a1f062d3b9840c9195c09951d8b2
| 2,580
|
ktoml
|
MIT License
|
file/src/commonMain/kotlin/cache/CacheFileConfig.kt
|
aSoft-Ltd
| 521,105,120
| false
| null |
package keep
import koncurrent.Executor
import kotlinx.serialization.StringFormat
import kotlinx.serialization.json.Json
import okio.FileSystem
import okio.Path
import kotlin.jvm.JvmField
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
interface CacheFileConfig : CacheConfig {
val fs: FileSystem
val dir: Path
val codec: StringFormat
val extension: String
companion object {
@JvmField
val DEFAULT_EXTENSION = "cache"
@JvmField
val DEFAULT_CODEC = Json { }
@JvmName("create")
@JvmStatic
@JvmOverloads
operator fun invoke(
fs: FileSystem,
path: Path,
namespace: String = CacheConfig.DEFAULT_NAMESPACE,
executor: Executor = CacheConfig.DEFAULT_EXECUTOR,
codec: StringFormat = DEFAULT_CODEC,
extension: String = DEFAULT_EXTENSION
): CacheFileConfig = object : CacheFileConfig {
override val fs: FileSystem = fs
override val dir: Path = path
override val codec: StringFormat = codec
override val namespace: String = namespace
override val executor: Executor = executor
override val extension: String = extension
}
}
}
| 0
|
Kotlin
|
0
| 2
|
45b36b1aaddfe70d0817ca33f1abc6466e3c8921
| 1,304
|
cache
|
MIT License
|
app/src/main/java/com/sfeatherstone/workmanagerexample/MainViewModel.kt
|
sfeatherstone
| 253,478,599
| false
| null |
package com.sfeatherstone.workmanagerexample
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.work.WorkInfo
import androidx.work.WorkManager
import java.util.*
class MainViewModel : ViewModel() {
data class JobDescription(val index: Int, val state: String, internal val liveData: LiveData<WorkInfo>, internal val observer: Observer<WorkInfo>)
private val currentJobs = mutableMapOf<UUID, JobDescription>()
var jobsByTag: LiveData<List<WorkInfo>>? = null
var jobsByTagObserver: Observer<List<WorkInfo>>? = null
private val mutableJobs: MutableLiveData<Map<UUID, JobDescription>> = MutableLiveData(currentJobs)
val jobs: LiveData<Map<UUID, JobDescription>> = mutableJobs
fun postToServer(applicationContext: Context, successPercent: Int, index: Int) {
val workManager = WorkManager.getInstance(applicationContext)
val uuid = PostToServerWorker.submitPost(applicationContext, 3000, successPercent, "Example-$index")
val liveData = workManager.getWorkInfoByIdLiveData(uuid)
val observer = Observer<WorkInfo> {
updateLiveData(it)
}
currentJobs[uuid] = JobDescription(index, "Submitted", liveData, observer)
liveData.observeForever(observer)
}
fun getAllJobs(applicationContext: Context) {
val workManager = WorkManager.getInstance(applicationContext)
jobsByTag = workManager.getWorkInfosByTagLiveData("com.sfeatherstone.workmanagerexample.PostToServerWorker")
jobsByTagObserver = Observer {
for(wi in it) {
if (!currentJobs.containsKey(wi.id)) {
val observer = Observer<WorkInfo> { workInfo ->
updateLiveData(workInfo)
}
val liveData = workManager.getWorkInfoByIdLiveData(wi.id)
currentJobs[wi.id] = JobDescription(0, "Historic", liveData, observer)
liveData.observeForever(observer)
}
}
}
jobsByTag?.observeForever(jobsByTagObserver!!)
}
override fun onCleared() {
super.onCleared()
// Need to clear observers as we have no lifecycle here
for(item in currentJobs) {
item.value.liveData.removeObserver(item.value.observer)
}
jobsByTag?.let {
it.removeObserver(jobsByTagObserver!!)
}
}
private fun updateLiveData(workInfo: WorkInfo) {
// Copy jobDescription with new status
val newJobDescription = currentJobs[workInfo.id]
?.copy(state = "id:${workInfo.id}\ntags:${workInfo.tags.joinToString(separator = ", ")}\nstate:${workInfo.state.name} progress:${workInfo.progress}")
newJobDescription?.let {
currentJobs[workInfo.id] = it
}
// Trigger change in LD
mutableJobs.value = currentJobs
}
}
| 0
|
Kotlin
|
0
| 0
|
1c66e0e034f5436acbb7acbe2f09c3baa2125ee0
| 3,032
|
example-WorkManager
|
Apache License 2.0
|
core/src/commonTest/kotlin/maryk/core/properties/types/GeoPointTest.kt
|
marykdb
| 290,454,412
| false
|
{"Kotlin": 3293783, "JavaScript": 1004}
|
package maryk.core.properties.types
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class GeoPointTest {
@Test
fun initTest() {
GeoPoint(56.2345, 140.233214)
GeoPoint(-23.532, -90.18231)
assertFailsWith<IllegalArgumentException> {
GeoPoint(-96.24242, -90.18231)
}
assertFailsWith<IllegalArgumentException> {
GeoPoint(106.35938, 110.3242)
}
assertFailsWith<IllegalArgumentException> {
GeoPoint(42.12423, 190.3242)
}
assertFailsWith<IllegalArgumentException> {
GeoPoint(42.12423, -190.3242)
}
}
@Test
fun convertToProtoBufLong() {
assertEquals(2415253385471452140L, GeoPoint(56.2345, 140.233214).asLong())
assertEquals(-1010691700701575804L, GeoPoint(-23.532, -90.18231).asLong())
}
@Test
fun convertCoordinates() {
val point = GeoPoint(56.2345, 140.233214)
val lat = point.latitudeAsInt()
val long = point.longitudeAsInt()
val converted = GeoPoint(lat, long)
assertEquals(point, converted)
}
@Test
fun convertToString() {
assertEquals("52.0906448,5.1212607", GeoPoint(52.0906448, 5.1212607).toString())
assertEquals("-54.8034246,-68.2969808", GeoPoint(-54.8034246, -68.2969808).toString())
}
@Test
fun parseFromString() {
assertEquals("52.0906448,5.1212607".toGeoPoint(), GeoPoint(52.0906448, 5.1212607))
assertEquals("-54.8034246, -68.2969808".toGeoPoint(), GeoPoint(-54.8034246, -68.2969808))
}
}
| 1
|
Kotlin
|
1
| 8
|
c3b4069317a3f7880ac33baef01f947b78648267
| 1,628
|
maryk
|
Apache License 2.0
|
InkAndroidExtensions/src/main/java/com/inlacou/inkandroidextensions/ActivityExtensions.kt
|
inlacou
| 400,138,100
| false
| null |
package com.inlacou.inkandroidextensions
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Point
import android.net.Uri
import android.os.Build
import android.util.DisplayMetrics
import android.view.Display
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.FileProvider
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.snackbar.Snackbar
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
fun Activity.windowSize(): Point {
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size)
return size
}
@RequiresApi(api = Build.VERSION_CODES.R)
fun Context.windowSize(): Point {
val displayMetrics = DisplayMetrics()
val display: Display = display!!
display.getRealMetrics(displayMetrics)
return Point(displayMetrics.widthPixels, displayMetrics.heightPixels)
}
fun Activity.startActivity(intent: Intent, requestCode: Int? = null){
if(requestCode!=null){
startActivityForResult(intent, requestCode)
}else{
startActivity(intent)
}
}
fun Activity.hideKeyboard(){
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Find the currently focused view, so we can grab the correct window token from it.
var view = currentFocus
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = View(this)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
/**
* callback boolean determines if it should continue this path or not
*/
fun Activity.iterateOverAllViews(doSomething: ((View) -> Boolean)? = null, debug: Boolean = false){
if(debug) Timber.d("family | start: ${getView()}")
var view = getView()
try {
while (view!=null){
view = view.parent as View?
if(debug) Timber.d("family | parent: $view")
}
}catch (e: java.lang.Exception){
if(debug) Timber.d("family | final parent: $view")
view?.let { handleView(it, debug = debug, callback = doSomething) }
}
}
private fun handleView(view: View, tag: String = " |", debug: Boolean = false, callback: ((View) -> Boolean)? = null){
if(debug) Timber.d("family$tag $view")
if(callback?.invoke(view)!=false) {
when (view) {
is AppBarLayout -> {
(0 until view.childCount)
.map { view.getChildAt(it) }
.forEach { handleView(it, "$tag appBarChild |", debug = debug, callback = callback) }
}
is LinearLayout -> {
(0 until view.childCount)
.map { view.getChildAt(it) }
.forEach { handleView(it, "$tag linearChild |", debug = debug, callback = callback) }
}
is DrawerLayout -> {
(0 until view.childCount)
.map { view.getChildAt(it) }
.forEach { handleView(it, "$tag drawerChild |", debug = debug, callback = callback) }
}
is ScrollView -> {
(0 until view.childCount)
.map { view.getChildAt(it) }
.forEach { handleView(it, "$tag scrollChild |", debug = debug, callback = callback) }
}
is FrameLayout -> {
(0 until view.childCount)
.map { view.getChildAt(it) }
.forEach { handleView(it, "$tag frameChild |", debug = debug, callback = callback) }
}
is RelativeLayout -> {
(0 until view.childCount)
.map { view.getChildAt(it) }
.forEach { handleView(it, "$tag relativeChild |", debug = debug, callback = callback) }
}
is CoordinatorLayout -> {
(0 until view.childCount)
.map { view.getChildAt(it) }
.forEach { handleView(it, "$tag coordinatorChild |", debug = debug, callback = callback) }
}
is ViewGroup -> {
(0 until view.childCount)
.map { view.getChildAt(it) }
.forEach { handleView(it, "$tag coordinatorChild |", debug = debug, callback = callback) }
}
}
}
}
fun Activity.handleThrowable(throwable: Throwable){
//if(throwable is VolleyError){
// handleGenericError(throwable, null)
//}else{
Timber.e(throwable.message)
//}
}
/*fun Activity?.handleGenericError(exception: Exception?, s: String? = null) {
Timber.d(".handleGenericError | Code: $s | Error: $exception | message: ${exception?.message}")
Timber.d(".handleGenericError | Code: ${this!=null} && ${exception!=null} && ${exception is VolleyError}")
if (this!=null && exception!=null && exception is VolleyError) {
try {
Timber.d(".handleGenericError2 | ${exception.errorMessage}")
} catch (e: Exception) {}
try {
val jsonObject = JSONObject(exception.errorMessage)
Timber.d(".handleGenericError | jsonObject: $jsonObject")
snackbar(when {
jsonObject.has("localized_description") -> jsonObject.getString("localized_description")
jsonObject.has("error_description") -> jsonObject.getString("error_description").let {
when(it){
"AUTH_INVALID_CREDENTIALS" -> getString(R.string.Auth_invalid_credentials)
else -> it
}
}
jsonObject.has("msg") -> jsonObject.getString("msg")
jsonObject.has("message") -> jsonObject.getString("message")
else -> this.getString(R.string.Unknown_server_error)
})
} catch (e: JSONException) {
e.printStackTrace()
snackbar(when(exception){
is NoConnectionError -> this.getString(R.string.Could_not_reach_server_check_internet_connection)
else -> this.getString(R.string.Unknown_server_error)
})
}
}
}*/
/**
* Saves the image as PNG to the app's cache directory.
* @param image Bitmap to save.
* @return Uri of the saved file or null
*/
fun Activity.saveImage(image: Bitmap, onComplete: (Uri?) -> Unit): Disposable {
return Observable.just(1).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.computation()).subscribe({
val imagesFolder = File(cacheDir, "images")
var uri: Uri? = null
try {
imagesFolder.mkdirs()
val file = File(imagesFolder, "shared_image.png")
val stream = FileOutputStream(file)
image.compress(Bitmap.CompressFormat.PNG, 90, stream)
stream.flush()
stream.close()
uri = FileProvider.getUriForFile(this, "$packageName.fileprovider", file)
} catch (e: IOException) {
Timber.d("IOException while trying to write file for sharing: " + e.message)
}
onComplete.invoke(uri)
},{})
}
fun Activity.toast(messageResId: Int, duration: Int = Toast.LENGTH_SHORT) = toast(getString(messageResId), duration)
fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Timber.d("toasted: $message")
Toast.makeText(this, message, duration).show()
}
fun Activity.dialog(messageResId: Int, titleResId: Int? = null) = dialog(getString(messageResId), if(titleResId!=null) getString(titleResId) else null)
fun Activity.dialog(message: CharSequence, title: CharSequence? = null) {
Timber.d("alerted: $message")
val builder = AlertDialog.Builder(this)
title?.let { builder.setTitle(it) }
message.let { builder.setMessage(message) }
builder.show()
}
fun Activity?.snackbar(message: String, length: Int = Snackbar.LENGTH_LONG) = this?.getView()?.let {
Timber.d("Snackbaring $message")
Snackbar.make(it, message, length).apply {
view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text).apply {
setTextColor(getColorCompat(R.color.snackbar_text_color_over_dark))
}
}.show()
}
fun Activity?.snackbar(messageResId: Int, length: Int = Snackbar.LENGTH_LONG) = this?.getView()?.let { snackbar(getString(messageResId), length) }
fun Activity?.getView(): View? = this?.window?.decorView?.findViewById(android.R.id.content)
fun Activity?.disableScreenTimeout() = this?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
fun Activity?.enableScreenTimeout() = this?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
| 0
|
Kotlin
|
0
| 0
|
5e6cc3d3d9358efca24a5cfe1c85802077c0323f
| 8,218
|
InkCommons
|
MIT License
|
src/main/kotlin/fr/yodamad/svn2git/service/util/GitTagManager.kt
|
yodamad
| 154,624,834
| false
| null |
package fr.yodamad.svn2git.service.util
import fr.yodamad.svn2git.data.WorkUnit
import fr.yodamad.svn2git.domain.enumeration.StatusEnum
import fr.yodamad.svn2git.domain.enumeration.StepEnum
import fr.yodamad.svn2git.functions.isFileInFolder
import fr.yodamad.svn2git.functions.listTagsOnly
import fr.yodamad.svn2git.io.Shell.execCommand
import fr.yodamad.svn2git.service.GitManager
import fr.yodamad.svn2git.service.HistoryManager
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.io.IOException
@Service
open class GitTagManager(val gitManager: GitManager,
val gitCommandManager: GitCommandManager,
val historyMgr: HistoryManager) {
private val LOG = LoggerFactory.getLogger(GitTagManager::class.java)
private val FAILED_TO_PUSH_TAG = "Failed to push tag"
/**
* Manage tags extracted from SVN
*
* @param workUnit
* @param remotes
*/
open fun manageTags(workUnit: WorkUnit, remotes: List<String>) {
listTagsOnly(remotes)?.stream()?.filter {
t -> workUnit.migration.tagsToMigrate == null || workUnit.migration.tagsToMigrate.split(",").any { a -> t.endsWith(a) }
}?.forEach { t: String ->
val warn: Boolean = pushTag(workUnit, t)
gitCommandManager.sleepBeforePush(workUnit, warn)
}
}
/**
* Push a tag
*
* @param workUnit Current work unit
* @param tag Tag to migrate
*/
open fun pushTag(workUnit: WorkUnit, tag: String): Boolean {
val history = historyMgr.startStep(workUnit.migration, StepEnum.GIT_PUSH, tag)
try {
// derive local tagName from remote tag name
val tagName = tag.replaceFirst(ORIGIN_TAGS.toRegex(), "")
LOG.debug("Tag $tagName")
// determine noHistory flag i.e was all selected or not
val noHistory = workUnit.migration.svnHistory != "all"
// checkout a new branch using local tagName and remote tag name
execCommand(workUnit.commandManager, workUnit.directory, "git checkout -b tmp_tag \"$tag\"")
// If this tag does not contain any files we will ignore it and add warning to logs.
if (!isFileInFolder(workUnit.directory)) {
// Switch over to master
execCommand(workUnit.commandManager, workUnit.directory, "git checkout master")
// Now we can delete the branch tmp_tag
execCommand(workUnit.commandManager, workUnit.directory, "git branch -D tmp_tag")
historyMgr.endStep(history, StatusEnum.IGNORED, "Ignoring Tag: $tag : Because there are no files to commit.")
} else {
// creates a temporary orphan branch and renames it to tmp_tag
if (noHistory) {
gitManager.removeHistory(workUnit, "tmp_tag", true, history)
}
// Checkout master.
execCommand(workUnit.commandManager, workUnit.directory, "git checkout master")
// create tag from tmp_tag branch.
execCommand(workUnit.commandManager, workUnit.directory, "git tag \"$tagName\" tmp_tag")
// add remote to master
gitManager.addRemote(workUnit, false)
// push the tag to remote
// crashes if branch with same name so prefixing with refs/tags/
execCommand(workUnit.commandManager, workUnit.directory, "git push -u origin \"refs/tags/$tagName\"")
// delete the tmp_tag branch now that the tag has been created.
execCommand(workUnit.commandManager, workUnit.directory, "git branch -D tmp_tag")
historyMgr.endStep(history, StatusEnum.DONE)
}
} catch (gitEx: IOException) {
LOG.error(FAILED_TO_PUSH_TAG, gitEx)
historyMgr.endStep(history, StatusEnum.FAILED, gitEx.message)
} catch (gitEx: InterruptedException) {
LOG.error(FAILED_TO_PUSH_TAG, gitEx)
historyMgr.endStep(history, StatusEnum.FAILED, gitEx.message)
}
return false
}
}
| 25
| null |
12
| 39
|
f76bfe53e72e4a342bf0ac4e4af6fbf4c27f3fd9
| 4,168
|
svn2git
|
Apache License 2.0
|
app/src/main/java/com/hotmail/or_dvir/televizia/TeleviziaApplication.kt
|
or-dvir
| 680,743,936
| false
| null |
package com.hotmail.or_dvir.televizia
import android.app.Application
import com.hotmail.or_dvir.televizia.di.repositoriesModule
import com.hotmail.or_dvir.televizia.di.viewModelsModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
class TeleviziaApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@TeleviziaApplication)
modules(repositoriesModule, viewModelsModule)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
807ca6ed49e26465224c0a9c654c3c6acdbe0048
| 599
|
TeleviZia
|
Apache License 2.0
|
app/src/main/java/vegabobo/dsusideloader/preferences/AppPrefs.kt
|
VegaBobo
| 454,183,288
| false
|
{"Kotlin": 244220, "Java": 11782, "Shell": 2256, "AIDL": 1346}
|
package vegabobo.dsusideloader.preferences
object AppPrefs {
/**
* Update feature only works if AUTHOR_SIGN_DIGEST is set
* with same SHA1 digest from signed apk OR is a DEBUG build
* if AUTHOR_SIGN_DIGEST doesn't match, also no problem
* app will work as expected, just without update feature.
* check AboutViewModel init
*/
const val UPDATE_CHECK_URL =
"https://raw.githubusercontent.com/VegaBobo/DSU-Sideloader/master/other/updater.json"
const val AUTHOR_SIGN_DIGEST = "0da046eb480972124e2fe2251ebc5b19ea9e13d9"
const val USER_PREFERENCES = "user_preferences"
const val BOOTLOADER_UNLOCKED_WARNING = "bootloader_unlocked_warning"
const val SAF_PATH = "writable_path"
const val DEVELOPER_OPTIONS = "developer_options"
const val USE_BUILTIN_INSTALLER = "builtin_installer"
const val KEEP_SCREEN_ON = "keep_screen_on"
const val UMOUNT_SD = "umount_sd"
const val DISABLE_STORAGE_CHECK = "disable_storage_check"
const val FULL_LOGCAT_LOGGING = "full_logcat_logging"
}
| 47
|
Kotlin
|
69
| 981
|
70cb6da9ecf9ae19c72ea680b02f1a0e20c77653
| 1,053
|
DSU-Sideloader
|
Apache License 2.0
|
game-server/api/src/main/kotlin/com/osrs/api/buffer/RSByteBuffer.kt
|
runetopic
| 613,076,716
| false
|
{"Kotlin": 296499, "Witcher Script": 2511}
|
package com.osrs.api.buffer
import java.nio.ByteBuffer
import kotlin.math.min
/**
* @author <NAME> */
class RSByteBuffer(
private val buffer: ByteBuffer
) {
constructor(array: ByteArray) : this(ByteBuffer.wrap(array))
private var accessBitsIndex = -1
fun readByte(): Int {
checkAccessingBytes()
return buffer.get().toInt()
}
fun readUByte(): Int {
checkAccessingBytes()
return buffer.get().toInt() and 0xFF
}
fun readUByteSubtract(): Int {
checkAccessingBytes()
return 128 - buffer.get().toInt() and 0xFF
}
fun readUByteAdd(): Int {
checkAccessingBytes()
return buffer.get().toInt() + 128 and 0xFF
}
fun readUByteNegate(): Int {
checkAccessingBytes()
return -buffer.get().toInt() and 0xFF
}
fun readShort(): Int {
checkAccessingBytes()
return buffer.short.toInt()
}
fun readUShort(): Int {
checkAccessingBytes()
return buffer.short.toInt() and 0xFFFF
}
fun readUShortAdd(): Int {
checkAccessingBytes()
return (buffer.get().toInt() and 0xFF shl 8) or (buffer.get().toInt() + 128 and 0xFF)
}
fun readUShortLittleEndian(): Int {
checkAccessingBytes()
return (buffer.get().toInt() and 0xFF) or (buffer.get().toInt() and 0xFF shl 8)
}
fun readUShortLittleEndianAdd(): Int {
checkAccessingBytes()
return (buffer.get().toInt() + 128 and 0xFF) or (buffer.get().toInt() and 0xFF shl 8)
}
fun readU24BitInt(): Int {
checkAccessingBytes()
return (buffer.get().toInt() and 0xFF shl 16) or (buffer.short.toInt() and 0xFFFF)
}
fun readInt(): Int {
checkAccessingBytes()
return buffer.int
}
fun readIntLittleEndian(): Int {
checkAccessingBytes()
return (buffer.get().toInt() and 0xFF) or (buffer.get().toInt() and 0xFF shl 8) or (buffer.get().toInt() and 0xFF shl 16) or (buffer.get().toInt() and 0xFF shl 24)
}
fun readIntMiddleEndian(): Int {
checkAccessingBytes()
return (buffer.short.toInt() and 0xFFFF) or (buffer.get().toInt() and 0xFF shl 24) or (buffer.get().toInt() and 0xFF shl 16)
}
fun readIntLittleMiddleEndian(): Int {
checkAccessingBytes()
return (buffer.get().toInt() and 0xFF shl 16) or (buffer.get().toInt() and 0xFF shl 24) or (buffer.get().toInt() and 0xFF) or (buffer.get().toInt() and 0xFF shl 8)
}
fun readLong(): Long {
checkAccessingBytes()
return buffer.long
}
fun readBytes(size: Int): ByteArray {
checkAccessingBytes()
return ByteArray(size) { buffer.get() }
}
fun readBytesAdd(size: Int): ByteArray {
checkAccessingBytes()
return ByteArray(size) { (buffer.get() + 128).toByte() }
}
fun readBytesReversed(size: Int): ByteArray {
checkAccessingBytes()
val bytes = ByteArray(size)
for (index in size - 1 downTo 0) {
bytes[index] = buffer.get()
}
return bytes
}
fun readBytesReversedAdd(size: Int): ByteArray {
checkAccessingBytes()
val bytes = ByteArray(size)
for (index in size - 1 downTo 0) {
bytes[index] = (buffer.get() + 128).toByte()
}
return bytes
}
tailrec fun readIncrSmallSmart(increment: Int = readUShortSmart(), offset: Int = 0): Int {
if (increment != Short.MAX_VALUE.toInt()) return offset + increment
return readIncrSmallSmart(offset = offset + Short.MAX_VALUE)
}
fun readUShortSmart(): Int {
checkAccessingBytes()
return if (unsignedPeek() < 128) buffer.get().toInt() and 0xFF else (buffer.short.toInt() and 0xFFFF) - 32768
}
fun readStringCp1252NullTerminated(): String {
checkAccessingBytes()
return String(readUChars(untilZero())).also {
discard(1)
}
}
fun readStringCp1252NullCircumfixed(): String {
checkAccessingBytes()
if (readByte() != 0) throw IllegalArgumentException()
return readStringCp1252NullTerminated()
}
fun writeByte(value: Int) {
checkAccessingBytes()
buffer.put(value.toByte())
}
fun writeByteSubtract(value: Int) {
checkAccessingBytes()
buffer.put((128 - value).toByte())
}
fun writeByteAdd(value: Int) {
checkAccessingBytes()
buffer.put((value + 128).toByte())
}
fun writeByteNegate(value: Int) {
checkAccessingBytes()
buffer.put((-value).toByte())
}
fun writeShort(value: Int) {
checkAccessingBytes()
buffer.putShort(value.toShort())
}
fun writeShortAdd(value: Int) {
checkAccessingBytes()
buffer.put((value shr 8).toByte())
buffer.put((value + 128).toByte())
}
fun writeShortLittleEndian(value: Int) {
checkAccessingBytes()
buffer.put(value.toByte())
buffer.put((value shr 8).toByte())
}
fun writeShortLittleEndianAdd(value: Int) {
checkAccessingBytes()
buffer.put((value + 128).toByte())
buffer.put((value shr 8).toByte())
}
fun write24BitInt(value: Int) {
checkAccessingBytes()
buffer.put((value shr 16).toByte())
buffer.putShort(value.toShort())
}
fun writeInt(value: Int) {
checkAccessingBytes()
buffer.putInt(value)
}
fun writeIntLittleEndian(value: Int) {
checkAccessingBytes()
buffer.put(value.toByte())
buffer.put((value shr 8).toByte())
buffer.put((value shr 16).toByte())
buffer.put((value shr 24).toByte())
}
fun writeIntMiddleEndian(value: Int) {
checkAccessingBytes()
buffer.putShort(value.toShort())
buffer.put((value shr 24).toByte())
buffer.put((value shr 16).toByte())
}
fun writeIntLittleMiddleEndian(value: Int) {
checkAccessingBytes()
buffer.put((value shr 16).toByte())
buffer.put((value shr 24).toByte())
buffer.put(value.toByte())
buffer.put((value shr 8).toByte())
}
fun writeLong(value: Long) {
checkAccessingBytes()
buffer.putLong(value)
}
fun writeBytes(bytes: ByteArray) {
checkAccessingBytes()
for (byte in bytes) {
buffer.put(byte)
}
}
fun writeBytesAdd(bytes: ByteArray) {
checkAccessingBytes()
for (byte in bytes) {
buffer.put((byte + 128).toByte())
}
}
fun writeBytesReversed(bytes: ByteArray) {
checkAccessingBytes()
for (index in bytes.size - 1 downTo 0) {
buffer.put(bytes[index])
}
}
fun writeBytesReversedAdd(bytes: ByteArray) {
checkAccessingBytes()
for (index in bytes.size - 1 downTo 0) {
buffer.put((bytes[index] + 128).toByte())
}
}
fun writeSmartByteShort(value: Int) {
checkAccessingBytes()
if (value in 0..127) {
buffer.put(value.toByte())
} else {
buffer.putShort((value + 32768).toShort())
}
}
fun writeStringCp1252NullTerminated(value: String) {
checkAccessingBytes()
for (char in value) {
buffer.put(char.code.toByte())
}
writeByte(0)
}
fun writeStringCp1252NullCircumfixed(value: String) {
checkAccessingBytes()
writeByte(0)
for (char in value) {
buffer.put(char.code.toByte())
}
writeByte(0)
}
fun fill(amount: Int, value: Int) {
checkAccessingBytes()
for (index in 0 until amount) {
buffer.put(value.toByte())
}
}
fun discard(amount: Int) {
buffer.position(buffer.position() + amount)
}
fun position(): Int = buffer.position()
fun position(newPosition: Int) {
buffer.position(newPosition)
}
fun flip(): ByteBuffer = buffer.flip()
fun clear() {
buffer.clear()
}
fun array(): ByteArray = buffer.array()
fun signedPeek(): Int = buffer[buffer.position()].toInt()
fun unsignedPeek(): Int = buffer[buffer.position()].toInt() and 0xFF
fun accessBits() {
checkAccessingBytes()
accessBitsIndex = buffer.position() * 8
}
fun rewindBits() {
checkAccessingBits()
buffer.position((accessBitsIndex + 7) / 8)
accessBitsIndex = buffer.position() * 8
}
fun accessBytes() {
checkAccessingBits()
buffer.position((accessBitsIndex + 7) / 8)
accessBitsIndex = -1
}
fun writeBits(count: Int, value: Int) {
checkAccessingBits()
writeBits(value, count, accessBitsIndex shr 3, accessBitsIndex % 8)
accessBitsIndex += count
}
private tailrec fun writeBits(value: Int, remainingBits: Int, byteIndex: Int, bitIndex: Int) {
if (remainingBits == 0) return
val bitOffset = 8 - bitIndex
// The maximum number of bits that can be written to the current byte.
val bitsToWrite = min(remainingBits, bitOffset)
val max = (1 shl bitsToWrite) - 1
// The relevant bits from the value.
val byteValue = (value ushr (remainingBits - bitsToWrite)) and max
// The relevant bits in the current byte.
val mask = max shl (bitOffset - bitsToWrite)
// The current byte from the buffer.
val currentValue = buffer.get(byteIndex).toInt()
// The current byte with the new bits.
val newValue = currentValue and mask.inv() or (byteValue shl (bitOffset - bitsToWrite))
buffer.put(byteIndex, newValue.toByte())
return writeBits(value, remainingBits - bitsToWrite, byteIndex + 1, 0)
}
private tailrec fun untilZero(length: Int = 0): Int {
if (buffer[buffer.position() + length].toInt() == 0) return length
return untilZero(length + 1)
}
private fun readUChars(n: Int): CharArray = CharArray(n) { (buffer.get().toInt() and 0xFF).toChar() }
private fun checkAccessingBytes() {
if (accessBitsIndex == -1) return
throw IllegalAccessException("Buffer must be in bytes access.")
}
private fun checkAccessingBits() {
if (accessBitsIndex != -1) return
throw IllegalAccessException("Buffer must be in bits access.")
}
}
| 1
|
Kotlin
|
1
| 10
|
2a5186b2b7befa7c364e0b989da68ed83070a926
| 10,431
|
osrs-server
|
MIT License
|
app/src/main/java/br/com/gesley/calculaflex/betterfuel/BetterFuelFragment.kt
|
Gesley
| 409,800,283
| false
|
{"Kotlin": 12197}
|
package br.com.gesley.calculaflex.betterfuel
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.navArgs
import br.com.gesley.calculaflex.R
import br.com.gesley.calculaflex.base.auth.BaseAuthFragment
import br.com.gesley.calculaflex.databinding.FragmentBetterFuelBinding
class BetterFuelFragment : BaseAuthFragment() {
override val layout: Int
get() = R.layout.fragment_better_fuel
}
| 0
|
Kotlin
|
0
| 0
|
85c5ec9bae5271ecea917c9a9713f91dbda1cb9d
| 501
|
calculaflex
|
MIT License
|
MRemoteLog/src/main/java/com/remotelog/component/RemoteLogComponent.kt
|
zhangsuixu
| 218,176,174
| false
|
{"Java": 285402, "Kotlin": 46476}
|
package com.remotelog.component
import com.remotelog.activity.RemoteLogActivity
import com.remotelog.module.RemoteLogModule
import dagger.Component
/**
* 时间 : 2019/10/6;
* 版本号 :
*/
@Component(modules = [RemoteLogModule::class])
interface RemoteLogComponent {
fun inject(activity: RemoteLogActivity)
}
| 1
|
Java
|
1
| 8
|
8126f9864850729963ae327d60f5e63a4b490d94
| 312
|
SynthesisTool
|
Apache License 2.0
|
app/src/main/java/app/odapplications/bitstashwallet/modules/transactions/transactionInfo/TransactionInfoModule.kt
|
bitstashco
| 220,133,996
| false
| null |
package io.horizontalsystems.bankwallet.modules.transactions.transactionInfo
import io.horizontalsystems.bankwallet.entities.Wallet
import io.horizontalsystems.bankwallet.viewHelpers.TextHelper
object TransactionInfoModule {
interface View {
fun showCopied()
}
interface ViewDelegate {
fun onCopy(value: String)
fun openFullInfo(transactionHash: String, coin: Wallet)
}
interface Interactor {
fun onCopy(value: String)
}
interface InteractorDelegate
interface Router {
fun openFullInfo(transactionHash: String, wallet: Wallet)
}
fun init(view: TransactionInfoViewModel, router: Router) {
val interactor = TransactionInfoInteractor(TextHelper)
val presenter = TransactionInfoPresenter(interactor, router)
view.delegate = presenter
presenter.view = view
interactor.delegate = presenter
}
}
| 4
| null |
3
| 11
|
64c242dbbcb6b4df475a608b1edb43f87e5091fd
| 921
|
BitStash-Android-Wallet
|
MIT License
|
dpadrecyclerview/src/androidTest/kotlin/com/rubensousa/dpadrecyclerview/test/tests/mutation/AdapterMutationTest.kt
|
rubensousa
| 530,412,665
| false
|
{"Kotlin": 1169718, "Shell": 2774}
|
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rubensousa.dpadrecyclerview.test.tests.mutation
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth.assertThat
import com.rubensousa.carioca.report.android.recording.TestRecording
import com.rubensousa.dpadrecyclerview.ChildAlignment
import com.rubensousa.dpadrecyclerview.ParentAlignment
import com.rubensousa.dpadrecyclerview.layoutmanager.layout.ViewBounds
import com.rubensousa.dpadrecyclerview.spacing.DpadLinearSpacingDecoration
import com.rubensousa.dpadrecyclerview.test.TestLayoutConfiguration
import com.rubensousa.dpadrecyclerview.test.helpers.assertFocusAndSelection
import com.rubensousa.dpadrecyclerview.test.helpers.assertItemAtPosition
import com.rubensousa.dpadrecyclerview.test.helpers.getRelativeItemViewBounds
import com.rubensousa.dpadrecyclerview.test.helpers.onRecyclerView
import com.rubensousa.dpadrecyclerview.test.helpers.selectLastPosition
import com.rubensousa.dpadrecyclerview.test.helpers.selectPosition
import com.rubensousa.dpadrecyclerview.test.helpers.waitForAdapterUpdate
import com.rubensousa.dpadrecyclerview.test.helpers.waitForIdleScrollState
import com.rubensousa.dpadrecyclerview.test.tests.AbstractTestAdapter
import com.rubensousa.dpadrecyclerview.test.tests.DpadRecyclerViewTest
import com.rubensousa.dpadrecyclerview.testfixtures.DpadSelectionEvent
import com.rubensousa.dpadrecyclerview.testing.KeyEvents
import com.rubensousa.dpadrecyclerview.testing.rules.DisableIdleTimeoutRule
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import kotlin.random.Random
class AdapterMutationTest : DpadRecyclerViewTest() {
@get:Rule
val idleTimeoutRule = DisableIdleTimeoutRule()
override fun getDefaultLayoutConfiguration(): TestLayoutConfiguration {
return TestLayoutConfiguration(
spans = 1,
orientation = RecyclerView.VERTICAL,
parentAlignment = ParentAlignment(
edge = ParentAlignment.Edge.NONE,
fraction = 0.5f
),
childAlignment = ChildAlignment(
fraction = 0.5f
)
)
}
private var itemWidth: Int = 0
private var itemHeight: Int = 0
@Before
fun setup() {
launchFragment()
val itemViewBounds = getRelativeItemViewBounds(position = 0)
itemWidth = itemViewBounds.width()
itemHeight = itemViewBounds.height()
}
@Test
fun testRemovalOfPivotMovesFocusToNextPosition() {
val oldViewBounds = getRelativeItemViewBounds(position = 0)
assertThat(getSelectionEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = 0))
)
assertThat(getSelectionAndAlignedEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = 0))
)
mutateAdapter { adapter ->
adapter.removeAt(0)
}
assertFocusAndSelection(0)
assertItemAtPosition(position = 0, item = 1)
val newViewBounds = getRelativeItemViewBounds(position = 0)
assertThat(newViewBounds).isEqualTo(oldViewBounds)
assertThat(getSelectionEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = 0), DpadSelectionEvent(position = 0))
)
assertThat(getSelectionAndAlignedEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = 0), DpadSelectionEvent(position = 0))
)
}
@Test
fun testRemovalOfNonPivotViewDoesNotChangeFocus() {
val oldViewBounds = getRelativeItemViewBounds(position = 0)
assertThat(getSelectionEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = 0))
)
assertThat(getSelectionAndAlignedEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = 0))
)
mutateAdapter { adapter ->
adapter.removeAt(1)
}
assertFocusAndSelection(0)
assertItemAtPosition(position = 0, item = 0)
val newViewBounds = getRelativeItemViewBounds(position = 0)
assertThat(newViewBounds).isEqualTo(oldViewBounds)
assertThat(getSelectionEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = 0))
)
assertThat(getSelectionAndAlignedEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = 0))
)
}
@Test
fun testRemovalOfPivotAsLastViewShouldSelectPreviousView() {
val lastPosition = selectLastPosition()
assertFocusAndSelection(lastPosition)
executeOnFragment { fragment ->
fragment.clearEvents()
}
mutateAdapter { adapter ->
adapter.removeAt(lastPosition)
}
assertFocusAndSelection(lastPosition - 1)
assertThat(getSelectionEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = lastPosition - 1))
)
assertThat(getSelectionAndAlignedEvents()).isEqualTo(
listOf(DpadSelectionEvent(position = lastPosition - 1))
)
}
@Test
fun testMovePivotWillKeepItsAlignmentAndFocus() {
val oldViewBounds = getRelativeItemViewBounds(position = 0)
mutateAdapter { adapter ->
adapter.move(from = 0, to = 1)
}
assertItemAtPosition(position = 1, item = 0)
val newViewBounds = getRelativeItemViewBounds(position = 1)
assertThat(newViewBounds).isEqualTo(oldViewBounds)
// Scroll up to check that the other item was moved
KeyEvents.pressUp()
waitForIdleScrollState()
assertItemAtPosition(position = 0, item = 1)
}
@Test
fun testMovingNonFocusedViewDoesNotUpdatePivot() {
val pivotPosition = 5
KeyEvents.pressDown(times = pivotPosition)
val oldViewBounds = getRelativeItemViewBounds(position = pivotPosition)
mutateAdapter { adapter ->
adapter.move(from = 3, to = 4)
}
assertFocusAndSelection(pivotPosition)
assertItemAtPosition(position = 3, item = 4)
assertItemAtPosition(position = 4, item = 3)
val newViewBounds = getRelativeItemViewBounds(position = pivotPosition)
assertThat(newViewBounds).isEqualTo(oldViewBounds)
}
@Test
fun testInsertingViewBeforePivot() {
val originalPivotPosition = 5
var currentPivotPosition = originalPivotPosition
KeyEvents.pressDown(times = originalPivotPosition)
val oldViewBounds = getRelativeItemViewBounds(position = originalPivotPosition)
mutateAdapter { adapter ->
adapter.addAt(item = -1, index = currentPivotPosition - 1)
}
currentPivotPosition++
assertFocusAndSelection(currentPivotPosition)
assertItemAtPosition(position = currentPivotPosition, item = 5)
assertItemAtPosition(position = currentPivotPosition - 1, item = 4)
assertItemAtPosition(position = currentPivotPosition - 2, item = -1)
val newViewBounds = getRelativeItemViewBounds(position = currentPivotPosition)
assertThat(newViewBounds).isEqualTo(oldViewBounds)
}
@Test
fun testInsertingViewAtPivotPosition() {
val originalPivotPosition = 5
var currentPivotPosition = originalPivotPosition
KeyEvents.pressDown(times = originalPivotPosition)
val oldViewBounds = getRelativeItemViewBounds(position = originalPivotPosition)
mutateAdapter { adapter ->
adapter.addAt(item = -1, index = currentPivotPosition)
}
currentPivotPosition++
assertFocusAndSelection(currentPivotPosition)
assertItemAtPosition(position = currentPivotPosition, item = 5)
assertItemAtPosition(position = currentPivotPosition - 1, item = -1)
val newViewBounds = getRelativeItemViewBounds(position = currentPivotPosition)
assertThat(newViewBounds).isEqualTo(oldViewBounds)
}
@Test
fun testInsertingViewAfterPivot() {
val originalPivotPosition = 5
KeyEvents.pressDown(times = originalPivotPosition)
val oldViewBounds = getRelativeItemViewBounds(position = originalPivotPosition)
mutateAdapter { adapter ->
adapter.addAt(item = -1, index = originalPivotPosition + 1)
}
assertFocusAndSelection(originalPivotPosition)
assertItemAtPosition(position = originalPivotPosition, item = 5)
assertItemAtPosition(position = originalPivotPosition + 1, item = -1)
val newViewBounds = getRelativeItemViewBounds(position = originalPivotPosition)
assertThat(newViewBounds).isEqualTo(oldViewBounds)
}
@Test
fun testQuickUpdatesDoNotCrash() {
val totalItems = 25
val random = Random.Default
val newItems = mutableSetOf<Int>()
lateinit var testAdapter: AbstractTestAdapter<*>
mutateAdapter { adapter ->
testAdapter = adapter
}
repeat(50) {
val newListSize = random.nextInt(totalItems)
repeat(newListSize) {
val item = random.nextInt(totalItems - 1)
newItems.add(item)
}
InstrumentationRegistry.getInstrumentation().runOnMainSync {
testAdapter.submitList(newItems.toMutableList())
}
newItems.clear()
Thread.sleep(250L)
}
Espresso.onIdle()
}
@TestRecording(keepOnSuccess = true)
@Test
fun testRemovalOfLargeInterval() {
// given
val startList = List(100) { it }
mutateAdapter { adapter ->
adapter.submitList(startList.toMutableList())
}
waitForAdapterUpdate()
// when
selectPosition(99, smooth = true)
mutateAdapter { adapter ->
adapter.submitList(List(25) { 1000 + it }.toMutableList())
}
waitForAdapterUpdate()
// then
assertFocusAndSelection(0)
}
@Test
fun testDecorationsAreCorrectAfterRemovingItem() {
// given
val verticalItemSpacing = 24
val verticalEdgeSpacing = 200
val perpendicularSpacing = 64
val decoration = DpadLinearSpacingDecoration.create(
itemSpacing = verticalItemSpacing,
edgeSpacing = verticalEdgeSpacing,
perpendicularEdgeSpacing = perpendicularSpacing
)
onRecyclerView("Setting decoration") { recyclerView ->
recyclerView.addItemDecoration(decoration)
}
// when
mutateAdapter { adapter ->
adapter.removeFrom(2, adapter.itemCount - 2)
}
waitForAdapterUpdate()
// then
assertChildDecorations(
childIndex = 1,
insets = ViewBounds(
left = perpendicularSpacing,
top = 0,
right = perpendicularSpacing,
bottom = verticalEdgeSpacing
),
)
}
@Test
fun testDecorationsAreCorrectAfterAddingItem() {
// given
val verticalItemSpacing = 24
val verticalEdgeSpacing = 200
val perpendicularSpacing = 64
val decoration = DpadLinearSpacingDecoration.create(
itemSpacing = verticalItemSpacing,
edgeSpacing = verticalEdgeSpacing,
perpendicularEdgeSpacing = perpendicularSpacing
)
onRecyclerView("Setting decoration") { recyclerView ->
recyclerView.addItemDecoration(decoration)
}
mutateAdapter { adapter ->
adapter.setList(mutableListOf(0))
adapter.notifyDataSetChanged()
}
waitForAdapterUpdate()
// when
mutateAdapter { adapter ->
adapter.add()
}
waitForAdapterUpdate()
// then
assertChildDecorations(
childIndex = 0,
insets = ViewBounds(
left = perpendicularSpacing,
top = verticalEdgeSpacing,
right = perpendicularSpacing,
bottom = verticalItemSpacing
),
)
}
@Test
fun testDecorationsAreCorrectAfterMovingItem() {
// given
val verticalItemSpacing = 24
val verticalEdgeSpacing = 200
val perpendicularSpacing = 64
val decoration = DpadLinearSpacingDecoration.create(
itemSpacing = verticalItemSpacing,
edgeSpacing = verticalEdgeSpacing,
perpendicularEdgeSpacing = perpendicularSpacing
)
onRecyclerView("Setting decoration") { recyclerView ->
recyclerView.addItemDecoration(decoration)
}
mutateAdapter { adapter ->
adapter.setList(mutableListOf(0, 1))
adapter.notifyDataSetChanged()
}
waitForAdapterUpdate()
// when
mutateAdapter { adapter ->
adapter.move(0, 1)
}
waitForAdapterUpdate()
// then
assertChildDecorations(
childIndex = 0,
insets = ViewBounds(
left = perpendicularSpacing,
top = verticalEdgeSpacing,
right = perpendicularSpacing,
bottom = verticalItemSpacing
),
)
assertChildDecorations(
childIndex = 1,
insets = ViewBounds(
left = perpendicularSpacing,
top = 0,
right = perpendicularSpacing,
bottom = verticalEdgeSpacing
),
)
}
@Test
fun testDecorationsAreCorrectAfterUpdatingItems() {
// given
val verticalItemSpacing = 24
val verticalEdgeSpacing = 200
val perpendicularSpacing = 64
val decoration = DpadLinearSpacingDecoration.create(
itemSpacing = verticalItemSpacing,
edgeSpacing = verticalEdgeSpacing,
perpendicularEdgeSpacing = perpendicularSpacing
)
onRecyclerView("Setting decoration") { recyclerView ->
recyclerView.addItemDecoration(decoration)
}
mutateAdapter { adapter ->
adapter.setList(mutableListOf(0, 1, 2))
adapter.notifyDataSetChanged()
}
waitForAdapterUpdate()
// when
mutateAdapter { adapter ->
adapter.setList(mutableListOf(0, 1))
adapter.notifyDataSetChanged()
}
waitForAdapterUpdate()
// then
assertChildDecorations(
childIndex = 0,
insets = ViewBounds(
left = perpendicularSpacing,
top = verticalEdgeSpacing,
right = perpendicularSpacing,
bottom = verticalItemSpacing
),
)
assertChildDecorations(
childIndex = 1,
insets = ViewBounds(
left = perpendicularSpacing,
top = 0,
right = perpendicularSpacing,
bottom = verticalEdgeSpacing
),
)
}
}
| 2
|
Kotlin
|
17
| 135
|
ef7df356ad9fbc5a2427c8447af35a0810573207
| 15,683
|
DpadRecyclerView
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/presta/customer/ui/components/topUp/DefaultLoanTopUpComponent.kt
|
morgan4080
| 726,765,347
| false
| null |
package com.presta.customer.ui.components.topUp
import com.arkivanov.decompose.ComponentContext
import com.arkivanov.essenty.lifecycle.Lifecycle
import com.arkivanov.essenty.lifecycle.LifecycleOwner
import com.arkivanov.essenty.lifecycle.doOnDestroy
import com.arkivanov.mvikotlin.core.instancekeeper.getStore
import com.arkivanov.mvikotlin.core.store.StoreFactory
import com.arkivanov.mvikotlin.extensions.coroutines.stateFlow
import com.presta.customer.network.loanRequest.model.LoanType
import com.presta.customer.network.onBoarding.model.PinStatus
import com.presta.customer.organisation.OrganisationModel
import com.presta.customer.ui.components.auth.store.AuthStore
import com.presta.customer.ui.components.auth.store.AuthStoreFactory
import com.presta.customer.ui.components.profile.coroutineScope
import com.presta.customer.ui.components.profile.store.ProfileStore
import com.presta.customer.ui.components.profile.store.ProfileStoreFactory
import com.presta.customer.ui.components.shortTermLoans.store.ShortTermLoansStore
import com.presta.customer.ui.components.shortTermLoans.store.ShortTermLoansStoreFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
fun CoroutineScope(context: CoroutineContext, lifecycle: Lifecycle): CoroutineScope {
val scope = CoroutineScope(context)
lifecycle.doOnDestroy(scope::cancel)
return scope
}
fun LifecycleOwner.coroutineScope(context: CoroutineContext): CoroutineScope =
CoroutineScope(context, lifecycle)
class DefaultLoanTopUpComponent(
componentContext: ComponentContext,
storeFactory: StoreFactory,
mainContext: CoroutineContext,
private val onProceedClicked: (
referencedLoanRefId: String,
refId: String,
amount: Double,
maxLoanPeriod: Int,
loanType: LoanType,
loanName: String,
interest: Double,
loanPeriodUnit: String,
currentTerm: Boolean,
minLoanPeriod: Int,
loanOperation:String
) -> Unit,
private val onBackNavClicked: () -> Unit,
override val maxAmount: Double,
override val minAmount: String,
override val loanRefId: String,
override val loanName: String,
override val interestRate: Double,
override val maxLoanPeriod: Int,
override val loanPeriodUnit: String,
override val loanOperation: String,
override val referencedLoanRefId: String,
override val minLoanPeriod: Int,
override val loanRefIds: String,
) : LoanTopUpComponent, ComponentContext by componentContext {
override fun onProceedSelected(
referencedLoanRefId: String,
loanRefId: String,
amount: Double,
maxLoanPeriod: Int,
loanType: LoanType,
loanName: String,
interest: Double,
loanPeriodUnit: String,
currentTerm: Boolean,
minLoanPeriod: Int,
loanOperation:String
) {
onProceedClicked(
referencedLoanRefId,
loanRefId,
amount,
maxLoanPeriod,
loanType,
loanName,
interest,
loanPeriodUnit,
currentTerm,
minLoanPeriod,
loanOperation
)
}
override fun onBackNavSelected() {
onBackNavClicked()
}
private val scope = coroutineScope(mainContext + SupervisorJob())
override val authStore: AuthStore =
instanceKeeper.getStore {
AuthStoreFactory(
storeFactory = storeFactory,
componentContext = componentContext,
phoneNumber = null,
isTermsAccepted = false,
isActive = false,
pinStatus = PinStatus.SET
).create()
}
@OptIn(ExperimentalCoroutinesApi::class)
override val authState: StateFlow<AuthStore.State> = authStore.stateFlow
override val shortTermloansStore: ShortTermLoansStore =
instanceKeeper.getStore {
ShortTermLoansStoreFactory(
storeFactory = storeFactory
).create()
}
@OptIn(ExperimentalCoroutinesApi::class)
override val shortTermloansState: StateFlow<ShortTermLoansStore.State> =
shortTermloansStore.stateFlow
override fun onAuthEvent(event: AuthStore.Intent) {
authStore.accept(event)
}
override fun onEvent(event: ShortTermLoansStore.Intent) {
shortTermloansStore.accept(event)
}
override val profileStore =
instanceKeeper.getStore {
ProfileStoreFactory(
storeFactory = storeFactory
).create()
}
@OptIn(ExperimentalCoroutinesApi::class)
override val profileState: StateFlow<ProfileStore.State> = profileStore.stateFlow
override fun onProfileEvent(event: ProfileStore.Intent) {
profileStore.accept(event)
}
private var authUserScopeJob: Job? = null
private fun checkAuthenticatedUser() {
if (authUserScopeJob?.isActive == true) return
authUserScopeJob = scope.launch {
authState.collect { state ->
if (state.cachedMemberData !== null) {
onAuthEvent(
AuthStore.Intent.CheckAuthenticatedUser(
token = state.cachedMemberData.accessToken,
state.cachedMemberData.refId
)
)
onEvent(
ShortTermLoansStore.Intent.GetPrestaShortTermProductById(
token = state.cachedMemberData.accessToken,
loanId = loanRefIds
)
)
onEvent(
ShortTermLoansStore.Intent.GetPrestaShortTermTopUpList(
token = state.cachedMemberData.accessToken,
session_id = state.cachedMemberData.session_id,
refId = state.cachedMemberData.refId
)
)
onEvent(
ShortTermLoansStore.Intent.GetPrestaLoanEligibilityStatus(
token = state.cachedMemberData.accessToken,
session_id = state.cachedMemberData.session_id,
customerRefId = state.cachedMemberData.refId
)
)
onEvent(
ShortTermLoansStore.Intent.GetLoanProductById(
token = state.cachedMemberData.accessToken,
loanRefId = loanRefIds
)
)
this.cancel()
}
}
}
}
private var refreshTokenScopeJob: Job? = null
private fun refreshToken() {
if (refreshTokenScopeJob?.isActive == true) return
refreshTokenScopeJob = scope.launch {
authState.collect { state ->
if (state.cachedMemberData !== null) {
onAuthEvent(
AuthStore.Intent.RefreshToken(
tenantId = OrganisationModel.organisation.tenant_id,
refId = state.cachedMemberData.refId
)
)
}
this.cancel()
}
}
}
init {
onAuthEvent(AuthStore.Intent.GetCachedMemberData)
checkAuthenticatedUser()
refreshToken()
}
init {
scope.launch {
authState.collect { state ->
if (state.cachedMemberData !== null) {
onProfileEvent(
ProfileStore.Intent.GetLoanBalances(
token = state.cachedMemberData.accessToken,
refId = state.cachedMemberData.refId,
)
)
this.cancel()
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d26cc0013c5bedf29d2f349b86e90052a0aca64e
| 8,323
|
kotlin-multiplatform
|
Apache License 2.0
|
src/main/kotlin/no/roedt/brukere/mfa/MFAService.kt
|
Roedt
| 300,015,002
| false
| null |
package no.roedt.brukere.mfa
import no.roedt.EpostSender
import no.roedt.brukere.Epost
import no.roedt.hypersys.login.AESUtil
import no.roedt.hypersys.login.LoginRequest
import org.eclipse.microprofile.config.inject.ConfigProperty
import javax.enterprise.context.Dependent
@Dependent
class MFAService(
private val mfaRepository: MFARepository,
private val epostSender: EpostSender,
private val aesUtil: AESUtil,
@ConfigProperty(name = "mockMFA", defaultValue = "true")
private val mockMFA: Boolean
) {
fun trengerMFA(mfaRequest: MFARequest): Boolean {
return if (mockMFA) false else !mfaRepository.erVerifisert(dekrypter(mfaRequest))
}
private fun dekrypter(mfaRequest: MFARequest): DekryptertMFARequest = DekryptertMFARequest(
enhetsid = aesUtil.decrypt(mfaRequest.enhetsid),
brukernavn = aesUtil.decrypt(mfaRequest.brukernavn)
)
private fun dekrypter(loginRequest: LoginRequest): SettVerifisertRequest = SettVerifisertRequest(
enhetsid = aesUtil.decrypt(loginRequest.enhetsid),
brukarnamn = aesUtil.decrypt(loginRequest.brukarnamn),
engangskode = aesUtil.decrypt(loginRequest.engangskode!!)
)
fun sendMFA(mfaRequest: MFARequest) {
if (mockMFA) {
return
}
val mfa = MFA(
engangskode = MFA.generer(),
verifisert = false,
epost = aesUtil.decrypt(mfaRequest.brukernavn),
enhetsid = aesUtil.decrypt(mfaRequest.enhetsid)
)
mfaRepository.lagre(mfa)
epostSender.sendEpost(epost = lagEpost(mfa), mottaker = mfa.epost)
}
private fun lagEpost(mfa: MFA) =
Epost(
tekst = "Din kode for Ringesentralen er ${mfa.engangskode}" +
System.lineSeparator().repeat(3) +
"Dette er ein automatisk utsendt e-post.",
tekstAaLoggeHvisDeaktivert = "MFA sendt til bruker",
loggFoerSendingTekst = "Person har no fått MFA-kode tilsendt",
tittel = "E-post frå Raudts Ringesentral"
)
fun verifiserEngangskode(loginRequest: LoginRequest) {
if (mockMFA) {
return
}
val trengerMFA = trengerMFA(
MFARequest(
enhetsid = loginRequest.enhetsid,
brukernavn = loginRequest.brukarnamn
)
)
if (!trengerMFA) {
return
}
if (mfaRepository.matcher(dekrypter(loginRequest))) {
mfaRepository.settVerifisert(dekrypter(loginRequest))
return
}
throw RuntimeException("Ugyldig engangskode")
}
}
| 17
| null |
0
| 1
|
3e04de69024fdf383a086309406eeed9d94608f2
| 2,642
|
ringesentralen-backend
|
MIT License
|
util/src/main/kotlin/gg/rsmod/util/AabbUtil.kt
|
2011Scape
| 578,880,245
| false
| null |
package gg.rsmod.util
/**
* Utility methods for axis-aligned bounding boxes.
*
* @author Tom <<EMAIL>>
*/
object AabbUtil {
data class Box(val x: Int, val z: Int, val width: Int, val length: Int) {
val x1: Int get() = x
val x2: Int get() = x + width
val z1: Int get() = z
val z2: Int get() = z + length
}
/**
* Checks to see if two AABB are bordering, but not overlapping.
*/
fun areBordering(x1: Int, z1: Int, width1: Int, length1: Int,
x2: Int, z2: Int, width2: Int, length2: Int): Boolean {
val a = Box(x1, z1, width1 - 1, length1 - 1)
val b = Box(x2, z2, width2 - 1, length2 - 1)
if (b.x1 in a.x1 .. a.x2 && b.z1 in a.z1 .. a.z2 || b.x2 in a.x1 .. a.x2 && b.z2 in a.z1 .. a.z2) {
return false
}
if (b.x1 > a.x2 + 1) {
return false
}
if (b.x2 < a.x1 - 1) {
return false
}
if (b.z1 > a.z2 + 1) {
return false
}
if (b.z2 < a.z1 - 1) {
return false
}
return true
}
fun areBorderingCustom(x1: Int, z1: Int, width1: Int, length1: Int,
x2: Int, z2: Int, width2: Int, length2: Int) : Boolean {
val a = Box(x1, z1, width1 - 1, length1 - 1)
val b = Box(x2, z2, width2 - 1, length2 - 1)
if (b.x1 in a.x1 .. a.x2 && b.z1 in a.z1 .. a.z2 || b.x2 in a.x1 .. a.x2 && b.z2 in a.z1 .. a.z2) {
return false
}
if (b.x1 > a.x2 + 1) {
return false
}
if (b.x2 < a.x1 - 1) {
return false
}
if (b.z1 > a.z2 + 1) {
return false
}
if (b.z2 < a.z1 - 1) {
return false
}
return true
}
fun areDiagonal(x1: Int, z1: Int, width1: Int, length1: Int,
x2: Int, z2: Int, width2: Int, length2: Int): Boolean {
val a = Box(x1, z1, width1 - 1, length1 - 1)
val b = Box(x2, z2, width2 - 1, length2 - 1)
/**
* South-west diagonal tile.
*/
if (a.x1 - 1 == b.x2 && a.z1 - 1 == b.z2) {
return true
}
/**
* South-east diagonal tile.
*/
if (a.x2 + 1 == b.x2 && a.z1 - 1 == b.z2) {
return true
}
/**
* North-west diagonal tile.
*/
if (a.x1 - 1 == b.x2 && a.z2 + 1 == b.z2) {
return true
}
/**
* North-east diagonal tile.
*/
if (a.x2 + 1 == b.x2 && a.z2 + 1 == b.z2) {
return true
}
return false
}
fun areOverlapping(x1: Int, z1: Int, width1: Int, length1: Int,
x2: Int, z2: Int, width2: Int, length2: Int): Boolean {
val a = Box(x1, z1, width1 - 1, length1 - 1)
val b = Box(x2, z2, width2 - 1, length2 - 1)
if (a.x1 > b.x2 || b.x1 > a.x2) {
return false
}
if (a.z1 > b.z2 || b.z1 > a.z2) {
return false
}
return true
}
}
| 36
| null |
138
| 32
|
da66bb6d68ebae531ee325b909a6536e798b1144
| 3,137
|
game
|
Apache License 2.0
|
Android-Kotlin/alarm123/app/src/main/java/fastcampus/aop/part3/chapter3/AlarmDisplayModel.kt
|
dkekdmf
| 469,109,428
| false
|
{"Jupyter Notebook": 237657, "Python": 61277, "Kotlin": 61159, "C": 27870, "JavaScript": 7802, "EJS": 6927, "HTML": 2245, "CSS": 111}
|
package fastcampus.aop.part3.chapter3
data class AlarmDisplayModel(
val hour: Int,
val minute: Int,
var onOff: Boolean
) {
val timeText: String
get() {
val h = "%02d".format(if (hour < 12) hour else hour - 12)
val m = "%02d".format(minute)
return "$h:$m"
}
val ampmText: String
get() {
return if (hour < 12) "AM" else "PM"
}
val onOffText: String
get() {
return if (onOff) "알람 끄기" else "알람 켜기"
}
fun makeDataForDB(): String {
return "$hour:$minute"
}
}
| 4
|
Jupyter Notebook
|
0
| 1
|
445ac449acd6f1bf9f3b49d37f4df4739b8feca8
| 607
|
Jaehoon
|
MIT License
|
src/main/kotlin/co/volight/soft/impl/lang/LangImpl.kt
|
2A5F
| 347,285,536
| false
| null |
package co.volight.soft.impl.lang
import co.volight.soft.ModId
import co.volight.soft.Soft
import co.volight.soft.api.lang.LangHandle
import co.volight.soft.api.lang.LangStr
import com.google.gson.Gson
import net.fabricmc.loader.api.FabricLoader
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.PathMatcher
typealias TextName = String
typealias LangName = String
typealias LangTextMap = Map<TextName, LangStr>
typealias LangMap = Map<LangName, LangTextMap>
typealias ModLangMap = MutableMap<ModId, LangHandle>
internal const val logName = "[SoftAPI:Lang]"
internal object LangImpl {
private val langs: ModLangMap = mutableMapOf()
fun get(modeName: ModId): LangHandle? {
return langs[modeName]
}
fun reg(modeName: ModId, path: String? = null): LangHandle? {
val container = FabricLoader.getInstance().getModContainer(modeName).orElseThrow { throw RuntimeException("Mod \"${modeName}\" not loaded") }
val langDir = container.getPath(path ?: "assets/${modeName}/lang/")
return try {
val langMap = loadLangMap(modeName, langDir)
val handle = LangHandle(modeName, langMap)
langs[modeName] = handle
Soft.LOGGER.info("$logName Language files of mod \"${modeName}\" loaded")
handle
} catch (e: Exception) {
Soft.LOGGER.error("$logName Failed to load the language file of mod \"${modeName}\"", e)
null
}
}
private fun loadLangMap(modname: ModId, langDir: Path): LangMap {
val jsonFile: PathMatcher = langDir.fileSystem.getPathMatcher("glob:**/*.json")
return sequence {
Files.walk(langDir).use { paths ->
for (path in paths.filter { !Files.isDirectory(it) && jsonFile.matches(it) }) {
Soft.LOGGER.debug("$logName loading $path")
val textMap = loadTextMap(path)
val rawMame = path.fileName.toString()
val name = rawMame.substring(0, rawMame.length - 5)
Soft.LOGGER.info("$logName mod \"${modname}\" loaded lang \"${name}\"")
yield(Pair(name, textMap))
}
}
}.toMap()
}
private fun loadTextMap(path: Path): LangTextMap {
val gson = Gson()
val strMap = gson.fromJson<Map<String, String>>(Files.newBufferedReader(path), Map::class.java)
return strMap.mapValues { LangStr.parse(it.value) }
}
}
| 0
|
Kotlin
|
0
| 1
|
ce1ee9ac9e292d9e5bd9e9c6e2f72511f9638a8f
| 2,504
|
soft
|
MIT License
|
app/src/main/java/com/blaubalu/detoxrank/ui/utils/Constants.kt
|
AdamBalu
| 749,353,748
| false
|
{"Kotlin": 439275}
|
package com.blaubalu.detoxrank.ui.utils
object Constants {
const val ACTION_SERVICE_START = "ACTION_SERVICE_START"
const val ACTION_SERVICE_CANCEL = "ACTION_SERVICE_CANCEL"
const val TIMER_STATE = "STOPWATCH_STATE"
const val NOTIFICATION_CHANNEL_ID = "STOPWATCH_NOTIFICATION_ID"
const val NOTIFICATION_CHANNEL_NAME = "STOPWATCH_NOTIFICATION"
const val NOTIFICATION_ID = 10
const val CLICK_REQUEST_CODE = 100
const val CANCEL_REQUEST_CODE = 101
const val NUMBER_OF_TASKS_DAILY = 2
const val NUMBER_OF_TASKS_WEEKLY = 4
const val NUMBER_OF_TASKS_MONTHLY = 3
const val KEY_TASK_DURATION = "KEY_TASK_DURATION"
const val DAILY_TASK_RP_GAIN = 70
const val WEEKLY_TASK_RP_GAIN = 250
const val MONTHLY_TASK_RP_GAIN = 500
const val UNCATEGORIZED_TASK_RP_GAIN = 30
const val SPECIAL_TASK_RP_GAIN = 1000
const val DAILY_TASK_XP_GAIN = 70
const val WEEKLY_TASK_XP_GAIN = 100
const val MONTHLY_TASK_XP_GAIN = 130
// achievements fixed IDs (to ensure achievement completion by their IDs)
const val ID_RUN_3_KM = 1
const val ID_RUN_5_KM = 2
const val ID_RUN_7_KM = 3
const val ID_RUN_10_KM = 4
const val ID_READ_20_PAGES = 5
const val ID_READ_50_PAGES = 6
const val ID_READ_100_PAGES = 7
const val ID_READ_250_PAGES = 8
const val ID_READ_A_BOOK = 9
const val ID_READ_5_BOOKS = 10
const val ID_READ_10_BOOKS = 11
const val ID_FINISH_CH_1 = 12
const val ID_FINISH_CH_2 = 13
const val ID_FINISH_CH_3 = 14
const val ID_FINISH_CH_4 = 15
const val ID_FINISH_CH_5 = 16
const val ID_FINISH_CH_6 = 17
const val ID_FINISH_ALL_CH = 18
const val ID_FINISH_FIRST_TASK = 19
const val ID_FINISH_5_TASKS = 20
const val ID_FINISH_10_TASKS = 21
const val ID_FINISH_25_TASKS = 22
const val ID_FINISH_50_TASKS = 23
const val ID_FINISH_100_TASKS = 24
const val ID_FINISH_250_TASKS = 25
const val ID_START_TIMER = 26
const val ID_TIMER_3_DAYS = 27
const val ID_TIMER_7_DAYS = 28
const val ID_TIMER_14_DAYS = 29
const val ID_TIMER_30_DAYS = 30
const val ID_READ_10_PAGES = 31
const val PAGES_10 = 10
const val PAGES_20 = 20
const val PAGES_50 = 50
const val PAGES_100 = 100
const val PAGES_250 = 250
const val BOOKS_1_PAGE_COUNT = 500
const val BOOKS_5_PAGE_COUNT = 2500
const val BOOKS_10_PAGE_COUNT = 5000
const val RP_PERCENTAGE_GAIN_TIMER_EASY_DIFFICULTY = 10
const val RP_PERCENTAGE_GAIN_TIMER_MEDIUM_DIFFICULTY = 20
const val RP_PERCENTAGE_GAIN_TIMER_HARD_DIFFICULTY = 30
const val TIMER_RP_GAIN_PER_SECOND = 0.005
const val TIMER_MEDIUM_DIFFICULTY_MULTIPLIER = 1.15
const val TIMER_HARD_DIFFICULTY_MULTIPLIER = 1.25
// RANK LOWER RP CAPS
const val BRONZE_I_LOWER_CAP = 0
const val BRONZE_II_LOWER_CAP = 300
const val BRONZE_III_LOWER_CAP = 1000
const val SILVER_I_LOWER_CAP = 2000
const val SILVER_II_LOWER_CAP = 3000
const val SILVER_III_LOWER_CAP = 4000
const val GOLD_I_LOWER_CAP = 5200
const val GOLD_II_LOWER_CAP = 6300
const val GOLD_III_LOWER_CAP = 7400
const val PLAT_I_LOWER_CAP = 8600
const val PLAT_II_LOWER_CAP = 9900
const val PLAT_III_LOWER_CAP = 11200
const val DIA_I_LOWER_CAP = 13000
const val DIA_II_LOWER_CAP = 15500
const val DIA_III_LOWER_CAP = 17000
const val MASTER_LOWER_CAP = 19000
const val LEGEND_LOWER_CAP = 25000
// RANK UPPER RP CAPS
const val BRONZE_I_UPPER_CAP = BRONZE_II_LOWER_CAP - 1
const val BRONZE_II_UPPER_CAP = BRONZE_III_LOWER_CAP - 1
const val BRONZE_III_UPPER_CAP = SILVER_I_LOWER_CAP - 1
const val SILVER_I_UPPER_CAP = SILVER_II_LOWER_CAP - 1
const val SILVER_II_UPPER_CAP = SILVER_III_LOWER_CAP - 1
const val SILVER_III_UPPER_CAP = GOLD_I_LOWER_CAP - 1
const val GOLD_I_UPPER_CAP = GOLD_II_LOWER_CAP - 1
const val GOLD_II_UPPER_CAP = GOLD_III_LOWER_CAP - 1
const val GOLD_III_UPPER_CAP = PLAT_I_LOWER_CAP - 1
const val PLAT_I_UPPER_CAP = PLAT_II_LOWER_CAP - 1
const val PLAT_II_UPPER_CAP = PLAT_III_LOWER_CAP - 1
const val PLAT_III_UPPER_CAP = DIA_I_LOWER_CAP - 1
const val DIA_I_UPPER_CAP = DIA_II_LOWER_CAP - 1
const val DIA_II_UPPER_CAP = DIA_III_LOWER_CAP - 1
const val DIA_III_UPPER_CAP = MASTER_LOWER_CAP - 1
const val MASTER_UPPER_CAP = LEGEND_LOWER_CAP - 1
const val CHAPTER_DIFFICULTY_EASY_RP_GAIN = 200
const val CHAPTER_DIFFICULTY_MEDIUM_RP_GAIN = 350
const val CHAPTER_DIFFICULTY_HARD_RP_GAIN = 500
const val CHAPTER_DIFFICULTY_EASY_XP_GAIN = 80
const val CHAPTER_DIFFICULTY_MEDIUM_XP_GAIN = 120
const val CHAPTER_DIFFICULTY_HARD_XP_GAIN = 175
const val MIN_LEVEL_TO_UNLOCK_SPECIAL_TASKS = 20
const val LOW_LEVEL_LOWER_CAP = 0
const val LOW_LEVEL_UPPER_CAP = 14
const val HIGH_LEVEL_LOWER_CAP = 15
const val HIGH_LEVEL_UPPER_CAP = 25
}
| 0
|
Kotlin
|
0
| 0
|
d168a379f1555a3f9260fc8d882c978cc7af5b63
| 4,942
|
DetoxRank
|
MIT License
|
compiler/testData/codegen/box/callableReference/bound/receiverEvaluatedOnce.kt
|
JetBrains
| 3,432,266
| false
| null |
// DONT_TARGET_EXACT_BACKEND: WASM
// WASM_MUTE_REASON: BINDING_RECEIVERS
var x = 0
class A {
fun f() = if (x == 1) "OK" else "Fail $x"
}
fun callTwice(f: () -> String): String {
f()
return f()
}
fun box(): String {
return callTwice(({ x++; A() }())::f)
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 275
|
kotlin
|
Apache License 2.0
|
clients/bazel-module-registry/src/main/kotlin/RemoteBazelModuleRegistryService.kt
|
oss-review-toolkit
| 107,540,288
| false
| null |
/*
* Copyright (C) 2024 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.clients.bazelmoduleregistry
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import org.apache.logging.log4j.kotlin.logger
import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
/**
* The client uses the Bazel Central Registry by default.
*/
const val DEFAULT_URL = "https://bcr.bazel.build"
/**
* Interface for a Bazel Module Registry, based on the directory structure of https://bcr.bazel.build/ and the Git
* repository it is based on (https://github.com/bazelbuild/bazel-central-registry/).
*/
interface RemoteBazelModuleRegistryService : BazelModuleRegistryService {
companion object {
/**
* Create a Bazel Module Registry client instance for communicating with a server running at the given [url],
* defaulting to the Bazel Central Registry, optionally with a pre-built OkHttp [client].
*/
fun create(url: String? = null, client: OkHttpClient? = null): RemoteBazelModuleRegistryService {
val bmrClient = client ?: OkHttpClient()
val contentType = "application/json".toMediaType()
val baseUrl = url ?: DEFAULT_URL
logger.info { "Creating remote Bazel module registry at '$baseUrl'." }
val retrofit = Retrofit.Builder()
.client(bmrClient)
.baseUrl(baseUrl)
.addConverterFactory(JSON.asConverterFactory(contentType))
.build()
return retrofit.create(RemoteBazelModuleRegistryService::class.java)
}
}
/**
* Retrieve the metadata for a module.
* E.g. https://bcr.bazel.build/modules/glog/metadata.json.
*/
@GET("modules/{name}/metadata.json")
override suspend fun getModuleMetadata(@Path("name") name: String): ModuleMetadata
/**
* Retrieve information about the source code for a specific version of a module.
* E.g. https://bcr.bazel.build/modules/glog/0.5.0/source.json.
*/
@GET("modules/{name}/{version}/source.json")
override suspend fun getModuleSourceInfo(
@Path("name") name: String,
@Path("version") version: String
): ModuleSourceInfo
}
| 309
| null |
308
| 1,578
|
7509ece17ed192dd3fbcbc421ef17f2d1f015a68
| 3,030
|
ort
|
Apache License 2.0
|
src/main/kotlin/wiki/mdzz/utils/map/HashMap.kt
|
limitLiu
| 231,546,946
| false
| null |
package wiki.mdzz.utils.map
import java.util.Objects
import wiki.mdzz.utils.queue.Queue
open class HashMap<K, V> : Map<K, V> {
companion object {
const val RED = false
const val BLACK = true
const val DEFAULT_CAPACITY = 1 shl 4
const val DEFAULT_LOAD_FACTOR = 0.75f
}
private var table: Array<Node<K, V>?>
private var size: Int = 0
override val isEmpty: Boolean
get() = size() == 0
override fun size(): Int {
return size
}
override fun clear() {
if (isEmpty) return
size = 0
table.fill(null)
}
override fun put(key: K, value: V): V? {
resize()
val index = getIndex(key)
var root = table[index]
if (root == null) {
root = createNode(key, value, null)
table[index] = root
++size
fixAfterPut(root)
return null
}
var parent: Node<K, V>?
var node = root
var cmp = 0
val h1 = getHash(key)
var result: Node<K, V>? = null
var searched = false
do {
parent = node
val k2: K = node!!.key
val h2 = node.hash
if (h1 > h2) {
cmp = 1
} else if (h1 < h2) {
cmp = -1
} else if (Objects.equals(key, k2)) {
cmp = 0
} else if (k2 != null && key is Comparable<*> && key.javaClass == k2.javaClass &&
(key as Comparable<K>).compareTo(k2).let { cmp = it; cmp != 0 }
) {
// Nothing to do
} else if (searched) {
cmp = System.identityHashCode(key) - System.identityHashCode(k2)
} else {
if (node.left != null && getNode(node.left, key).let {
result = it; result != null
}) {
node = result
cmp = 0
} else {
searched = true
cmp = System.identityHashCode(key) - System.identityHashCode(k2)
}
}
if (cmp > 0) {
node = node!!.right
} else if (cmp < 0) {
node = node!!.left
} else {
val oldValue: V = node!!.value
node.key = key
node.value = value
node.hash = h1
return oldValue
}
} while (node != null)
val newNode = createNode(key, value, parent)
if (cmp > 0) {
parent!!.right = newNode
} else {
parent!!.left = newNode
}
++size
fixAfterPut(newNode)
return null
}
private fun resize() {
if ((size.toFloat() / table.size.toFloat()) <= DEFAULT_LOAD_FACTOR) {
return
}
val oldTable = table
table = arrayOfNulls(oldTable.size shl 1)
val queue = Queue<Node<K, V>>()
for (kvNode in oldTable) {
if (kvNode == null) continue
queue.offer(kvNode)
while (!queue.isEmpty) {
val node = queue.poll()
assert(node != null)
if (node!!.left != null) {
queue.offer(node.left)
}
if (node.right != null) {
queue.offer(node.right)
}
moveNode(node)
}
}
}
private fun moveNode(newNode: Node<K, V>) {
newNode.parent = null
newNode.left = null
newNode.right = null
newNode.color = RED
val index = getIndex(newNode)
var root = table[index]
if (root == null) {
root = newNode
table[index] = root
fixAfterPut(root)
return
}
var parent: Node<K, V>?
var node = root
var cmp = 0
val k1: K = newNode.key
val h1 = newNode.hash
do {
parent = node
val k2: K = node!!.key
val h2 = node.hash
if (h1 > h2) {
cmp = 1
} else if (h1 < h2) {
cmp = -1
} else if (
k2 != null &&
k1 is Comparable<*> &&
k1.javaClass == k2.javaClass
&& (k1 as Comparable<K>).compareTo(k2).let { cmp = it; cmp != 0 }
) {
cmp = System.identityHashCode(k1) - System.identityHashCode(k2)
}
if (cmp > 0) {
node = node.right
} else if (cmp < 0) {
node = node.left
}
} while (node != null)
newNode.parent = parent
if (cmp > 0) {
parent?.right = newNode
} else {
parent?.left = newNode
}
fixAfterPut(newNode)
}
private fun fixAfterPut(node: Node<K, V>?) {
val parent = node?.parent
if (parent == null) {
setBlack(node)
return
}
if (isBlack(parent)) return
val uncle = parent.sibling()
val grand = setRed(parent.parent)
if (isRed(uncle)) {
setBlack(parent)
setBlack(uncle)
fixAfterPut(grand)
return
}
if (parent.isLeftChild()) {
if (node.isLeftChild()) {
setBlack(parent)
} else {
setBlack(node)
rotateLeft(parent)
}
rotateRight(grand)
} else {
if (node.isLeftChild()) {
setBlack(node)
rotateRight(parent)
} else {
setBlack(parent)
}
rotateLeft(grand)
}
}
override fun set(key: K, value: V) {
put(key, value)
}
override fun get(key: K): V? {
return getNode(key)?.value
}
override fun remove(key: K?): V? {
return remove(getNode(key))
}
protected open fun afterRemove(willRemove: Node<K, V>, shouldRemove: Node<K, V>) {
}
protected open fun createNode(key: K, value: V, parent: Node<K, V>?): Node<K, V> {
return Node(key, value, parent)
}
protected open fun remove(valNode: Node<K, V>?): V? {
if (valNode == null) return null
var node = valNode
--size
val oldValue = node.value
if (node.hasTwoChildren()) {
val s = successor(valNode)
if (s != null) {
node.key = s.key
node.value = s.value
node.hash = s.hash
node = s
}
}
val replacement = node.left ?: node.right
val index = getIndex(node)
if (replacement != null) {
replacement.parent = node.parent
if (node.parent == null) {
table[index] = replacement
} else if (node == node.parent!!.left) {
node.parent!!.left = replacement
} else {
node.parent!!.right = replacement
}
fixAfterRemove(replacement)
} else if (node.parent == null) {
table[index] = null
} else {
if (node == node.parent?.left) {
node.parent?.left = null
} else {
node.parent?.right = null
}
fixAfterRemove(node)
}
afterRemove(valNode, node)
return oldValue
}
private fun fixAfterRemove(node: Node<K, V>?) {
if (isRed(node)) {
setBlack(node)
return
}
val parent: Node<K, V> = node?.parent ?: return
val left = parent.left == null || node.isLeftChild()
var sibling = if (left) {
parent.right
} else {
parent.left
}
if (left) {
if (isRed(sibling)) {
setBlack(sibling)
setRed(parent)
rotateLeft(parent)
sibling = parent.right
}
if (isBlack(sibling?.left) && isBlack(sibling?.right)) {
val parentBlack = isBlack(parent)
setBlack(parent)
setRed(sibling)
if (parentBlack) {
fixAfterRemove(parent)
}
} else {
if (isBlack(sibling?.right)) {
rotateRight(sibling)
sibling = parent.right
}
setColor(sibling, colorOf(parent))
setBlack(sibling?.right)
setBlack(parent)
rotateLeft(parent)
}
} else {
if (isRed(sibling)) {
setBlack(sibling)
setRed(parent)
rotateRight(parent)
sibling = parent.left
}
if (isBlack(sibling?.left) && isBlack(sibling?.right)) {
val parentBlack = isBlack(parent)
setBlack(parent)
setRed(sibling)
if (parentBlack) {
fixAfterRemove(parent)
}
} else {
if (isBlack(sibling?.left)) {
rotateLeft(sibling)
sibling = parent.left
}
setColor(sibling, colorOf(parent))
setBlack(sibling?.left)
setBlack(parent)
rotateRight(parent)
}
}
}
private fun rotateLeft(grand: Node<K, V>?) {
val parent = grand?.right
val child = parent?.left
if (grand != null) {
grand.right = child
}
if (parent != null) {
parent.left = grand
}
afterRotate(grand, parent, child)
}
private fun rotateRight(grand: Node<K, V>?) {
val parent = grand?.left
val child = parent?.right
if (grand != null) {
grand.left = child
}
if (parent != null) {
parent.right = grand
}
afterRotate(grand, parent, child)
}
private fun afterRotate(grand: Node<K, V>?, parent: Node<K, V>?, child: Node<K, V>?) {
parent?.parent = grand!!.parent
if (grand.isLeftChild()) {
grand.parent?.left = grand
} else if (grand.isRightChild()) {
grand.parent?.right = parent
} else {
table[getIndex(grand)] = parent
}
if (child != null) {
child.parent = grand
}
grand.parent = parent
}
private fun isRed(node: Node<K, V>?): Boolean {
return colorOf(node) == RED
}
private fun isBlack(node: Node<K, V>?): Boolean {
return colorOf(node) == BLACK
}
private fun colorOf(node: Node<K, V>?): Boolean {
return node?.color ?: BLACK
}
private fun setBlack(node: Node<K, V>?): Node<K, V>? {
return setColor(node, BLACK)
}
private fun setRed(node: Node<K, V>?): Node<K, V>? {
return setColor(node, RED)
}
private fun setColor(node: Node<K, V>?, color: Boolean): Node<K, V>? {
if (node == null) return null
node.color = color
return node
}
private fun successor(current: Node<K, V>?): Node<K, V>? {
if (current == null) return null
var node = current
var p = node.right
if (p != null) {
while (p?.left != null) {
p = p.left
}
return p
}
while (node?.parent != null && node == node.parent?.right) {
node = node.parent
}
return node?.parent
}
override fun contains(key: K?): Boolean {
return getNode(key) != null
}
override fun containsValue(value: V): Boolean {
if (isEmpty) return false
val queue = Queue<Node<K, V>>()
for (kvNode in table) {
if (kvNode == null) continue
queue.offer(kvNode)
while (!queue.isEmpty) {
val node = queue.poll()
assert(node != null)
if (Objects.equals(value, node!!.value)) return true
if (node.left != null) {
queue.offer(node.left)
}
if (node.right != null) {
queue.offer(node.right)
}
}
}
return false
}
override fun traversal(visitor: ((k: K?, v: V?) -> Boolean)?) {
val queue = Queue<Node<K, V>>()
for (kvNode in table) {
if (kvNode == null) continue
queue.offer(kvNode)
while (!queue.isEmpty) {
val node = queue.poll()
assert(visitor != null)
assert(node != null)
if (visitor!!.invoke(node!!.key, node.value)) return
if (node.left != null) {
queue.offer(node.left)
}
if (node.right != null) {
queue.offer(node.right)
}
}
}
}
private fun getNode(key: K?): Node<K, V>? {
val root = table[getIndex(key)]
return if (root == null) {
null
} else {
getNode(root, key)
}
}
private fun getIndex(key: K?): Int {
return getHash(key) and (table.size - 1)
}
private fun getIndex(node: Node<K, V>): Int {
return node.hash and (table.size - 1)
}
private fun getHash(key: K?): Int {
if (key == null) return 0
val temp = key.hashCode()
return temp xor (temp ushr 16)
}
private fun getNode(valNode: Node<K, V>?, k1: K?): Node<K, V>? {
var node = valNode
val h1 = getHash(k1)
var result: Node<K, V>? = null
var cmp = 0
while (node != null) {
val k2 = node.key
val h2 = node.hash
if (h1 > h2) {
node = node.right
} else if (h1 < h2) {
node = node.left
} else if (Objects.equals(k1, k2)) {
return node
} else if (k2 != null
&& k1 is Comparable<*>
&& k1.javaClass == k2.javaClass
&& (k1 as Comparable<K>).compareTo(k2).let { cmp = it; cmp != 0 }
) {
node = if (cmp > 0) {
node.right
} else {
node.left
}
} else if (node.right != null && getNode(node.right, k1).let {
result = it; result != null
}) {
return result
} else {
node = node.left
}
}
return null
}
init {
table = arrayOfNulls<Node<K, V>>(DEFAULT_CAPACITY)
}
open inner class Node<K, V>(var key: K, var value: V, var parent: Node<K, V>?) {
var color: Boolean = TreeMap.RED
var left: Node<K, V>? = null
var right: Node<K, V>? = null
var hash: Int = 0
init {
val hash = key?.hashCode() ?: 0
this.hash = hash xor (hash ushr 16)
}
fun hasTwoChildren(): Boolean {
return left != null && right != null
}
fun isLeftChild(): Boolean {
return parent != null && this == parent?.left
}
fun isRightChild(): Boolean {
return parent != null && this == parent?.right
}
fun sibling(): Node<K, V>? {
if (isLeftChild()) {
return parent?.right
}
if (isRightChild()) {
return parent?.left
}
return null
}
}
}
| 0
|
Kotlin
|
1
| 0
|
e613e47ad22d42eb4efa0b99f6f9da620e63982d
| 15,889
|
algorithm
|
MIT License
|
app/shared/platform/impl/src/commonJvmMain/kotlin/build/wallet/platform/data/FileManagerImpl.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
|
package build.wallet.platform.data
import build.wallet.catching
import build.wallet.logging.logFailure
import build.wallet.mapUnit
import build.wallet.platform.data.File.join
import com.github.michaelbull.result.Result
import com.github.michaelbull.result.mapError
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okio.FileSystem
import okio.Path.Companion.toPath
import java.io.File
import java.util.zip.ZipFile
class FileManagerImpl(
private val fileDirectoryProvider: FileDirectoryProvider,
) : FileManager {
override suspend fun writeFile(
data: ByteArray,
fileName: String,
): FileManagerResult<Unit> {
return Result
.catching {
withContext(Dispatchers.IO) {
val filePath = (fileDirectoryProvider.filesDir().join(fileName)).toPath()
FileSystem.SYSTEM.write(filePath) {
write(data)
}
}
}
.mapError { FileManagerError(it) }
.logFailure { "Failed to write to file [$fileName]" }
.mapUnit()
.toFileManagerResult()
}
override suspend fun readFileAsString(fileName: String): FileManagerResult<String> {
return Result
.catching {
withContext(Dispatchers.IO) {
File(fileDirectoryProvider.filesDir().join(fileName)).readText()
}
}
.mapError { FileManagerError(it) }
.logFailure { "Failed to read file [$fileName] as string" }
.toFileManagerResult()
}
override suspend fun readFileAsBytes(fileName: String): FileManagerResult<ByteArray> {
return Result
.catching {
withContext(Dispatchers.IO) {
File(fileDirectoryProvider.filesDir().join(fileName)).readBytes()
}
}
.mapError { FileManagerError(it) }
.logFailure { "Failed to read file [$fileName] as bytes" }
.toFileManagerResult()
}
override suspend fun unzipFile(
zipPath: String,
targetDirectory: String,
): FileManagerResult<Unit> {
return Result
.catching {
withContext(Dispatchers.IO) {
unzip(zipPath, targetDirectory)
}
}
.mapError { FileManagerError(it) }
.logFailure { "Failed to unzip file [$zipPath] into target dir [$targetDirectory]" }
.toFileManagerResult()
}
override suspend fun fileExists(fileName: String): Boolean {
return File(fileDirectoryProvider.filesDir(), fileName).exists()
}
override suspend fun removeDir(path: String): FileManagerResult<Unit> {
return Result
.catching {
withContext(Dispatchers.IO) {
if (!File(fileDirectoryProvider.filesDir(), path).deleteRecursively()) {
throw FileManagerError(Error("can't delete"))
}
}
}
.mapError { FileManagerError(it) }
.logFailure { "Failed to delete $path" }
.toFileManagerResult()
}
override suspend fun mkdirs(path: String): FileManagerResult<Boolean> {
return Result.catching {
withContext(Dispatchers.IO) {
val filePath = (fileDirectoryProvider.filesDir().join(path)).toPath()
File(path).mkdirs()
}
}
.mapError { FileManagerError(it) }
.logFailure { "Failed to make directories for dir [$path]" }
.toFileManagerResult()
}
@Suppress("NestedBlockDepth")
private fun unzip(
zipPath: String,
targetDirectory: String,
) {
val zipFile = ZipFile(File(fileDirectoryProvider.filesDir(), zipPath).absolutePath)
val targetFile = File(fileDirectoryProvider.filesDir(), targetDirectory)
targetFile.mkdirs()
zipFile.entries().asSequence().forEach { entry ->
val newFile = File(targetFile, entry.name)
val canonicalTargetDirPath = targetFile.canonicalPath
val canonicalNewFilePath = newFile.canonicalPath
/**
* Validate the path of the new file before it's created.
* Checks if the canonical path of the new file starts with the canonical path of the target
* directory.
* Prevents a Zip Slip vulnerability attach which is a form of directory traversal attack.
* Without this validation, a zip entry could potentially write a file outside the target directory.
*/
if (!canonicalNewFilePath.startsWith(canonicalTargetDirPath)) {
throw SecurityException("Zip entry is outside of the target dir: ${entry.name}")
}
if (entry.isDirectory) {
newFile.mkdirs()
} else {
zipFile.getInputStream(entry).use { input ->
newFile.outputStream().use { output ->
input.copyTo(output)
}
}
}
}
zipFile.close()
}
}
| 3
|
C
|
16
| 98
|
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
| 4,617
|
bitkey
|
MIT License
|
idea/testData/copyPaste/imports/FunctionAlreadyImported.expected.kt
|
JakeWharton
| 99,388,807
| false
| null |
package to
import a.g
fun f() {
g()
}
| 0
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 43
|
kotlin
|
Apache License 2.0
|
sketch-extensions-core/src/commonTest/kotlin/com/github/panpf/sketch/extensions/core/test/util/DownloadTest.kt
|
panpf
| 14,798,941
| false
|
{"Kotlin": 2817618, "Shell": 672}
|
package com.github.panpf.sketch.extensions.core.test.util
import com.github.panpf.sketch.cache.DiskCache
import com.github.panpf.sketch.images.MyImages
import com.github.panpf.sketch.test.singleton.getTestContextAndSketch
import com.github.panpf.sketch.test.utils.MyImagesHttpStack
import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch
import com.github.panpf.sketch.util.enqueueDownload
import com.github.panpf.sketch.util.executeDownload
import com.github.panpf.sketch.util.toUri
import kotlinx.coroutines.test.runTest
import okio.use
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class DownloadTest {
@Test
fun test() = runTest {
val (_, defaultSketch) = getTestContextAndSketch()
val (_, newSketch) = getTestContextAndNewSketch {
httpStack(MyImagesHttpStack(defaultSketch))
}
try {
val downloadCache = newSketch.downloadCache
downloadCache.clear()
assertEquals(expected = 0L, actual = downloadCache.size)
val imageUri = "http://${MyImages.jpeg.uri.toUri().authority}"
assertFalse(downloadCache.existWithLock(imageUri))
val imageUri2 = "http://${MyImages.png.uri.toUri().authority}"
assertFalse(downloadCache.existWithLock(imageUri2))
newSketch.enqueueDownload(imageUri).job.await()
assertTrue(downloadCache.existWithLock(imageUri))
assertFalse(downloadCache.existWithLock(imageUri2))
newSketch.executeDownload(imageUri2)
assertTrue(downloadCache.existWithLock(imageUri))
assertTrue(downloadCache.existWithLock(imageUri2))
} finally {
newSketch.downloadCache.fileSystem.deleteRecursively(newSketch.downloadCache.directory)
newSketch.resultCache.fileSystem.deleteRecursively(newSketch.resultCache.directory)
}
}
private suspend fun DiskCache.existWithLock(key: String): Boolean {
return withLock(key) {
openSnapshot(key)?.use { } != null
}
}
}
| 1
|
Kotlin
|
307
| 1,998
|
5cb3aaf167f23262c8b9c2e9a7ab8d8f8c0bad5b
| 2,126
|
sketch
|
Apache License 2.0
|
core/src/main/kotlin/com/labijie/infra/mqts/impl/NoopTransactionRedoSupported.kt
|
hongque-pro
| 314,188,221
| false
| null |
package com.labijie.infra.mqts.impl
import com.labijie.infra.mqts.TransactionSourceAttribute
import com.labijie.infra.mqts.abstractions.ITransactionRedoSupported
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* Created with IntelliJ IDEA.
* @author Anders Xiao
* @date 2018-11-26
*/
class NoopTransactionRedoSupported() : ITransactionRedoSupported {
companion object {
val logger: Logger by lazy { LoggerFactory.getLogger(NoopTransactionRedoSupported::class.java) }
}
@Throws(UnsupportedOperationException::class)
override fun start(transactionSources: Iterable<TransactionSourceAttribute>) {
logger.warn("MQTS redo supported was not found, so transaction can not be redo.")
}
}
| 0
|
Kotlin
|
0
| 1
|
40fe893cfc62ee2442851c2b4f81519ab6465129
| 733
|
infra-mqts
|
Apache License 2.0
|
src/main/kotlin/io/goauthentik/api/models/AuthenticatedSession.kt
|
goauthentik
| 687,459,450
| false
|
{"Kotlin": 3703856, "Go": 1227, "Makefile": 859}
|
/**
* authentik
*
* Making authentication simple.
*
* The version of the OpenAPI document: 2023.10.3
* Contact: <EMAIL>
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package io.goauthentik.api.models
import io.goauthentik.api.models.AuthenticatedSessionGeoIp
import io.goauthentik.api.models.AuthenticatedSessionUserAgent
import com.squareup.moshi.Json
/**
* AuthenticatedSession Serializer
*
* @param current Check if session is currently active session
* @param userAgent
* @param geoIp
* @param user
* @param lastIp
* @param lastUsed
* @param uuid
* @param lastUserAgent
* @param expires
*/
data class AuthenticatedSession (
/* Check if session is currently active session */
@Json(name = "current")
val current: kotlin.Boolean,
@Json(name = "user_agent")
val userAgent: AuthenticatedSessionUserAgent,
@Json(name = "geo_ip")
val geoIp: AuthenticatedSessionGeoIp?,
@Json(name = "user")
val user: kotlin.Int,
@Json(name = "last_ip")
val lastIp: kotlin.String,
@Json(name = "last_used")
val lastUsed: java.time.OffsetDateTime,
@Json(name = "uuid")
val uuid: java.util.UUID? = null,
@Json(name = "last_user_agent")
val lastUserAgent: kotlin.String? = null,
@Json(name = "expires")
val expires: java.time.OffsetDateTime? = null
)
| 1
|
Kotlin
|
0
| 0
|
a7dba25c2c3cfbad21bdb3e459dc66f516ddfb56
| 1,564
|
client-kotlin
|
Info-ZIP License
|
csstype-kotlin/src/jsMain/kotlin/web/cssom/BoxSizing.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6824465}
|
// Automatically generated - do not modify!
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.cssom
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface BoxSizing {
companion object {
@JsValue("border-box")
val borderBox: BoxSizing
@JsValue("content-box")
val contentBox: BoxSizing
}
}
| 0
|
Kotlin
|
7
| 28
|
43e14a99f90c9f1ea164f382f423cb05a58df22b
| 389
|
types-kotlin
|
Apache License 2.0
|
src/main/kotlin/LaunchCommandBuilder.kt
|
YaeMonilc
| 677,998,156
| false
| null |
import entity.*
import java.io.File
/**
* The Launch Command Object Builder
* @author YaeMonilc
*/
class LaunchCommandBuilder(
val config: GameConfig,
val user: User,
val memorySetting: MemorySetting = MemorySetting(),
val launcherConfig: LauncherConfig = LauncherConfig()
) {
private val launchCommand = LaunchCommand()
private val jvmArgs: MutableList<String> = mutableListOf()
private val minecraftArgs: LinkedHashMap<String, String> = LinkedHashMap()
init {
launchCommand.os = config.os
jvmArgs.add("-Xmx${memorySetting.max}m")
jvmArgs.add("-Xmn${memorySetting.min}m")
jvmArgs.add("-Dfile.encoding=${config.charset}")
jvmArgs.add("-Dsun.stdout.encoding=${config.charset}")
jvmArgs.add("-Dsun.stderr.encoding=${config.charset}")
jvmArgs.add("-Djava.rmi.server.useCodebaseOnly=true")
jvmArgs.add("-Dcom.sun.jndi.rmi.object.trustURLCodebase=false")
jvmArgs.add("-Dcom.sun.jndi.cosnaming.object.trustURLCodebase=false")
jvmArgs.add("-XX:+UnlockExperimentalVMOptions")
jvmArgs.add("-XX:+UseG1GC")
jvmArgs.add("-XX:G1NewSizePercent=20")
jvmArgs.add("-XX:G1ReservePercent=20")
jvmArgs.add("-XX:MaxGCPauseMillis=50")
jvmArgs.add("-XX:G1HeapRegionSize=32m")
jvmArgs.add("-XX:-UseAdaptiveSizePolicy")
jvmArgs.add("-XX:-OmitStackTraceInFastThrow")
jvmArgs.add("-XX:-DontCompileHugeMethods")
jvmArgs.add("-Dfml.ignoreInvalidMinecraftCertificates=true")
jvmArgs.add("-Dfml.ignorePatchDiscrepancies=true")
jvmArgs.add("-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump")
jvmArgs.add("-Dminecraft.launcher.brand=${launcherConfig.name}")
jvmArgs.add("-Dminecraft.launcher.version=${launcherConfig.version}")
val versionJson = config.versionJson
val versionPath = config.minecraftPath.getVersion(versionJson.id).absolutePath
val gameJar = File(versionPath, "${versionJson.id}.jar").absolutePath
val nativesPath = File(versionPath, "/natives").absolutePath
jvmArgs.add("-Djava.library.path=$nativesPath")
jvmArgs.add("-Djna.tmpdir=$nativesPath")
jvmArgs.add("-Dorg.lwjgl.system.SharedLibraryExtractPath=$nativesPath")
jvmArgs.add("-Dio.netty.native.workdir=$nativesPath")
val loggingFile = File(versionPath, "log4j2.xml")
if (loggingFile.exists()) {
jvmArgs.add("-Dlog4j2.formatMsgNoLookups=true")
jvmArgs.add("-Dlog4j.configurationFile=${loggingFile.absolutePath}")
}
jvmArgs.add("-Dminecraft.client.jar=$gameJar")
val librariesString = StringBuilder()
versionJson.libraries.filter { library ->
library.rules?.any { (it.os?.name == config.os && it.action == "allow") ||
(it.action == "disallow" && it.os?.name != config.os) } ?: false || library.rules == null
}.forEach { library ->
library.downloads.artifact?.let {
librariesString.append("${File(config.minecraftPath.getLibraries(), it.path).absolutePath};")
}
library.downloads.classifiers?.let { classifiers ->
val artifact = when(config.os) {
OS.LINUX -> classifiers.nativesLinux
OS.OSX -> classifiers.nativesOSX
OS.WNIDOWS -> classifiers.nativesWindows
else -> null
}
artifact?.let {
librariesString.append("${File(config.minecraftPath.getLibraries(), it.path).absolutePath};")
}
}
}
jvmArgs.add("-cp")
jvmArgs.add("$librariesString$gameJar")
jvmArgs.add(versionJson.mainClass)
minecraftArgs["--version"] = versionJson.id
minecraftArgs["--gameDir"] = versionPath
minecraftArgs["--assetsDir"] = config.minecraftPath.getAssets().absolutePath
minecraftArgs["--assetIndex"] = versionJson.assetIndex.id
minecraftArgs["--username"] = user.name
minecraftArgs["--uuid"] = user.authUUID
minecraftArgs["--accessToken"] = user.accessToken
minecraftArgs["--userType"] = user.userType
minecraftArgs["--versionType"] = "${launcherConfig.name} ${launcherConfig.version}"
}
/**
* @author YaeMonilc
* @return entity.LaunchCommand
*/
fun build(): LaunchCommand {
val command = StringBuilder()
command.append(config.javaPath)
jvmArgs.forEach {
command.append(" '$it'")
}
minecraftArgs.forEach { t, u ->
command.append("${if (t.isBlank()) "" else " '$t'"} '$u'")
}
launchCommand.command = command.toString()
return launchCommand
}
}
| 0
|
Kotlin
|
0
| 1
|
6c320b0e4464ab8439056fbe2dd8f5fc52e97c97
| 4,852
|
MinecraftLauncherCore
|
Apache License 2.0
|
shared/src/commonMain/kotlin/dev/avatsav/linkding/domain/TagList.kt
|
avatsav
| 576,855,763
| false
|
{"Kotlin": 190189, "Swift": 589}
|
package dev.avatsav.linkding.domain
import kotlinx.serialization.Serializable
@Serializable
data class TagList(
val count: Long,
val next: String?,
val previous: String?,
val results: List<Tag>,
)
| 2
|
Kotlin
|
0
| 8
|
1d853d58d9d584c270f7e2ed11392e2aec0bdf34
| 215
|
linkding-apps
|
MIT License
|
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/routes/behandling/vilkår/kvp/OppdaterKvpRoute.kt
|
navikt
| 487,246,438
| false
|
{"Kotlin": 1042302, "Shell": 1318, "Dockerfile": 495, "HTML": 45}
|
package no.nav.tiltakspenger.vedtak.routes.behandling.vilkår.kvp
import io.ktor.http.HttpStatusCode
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.post
import mu.KotlinLogging
import no.nav.tiltakspenger.felles.Saksbehandler
import no.nav.tiltakspenger.libs.common.BehandlingId
import no.nav.tiltakspenger.libs.common.CorrelationId
import no.nav.tiltakspenger.saksbehandling.domene.vilkår.kvp.LeggTilKvpSaksopplysningCommand
import no.nav.tiltakspenger.saksbehandling.service.behandling.vilkår.kvp.KvpVilkårService
import no.nav.tiltakspenger.vedtak.auditlog.AuditLogEvent
import no.nav.tiltakspenger.vedtak.auditlog.AuditService
import no.nav.tiltakspenger.vedtak.auth2.TokenService
import no.nav.tiltakspenger.vedtak.routes.behandling.BEHANDLING_PATH
import no.nav.tiltakspenger.vedtak.routes.correlationId
import no.nav.tiltakspenger.vedtak.routes.dto.PeriodeDTO
import no.nav.tiltakspenger.vedtak.routes.withBehandlingId
import no.nav.tiltakspenger.vedtak.routes.withBody
import no.nav.tiltakspenger.vedtak.routes.withSaksbehandler
/** Brukes ikke i MVPen. */
fun Route.oppdaterKvpRoute(
kvpVilkårService: KvpVilkårService,
auditService: AuditService,
tokenService: TokenService,
) {
val logger = KotlinLogging.logger {}
data class DeltarForPeriode(
val periode: PeriodeDTO,
val deltar: Boolean,
)
data class Body(
val ytelseForPeriode: List<DeltarForPeriode>,
/** Drop-down i frontend. */
val årsakTilEndring: ÅrsakTilEndringDTO,
) {
fun toCommand(
behandlingId: BehandlingId,
saksbehandler: Saksbehandler,
correlationId: CorrelationId,
): LeggTilKvpSaksopplysningCommand =
LeggTilKvpSaksopplysningCommand(
deltakelseForPeriode =
this.ytelseForPeriode.map {
LeggTilKvpSaksopplysningCommand.DeltakelseForPeriode(
periode = it.periode.toDomain(),
deltar = it.deltar,
)
},
årsakTilEndring = this.årsakTilEndring.toDomain(),
behandlingId = behandlingId,
saksbehandler = saksbehandler,
correlationId = correlationId,
)
}
post("$BEHANDLING_PATH/{behandlingId}/vilkar/kvp") {
logger.debug("Mottatt post-request på '$BEHANDLING_PATH/{behandlingId}/vilkar/kvp' - oppdaterer vilkår om kvalifikasjonsprogrammet")
call.withSaksbehandler(tokenService = tokenService) { saksbehandler ->
call.withBehandlingId { behandlingId ->
call.withBody<Body> { body ->
if (body.ytelseForPeriode.isEmpty()) {
throw IllegalArgumentException(
"Dersom saksbehandler ønsker å legge til en kvp-saksopplysning må hen spesifisere minst én periode",
)
}
val correlationId = call.correlationId()
kvpVilkårService.leggTilSaksopplysning(
body.toCommand(behandlingId, saksbehandler, correlationId),
).let {
auditService.logMedBehandlingId(
behandlingId = behandlingId,
navIdent = saksbehandler.navIdent,
action = AuditLogEvent.Action.UPDATE,
contextMessage = "Oppdaterer data om vilkåret kvalifikasjonsprogrammet",
correlationId = correlationId,
)
call.respond(
status = HttpStatusCode.Created,
message = it.vilkårssett.kvpVilkår.toDTO(),
)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
c23890a313eac464b2eae8d6e6f143b47a4b693e
| 3,933
|
tiltakspenger-vedtak
|
MIT License
|
app/src/main/java/org/itstep/liannoi/androidpaging/application/storage/users/models/UserDao.kt
|
liannoi
| 290,314,559
| false
| null |
package org.itstep.liannoi.androidpaging.application.storage.users.models
import androidx.room.Dao
import androidx.room.Query
import io.reactivex.Maybe
import org.itstep.liannoi.androidpaging.application.ApplicationDefaults
import org.itstep.liannoi.androidpaging.application.common.storage.BaseDao
@Dao
interface UserDao : BaseDao<User> {
@Query("SELECT U.UserId, U.Name, U.Salary FROM Users AS U ORDER BY U.UserId ASC LIMIT :itemsPerPage OFFSET :startPosition")
fun getAll(
startPosition: Int = ApplicationDefaults.PAGING_START_POSITION,
itemsPerPage: Int = ApplicationDefaults.PAGING_ITEMS_PER_PAGE
): Maybe<List<User>>
}
| 4
|
Kotlin
|
0
| 0
|
3afe76b1dcdb0d1e5562ea5f098c39db9dda33e9
| 656
|
android-paging
|
Apache License 2.0
|
app/src/main/kotlin/dev/aaa1115910/bv/activities/video/TagActivity.kt
|
aaa1115910
| 571,702,700
| false
|
{"Kotlin": 1537138}
|
package dev.aaa1115910.bv.activities.video
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import dev.aaa1115910.bv.screen.TagScreen
import dev.aaa1115910.bv.ui.theme.BVTheme
class TagActivity : ComponentActivity() {
companion object {
fun actionStart(context: Context, tagId: Int, tagName: String) {
context.startActivity(
Intent(context, TagActivity::class.java).apply {
putExtra("tagId", tagId)
putExtra("tagName", tagName)
}
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
BVTheme {
TagScreen()
}
}
}
}
| 18
|
Kotlin
|
112
| 999
|
e93863f4f266485e16e1768fcea6e6b9ad0b276b
| 885
|
bv
|
MIT License
|
components/bridge/dao/api/src/main/java/com/flipperdevices/bridge/dao/api/delegates/key/UpdateKeyApi.kt
|
flipperdevices
| 288,258,832
| false
|
{"Kotlin": 2760721, "FreeMarker": 10084, "CMake": 1780, "C++": 1152, "Fluent": 21}
|
package com.flipperdevices.bridge.dao.api.delegates.key
import com.flipperdevices.bridge.dao.api.model.FlipperKey
import com.flipperdevices.bridge.dao.api.model.FlipperKeyPath
import kotlinx.coroutines.flow.Flow
interface UpdateKeyApi {
/**
* Notifies you when the key path has changed. The first object sends the {@param originalPath}
*/
fun subscribeOnUpdatePath(originalPath: FlipperKeyPath): Flow<FlipperKeyPath>
/**
* Calculates the difference between the two keys and updates only the difference between them.
* If necessary, marks the file as necessary for synchronization.
*/
suspend fun updateKey(oldKey: FlipperKey, newKey: FlipperKey)
}
| 13
|
Kotlin
|
131
| 999
|
ef27b6b6a78a59b603ac858de2c88f75b743f432
| 692
|
Flipper-Android-App
|
MIT License
|
plugins/git4idea/src/git4idea/index/actions/GitFileStatusNodeAction.kt
|
hieuprogrammer
| 284,920,751
| true
| null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.index.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcsUtil.VcsFileUtil
import com.intellij.vcsUtil.VcsUtil
import com.intellij.xml.util.XmlStringUtil
import git4idea.i18n.GitBundle
import git4idea.index.ui.GIT_FILE_STATUS_NODES_STREAM
import git4idea.index.ui.GitFileStatusNode
import git4idea.index.ui.NodeKind
import git4idea.index.vfs.GitIndexFileSystemRefresher
import git4idea.util.GitFileUtils
import java.util.function.Supplier
import javax.swing.Icon
import kotlin.streams.toList
class GitAddAction : GitFileStatusNodeAction(GitAddOperation)
class GitResetAction : GitFileStatusNodeAction(GitResetOperation)
class GitRevertAction : GitFileStatusNodeAction(GitRevertOperation)
abstract class GitFileStatusNodeAction(private val operation: StagingAreaOperation)
: DumbAwareAction(operation.actionText, Presentation.NULL_STRING, operation.icon) {
override fun update(e: AnActionEvent) {
val statusInfoStream = e.getData(GIT_FILE_STATUS_NODES_STREAM)
e.presentation.isEnabledAndVisible = e.project != null && statusInfoStream != null &&
statusInfoStream.anyMatch(operation::matches)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val nodes = e.getRequiredData(GIT_FILE_STATUS_NODES_STREAM).filter(operation::matches).toList()
performStageOperation(project, nodes, operation)
}
}
object GitAddOperation : StagingAreaOperation {
override val actionText get() = GitBundle.messagePointer("add.action.name")
override val progressTitle get() = GitBundle.message("add.adding")
override val icon = AllIcons.General.Add
override fun matches(statusNode: GitFileStatusNode) = statusNode.kind == NodeKind.UNSTAGED || statusNode.kind == NodeKind.UNTRACKED
override fun processPaths(project: Project, root: VirtualFile, paths: List<FilePath>) {
GitFileUtils.addPaths(project, root, paths, false)
}
override fun showErrorMessage(project: Project, exceptions: Collection<VcsException>) {
showErrorMessage(project, VcsBundle.message("error.adding.files.title"), exceptions)
}
}
object GitResetOperation : StagingAreaOperation {
override val actionText get() = GitBundle.messagePointer("stage.reset.action.text")
override val progressTitle get() = GitBundle.message("stage.reset.process")
override val icon = AllIcons.General.Remove
override fun matches(statusNode: GitFileStatusNode) = statusNode.kind == NodeKind.STAGED
override fun processPaths(project: Project, root: VirtualFile, paths: List<FilePath>) {
GitFileUtils.resetPaths(project, root, paths)
}
override fun showErrorMessage(project: Project, exceptions: Collection<VcsException>) {
showErrorMessage(project, GitBundle.message("stage.reset.error.title"), exceptions)
}
}
object GitRevertOperation : StagingAreaOperation {
override val actionText get() = GitBundle.messagePointer("stage.revert.action.text")
override val progressTitle get() = GitBundle.message("stage.revert.process")
override val icon = AllIcons.Actions.Rollback
override fun matches(statusNode: GitFileStatusNode) = statusNode.kind == NodeKind.UNSTAGED
override fun processPaths(project: Project, root: VirtualFile, paths: List<FilePath>) {
GitFileUtils.revertUnstagedPaths(project, root, paths)
LocalFileSystem.getInstance().refreshFiles(paths.mapNotNull { it.virtualFile })
}
override fun showErrorMessage(project: Project, exceptions: Collection<VcsException>) {
showErrorMessage(project, GitBundle.message("stage.revert.error.title"), exceptions)
}
}
fun performStageOperation(project: Project, nodes: List<GitFileStatusNode>, operation: StagingAreaOperation) {
FileDocumentManager.getInstance().saveAllDocuments()
runProcess(project, operation.progressTitle, true) {
val paths = nodes.map { it.filePath }
val exceptions = mutableListOf<VcsException>()
VcsUtil.groupByRoots(project, paths) { it }.forEach { (vcsRoot, paths) ->
try {
operation.processPaths(project, vcsRoot.path, paths)
VcsFileUtil.markFilesDirty(project, paths)
GitIndexFileSystemRefresher.getInstance(project).refresh { paths.contains(it.filePath) }
}
catch (ex: VcsException) {
exceptions.add(ex)
}
}
if (exceptions.isNotEmpty()) {
operation.showErrorMessage(project, exceptions)
}
}
}
fun <T> runProcess(project: Project, title: @NlsContexts.ProgressTitle String, canBeCancelled: Boolean, process: () -> T): T {
return ProgressManager.getInstance().runProcessWithProgressSynchronously<T, Exception>(ThrowableComputable { process() },
title, canBeCancelled, project)
}
private fun showErrorMessage(project: Project, messageTitle: String, exceptions: Collection<Exception>) {
VcsBalloonProblemNotifier.showOverVersionControlView(project, XmlStringUtil.wrapInHtmlTag("$messageTitle:", "b")
+ "\n" + exceptions.joinToString("\n") { it.localizedMessage },
MessageType.ERROR)
}
interface StagingAreaOperation {
val actionText: Supplier<String>
val progressTitle: String
val icon: Icon?
fun matches(statusNode: GitFileStatusNode): Boolean
@Throws(VcsException::class)
fun processPaths(project: Project, root: VirtualFile, paths: List<FilePath>)
fun showErrorMessage(project: Project, exceptions: Collection<VcsException>)
}
| 1
| null |
1
| 2
|
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 6,443
|
intellij-community
|
Apache License 2.0
|
glucose/src/main/java/com/desugar/glucose/events/Event.kt
|
desugar-64
| 585,358,949
| false
| null |
package com.desugar.glucose.events
abstract class Event {
enum class EventType {
None,
WindowClose, WindowResize, WindowFocus, WindowLostFocus, WindowMoved,
AppTick, AppUpdate, AppRender,
KeyPressed, KeyReleased,
TouchPressed, TouchMoved, TouchReleased,
MouseMoved, MouseButtonPressed, MouseButtonReleased, MouseScrolled
}
enum class EventCategory(internal val bit: Int) {
None(0),
EventCategoryApplication(bit(1)),
EventCategoryInput(bit(2)),
EventCategoryKeyboard(bit(3)),
EventCategoryTouch(bit(4)),
EventCategoryMouse(bit(5)),
EventCategoryMouseButton(bit(6));
}
var isHandled: Boolean = false
abstract val name: String
abstract val type: EventType
abstract val categoryFlags: Int
fun isInCategory(category: EventCategory): Boolean {
return categoryFlags and category != 0
}
override fun toString(): String {
return "Event(name='$name', isHandled=$isHandled, type=$type, categoryFlags=$categoryFlags)"
}
private infix fun Int.and(category: EventCategory): Int {
return this and category.bit
}
infix fun Int.or(category: EventCategory): Int {
return this or category.bit
}
infix fun EventCategory.or(other: EventCategory): Int {
return this.bit or other.bit
}
}
@JvmInline
value class EventDispatcher(
val event: Event
) {
inline fun <reified E : Event> dispatch(func: (E) -> Boolean): Boolean {
return if (event is E) {
event.isHandled = func.invoke(event)
true
} else {
false
}
}
}
fun bit(x: Int): Int {
return 1 shl x
}
| 0
|
Kotlin
|
0
| 0
|
3715d8af08db2b4052fc1786130cbfb82081a3bc
| 1,729
|
android-opengl-renderer
|
Apache License 2.0
|
app/src/main/java/com/anyjob/ui/explorer/search/SearchFragment.kt
|
y0ung3r
| 485,848,073
| false
| null |
package com.anyjob.ui.explorer.search
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.graphics.ColorUtils
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentContainerView
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.anyjob.R
import com.anyjob.databinding.FragmentSearchBinding
import com.anyjob.domain.profile.models.MapsAddress
import com.anyjob.domain.profile.models.User
import com.anyjob.domain.search.OrderCreationParameters
import com.anyjob.domain.services.models.Service
import com.anyjob.ui.animations.VisibilityMode
import com.anyjob.ui.animations.extensions.fade
import com.anyjob.ui.animations.fade.FadeParameters
import com.anyjob.ui.animations.radar.RadarParameters
import com.anyjob.ui.animations.radar.extensions.startRadar
import com.anyjob.ui.explorer.ExplorerActivity
import com.anyjob.ui.explorer.search.controls.bottomSheets.GeolocationUnavailableBottomSheetDialog
import com.anyjob.ui.explorer.search.controls.bottomSheets.addresses.AddressesBottomSheetDialog
import com.anyjob.ui.explorer.search.controls.bottomSheets.addresses.models.UserAddress
import com.anyjob.ui.explorer.search.controls.bottomSheets.services.ServicesBottomSheetDialog
import com.anyjob.ui.explorer.search.viewModels.SearchViewModel
import com.anyjob.ui.explorer.viewModels.ExplorerViewModel
import com.anyjob.ui.extensions.getZoomLevel
import com.anyjob.ui.extensions.observeOnce
import com.anyjob.ui.extensions.showToast
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.Circle
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MapStyleOptions
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.chip.Chip
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.*
class SearchFragment : Fragment() {
private val _activityViewModel by sharedViewModel<ExplorerViewModel>()
private val _viewModel by viewModel<SearchViewModel>()
private lateinit var _binding: FragmentSearchBinding
private lateinit var _googleMap: GoogleMap
private lateinit var _addressesBottomSheet: BottomSheetDialog
private lateinit var _servicesBottomSheet: BottomSheetDialog
private var _searchRadiiViews = ArrayList<Circle>()
private val _fragmentHost by lazy {
requireActivity().findViewById<FragmentContainerView>(R.id.explorer_fragments_container)
}
private val _toolbar by lazy {
val activity = requireActivity() as ExplorerActivity
return@lazy activity.binding.toolbar
}
private val _navigationController by lazy {
findNavController()
}
private val _mapView by lazy {
childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
}
private val _searchBottomSheetBehavior by lazy {
BottomSheetBehavior.from(_binding.searchBottomSheet.bottomSheetLayout)
}
private val _searchProgressBottomSheetBehavior by lazy {
BottomSheetBehavior.from(_binding.searchProgressBottomSheet.bottomSheetLayout)
}
private fun getSearchRadius(chipId: Int): Float = when (chipId) {
R.id.one_kilometer_chip -> 1000.0f
R.id.two_kilometers_chip -> 2000.0f
R.id.three_kilometers_chip -> 3000.0f
R.id.five_kilometers_chip -> 5000.0f
else -> 500.0f
}
private val _searchBottomSheetCallback = object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
if (bottomSheet.visibility == View.VISIBLE) {
when (newState) {
BottomSheetBehavior.STATE_EXPANDED -> drawSearchRadius(
_googleMap.cameraPosition.target,
getSearchRadius(_binding.searchBottomSheet.availableRadii.checkedChipId)
)
BottomSheetBehavior.STATE_COLLAPSED -> removeLastSearchRadius()
}
}
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
// Ignore...
}
}
private val _locationProvider by lazy {
LocationServices.getFusedLocationProviderClient(
requireActivity()
)
}
private val _locationPermissions = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (!isGranted) {
showLocationPermissionsRationaleDialog()
}
}
private fun requestLocationPermissions() {
_locationPermissions.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
private fun showLocationPermissionsRationaleDialog() {
val context = requireContext()
GeolocationUnavailableBottomSheetDialog(
context,
R.style.Theme_AnyJob_BottomSheetDialog
)
.show()
}
private fun isPermissionsDenied(): Boolean {
val context = requireContext()
val finePermissionGranted = ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
val coarsePermissionGranted = ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
return !finePermissionGranted || !coarsePermissionGranted
}
private fun moveCamera(address: Address) {
val radius = getSearchRadius(
_binding.searchBottomSheet.availableRadii.checkedChipId
)
moveCamera(
LatLng(address.latitude, address.longitude),
getZoomLevel(radius)
)
}
private fun moveCamera(location: LatLng, zoom: Float) {
val coordinates = LatLng(location.latitude, location.longitude)
val cameraUpdate = CameraUpdateFactory.newLatLngZoom(coordinates, zoom)
_googleMap.animateCamera(cameraUpdate)
}
private fun moveCameraToUserLocation() {
if (isPermissionsDenied()) {
return requestLocationPermissions()
}
if (!_googleMap.isMyLocationEnabled) {
_googleMap.isMyLocationEnabled = true
}
_locationProvider.lastLocation.addOnSuccessListener { location ->
val radius = getSearchRadius(
_binding.searchBottomSheet.availableRadii.checkedChipId
)
if (location != null) {
moveCamera(
LatLng(location.latitude, location.longitude),
getZoomLevel(radius)
)
}
}
}
private fun drawSearchRadius(position: LatLng, radius: Float, radarParameters: RadarParameters? = null): Circle {
removeLastSearchRadius()
val searchRadius = _googleMap.addCircle(
CircleOptions().apply {
center(position)
strokeColor(Color.TRANSPARENT)
fillColor(
Color.parseColor(
getString(R.color.light_purple)
)
)
}
)
val animationParameters = radarParameters ?: RadarParameters()
val fillColor = Color.alpha(searchRadius.fillColor)
startRadar(
animationParameters.apply {
mode = VisibilityMode.Show
maxRadius = radius
onUpdate = { radiusFraction, invertedRadiusFraction ->
searchRadius.radius = radiusFraction
if (infinity) {
val alpha = (invertedRadiusFraction / radius * fillColor).toInt()
searchRadius.fillColor = ColorUtils.setAlphaComponent(searchRadius.fillColor, alpha)
}
}
}
)
_searchRadiiViews.add(searchRadius)
return searchRadius
}
private fun removeLastSearchRadius() {
_searchRadiiViews.lastOrNull()?.also {
startRadar(
RadarParameters().apply {
mode = VisibilityMode.Hide
animationLength = 500
maxRadius = it.radius.toFloat()
onUpdate = { radiusFraction, _ ->
it.radius = radiusFraction
if (it.radius == 0.0) {
it.remove()
_searchRadiiViews.remove(it)
}
}
}
)
}
}
private fun onMapReady(googleMap: GoogleMap) {
_googleMap = googleMap
_googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
requireContext(),
R.raw.map_style
)
)
val geocoder = Geocoder(
requireContext(),
Locale.getDefault()
)
_googleMap.uiSettings.isMyLocationButtonEnabled = true
_googleMap.uiSettings.isRotateGesturesEnabled = false
_googleMap.uiSettings.isTiltGesturesEnabled = false
_googleMap.uiSettings.isMyLocationButtonEnabled = false
_googleMap.setOnCameraIdleListener {
lifecycleScope.launch {
val position = _googleMap.cameraPosition.target
try {
val addresses = withContext(Dispatchers.Default) {
geocoder.getFromLocation(position.latitude, position.longitude, 1)
}
if (addresses.any()) {
val address = addresses[0]
_activityViewModel.updateCurrentAddress(address)
}
}
catch (exception: Exception) {
showToast(
getString(R.string.failed_to_determine_address)
)
}
finally {
_searchBottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
}
}
}
_googleMap.setOnCameraMoveStartedListener {
_searchBottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
}
moveCameraToUserLocation()
}
private fun onCurrentLocationButtonClick(button: View) {
moveCameraToUserLocation()
}
private fun onUserChangeRadius(chipGroup: View, selectedChip: Int) {
val radius = getSearchRadius(selectedChip)
val location = _googleMap.cameraPosition.target
drawSearchRadius(location, radius)
moveCamera(
LatLng(location.latitude, location.longitude),
getZoomLevel(radius)
)
}
private fun onUserStartSearching(button: View) {
_binding.currentLocationButton.fade(
FadeParameters().apply {
mode = VisibilityMode.Hide
animationLength = 300
}
)
_binding.searchBottomSheet.bottomSheetLayout.visibility = View.GONE
_binding.searchProgressBottomSheet.bottomSheetLayout.visibility = View.VISIBLE
_binding.mapPin.isTouchEventsDisabled = true
_googleMap.uiSettings.isScrollGesturesEnabled = false
_googleMap.uiSettings.isZoomGesturesEnabled = false
val chipId = _binding.searchBottomSheet.availableRadii.checkedChipId
val chip = _binding.searchBottomSheet.availableRadii.findViewById<Chip>(chipId)
val radius = getSearchRadius(chipId)
val position = _googleMap.cameraPosition.target
val radarParameters = RadarParameters().apply {
infinity = true
animationLength = 3500
}
drawSearchRadius(position, radius, radarParameters)
moveCamera(
position,
getZoomLevel(radius)
)
_binding.searchProgressBottomSheet.searchInProgressDescription.text = getString(
R.string.search_progress_description,
chip.text
)
_activityViewModel.getAuthorizedUser().observeOnce(this@SearchFragment) { authorizedUser ->
authorizedUser?.also {
_viewModel.service.observeOnce(this@SearchFragment) { service ->
_viewModel.startWorkerSearching(
OrderCreationParameters(
invokerId = it.id,
address = MapsAddress(
position.latitude,
position.longitude
),
radius.toDouble(),
service
),
::onWorkerFound
)
.observeOnce(this@SearchFragment) { order ->
_activityViewModel.setOrder(order)
}
}
}
}
}
private fun onWorkerFound(worker: User) {
_activityViewModel.setWorker(worker)
_navigationController.navigate(R.id.path_to_order_overview_fragment_from_navigation_search)
}
private fun onUserCancelSearching(button: View) {
_binding.currentLocationButton.fade(
FadeParameters().apply {
mode = VisibilityMode.Show
animationLength = 300
}
)
_binding.searchProgressBottomSheet.bottomSheetLayout.visibility = View.GONE
_binding.searchBottomSheet.bottomSheetLayout.visibility = View.VISIBLE
_searchBottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
_binding.mapPin.isTouchEventsDisabled = false
_googleMap.uiSettings.isScrollGesturesEnabled = true
_googleMap.uiSettings.isZoomGesturesEnabled = true
removeLastSearchRadius()
val position = _googleMap.cameraPosition.target
val radius = getSearchRadius(
_binding.searchBottomSheet.availableRadii.checkedChipId
)
moveCamera(
position,
getZoomLevel(radius)
)
_activityViewModel.order.observeOnce(this@SearchFragment) { order ->
_viewModel.cancelWorkerSearching(order)
}
}
private fun onAddressSelected(userAddress: UserAddress) {
_addressesBottomSheet.dismiss()
moveCamera(userAddress.source)
}
private fun onAddressTitleClick(view: View) {
_addressesBottomSheet = AddressesBottomSheetDialog(
requireContext(),
R.style.Theme_AnyJob_BottomSheetDialog,
::onAddressSelected
)
_addressesBottomSheet.show()
}
private fun onServiceSelected(service: Service) {
_viewModel.setService(service)
_binding.searchBottomSheet.selectServiceButton.text = service.title
_binding.searchBottomSheet.startSearchingButton.visibility = View.VISIBLE
_servicesBottomSheet.dismiss()
}
private fun openServicesBottomSheet(view: View) {
_viewModel.getServicesList().observe(this@SearchFragment) { services ->
_servicesBottomSheet = ServicesBottomSheetDialog(
requireContext(),
R.style.Theme_AnyJob_BottomSheetDialog,
services,
::onServiceSelected
)
_servicesBottomSheet.show()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentSearchBinding.inflate(inflater, container, false)
_mapView.getMapAsync(::onMapReady)
_binding.currentLocationButton.setOnClickListener(::onCurrentLocationButtonClick)
_fragmentHost.fitsSystemWindows = true
_searchBottomSheetBehavior.apply {
addBottomSheetCallback(_searchBottomSheetCallback)
isGestureInsetBottomIgnored = true
state = BottomSheetBehavior.STATE_EXPANDED
}
_searchProgressBottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
_binding.searchBottomSheet.selectServiceButton.setOnClickListener(::openServicesBottomSheet)
_binding.searchBottomSheet.availableRadii.setOnCheckedChangeListener(::onUserChangeRadius)
_binding.searchBottomSheet.startSearchingButton.setOnClickListener(::onUserStartSearching)
_binding.searchProgressBottomSheet.cancelButton.setOnClickListener(::onUserCancelSearching)
_toolbar.setOnClickListener(::onAddressTitleClick)
return _binding.root
}
}
| 0
|
Kotlin
|
0
| 0
|
1f3d030f3becbb9d8007edfca289ec68b96678eb
| 17,449
|
AnyJob
|
MIT License
|
educational-core/src/com/jetbrains/edu/learning/marketplace/api/MarketplaceSubmissionsConnector.kt
|
JetBrains
| 43,696,115
| false
| null |
package com.jetbrains.edu.learning.marketplace.api
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.google.common.annotations.VisibleForTesting
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.util.messages.Topic
import com.jetbrains.edu.coursecreator.CCNotificationUtils
import com.jetbrains.edu.coursecreator.actions.mixins.AnswerPlaceholderDependencyMixin
import com.jetbrains.edu.coursecreator.actions.mixins.AnswerPlaceholderWithAnswerMixin
import com.jetbrains.edu.learning.*
import com.jetbrains.edu.learning.api.ConnectorUtils
import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder
import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholderDependency
import com.jetbrains.edu.learning.courseFormat.EduCourse
import com.jetbrains.edu.learning.courseFormat.ext.allTasks
import com.jetbrains.edu.learning.courseFormat.tasks.Task
import com.jetbrains.edu.learning.courseFormat.tasks.TheoryTask
import com.jetbrains.edu.learning.marketplace.GRAZIE_STAGING_URL
import com.jetbrains.edu.learning.marketplace.settings.MarketplaceSettings
import com.jetbrains.edu.learning.messages.EduCoreBundle
import okhttp3.ConnectionPool
import org.apache.commons.httpclient.HttpStatus
import retrofit2.converter.jackson.JacksonConverterFactory
import java.time.Instant
import java.util.*
class MarketplaceSubmissionsConnector {
private val connectionPool: ConnectionPool = ConnectionPool()
private val converterFactory: JacksonConverterFactory
val objectMapper: ObjectMapper by lazy {
val objectMapper = ConnectorUtils.createRegisteredMapper(SimpleModule())
objectMapper.addMixIn(AnswerPlaceholder::class.java, AnswerPlaceholderWithAnswerMixin::class.java)
objectMapper.addMixIn(AnswerPlaceholderDependency::class.java, AnswerPlaceholderDependencyMixin::class.java)
objectMapper
}
private val grazieUrl: String = GRAZIE_STAGING_URL
init {
converterFactory = JacksonConverterFactory.create(objectMapper)
}
private val submissionsService: SubmissionsService
get() = submissionsService(MarketplaceSettings.INSTANCE.account?.getJwtToken())
private fun submissionsService(accessToken: String?): SubmissionsService {
val retrofit = createRetrofitBuilder(grazieUrl, connectionPool, accessToken = accessToken, authHeaderName = "Grazie-Authenticate-JWT", authHeaderValue = null)
.addConverterFactory(converterFactory)
.build()
return retrofit.create(SubmissionsService::class.java)
}
fun createSubmissionsDocument(project: Project,
submissionDocument: SubmissionDocument,
task: Task,
submissionId: Int,
showErrorNotification: Boolean = true) {
if (!isUserAuthorizedWithJwtToken()) return
LOG.info("Creating new submission document for task ${task.name}")
val response = submissionsService.createDocument(submissionDocument).executeParsingErrors(true)
.flatMap {
val resultResponse = it.body()
return@flatMap if (resultResponse == null) Err("Nullable response body received")
else Ok(resultResponse)
}.onError {
LOG.error("Failed to create submission document for task ${task.name}: ${it}")
if (showErrorNotification) {
CCNotificationUtils.showErrorNotification(project,
EduCoreBundle.message("notification.submissions.failed.to.post", task.name),
action = CCNotificationUtils.showLogAction)
}
return
}
val documentId = response.id
addDocumentPath(task, documentId, submissionId)
task.submissionsId = documentId
LOG.info("Submission document for task ${task.name} successfully created")
}
fun updateSubmissionsDocument(project: Project, submissionDocument: SubmissionDocument, task: Task) {
if (!isUserAuthorizedWithJwtToken()) return
LOG.info("Updating submission document with documentId = ${task.submissionsId} for task ${task.name}")
submissionsService.updateDocument(submissionDocument).executeParsingErrors(true)
.flatMap {
val resultResponse = it.body()
return@flatMap if (resultResponse == null) Err("Nullable response body received")
else Ok(resultResponse)
}.onError {
LOG.error("Failed to update submission document with documentId = ${task.submissionsId} for task ${task.name}: ${it}")
CCNotificationUtils.showErrorNotification(project,
EduCoreBundle.message("notification.submissions.failed.to.post", task.name),
action = CCNotificationUtils.showLogAction)
return
}
LOG.info("Submission document with documentId = ${task.submissionsId} for task ${task.name} successfully updated")
}
private fun addDocumentPath(task: Task, documentId: String, submissionId: Int) {
val path = "${task.course.id}/${task.id}/$submissionId"
LOG.info("Adding path $path to submission document for documentId = $documentId")
val response = submissionsService.addPathToDocument(Descriptor(documentId, path)).executeHandlingExceptions()
if (response != null && response.isSuccessful) {
LOG.info("Path $path for documentId = $documentId successfully added")
}
else {
LOG.error("Failed to add path to submission document with documentId = $documentId")
}
}
fun getAllSubmissions(course: EduCourse): MutableMap<Int, List<MarketplaceSubmission>> {
val descriptorsList = getDescriptorsList("/${course.id}")
val submissionsByTaskId = mutableMapOf<Int, List<MarketplaceSubmission>>()
val documentIdByTaskId = mutableMapOf<Int, String>()
for (descriptor in descriptorsList) {
val taskId = parseTaskIdFromPath(descriptor.path)
documentIdByTaskId[taskId] = descriptor.id
submissionsByTaskId[taskId] = getSubmissions(descriptor.id)
}
val allTasks: List<Task> = course.allTasks
for (task in allTasks) {
val taskId = task.id
if (documentIdByTaskId.containsKey(taskId)) {
task.submissionsId = documentIdByTaskId[taskId]
}
// documentIdByTaskId contains already existing submissions, we should put empty lists for tasks that have no submissions yet
else {
submissionsByTaskId[taskId] = listOf()
}
}
return submissionsByTaskId
}
fun getSubmissions(task: Task, courseId: Int): List<MarketplaceSubmission> {
val documentId = getDocumentId(courseId, task.id) ?: return listOf()
task.submissionsId = documentId
return getSubmissions(documentId)
}
private fun getSubmissions(documentId: String): List<MarketplaceSubmission> {
val versionsList = getDocVersionsIds(documentId) ?: return listOf()
return versionsList.mapNotNull { getSubmission(documentId, it) }
}
@VisibleForTesting
fun getSubmission(documentId: String, version: Version): MarketplaceSubmission? {
val submissionDocument = SubmissionDocument(documentId, versionId = version.id)
val response = submissionsService.getSubmissionContent(submissionDocument).executeHandlingExceptions()
val content = response?.body()?.content
val submissionContent = objectMapper.readValue(content, Content::class.java) ?: return null
// TODO: double wrapping into "content" is a bug on grazie side, should be fixed on our side when ready
val submission = objectMapper.readValue(submissionContent.content, MarketplaceSubmission::class.java) ?: return null
submission.time = Date.from(Instant.ofEpochSecond(version.timestamp))
return submission
}
@VisibleForTesting
fun getDocVersionsIds(documentId: String): List<Version>? {
val document = Document(documentId)
val response = submissionsService.getVersionsList(document).executeHandlingExceptions()
return response?.body()?.versionsList
}
@VisibleForTesting
fun getDocumentId(courseId: Int, taskId: Int): String? {
val path = "/$courseId/$taskId"
val descriptorsList = getDescriptorsList(path)
if (descriptorsList.isEmpty()) return null
if (descriptorsList.size > 1) error("More than one descriptor found for task $taskId")
val documentId = descriptorsList[0].id
LOG.info("Successfully loaded documentId for taskId = $taskId")
return documentId
}
private fun getDescriptorsList(path: String): List<Descriptor> {
LOG.info("Loading descriptors list for path = $path")
val response = submissionsService.getDescriptorsList(DocumentPath(path)).executeHandlingExceptions()
if (response != null && response.isSuccessful) {
return response.body()?.descriptorsList ?: return emptyList()
}
else {
LOG.error("Failed to load descriptors list for path = $path")
return emptyList()
}
}
// Descriptor path format: /courseId/taskId/submissionId,
// ex.: /16630/186011/2009178346
private fun parseTaskIdFromPath(path: String): Int {
return try {
Integer.parseInt(path.split("/")[TASK_ID_INDEX])
}
catch (e: NumberFormatException) {
throw DescriptorPathFormatException(path, EduCoreBundle.message("error.incorrect.task.id.format", e.message.toString()))
}
catch(e: IndexOutOfBoundsException) {
throw DescriptorPathFormatException(path, EduCoreBundle.message("error.incorrect.descriptor.path.format", e.message.toString()))
}
}
fun markTheoryTaskAsCompleted(project: Project, task: TheoryTask) {
if (task.submissionsId == null) {
val emptySubmissionData = MarketplaceSubmission(task)
val submissionId = emptySubmissionData.id ?: error("Submission id not generated at creation")
val submissionDocument = SubmissionDocument(docId = task.submissionsId,
submissionContent = ObjectMapper().writeValueAsString(emptySubmissionData).trimIndent())
createSubmissionsDocument(project, submissionDocument, task, submissionId, false)
}
}
fun isJwtTokenValid(token: String): Boolean {
val submissionServiceWithCheckedToken = submissionsService(token)
// any path can be used, if token is valid - empty list with HttpStatus.OK will be returned, HttpStatus.SC_UNAUTHORIZED otherwise
val path = "/testPath"
LOG.info("Validating inserted token: $token")
val response = submissionServiceWithCheckedToken.getDescriptorsList(DocumentPath(path)).executeHandlingExceptions()
return if (response != null && response.code() != HttpStatus.SC_UNAUTHORIZED) {
LOG.info("Inserted token: $token is valid")
true
}
else {
LOG.error("Invalid token: $token inserted")
false
}
}
companion object {
private val LOG = logger<MarketplaceConnector>()
private const val TASK_ID_INDEX = 2
@JvmStatic
val GRAZIE_AUTHORIZATION_TOPIC = Topic.create("Edu.grazieLoggedIn", EduLogInListener::class.java)
@JvmStatic
fun getInstance(): MarketplaceSubmissionsConnector = service()
fun isUserAuthorizedWithJwtToken(): Boolean {
val user = MarketplaceSettings.INSTANCE.account
if (user == null) {
// we check that user isn't null before `postCourse` call
LOG.warn("User is null when posting the course")
return false
}
else if (!user.isJwtTokenProvided()){
LOG.warn("User is not authorised to submissions repository when posting submissions. Jwt token is empty.")
return false
}
return true
}
}
private class DescriptorPathFormatException(descriptorPath: String, details: String) : IllegalStateException(
buildString {
appendLine(EduCoreBundle.message("error.incorrect.descriptor.path.message", descriptorPath))
appendLine(details)
})
}
| 5
| null |
44
| 99
|
cfc24fe13318de446b8adf6e05d1a7c15d9511b5
| 11,965
|
educational-plugin
|
Apache License 2.0
|
example/src/main/java/com/crowdin/platform/example/SplashScreenActivity.kt
|
crowdin
| 193,449,073
| false
| null |
package com.crowdin.platform.example
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import com.crowdin.platform.Crowdin
class SplashScreenActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
//Comment if you want open Main Activity after time span
// startMainActivityAfterTimeSpan()
//Uncomment if you want load translations and after that open Main Activity
startMainActivityAfterLoadingTranslations()
}
private fun startMainActivityAfterTimeSpan() {
Handler(Looper.myLooper()!!).postDelayed({
startMainActivity()
}, 500)
}
private fun startMainActivityAfterLoadingTranslations() {
Crowdin.forceUpdate(this) {
startMainActivity()
}
}
private fun startMainActivity() {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
| 6
|
Kotlin
|
38
| 98
|
468e9d2c50cf37ed1aa2a540a2f66e410f4b7ab5
| 1,111
|
mobile-sdk-android
|
MIT License
|
Mobile/app/src/main/java/com/tzeentch/workfinder/dto/AuthResultDto.kt
|
Tzeentch-Hack
| 704,442,654
| false
|
{"Kotlin": 84798, "Python": 47445, "HTML": 37686, "Dockerfile": 327}
|
package com.tzeentch.workfinder.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class AuthResultDto(
@SerialName("access_token") val token: String,
)
| 0
|
Kotlin
|
0
| 0
|
77b32717caab70554f70ae7cc894c72b8bd00c0c
| 213
|
Work-Finder
|
MIT License
|
intellij-plugin/src/main/kotlin/com/apollographql/ijplugin/util/Files.kt
|
apollographql
| 69,469,299
| false
| null |
package com.apollographql.ijplugin.util
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.GeneratedSourcesFilter
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiUtilCore
fun Project.findPsiFilesByName(fileName: String, searchScope: GlobalSearchScope): List<PsiFile> {
val virtualFiles = FilenameIndex.getVirtualFilesByName(fileName, searchScope)
return PsiUtilCore.toPsiFiles(PsiManager.getInstance(this), virtualFiles)
}
fun VirtualFile.isGenerated(project: Project): Boolean {
return GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(this, project) || isApolloGenerated() || name.endsWith(".keystream")
}
| 176
| null |
660
| 3,588
|
c63155882c9ef5d0981bc6b12cdee99c2117f928
| 835
|
apollo-kotlin
|
MIT License
|
tts/src/androidMain/kotlin/nl/marc_apps/tts/utils/TtsProgressConverter.kt
|
Marc-JB
| 279,524,415
| false
|
{"Kotlin": 62339}
|
package nl.marc_apps.tts.utils
import android.os.Build
import android.speech.tts.UtteranceProgressListener
import androidx.annotation.RequiresApi
import nl.marc_apps.tts.errors.TextToSpeechSynthesisInterruptedError
import nl.marc_apps.tts.errors.UnknownTextToSpeechSynthesisError
import java.util.*
/**
* @hide
*/
@RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
class TtsProgressConverter(
val onStart: (UUID) -> Unit,
val onComplete: (UUID, Result<Unit>) -> Unit
) : UtteranceProgressListener() {
override fun onStart(utteranceId: String?) {
val id = getContinuationId(utteranceId) ?: return
onStart(id)
}
override fun onDone(utteranceId: String?) {
val id = getContinuationId(utteranceId) ?: return
onComplete(id, Result.success(Unit))
}
override fun onError(utteranceId: String?) {
val id = getContinuationId(utteranceId) ?: return
onComplete(id, Result.failure(UnknownTextToSpeechSynthesisError()))
}
override fun onError(utteranceId: String?, errorCode: Int) {
val id = getContinuationId(utteranceId) ?: return
onComplete(id, Result.failure(ErrorCodes.mapToThrowable(errorCode)))
}
override fun onStop(utteranceId: String?, interrupted: Boolean) {
val id = getContinuationId(utteranceId) ?: return
onComplete(id, Result.failure(TextToSpeechSynthesisInterruptedError()))
}
}
| 2
|
Kotlin
|
2
| 9
|
4624820c64db53bb5b21b0d2dd06ea7faaa23c91
| 1,423
|
TextToSpeechKt
|
MIT License
|
transmission/src/main/java/com/trendyol/transmission/transformer/query/QueryResult.kt
|
Trendyol
| 771,942,025
| false
|
{"Kotlin": 46606}
|
package com.trendyol.transmission.transformer.query
import com.trendyol.transmission.Transmission
sealed class QueryResult<D : Transmission.Data>(
open val owner: String,
open val data: D?,
open val type: String
) {
data class Data<D : Transmission.Data>(
override val owner: String,
override val data: D?,
override val type: String
) : QueryResult<D>(owner, data, type)
data class Computation<D : Transmission.Data>(
override val owner: String,
override val data: D?,
override val type: String,
) : QueryResult<D>(owner = owner, data = data, type = type)
}
| 0
|
Kotlin
|
0
| 14
|
35316fd3718302ec998fb6230891e3aa49296aa7
| 637
|
transmission
|
MIT License
|
app/src/main/java/com/benhagy/gamefinder3/presentation/bookmarks_screen/components/UserRatingBar.kt
|
ben-hagy
| 671,589,018
| false
| null |
package com.benhagy.gamefinder3.presentation.bookmarks_screen.components
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarOutline
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import com.smarttoolfactory.ratingbar.RatingBar
import com.smarttoolfactory.ratingbar.model.Shimmer
// rating bar implemented via github library
@Composable
fun UserRatingBar(
rating: Float?,
onRatingChange: ((Float) -> Unit)?
) {
RatingBar(
rating = rating ?: 0.0f,
space = 2.5.dp,
imageVectorEmpty = Icons.Default.StarOutline,
imageVectorFFilled = Icons.Default.Star,
shimmer = Shimmer(
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.35f),
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 2500,
easing = LinearEasing
),
repeatMode = RepeatMode.Reverse
)
),
tintEmpty = MaterialTheme.colorScheme.onBackground.copy(alpha = .5f),
tintFilled = MaterialTheme.colorScheme.tertiary,
itemSize = 32.dp,
onRatingChange = onRatingChange
)
}
| 0
|
Kotlin
|
0
| 0
|
036eeb69dd0d13a01b1beb8bf3872dc5c44ebd8d
| 1,550
|
Gamefinder3
|
MIT License
|
app/src/main/java/com/hodinv/music/mvp/MvpActivity.kt
|
vgtitov
| 238,857,009
| false
| null |
package com.hodinv.music.mvp
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
/**
* Created by vasily on 25.05.17.
*/
abstract class MvpActivity<V : MvpView, R : MvpRouter, P : MvpPresenter<V, R>> : AppCompatActivity() {
var presenter: P? = null
abstract fun createPresenter(): P
abstract fun getView(): V
abstract fun getRouter(): R
fun initOrRestorePresenter() {
@Suppress("UNCHECKED_CAST")
presenter = MvpActivity.getPresenter(this.localClassName) as P?
if (presenter == null) {
presenter = createPresenter()
MvpActivity.savePresenter(this.localClassName, presenter!!)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initOrRestorePresenter()
}
override fun onStart() {
super.onStart()
presenter?.view = getView()
presenter?.router = getRouter()
presenter?.setOrResetView()
}
override fun onStop() {
super.onStop()
presenter?.unbindListeners()
presenter?.view = null
presenter?.router = null
}
override fun finish() {
super.finish()
dismissPresenter(this.localClassName)
presenter?.dismiss()
}
override fun onBackPressed() {
super.onBackPressed()
dismissPresenter(this.localClassName)
presenter?.dismiss()
}
companion object {
var presenters = HashMap<String, MvpPresenter<*, *>>()
fun getPresenter(classKey: String): MvpPresenter<*, *>? {
return presenters[classKey]
}
fun savePresenter(localClassName: String, presenter: MvpPresenter<*, *>) {
presenters.put(localClassName, presenter)
}
fun dismissPresenter(classKey: String) {
presenters.remove(classKey)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4e7d3483c87beafa55bb90a75b94ebf60e31e465
| 1,903
|
synthesizer
|
Creative Commons Attribution 3.0 Unported
|
clippylib/src/main/java/com/ferranpons/clippylib/backend/converter/mapping/ClippyMapping.kt
|
ferranpons
| 117,086,375
| false
|
{"Kotlin": 75990}
|
package com.ferranpons.clippylib.backend.converter.mapping
import com.ferranpons.clippylib.R
class ClippyMapping : AgentMapping {
override val mapping: IntArray
get() = IMAGE_MAPPING
override val soundMapping: IntArray
get() = SOUND_MAPPING
override val numberRows: Int
get() = NUMBER_ROWS
override val numberColumns: Int
get() = NUMBER_COLUMNS
override val emptyFrameId: Int
get() = R.drawable.clippy_0917
override val firstFrameId: Int
get() = R.drawable.clippy_0000
companion object {
private const val NUMBER_COLUMNS = 27
private const val NUMBER_ROWS = 34
private val IMAGE_MAPPING = intArrayOf(R.drawable.clippy_0000, R.drawable.clippy_0001, R.drawable.clippy_0002, R.drawable.clippy_0003, R.drawable.clippy_0004, R.drawable.clippy_0005, R.drawable.clippy_0006, R.drawable.clippy_0007, R.drawable.clippy_0008, R.drawable.clippy_0009, R.drawable.clippy_0010, R.drawable.clippy_0011, R.drawable.clippy_0012, R.drawable.clippy_0013, R.drawable.clippy_0014, R.drawable.clippy_0015, R.drawable.clippy_0016, R.drawable.clippy_0017, R.drawable.clippy_0018, R.drawable.clippy_0019, R.drawable.clippy_0020, R.drawable.clippy_0021, R.drawable.clippy_0022, R.drawable.clippy_0023, R.drawable.clippy_0024, R.drawable.clippy_0025, R.drawable.clippy_0026, R.drawable.clippy_0027, R.drawable.clippy_0028, R.drawable.clippy_0029, R.drawable.clippy_0030, R.drawable.clippy_0031, R.drawable.clippy_0032, R.drawable.clippy_0033, R.drawable.clippy_0034, R.drawable.clippy_0035, R.drawable.clippy_0036, R.drawable.clippy_0037, R.drawable.clippy_0038, R.drawable.clippy_0039, R.drawable.clippy_0040, R.drawable.clippy_0041, R.drawable.clippy_0042, R.drawable.clippy_0043, R.drawable.clippy_0044, R.drawable.clippy_0045, R.drawable.clippy_0046, R.drawable.clippy_0047, R.drawable.clippy_0048, R.drawable.clippy_0049, R.drawable.clippy_0050, R.drawable.clippy_0051, R.drawable.clippy_0052, R.drawable.clippy_0053, R.drawable.clippy_0054, R.drawable.clippy_0055, R.drawable.clippy_0056, R.drawable.clippy_0057, R.drawable.clippy_0058, R.drawable.clippy_0059, R.drawable.clippy_0060, R.drawable.clippy_0061, R.drawable.clippy_0062, R.drawable.clippy_0063, R.drawable.clippy_0064, R.drawable.clippy_0065, R.drawable.clippy_0066, R.drawable.clippy_0067, R.drawable.clippy_0068, R.drawable.clippy_0069, R.drawable.clippy_0070, R.drawable.clippy_0071, R.drawable.clippy_0072, R.drawable.clippy_0073, R.drawable.clippy_0074, R.drawable.clippy_0075, R.drawable.clippy_0076, R.drawable.clippy_0077, R.drawable.clippy_0078, R.drawable.clippy_0079, R.drawable.clippy_0080, R.drawable.clippy_0081, R.drawable.clippy_0082, R.drawable.clippy_0083, R.drawable.clippy_0084, R.drawable.clippy_0085, R.drawable.clippy_0086, R.drawable.clippy_0087, R.drawable.clippy_0088, R.drawable.clippy_0089, R.drawable.clippy_0090, R.drawable.clippy_0091, R.drawable.clippy_0092, R.drawable.clippy_0093, R.drawable.clippy_0094, R.drawable.clippy_0095, R.drawable.clippy_0096, R.drawable.clippy_0097, R.drawable.clippy_0098, R.drawable.clippy_0099, R.drawable.clippy_0100, R.drawable.clippy_0101, R.drawable.clippy_0102, R.drawable.clippy_0103, R.drawable.clippy_0104, R.drawable.clippy_0105, R.drawable.clippy_0106, R.drawable.clippy_0107, R.drawable.clippy_0108, R.drawable.clippy_0109, R.drawable.clippy_0110, R.drawable.clippy_0111, R.drawable.clippy_0112, R.drawable.clippy_0113, R.drawable.clippy_0114, R.drawable.clippy_0115, R.drawable.clippy_0116, R.drawable.clippy_0117, R.drawable.clippy_0118, R.drawable.clippy_0119, R.drawable.clippy_0120, R.drawable.clippy_0121, R.drawable.clippy_0122, R.drawable.clippy_0123, R.drawable.clippy_0124, R.drawable.clippy_0125, R.drawable.clippy_0126, R.drawable.clippy_0127, R.drawable.clippy_0128, R.drawable.clippy_0129, R.drawable.clippy_0130, R.drawable.clippy_0131, R.drawable.clippy_0132, R.drawable.clippy_0133, R.drawable.clippy_0134, R.drawable.clippy_0135, R.drawable.clippy_0136, R.drawable.clippy_0137, R.drawable.clippy_0138, R.drawable.clippy_0139, R.drawable.clippy_0140, R.drawable.clippy_0141, R.drawable.clippy_0142, R.drawable.clippy_0143, R.drawable.clippy_0144, R.drawable.clippy_0145, R.drawable.clippy_0146, R.drawable.clippy_0147, R.drawable.clippy_0148, R.drawable.clippy_0149, R.drawable.clippy_0150, R.drawable.clippy_0151, R.drawable.clippy_0152, R.drawable.clippy_0153, R.drawable.clippy_0154, R.drawable.clippy_0155, R.drawable.clippy_0156, R.drawable.clippy_0157, R.drawable.clippy_0158, R.drawable.clippy_0159, R.drawable.clippy_0160, R.drawable.clippy_0161, R.drawable.clippy_0162, R.drawable.clippy_0163, R.drawable.clippy_0164, R.drawable.clippy_0165, R.drawable.clippy_0166, R.drawable.clippy_0167, R.drawable.clippy_0168, R.drawable.clippy_0169, R.drawable.clippy_0170, R.drawable.clippy_0171, R.drawable.clippy_0172, R.drawable.clippy_0173, R.drawable.clippy_0174, R.drawable.clippy_0175, R.drawable.clippy_0176, R.drawable.clippy_0177, R.drawable.clippy_0178, R.drawable.clippy_0179, R.drawable.clippy_0180, R.drawable.clippy_0181, R.drawable.clippy_0182, R.drawable.clippy_0183, R.drawable.clippy_0184, R.drawable.clippy_0185, R.drawable.clippy_0186, R.drawable.clippy_0187, R.drawable.clippy_0188, R.drawable.clippy_0189, R.drawable.clippy_0190, R.drawable.clippy_0191, R.drawable.clippy_0192, R.drawable.clippy_0193, R.drawable.clippy_0194, R.drawable.clippy_0195, R.drawable.clippy_0196, R.drawable.clippy_0197, R.drawable.clippy_0198, R.drawable.clippy_0199, R.drawable.clippy_0200, R.drawable.clippy_0201, R.drawable.clippy_0202, R.drawable.clippy_0203, R.drawable.clippy_0204, R.drawable.clippy_0205, R.drawable.clippy_0206, R.drawable.clippy_0207, R.drawable.clippy_0208, R.drawable.clippy_0209, R.drawable.clippy_0210, R.drawable.clippy_0211, R.drawable.clippy_0212, R.drawable.clippy_0213, R.drawable.clippy_0214, R.drawable.clippy_0215, R.drawable.clippy_0216, R.drawable.clippy_0217, R.drawable.clippy_0218, R.drawable.clippy_0219, R.drawable.clippy_0220, R.drawable.clippy_0221, R.drawable.clippy_0222, R.drawable.clippy_0223, R.drawable.clippy_0224, R.drawable.clippy_0225, R.drawable.clippy_0226, R.drawable.clippy_0227, R.drawable.clippy_0228, R.drawable.clippy_0229, R.drawable.clippy_0230, R.drawable.clippy_0231, R.drawable.clippy_0232, R.drawable.clippy_0233, R.drawable.clippy_0234, R.drawable.clippy_0235, R.drawable.clippy_0236, R.drawable.clippy_0237, R.drawable.clippy_0238, R.drawable.clippy_0239, R.drawable.clippy_0240, R.drawable.clippy_0241, R.drawable.clippy_0242, R.drawable.clippy_0243, R.drawable.clippy_0244, R.drawable.clippy_0245, R.drawable.clippy_0246, R.drawable.clippy_0247, R.drawable.clippy_0248, R.drawable.clippy_0249, R.drawable.clippy_0250, R.drawable.clippy_0251, R.drawable.clippy_0252, R.drawable.clippy_0253, R.drawable.clippy_0254, R.drawable.clippy_0255, R.drawable.clippy_0256, R.drawable.clippy_0257, R.drawable.clippy_0258, R.drawable.clippy_0259, R.drawable.clippy_0260, R.drawable.clippy_0261, R.drawable.clippy_0262, R.drawable.clippy_0263, R.drawable.clippy_0264, R.drawable.clippy_0265, R.drawable.clippy_0266, R.drawable.clippy_0267, R.drawable.clippy_0268, R.drawable.clippy_0269, R.drawable.clippy_0270, R.drawable.clippy_0271, R.drawable.clippy_0272, R.drawable.clippy_0273, R.drawable.clippy_0274, R.drawable.clippy_0275, R.drawable.clippy_0276, R.drawable.clippy_0277, R.drawable.clippy_0278, R.drawable.clippy_0279, R.drawable.clippy_0280, R.drawable.clippy_0281, R.drawable.clippy_0282, R.drawable.clippy_0283, R.drawable.clippy_0284, R.drawable.clippy_0285, R.drawable.clippy_0286, R.drawable.clippy_0287, R.drawable.clippy_0288, R.drawable.clippy_0289, R.drawable.clippy_0290, R.drawable.clippy_0291, R.drawable.clippy_0292, R.drawable.clippy_0293, R.drawable.clippy_0294, R.drawable.clippy_0295, R.drawable.clippy_0296, R.drawable.clippy_0297, R.drawable.clippy_0298, R.drawable.clippy_0299, R.drawable.clippy_0300, R.drawable.clippy_0301, R.drawable.clippy_0302, R.drawable.clippy_0303, R.drawable.clippy_0304, R.drawable.clippy_0305, R.drawable.clippy_0306, R.drawable.clippy_0307, R.drawable.clippy_0308, R.drawable.clippy_0309, R.drawable.clippy_0310, R.drawable.clippy_0311, R.drawable.clippy_0312, R.drawable.clippy_0313, R.drawable.clippy_0314, R.drawable.clippy_0315, R.drawable.clippy_0316, R.drawable.clippy_0317, R.drawable.clippy_0318, R.drawable.clippy_0319, R.drawable.clippy_0320, R.drawable.clippy_0321, R.drawable.clippy_0322, R.drawable.clippy_0323, R.drawable.clippy_0324, R.drawable.clippy_0325, R.drawable.clippy_0326, R.drawable.clippy_0327, R.drawable.clippy_0328, R.drawable.clippy_0329, R.drawable.clippy_0330, R.drawable.clippy_0331, R.drawable.clippy_0332, R.drawable.clippy_0333, R.drawable.clippy_0334, R.drawable.clippy_0335, R.drawable.clippy_0336, R.drawable.clippy_0337, R.drawable.clippy_0338, R.drawable.clippy_0339, R.drawable.clippy_0340, R.drawable.clippy_0341, R.drawable.clippy_0342, R.drawable.clippy_0343, R.drawable.clippy_0344, R.drawable.clippy_0345, R.drawable.clippy_0346, R.drawable.clippy_0347, R.drawable.clippy_0348, R.drawable.clippy_0349, R.drawable.clippy_0350, R.drawable.clippy_0351, R.drawable.clippy_0352, R.drawable.clippy_0353, R.drawable.clippy_0354, R.drawable.clippy_0355, R.drawable.clippy_0356, R.drawable.clippy_0357, R.drawable.clippy_0358, R.drawable.clippy_0359, R.drawable.clippy_0360, R.drawable.clippy_0361, R.drawable.clippy_0362, R.drawable.clippy_0363, R.drawable.clippy_0364, R.drawable.clippy_0365, R.drawable.clippy_0366, R.drawable.clippy_0367, R.drawable.clippy_0368, R.drawable.clippy_0369, R.drawable.clippy_0370, R.drawable.clippy_0371, R.drawable.clippy_0372, R.drawable.clippy_0373, R.drawable.clippy_0374, R.drawable.clippy_0375, R.drawable.clippy_0376, R.drawable.clippy_0377, R.drawable.clippy_0378, R.drawable.clippy_0379, R.drawable.clippy_0380, R.drawable.clippy_0381, R.drawable.clippy_0382, R.drawable.clippy_0383, R.drawable.clippy_0384, R.drawable.clippy_0385, R.drawable.clippy_0386, R.drawable.clippy_0387, R.drawable.clippy_0388, R.drawable.clippy_0389, R.drawable.clippy_0390, R.drawable.clippy_0391, R.drawable.clippy_0392, R.drawable.clippy_0393, R.drawable.clippy_0394, R.drawable.clippy_0395, R.drawable.clippy_0396, R.drawable.clippy_0397, R.drawable.clippy_0398, R.drawable.clippy_0399, R.drawable.clippy_0400, R.drawable.clippy_0401, R.drawable.clippy_0402, R.drawable.clippy_0403, R.drawable.clippy_0404, R.drawable.clippy_0405, R.drawable.clippy_0406, R.drawable.clippy_0407, R.drawable.clippy_0408, R.drawable.clippy_0409, R.drawable.clippy_0410, R.drawable.clippy_0411, R.drawable.clippy_0412, R.drawable.clippy_0413, R.drawable.clippy_0414, R.drawable.clippy_0415, R.drawable.clippy_0416, R.drawable.clippy_0417, R.drawable.clippy_0418, R.drawable.clippy_0419, R.drawable.clippy_0420, R.drawable.clippy_0421, R.drawable.clippy_0422, R.drawable.clippy_0423, R.drawable.clippy_0424, R.drawable.clippy_0425, R.drawable.clippy_0426, R.drawable.clippy_0427, R.drawable.clippy_0428, R.drawable.clippy_0429, R.drawable.clippy_0430, R.drawable.clippy_0431, R.drawable.clippy_0432, R.drawable.clippy_0433, R.drawable.clippy_0434, R.drawable.clippy_0435, R.drawable.clippy_0436, R.drawable.clippy_0437, R.drawable.clippy_0438, R.drawable.clippy_0439, R.drawable.clippy_0440, R.drawable.clippy_0441, R.drawable.clippy_0442, R.drawable.clippy_0443, R.drawable.clippy_0444, R.drawable.clippy_0445, R.drawable.clippy_0446, R.drawable.clippy_0447, R.drawable.clippy_0448, R.drawable.clippy_0449, R.drawable.clippy_0450, R.drawable.clippy_0451, R.drawable.clippy_0452, R.drawable.clippy_0453, R.drawable.clippy_0454, R.drawable.clippy_0455, R.drawable.clippy_0456, R.drawable.clippy_0457, R.drawable.clippy_0458, R.drawable.clippy_0459, R.drawable.clippy_0460, R.drawable.clippy_0461, R.drawable.clippy_0462, R.drawable.clippy_0463, R.drawable.clippy_0464, R.drawable.clippy_0465, R.drawable.clippy_0466, R.drawable.clippy_0467, R.drawable.clippy_0468, R.drawable.clippy_0469, R.drawable.clippy_0470, R.drawable.clippy_0471, R.drawable.clippy_0472, R.drawable.clippy_0473, R.drawable.clippy_0474, R.drawable.clippy_0475, R.drawable.clippy_0476, R.drawable.clippy_0477, R.drawable.clippy_0478, R.drawable.clippy_0479, R.drawable.clippy_0480, R.drawable.clippy_0481, R.drawable.clippy_0482, R.drawable.clippy_0483, R.drawable.clippy_0484, R.drawable.clippy_0485, R.drawable.clippy_0486, R.drawable.clippy_0487, R.drawable.clippy_0488, R.drawable.clippy_0489, R.drawable.clippy_0490, R.drawable.clippy_0491, R.drawable.clippy_0492, R.drawable.clippy_0493, R.drawable.clippy_0494, R.drawable.clippy_0495, R.drawable.clippy_0496, R.drawable.clippy_0497, R.drawable.clippy_0498, R.drawable.clippy_0499, R.drawable.clippy_0500, R.drawable.clippy_0501, R.drawable.clippy_0502, R.drawable.clippy_0503, R.drawable.clippy_0504, R.drawable.clippy_0505, R.drawable.clippy_0506, R.drawable.clippy_0507, R.drawable.clippy_0508, R.drawable.clippy_0509, R.drawable.clippy_0510, R.drawable.clippy_0511, R.drawable.clippy_0512, R.drawable.clippy_0513, R.drawable.clippy_0514, R.drawable.clippy_0515, R.drawable.clippy_0516, R.drawable.clippy_0517, R.drawable.clippy_0518, R.drawable.clippy_0519, R.drawable.clippy_0520, R.drawable.clippy_0521, R.drawable.clippy_0522, R.drawable.clippy_0523, R.drawable.clippy_0524, R.drawable.clippy_0525, R.drawable.clippy_0526, R.drawable.clippy_0527, R.drawable.clippy_0528, R.drawable.clippy_0529, R.drawable.clippy_0530, R.drawable.clippy_0531, R.drawable.clippy_0532, R.drawable.clippy_0533, R.drawable.clippy_0534, R.drawable.clippy_0535, R.drawable.clippy_0536, R.drawable.clippy_0537, R.drawable.clippy_0538, R.drawable.clippy_0539, R.drawable.clippy_0540, R.drawable.clippy_0541, R.drawable.clippy_0542, R.drawable.clippy_0543, R.drawable.clippy_0544, R.drawable.clippy_0545, R.drawable.clippy_0546, R.drawable.clippy_0547, R.drawable.clippy_0548, R.drawable.clippy_0549, R.drawable.clippy_0550, R.drawable.clippy_0551, R.drawable.clippy_0552, R.drawable.clippy_0553, R.drawable.clippy_0554, R.drawable.clippy_0555, R.drawable.clippy_0556, R.drawable.clippy_0557, R.drawable.clippy_0558, R.drawable.clippy_0559, R.drawable.clippy_0560, R.drawable.clippy_0561, R.drawable.clippy_0562, R.drawable.clippy_0563, R.drawable.clippy_0564, R.drawable.clippy_0565, R.drawable.clippy_0566, R.drawable.clippy_0567, R.drawable.clippy_0568, R.drawable.clippy_0569, R.drawable.clippy_0570, R.drawable.clippy_0571, R.drawable.clippy_0572, R.drawable.clippy_0573, R.drawable.clippy_0574, R.drawable.clippy_0575, R.drawable.clippy_0576, R.drawable.clippy_0577, R.drawable.clippy_0578, R.drawable.clippy_0579, R.drawable.clippy_0580, R.drawable.clippy_0581, R.drawable.clippy_0582, R.drawable.clippy_0583, R.drawable.clippy_0584, R.drawable.clippy_0585, R.drawable.clippy_0586, R.drawable.clippy_0587, R.drawable.clippy_0588, R.drawable.clippy_0589, R.drawable.clippy_0590, R.drawable.clippy_0591, R.drawable.clippy_0592, R.drawable.clippy_0593, R.drawable.clippy_0594, R.drawable.clippy_0595, R.drawable.clippy_0596, R.drawable.clippy_0597, R.drawable.clippy_0598, R.drawable.clippy_0599, R.drawable.clippy_0600, R.drawable.clippy_0601, R.drawable.clippy_0602, R.drawable.clippy_0603, R.drawable.clippy_0604, R.drawable.clippy_0605, R.drawable.clippy_0606, R.drawable.clippy_0607, R.drawable.clippy_0608, R.drawable.clippy_0609, R.drawable.clippy_0610, R.drawable.clippy_0611, R.drawable.clippy_0612, R.drawable.clippy_0613, R.drawable.clippy_0614, R.drawable.clippy_0615, R.drawable.clippy_0616, R.drawable.clippy_0617, R.drawable.clippy_0618, R.drawable.clippy_0619, R.drawable.clippy_0620, R.drawable.clippy_0621, R.drawable.clippy_0622, R.drawable.clippy_0623, R.drawable.clippy_0624, R.drawable.clippy_0625, R.drawable.clippy_0626, R.drawable.clippy_0627, R.drawable.clippy_0628, R.drawable.clippy_0629, R.drawable.clippy_0630, R.drawable.clippy_0631, R.drawable.clippy_0632, R.drawable.clippy_0633, R.drawable.clippy_0634, R.drawable.clippy_0635, R.drawable.clippy_0636, R.drawable.clippy_0637, R.drawable.clippy_0638, R.drawable.clippy_0639, R.drawable.clippy_0640, R.drawable.clippy_0641, R.drawable.clippy_0642, R.drawable.clippy_0643, R.drawable.clippy_0644, R.drawable.clippy_0645, R.drawable.clippy_0646, R.drawable.clippy_0647, R.drawable.clippy_0648, R.drawable.clippy_0649, R.drawable.clippy_0650, R.drawable.clippy_0651, R.drawable.clippy_0652, R.drawable.clippy_0653, R.drawable.clippy_0654, R.drawable.clippy_0655, R.drawable.clippy_0656, R.drawable.clippy_0657, R.drawable.clippy_0658, R.drawable.clippy_0659, R.drawable.clippy_0660, R.drawable.clippy_0661, R.drawable.clippy_0662, R.drawable.clippy_0663, R.drawable.clippy_0664, R.drawable.clippy_0665, R.drawable.clippy_0666, R.drawable.clippy_0667, R.drawable.clippy_0668, R.drawable.clippy_0669, R.drawable.clippy_0670, R.drawable.clippy_0671, R.drawable.clippy_0672, R.drawable.clippy_0673, R.drawable.clippy_0674, R.drawable.clippy_0675, R.drawable.clippy_0676, R.drawable.clippy_0677, R.drawable.clippy_0678, R.drawable.clippy_0679, R.drawable.clippy_0680, R.drawable.clippy_0681, R.drawable.clippy_0682, R.drawable.clippy_0683, R.drawable.clippy_0684, R.drawable.clippy_0685, R.drawable.clippy_0686, R.drawable.clippy_0687, R.drawable.clippy_0688, R.drawable.clippy_0689, R.drawable.clippy_0690, R.drawable.clippy_0691, R.drawable.clippy_0692, R.drawable.clippy_0693, R.drawable.clippy_0694, R.drawable.clippy_0695, R.drawable.clippy_0696, R.drawable.clippy_0697, R.drawable.clippy_0698, R.drawable.clippy_0699, R.drawable.clippy_0700, R.drawable.clippy_0701, R.drawable.clippy_0702, R.drawable.clippy_0703, R.drawable.clippy_0704, R.drawable.clippy_0705, R.drawable.clippy_0706, R.drawable.clippy_0707, R.drawable.clippy_0708, R.drawable.clippy_0709, R.drawable.clippy_0710, R.drawable.clippy_0711, R.drawable.clippy_0712, R.drawable.clippy_0713, R.drawable.clippy_0714, R.drawable.clippy_0715, R.drawable.clippy_0716, R.drawable.clippy_0717, R.drawable.clippy_0718, R.drawable.clippy_0719, R.drawable.clippy_0720, R.drawable.clippy_0721, R.drawable.clippy_0722, R.drawable.clippy_0723, R.drawable.clippy_0724, R.drawable.clippy_0725, R.drawable.clippy_0726, R.drawable.clippy_0727, R.drawable.clippy_0728, R.drawable.clippy_0729, R.drawable.clippy_0730, R.drawable.clippy_0731, R.drawable.clippy_0732, R.drawable.clippy_0733, R.drawable.clippy_0734, R.drawable.clippy_0735, R.drawable.clippy_0736, R.drawable.clippy_0737, R.drawable.clippy_0738, R.drawable.clippy_0739, R.drawable.clippy_0740, R.drawable.clippy_0741, R.drawable.clippy_0742, R.drawable.clippy_0743, R.drawable.clippy_0744, R.drawable.clippy_0745, R.drawable.clippy_0746, R.drawable.clippy_0747, R.drawable.clippy_0748, R.drawable.clippy_0749, R.drawable.clippy_0750, R.drawable.clippy_0751, R.drawable.clippy_0752, R.drawable.clippy_0753, R.drawable.clippy_0754, R.drawable.clippy_0755, R.drawable.clippy_0756, R.drawable.clippy_0757, R.drawable.clippy_0758, R.drawable.clippy_0759, R.drawable.clippy_0760, R.drawable.clippy_0761, R.drawable.clippy_0762, R.drawable.clippy_0763, R.drawable.clippy_0764, R.drawable.clippy_0765, R.drawable.clippy_0766, R.drawable.clippy_0767, R.drawable.clippy_0768, R.drawable.clippy_0769, R.drawable.clippy_0770, R.drawable.clippy_0771, R.drawable.clippy_0772, R.drawable.clippy_0773, R.drawable.clippy_0774, R.drawable.clippy_0775, R.drawable.clippy_0776, R.drawable.clippy_0777, R.drawable.clippy_0778, R.drawable.clippy_0779, R.drawable.clippy_0780, R.drawable.clippy_0781, R.drawable.clippy_0782, R.drawable.clippy_0783, R.drawable.clippy_0784, R.drawable.clippy_0785, R.drawable.clippy_0786, R.drawable.clippy_0787, R.drawable.clippy_0788, R.drawable.clippy_0789, R.drawable.clippy_0790, R.drawable.clippy_0791, R.drawable.clippy_0792, R.drawable.clippy_0793, R.drawable.clippy_0794, R.drawable.clippy_0795, R.drawable.clippy_0796, R.drawable.clippy_0797, R.drawable.clippy_0798, R.drawable.clippy_0799, R.drawable.clippy_0800, R.drawable.clippy_0801, R.drawable.clippy_0802, R.drawable.clippy_0803, R.drawable.clippy_0804, R.drawable.clippy_0805, R.drawable.clippy_0806, R.drawable.clippy_0807, R.drawable.clippy_0808, R.drawable.clippy_0809, R.drawable.clippy_0810, R.drawable.clippy_0811, R.drawable.clippy_0812, R.drawable.clippy_0813, R.drawable.clippy_0814, R.drawable.clippy_0815, R.drawable.clippy_0816, R.drawable.clippy_0817, R.drawable.clippy_0818, R.drawable.clippy_0819, R.drawable.clippy_0820, R.drawable.clippy_0821, R.drawable.clippy_0822, R.drawable.clippy_0823, R.drawable.clippy_0824, R.drawable.clippy_0825, R.drawable.clippy_0826, R.drawable.clippy_0827, R.drawable.clippy_0828, R.drawable.clippy_0829, R.drawable.clippy_0830, R.drawable.clippy_0831, R.drawable.clippy_0832, R.drawable.clippy_0833, R.drawable.clippy_0834, R.drawable.clippy_0835, R.drawable.clippy_0836, R.drawable.clippy_0837, R.drawable.clippy_0838, R.drawable.clippy_0839, R.drawable.clippy_0840, R.drawable.clippy_0841, R.drawable.clippy_0842, R.drawable.clippy_0843, R.drawable.clippy_0844, R.drawable.clippy_0845, R.drawable.clippy_0846, R.drawable.clippy_0847, R.drawable.clippy_0848, R.drawable.clippy_0849, R.drawable.clippy_0850, R.drawable.clippy_0851, R.drawable.clippy_0852, R.drawable.clippy_0853, R.drawable.clippy_0854, R.drawable.clippy_0855, R.drawable.clippy_0856, R.drawable.clippy_0857, R.drawable.clippy_0858, R.drawable.clippy_0859, R.drawable.clippy_0860, R.drawable.clippy_0861, R.drawable.clippy_0862, R.drawable.clippy_0863, R.drawable.clippy_0864, R.drawable.clippy_0865, R.drawable.clippy_0866, R.drawable.clippy_0867, R.drawable.clippy_0868, R.drawable.clippy_0869, R.drawable.clippy_0870, R.drawable.clippy_0871, R.drawable.clippy_0872, R.drawable.clippy_0873, R.drawable.clippy_0874, R.drawable.clippy_0875, R.drawable.clippy_0876, R.drawable.clippy_0877, R.drawable.clippy_0878, R.drawable.clippy_0879, R.drawable.clippy_0880, R.drawable.clippy_0881, R.drawable.clippy_0882, R.drawable.clippy_0883, R.drawable.clippy_0884, R.drawable.clippy_0885, R.drawable.clippy_0886, R.drawable.clippy_0887, R.drawable.clippy_0888, R.drawable.clippy_0889, R.drawable.clippy_0890, R.drawable.clippy_0891, R.drawable.clippy_0892, R.drawable.clippy_0893, R.drawable.clippy_0894, R.drawable.clippy_0895, R.drawable.clippy_0896, R.drawable.clippy_0897, R.drawable.clippy_0898, R.drawable.clippy_0899, R.drawable.clippy_0900, R.drawable.clippy_0901, R.drawable.clippy_0902, R.drawable.clippy_0903, R.drawable.clippy_0904, R.drawable.clippy_0905, R.drawable.clippy_0906, R.drawable.clippy_0907, R.drawable.clippy_0908, R.drawable.clippy_0909, R.drawable.clippy_0910, R.drawable.clippy_0911, R.drawable.clippy_0912, R.drawable.clippy_0913, R.drawable.clippy_0914, R.drawable.clippy_0915, R.drawable.clippy_0916, R.drawable.clippy_0917)
private val SOUND_MAPPING = intArrayOf(R.raw.clippy_snd_01, R.raw.clippy_snd_02, R.raw.clippy_snd_03, R.raw.clippy_snd_04, R.raw.clippy_snd_05, R.raw.clippy_snd_06, R.raw.clippy_snd_07, R.raw.clippy_snd_08, R.raw.clippy_snd_09, R.raw.clippy_snd_10, R.raw.clippy_snd_11, R.raw.clippy_snd_12, R.raw.clippy_snd_13, R.raw.clippy_snd_14, R.raw.clippy_snd_15)
}
}
| 0
|
Kotlin
|
1
| 0
|
e5f1a5e9c54d30a1f5bc982740500921b0642e01
| 23,116
|
klippy
|
Apache License 2.0
|
test/src/me/anno/tests/sdf/SDFShapes.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.tests.sdf
import me.anno.ecs.Entity
import me.anno.engine.OfficialExtensions
import me.anno.engine.ui.render.SceneView.Companion.testSceneWithUI
import me.anno.io.files.Reference.getReference
import me.anno.sdf.SDFComponent
import me.anno.sdf.shapes.SDFBezierCurve
import me.anno.sdf.shapes.SDFBlob
import me.anno.sdf.shapes.SDFBoundingBox
import me.anno.sdf.shapes.SDFBox
import me.anno.sdf.shapes.SDFCone
import me.anno.sdf.shapes.SDFCylinder
import me.anno.sdf.shapes.SDFDeathStar
import me.anno.sdf.shapes.SDFDoor
import me.anno.sdf.shapes.SDFEllipsoid
import me.anno.sdf.shapes.SDFHeart
import me.anno.sdf.shapes.SDFHexPrism
import me.anno.sdf.shapes.SDFHyperBBox
import me.anno.sdf.shapes.SDFHyperCube
import me.anno.sdf.shapes.SDFMesh
import me.anno.sdf.shapes.SDFPolygon
import me.anno.sdf.shapes.SDFPyramid
import me.anno.sdf.shapes.SDFRegular
import me.anno.sdf.shapes.SDFRoundCone
import me.anno.sdf.shapes.SDFSphere
import me.anno.sdf.shapes.SDFStairs
import me.anno.sdf.shapes.SDFStar
import me.anno.sdf.shapes.SDFTorus
import me.anno.sdf.shapes.SDFTriangle
import me.anno.utils.types.Floats.toRadians
import me.anno.utils.types.Strings.upperSnakeCaseToTitle
import org.joml.Vector3f
fun createShapesScene(): Entity {
val scene = Entity()
fun place(shape: SDFComponent, pos: Vector3f) {
shape.position.set(pos)
scene.add(shape)
}
place(SDFBox(), Vector3f(0f, 0f, 5f))
place(SDFHyperCube().apply {
rotation4d = rotation4d
.rotateY((-35f).toRadians())
.rotateX((47f).toRadians())
.rotateZ((-33f).toRadians())
}, Vector3f(5f, 0f, 5f))
place(SDFBoundingBox(), Vector3f(0f, 0f, 10f))
place(SDFHyperBBox().apply {
rotation4d = rotation4d
.rotateY((-35f).toRadians())
.rotateX((47f).toRadians())
.rotateZ((-33f).toRadians())
}, Vector3f(5f, 0f, 10f))
place(SDFSphere(), Vector3f())
place(SDFCone(), Vector3f(5f, -1f, 0f))
place(SDFRoundCone(), Vector3f(10f, -1f, 0f))
place(SDFPyramid(), Vector3f(15f, -1f, 0f))
place(SDFTorus(), Vector3f(20f, 0f, 0f))
place(SDFCylinder(), Vector3f(25f, 0f, 0f))
// todo heightmap
// special shapes
place(SDFHeart().apply { bound11() }, Vector3f(0f, 0f, 15f))
place(SDFDeathStar(), Vector3f(5f, 0f, 15f))
place(SDFDoor().apply { bound11() }, Vector3f(10f, 0f, 15f))
place(SDFStairs().apply {
stepCount = 15
stepWidth = 0.28f
stepHeight = 0.17f
bound11(0.5f)
}, Vector3f(15f - 15f * 0.28f * 0.5f, -1f, 15f))
place(SDFStar().apply { bound11() }, Vector3f(20f, 0f, 15f))
place(SDFPolygon().apply { bound11() }, Vector3f(25f, 0f, 15f))
place(SDFHexPrism(), Vector3f(0f, 0f, 20f))
place(SDFTriangle(), Vector3f(5f, 0f, 20f))
place(SDFEllipsoid().apply { halfAxes.set(1f, 0.5f, 1f) }, Vector3f(10f, 0f, 20f))
place(SDFBlob(), Vector3f(10f, 0f, 20f))
place(SDFRegular().apply {
name = "Octahedron"
type = SDFRegular.Type.OCTAHEDRON
}, Vector3f(15f, 0f, 20f))
place(SDFRegular().apply {
name = "Dodecahedron"
type = SDFRegular.Type.DODECAHEDRON
}, Vector3f(20f, 0f, 20f))
place(SDFRegular().apply {
name = "Icosahedron"
type = SDFRegular.Type.ICOSAHEDRON
}, Vector3f(25f, 0f, 20f))
place(SDFBezierCurve(), Vector3f(30f, 0f, 20f))
// place(SDFPlane().apply { limit = 20f }, Vector3f(0f, -1.2f, 0f))
/**
* This creates raytracers inside a raymarcher, which is a really bad idea (performance-wise).
* This is only good for small meshes, and then you have to decide whether to use textures, or just code;
* Symmetries aren't used ofc, so that might reduce performance by 2- or 4-fold as well.
*
* Using Susanne as the sample mesh, with 2 small spheres, reduced my performance to 60 fps on a RTX 3070 (BAD!!!).
* */
val sampleMesh = getReference("res://icon-lowpoly.obj")
for ((index, type) in SDFMesh.SDFMeshTechnique.entries.withIndex()) {
place(SDFMesh().apply {
name = "SDFMesh - ${type.name.upperSnakeCaseToTitle()}"
meshFile = sampleMesh
smoothness = 0.01f
technique = type
}, Vector3f(20f + 5f * index, 0f, 10f))
}
return scene
}
/**
* Scene, which shows most SDF shapes
* */
fun main() {
OfficialExtensions.initForTests()
testSceneWithUI("SDF Shapes", createShapesScene())
}
| 0
| null |
3
| 24
|
013af4d92e0f89a83958008fbe1d1fdd9a10e992
| 4,488
|
RemsEngine
|
Apache License 2.0
|
src/main/kotlin/com/simiacryptus/jopenai/models/OpenAIModel.kt
|
SimiaCryptus
| 616,165,852
| false
| null |
package com.simiacryptus.jopenai.models
interface OpenAIModel {
val modelName: String
}
| 0
| null |
1
| 1
|
7a6699f3e4302f0c4f13e190ab8a1d862b54d3f7
| 94
|
jo-penai
|
Apache License 2.0
|
app/src/main/java/com/commit451/gitlab/util/Gravatar.kt
|
Commit451
| 39,787,724
| false
| null |
package com.commit451.gitlab.util
import android.net.Uri
object Gravatar {
fun init(email: String? = null): Builder {
return Builder(email)
}
class Builder constructor(private val mEmail: String?) {
private var ssl = false
private var extension = false
private var size = -1
private var defaultImage: String? = null
private var forceDefault = false
private var rating: String? = null
fun ssl(): Builder {
ssl = true
return this
}
fun extension(): Builder {
extension = true
return this
}
fun size(size: Int): Builder {
if (size < 1 || size > 2048) {
throw IllegalArgumentException("Image size must be from 1px up to 2048px")
}
this.size = size
return this
}
fun defaultImage(defaultImage: DefaultImage): Builder {
when (defaultImage) {
DefaultImage._404 -> this.defaultImage = "404"
DefaultImage.MYSTERY_MAN -> this.defaultImage = "mm"
DefaultImage.IDENTICON -> this.defaultImage = "identicon"
DefaultImage.MONSTERID -> this.defaultImage = "monsterid"
DefaultImage.WAVATAR -> this.defaultImage = "wavatar"
DefaultImage.RETRO -> this.defaultImage = "retro"
DefaultImage.BLANK -> this.defaultImage = "blank"
}
return this
}
fun build(): Uri {
val uriBuilder = StringBuilder()
if (ssl) {
uriBuilder.append("https://secure.gravatar.com/avatar/")
} else {
uriBuilder.append("http://www.gravatar.com/avatar/")
}
if (mEmail != null) {
uriBuilder.append(Hash.md5(mEmail))
} else {
uriBuilder.append("00000000000000000000000000000000")
}
if (extension) {
uriBuilder.append(".jpg")
}
val queryBuilder = StringBuilder()
if (size != -1) {
queryBuilder.append("&s=").append(size)
}
if (defaultImage != null) {
queryBuilder.append("&d=").append(defaultImage)
}
if (forceDefault) {
queryBuilder.append("&f=y")
}
if (rating != null) {
queryBuilder.append("&r=").append(rating)
}
val query = queryBuilder.toString()
if (query.isNotEmpty()) {
uriBuilder.append("?").append(query.substring(1))
}
return Uri.parse(uriBuilder.toString())
}
}
enum class DefaultImage {
_404, MYSTERY_MAN, IDENTICON, MONSTERID, WAVATAR, RETRO, BLANK
}
}
| 6
|
Kotlin
|
27
| 248
|
504b5311c00ac2b87ba728d74925c6f46e6c5781
| 2,881
|
LabCoat
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.