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/io/github/droidkaigi/confsched2018/util/ext/TextViewExt.kt
|
DroidKaigi
| 115,203,383
| false
| null |
package io.github.droidkaigi.confsched2018.util.ext
import android.widget.TextView
// Prevent requestLayout()
fun TextView.setTextIfChanged(newText: String) {
if (newText != text) {
text = newText
}
}
val TextView.selectedText: CharSequence
get() = text.subSequence(selectionStart, selectionEnd)
| 30
|
Kotlin
|
337
| 1,340
|
f19dd63f8b691d44ba7f758d92c2ca615cdad08d
| 319
|
conference-app-2018
|
Apache License 2.0
|
app/src/main/java/dev/falhad/movieshowcase/model/db/dao/SettingDao.kt
|
falhad
| 509,160,308
| false
| null |
package dev.falhad.movieshowcase.model.db.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy.REPLACE
import androidx.room.Query
import dev.falhad.movieshowcase.model.db.entity.SettingEntity
@Dao
interface SettingDao {
@Query("SELECT * FROM settings")
fun getAll(): LiveData<List<SettingEntity>>
@Insert(onConflict = REPLACE)
suspend fun insertAll(vararg settings: SettingEntity)
@Delete
suspend fun delete(settings: SettingEntity)
@Query("DELETE FROM settings")
suspend fun deleteAll()
}
| 0
|
Kotlin
|
0
| 0
|
8529f0b1c4eb9e19a13521ef030882c991a9e270
| 636
|
mvp-movie
|
MIT License
|
adapty/src/main/java/com/adapty/internal/data/cloud/AdaptyResponseTypeAdapterFactory.kt
|
adaptyteam
| 238,537,754
| false
|
{"Kotlin": 408771}
|
package com.adapty.internal.data.cloud
import androidx.annotation.RestrictTo
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal class AdaptyResponseTypeAdapterFactory<TYPE>(
private val typeToken: TypeToken<TYPE>,
private val responseDataExtractor: ResponseDataExtractor,
) : TypeAdapterFactory {
override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
try {
if (!typeToken.isAssignableFrom(type.type)) {
return null
}
} catch (t: Throwable) { return null }
val delegateAdapter =
gson.getDelegateAdapter(this, typeToken)
val elementAdapter = gson.getAdapter(JsonElement::class.java)
val result = object : TypeAdapter<TYPE>() {
override fun write(out: JsonWriter, value: TYPE) {
write(out, value, delegateAdapter)
}
override fun read(`in`: JsonReader): TYPE? {
return read(`in`, delegateAdapter, elementAdapter)
}
}.nullSafe()
return result as TypeAdapter<T>
}
private fun write(
out: JsonWriter,
value: TYPE,
delegateAdapter: TypeAdapter<TYPE>,
) {
delegateAdapter.write(out, value)
}
private fun read(
`in`: JsonReader,
delegateAdapter: TypeAdapter<TYPE>,
elementAdapter: TypeAdapter<JsonElement>,
): TYPE? {
val jsonElement = elementAdapter.read(`in`)
return delegateAdapter.fromJsonTree(
responseDataExtractor.extract(jsonElement) ?: jsonElement
)
}
}
| 2
|
Kotlin
|
14
| 80
|
49bc4d25fffc19183221652d24df0996b4178b4e
| 1,876
|
AdaptySDK-Android
|
MIT License
|
app/src/main/java/com/krygodev/coctailsrecipesapp/ui/fragments/FavouriteCoctailsFragment.kt
|
krygo-dev
| 360,652,871
| false
| null |
package com.krygodev.coctailsrecipesapp.ui.fragments
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.krygodev.coctailsrecipesapp.R
import com.krygodev.coctailsrecipesapp.adapters.FavouritesAdapter
import com.krygodev.coctailsrecipesapp.ui.viewmodels.FavouritesViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_favourite_coctails.*
@AndroidEntryPoint
class FavouriteCoctailsFragment : Fragment(R.layout.fragment_favourite_coctails) {
private val viewModel: FavouritesViewModel by viewModels()
private lateinit var favouritesAdapter: FavouritesAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
favouritesAdapter.setOnItemClickListener { cocktail ->
val bundle = Bundle().apply {
putInt("cocktailID", cocktail.idDrink.toInt())
}
findNavController().navigate(R.id.action_favouriteCoctailsFragment_to_cocktailDetailsFragment, bundle)
}
favouritesAdapter.setOnItemLongClickListener { cocktail ->
viewModel.deleteCocktail(cocktail)
Snackbar.make(view, "Removed from favourites!", Snackbar.LENGTH_SHORT).show()
}
viewModel.getFavouritesCocktails().observe(viewLifecycleOwner, { cocktails ->
favouritesAdapter.differ.submitList(cocktails)
})
}
private fun setupRecyclerView() {
favouritesAdapter = FavouritesAdapter()
favouriteCoctailsRecyclerView.apply {
adapter = favouritesAdapter
layoutManager = GridLayoutManager(activity, 2)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fee3d11246e2bf8ca54a366a2cecb58855bcb3c3
| 1,959
|
CocktailsRecipesApp
|
MIT License
|
domain/src/test/java/com/bolaware/movieproapp/SearchMovieUseCaseTest.kt
|
bolaware
| 222,885,334
| false
| null |
package com.bolaware.movieproapp
import com.bolaware.movieproapp.domain.executor.PostExecutionThread
import com.bolaware.movieproapp.domain.interactor.search.SearchMoviesUseCase
import com.bolaware.movieproapp.domain.model.MovieSummary
import com.bolaware.movieproapp.domain.repository.IMoviesProRepository
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import io.reactivex.Single
import konveyor.base.randomBuild
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import java.lang.UnsupportedOperationException
class SearchMovieUseCaseTest {
lateinit var searchMoviesUseCase : SearchMoviesUseCase
@Mock
lateinit var repository: IMoviesProRepository
@Mock
lateinit var postExecutionThread: PostExecutionThread
@Before
fun setUp(){
MockitoAnnotations.initMocks(this)
searchMoviesUseCase = SearchMoviesUseCase(repository, postExecutionThread)
}
@Test
fun `test buildUseCaseSingle() completes`(){
val searchTerm = randomBuild<String>()
val returnedMovies = listOf<MovieSummary>(randomBuild(), randomBuild())
val searchMoviesUseCaseParam = SearchMoviesUseCase.Params(searchTerm)
`stub repo's searchMovies()`(searchTerm, returnedMovies)
val testObserver = searchMoviesUseCase.buildUseCaseSingle(searchMoviesUseCaseParam).test()
testObserver.assertComplete()
}
@Test
fun `test repo getMovie() is called`(){
val searchTerm = randomBuild<String>()
val returnedMovies = listOf<MovieSummary>(randomBuild(), randomBuild())
val searchMoviesUseCaseParam = SearchMoviesUseCase.Params(searchTerm)
`stub repo's searchMovies()`(searchTerm, returnedMovies)
searchMoviesUseCase.buildUseCaseSingle(searchMoviesUseCaseParam)
verify(repository).searchMovies(any())
}
@Test(expected = UnsupportedOperationException::class)
fun `test buildUseCaseSingle() throws error when null param is passed`(){
searchMoviesUseCase.buildUseCaseSingle(null)
}
@Test
fun `test buildUseCaseSingle() that correct param is passed`(){
val paramArgumentCaptor = argumentCaptor<String>()
val searchTerm = randomBuild<String>()
val returnedMovies = listOf<MovieSummary>(randomBuild(), randomBuild())
val searchMoviesUseCaseParam = SearchMoviesUseCase.Params(searchTerm)
`stub repo's searchMovies()`(searchTerm, returnedMovies)
searchMoviesUseCase.buildUseCaseSingle(searchMoviesUseCaseParam)
verify(repository).searchMovies(paramArgumentCaptor.capture())
Assert.assertEquals(searchTerm, paramArgumentCaptor.firstValue)
}
@Test
fun `test buildUseCaseSingle() that correct response is returned`(){
val searchTerm = randomBuild<String>()
val returnedMovies = listOf<MovieSummary>(randomBuild(), randomBuild())
val searchMoviesUseCaseParam = SearchMoviesUseCase.Params(searchTerm)
`stub repo's searchMovies()`(searchTerm, returnedMovies)
val testObserver = searchMoviesUseCase.buildUseCaseSingle(searchMoviesUseCaseParam).test()
testObserver.assertValue(returnedMovies)
}
fun `stub repo's searchMovies()`(searchTerm : String, movies : List<MovieSummary>){
whenever(repository.searchMovies(searchTerm)).thenReturn(Single.just(movies))
}
}
| 1
| null |
1
| 2
|
1fb9932eeceab7e4b4e4dfb39bc3fe8df661bff8
| 3,556
|
MovieProApp
|
Apache License 2.0
|
plugin-unity-agent/src/main/kotlin/jetbrains/buildServer/unity/MacOsUnityDetector.kt
|
JetBrains
| 159,985,216
| false
| null |
/*
* Copyright 2000-2023 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.unity
import com.intellij.openapi.diagnostic.Logger
import com.vdurmont.semver4j.Semver
import org.apache.commons.configuration.plist.XMLPropertyListConfiguration
import java.io.File
class MacOsUnityDetector : UnityDetectorBase() {
override val editorPath = "Unity.app/Contents/MacOS"
override val editorExecutable = "Unity"
override val appConfigDir = "$userHome/Library/Application support"
override fun findInstallations() = sequence {
getHintPaths().distinct().forEach { path ->
val version = getVersionFromInstall(path) ?: return@forEach
yield(version to path)
}
}
override fun getHintPaths() = sequence {
yieldAll(super.getHintPaths())
yieldAll(findUnityPaths(File("/Applications")))
}
override fun getVersionFromInstall(editorRoot: File): Semver? {
LOG.debug("Looking for Unity installation in $editorRoot")
val executable = getEditorPath(editorRoot)
if (!executable.exists()) {
LOG.debug("Cannot find $executable")
return null
}
val plistFile = File(editorRoot, "Unity.app/Contents/Info.plist")
if (!plistFile.exists()) {
LOG.debug("Cannot find $plistFile")
return null
}
val config = XMLPropertyListConfiguration(plistFile)
// Unity version looks like that: 2017.1.1f1
// where suffix could be the following:
// * a - alpha
// * b - beta
// * p - patch
// * rc - release candidate
// * f - final
val version = config.getString("CFBundleVersion")
?.split("a", "b", "p", "rc", "f")
?.firstOrNull()
?: return null
return try {
Semver(version, Semver.SemverType.LOOSE)
} catch (e: Exception) {
LOG.infoAndDebugDetails("Invalid Unity version $version in directory $editorRoot", e)
null
}
}
companion object {
private val LOG = Logger.getInstance(MacOsUnityDetector::class.java.name)
}
}
| 41
|
Kotlin
|
38
| 68
|
0fc7156aaf4e9f6b2e40509ded24688123ae804b
| 2,726
|
teamcity-unity-plugin
|
Apache License 2.0
|
app/src/main/java/com/inlacou/commons/ui/activities/BaseActCtrl.kt
|
inlacou
| 400,138,100
| false
|
{"Kotlin": 513611, "Shell": 139}
|
package com.inlacou.commons.ui.activities
import android.content.Intent
import io.reactivex.rxjava3.disposables.Disposable
/**
* Created by inlacou on 19/03/18.
*/
abstract class BaseActCtrl(val _view: BaseAct, val _model: Any) {
val disposables: MutableList<Disposable?>
get() = _view.disposables
open fun onCreate() {}
open fun onStart() {}
open fun onResume() {}
open fun onStop() {}
open fun onPause() {}
open fun onDestroy() {}
open fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {}
open fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {}
}
| 0
|
Kotlin
|
0
| 0
|
aa90dfc787a4fae77765d333d327929750da7d18
| 638
|
InkCommons
|
MIT License
|
Utils.kt
|
GrgnPl
| 527,281,069
| false
| null |
package com.example.photos_app
import android.content.ContentResolver
import android.net.Uri
import android.provider.OpenableColumns
import android.view.View
import com.google.android.material.snackbar.Snackbar
fun View.snackbar(message: String) {
Snackbar.make(
this,
message,
Snackbar.LENGTH_LONG
).also { snackbar ->
snackbar.setAction("Ok") {
snackbar.dismiss()
}
}.show()
}
fun ContentResolver.getFileName(fileUri: Uri): String {
var name = ""
val returnCursor = this.query(fileUri, null, null, null, null)
if (returnCursor != null) {
val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
returnCursor.moveToFirst()
name = returnCursor.getString(nameIndex)
returnCursor.close()
}
return name
}
| 0
| null |
0
| 1
|
5180935056e7a0fbf9141663a917763085841de6
| 837
|
Retrofit
|
MIT License
|
sampleapplication/src/main/java/com/evervault/sampleapplication/navigation/Route.kt
|
evervault
| 650,073,299
| false
|
{"Kotlin": 331362, "Java": 1240, "Shell": 273}
|
package com.evervault.sampleapplication.navigation
sealed class Route(val route: String) {
object Home : Route("home")
object BasicEncryption : Route("BasicEncryption")
object FileEncryption : Route("FileEncryption")
object CreditCardInput : Route("CreditCardInput")
object CreditCardInputWithPlaceholders : Route("CreditCardInputWithPlaceholders")
object CreditCardInputCustom : Route("CreditCardInputCustom")
object CreditCardInputRows : Route("CreditCardInputRows")
object CreditCardInputRowsWithPlaceholders : Route("CreditCardInputRowsWithPlaceholders")
object CreditCardInputCustomStyle : Route("CreditCardInputCustomStyle")
object InlinePaymentCard : Route("InlinePaymentCard")
object InlinePaymentCardCustomStyle : Route("InlinePaymentCardCustomStyle")
object RowsPaymentCard : Route("RowsPaymentCard")
object CreditCardInputCustomComposables : Route("CreditCardInputCustomComposables")
object CreditCardInputCustomComposablesWithoutLabels :
Route("CreditCardInputCustomComposablesWithoutLabels")
object CreditCardInputCustomCardOnly: Route("CreditCardInputCustomCardOnly")
object Enclave : Route("Enclave")
}
| 3
|
Kotlin
|
1
| 4
|
fd158425048b638a3b4ca9948da31fed5c556468
| 1,207
|
evervault-android
|
MIT License
|
android/libraries/libHorses/src/main/java/nl/entreco/giddyapp/libhorses/cycle/InstantHorseCycler.kt
|
Entreco
| 164,009,012
| false
| null |
package nl.entreco.giddyapp.libhorses.cycle
import nl.entreco.giddyapp.libhorses.Horse
import kotlin.math.min
internal class InstantHorseCycler : HorseCycler {
companion object {
private const val MAX_HORSES = 5
}
override fun initialHorses(collection: List<Horse>): List<Horse> {
return when {
collection.isEmpty() -> listOf(Horse.None, Horse.Install)
collection.size < 2 -> listOf(collection[0], Horse.Install)
else -> {
collection.subList(0, min(collection.size, MAX_HORSES)).toMutableList().apply {
add(Horse.Install)
}
}
}
}
override fun recycle(done: (List<Horse>) -> Unit) {
done(emptyList())
}
}
| 23
| null |
1
| 1
|
59960640ecd182c502df2d52fa17ed619d415c91
| 764
|
GiddyApp
|
Apache License 2.0
|
services/s3/common/test/aws/sdk/kotlin/services/s3/model/TestS3Size.kt
|
awslabs
| 121,333,316
| false
| null |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package aws.sdk.kotlin.services.s3.model
import kotlin.test.Test
import kotlin.test.assertIs
class TestS3Size {
@Test
fun testSizeIsLong() {
// verify no regressions in `Size` shape reverting to `Integer` (it should be `Long`)
// see: https://github.com/awslabs/aws-sdk-kotlin/issues/309
val obj = Object { size = 100 }
val req = PutObjectRequest { contentLength = 100 }
assertIs<Long>(obj.size)
assertIs<Long>(req.contentLength)
}
}
| 79
|
Kotlin
|
7
| 98
|
05fb6d3631b02e87034f60e57051c25b7b70351d
| 615
|
aws-sdk-kotlin
|
Apache License 2.0
|
app/src/main/java/com/dede/nativetools/util/ProcessKt.kt
|
hushenghao
| 242,718,110
| false
| null |
@file:JvmName("ProcessKt")
package com.dede.nativetools.util
import android.app.ActivityManager
import android.app.Application
import android.content.ComponentCallbacks2
import android.content.Context
import android.os.Build
import android.os.Process
import com.google.firebase.perf.metrics.AddTrace
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
private fun Context.runningProcesses(): List<ActivityManager.RunningAppProcessInfo> {
val activityManager = requireSystemService<ActivityManager>()
return activityManager.runningAppProcesses ?: emptyList()
}
fun Context.currentProcess(): ActivityManager.RunningAppProcessInfo? {
val list = this.runningProcesses()
if (list.isEmpty()) {
return null
}
val pid = Process.myPid()
for (info in list) {
if (info.pid == pid) {
return info
}
}
return null
}
fun Context.mainProcess(): ActivityManager.RunningAppProcessInfo? {
val list = this.runningProcesses()
if (list.isEmpty()) {
return null
}
val packageName = this.packageName
for (info in list) {
if (info.processName == packageName) {
return info
}
}
return null
}
@AddTrace(name = "主进程判断")
fun Context.isMainProcess(): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val processName = Application.getProcessName()
if (processName.isNotEmpty()) {
return processName == this.packageName
}
}
return currentProcess().isMainProcess(this)
}
fun Context.processName(): String? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return Application.getProcessName()
}
return currentProcess()?.processName
}
@OptIn(ExperimentalContracts::class)
fun ActivityManager.RunningAppProcessInfo?.isMainProcess(context: Context): Boolean {
contract { returns(true) implies (this@isMainProcess != null) }
val packageName = context.packageName
if (this == null) return false
return packageName.isNotEmpty() && this.processName == packageName
}
@OptIn(ExperimentalContracts::class)
fun ActivityManager.RunningAppProcessInfo?.isForeground(): Boolean {
contract { returns(true) implies (this@isForeground != null) }
if (this == null) return false
val uiHidden = this.lastTrimLevel >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
val cached =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this.importance >= ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED
} else {
@Suppress("DEPRECATION")
this.importance >= ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND
}
return !uiHidden && !cached
}
| 1
| null |
5
| 5
|
f7550e37d20efe555914c0c2428a048b131a89aa
| 2,748
|
NativeTools
|
Apache License 2.0
|
spigot/src/main/kotlin/io/pixeloutlaw/minecraft/spigot/config/FileAwareYamlConfiguration.kt
|
MythicDrops
| 10,021,467
| false
| null |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2021 <NAME>
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.pixeloutlaw.minecraft.spigot.config
import io.pixeloutlaw.kindling.Log
import org.bukkit.configuration.ConfigurationSection
import org.bukkit.configuration.file.YamlConfiguration
import java.io.File
/**
* An instance of [YamlConfiguration] that is also a [FileAwareConfiguration].
*/
open class FileAwareYamlConfiguration @JvmOverloads constructor(override var file: File? = null) :
YamlConfiguration(), FileAwareConfiguration {
init {
load()
}
/**
* Loads from the file passed into the constructor. Ignores any exceptions thrown.
*
* Equivalent of calling [load] and passing in [file].
*/
final override fun load() {
val fileToLoad = file
if (fileToLoad == null) {
Log.warn("Cannot load from a null file")
return
}
try {
load(fileToLoad)
} catch (ignored: Throwable) {
Log.error("Unable to load FileAwareYamlConfiguration", ignored)
}
}
/**
* Saves to the file passed into the constructor. Ignores any exceptions thrown.
*
* Equivalent of calling [save] and passing in [file].
*/
final override fun save() {
val fileToSave = file
if (fileToSave == null) {
Log.warn("Cannot save to a null file")
return
}
try {
save(fileToSave)
} catch (ignored: Throwable) {
Log.error("Unable to save FileAwareYamlConfiguration", ignored)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ConfigurationSection) return false
val ourKeys = getKeys(true)
val theirKeys = other.getKeys(true)
if (theirKeys != ourKeys) return false
for (key in ourKeys) {
val ourValue = get(key)
val theirValue = other.get(key)
if (ourValue != theirValue) {
return false
}
}
return true
}
override fun toString(): String {
val keysAndValues = getKeys(true).mapNotNull {
if (isConfigurationSection(it)) {
return@mapNotNull null
}
it to get(it)
}.toMap()
return "FileAwareYamlConfiguration($keysAndValues)"
}
override fun hashCode(): Int {
return file?.hashCode() ?: 0
}
}
| 64
| null |
43
| 40
|
e08d2ad3befda5e18bd763b6f30f00fa4ff44c35
| 3,590
|
MythicDrops
|
MIT License
|
app/src/main/java/ir/composenews/ui/MainActivity.kt
|
Kaaveh
| 576,928,671
| false
| null |
package ir.composenews.ui
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import com.google.accompanist.adaptive.calculateDisplayFeatures
import dagger.hilt.android.AndroidEntryPoint
import ir.composenews.designsystem.theme.ComposeNewsTheme
import ir.composenews.navigation.MainContract
import ir.composenews.permission.enum.PermissionType
import ir.composenews.permission.manager.PermissionManager
import ir.composenews.permission.manager.PermissionManagerImpl
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentList
@AndroidEntryPoint
class MainActivity : ComponentActivity(), PermissionManager by PermissionManagerImpl() {
private val viewModel: MainViewModel by viewModels()
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
performPermission(
PermissionType.POST_NOTIFICATIONS,
this
)
setContent {
ComposeNewsTheme {
val windowSize = calculateWindowSizeClass(this)
val displayFeatures = calculateDisplayFeatures(this)
val uiState = viewModel.state.collectAsState()
ComposeNewsApp(
windowSize = windowSize,
displayFeatures = displayFeatures.toPersistentList(),
uiState = uiState.value,
closeDetailScreen = { viewModel.closeDetailScreen() },
onMarketSelected = { market, contentType ->
viewModel.event(
MainContract.Event.SetMarket(
market = market,
contentType = contentType
)
)
}
)
}
}
}
}
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Preview(showBackground = true)
@Composable
fun ComposeNewsAppPreview() {
ComposeNewsTheme {
ComposeNewsApp(
windowSize = WindowSizeClass.calculateFromSize(DpSize(400.dp, 900.dp)),
displayFeatures = persistentListOf(),
uiState = MainContract.State(),
closeDetailScreen = {},
)
}
}
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Preview(showBackground = true, widthDp = 700, heightDp = 500)
@Composable
fun ComposeNewsAppPreviewTablet() {
ComposeNewsTheme {
ComposeNewsApp(
windowSize = WindowSizeClass.calculateFromSize(DpSize(700.dp, 500.dp)),
displayFeatures = persistentListOf(),
uiState = MainContract.State(),
closeDetailScreen = {},
)
}
}
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Preview(showBackground = true, widthDp = 500, heightDp = 700)
@Composable
fun ComposeNewsAppPreviewTabletPortrait() {
ComposeNewsTheme {
ComposeNewsApp(
windowSize = WindowSizeClass.calculateFromSize(DpSize(500.dp, 700.dp)),
displayFeatures = persistentListOf(),
uiState = MainContract.State(),
closeDetailScreen = {},
)
}
}
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Preview(showBackground = true, widthDp = 1100, heightDp = 600)
@Composable
fun ComposeNewsAppPreviewDesktop() {
ComposeNewsTheme {
ComposeNewsApp(
windowSize = WindowSizeClass.calculateFromSize(DpSize(1100.dp, 600.dp)),
displayFeatures = persistentListOf(),
uiState = MainContract.State(),
closeDetailScreen = {},
)
}
}
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Preview(showBackground = true, widthDp = 600, heightDp = 1100)
@Composable
fun ComposeNewsAppPreviewDesktopPortrait() {
ComposeNewsTheme {
ComposeNewsApp(
windowSize = WindowSizeClass.calculateFromSize(DpSize(600.dp, 1100.dp)),
displayFeatures = persistentListOf(),
uiState = MainContract.State(),
closeDetailScreen = {},
)
}
}
| 7
| null |
52
| 315
|
ce21f7cdea8b8ae5babc383571c60c5be79b0cdb
| 4,681
|
ComposeNews
|
Apache License 2.0
|
the.orm.itest/src/test/kotlin/io/the/orm/test/functional/exp/SchemaLoadingTest.kt
|
christophsturm
| 260,202,802
| false
|
{"Kotlin": 176994}
|
package io.the.orm.test.functional.exp
import failgood.Ignored
import failgood.Test
import io.the.orm.dbio.DBResult
import io.the.orm.mapper.SimpleResultMapper
import io.the.orm.test.DBS
import io.the.orm.test.describeOnAllDbs
import io.the.orm.test.functional.USERS_SCHEMA
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.toList
import kotlin.test.assertEquals
@Test
object SchemaLoadingTest {
val context =
describeOnAllDbs(
"detecting the table structure",
DBS.databases,
USERS_SCHEMA,
ignored = Ignored.Because("Unfinished")
// the current problem is that it finds properties of all databases, instead only of the current database.
// (needs to filter by table_catalog)
) { connectionProvider ->
it("prints result", ignored = Ignored.Because("only for debugging")) {
connectionProvider.withConnection { conn ->
println(
conn.createStatement(
"select column_name, data_type, table_catalog, character_maximum_length," +
" column_default, is_nullable " +
"from INFORMATION_SCHEMA.COLUMNS where lower(table_name) = 'users'"
).execute().asMapFlow().toList()
)
println(
conn.createStatement(
"select database()"
).execute().asMapFlow().toList()
)
}
}
it("can get the table structure") {
connectionProvider.withConnection { conn ->
val columns = conn.createStatement(
"select column_name, data_type, character_maximum_length, column_default, is_nullable\n" +
"from INFORMATION_SCHEMA.COLUMNS where lower(table_name) = 'users'"
).execute().mapToList<Columns>().toList()
/*
id bigint not null default nextval('users_id_seq') primary key,
name varchar(100) not null,
email varchar(100) unique,
is_cool boolean,
bio text,
favorite_color varchar(10),
birthday date,
weight decimal(5, 2),
balance decimal(5, 2)
*/
assertEquals(
listOf(
"id",
"name",
"email",
"is_cool",
"bio",
"favorite_color",
"birthday",
"weight",
"balance"
).sorted(),
columns.map { it.columnName.lowercase() }.sorted()
)
}
}
}
}
private suspend inline fun <reified T : Any> DBResult.mapToList(): Flow<T> {
val mapper = SimpleResultMapper.forClass(T::class)
return mapper.mapQueryResult(this)
}
data class Columns(
val columnName: String,
val dataType: String,
val characterMaximumLength: Long?,
val isNullable: String
)
| 14
|
Kotlin
|
0
| 0
|
2625d48f2b4eeb862863262ac7bc3aa7d3c27256
| 3,402
|
the.orm
|
MIT License
|
example-spark-runner/src/main/kotlin/io/github/arthurpessoa/schema/Movie.kt
|
arthurpessoa
| 708,798,233
| false
|
{"Kotlin": 30425}
|
package io.github.arthurpessoa.schema
import org.apache.beam.sdk.schemas.JavaBeanSchema
import org.apache.beam.sdk.schemas.annotations.DefaultSchema
import java.io.Serializable
@DefaultSchema(JavaBeanSchema::class)
data class Movie(
var id: Long? = null,
var name: String? = null
) : Serializable
| 0
|
Kotlin
|
0
| 3
|
117f6e7b93e1af4c406add3f4b015c8eabaf6c6f
| 306
|
kotlin-beam-starter
|
MIT License
|
app/src/main/java/io/jachoteam/kaska/screens/login/LoginActivity.kt
|
tynarbekov
| 159,201,128
| false
|
{"Kotlin": 129794, "Java": 63242}
|
package io.jachoteam.kaska.screens.login
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import io.jachoteam.kaska.screens.common.BaseActivity
import io.jachoteam.kaska.screens.common.coordinateBtnAndInputs
import io.jachoteam.kaska.screens.home.HomeActivity
import io.jachoteam.kaska.screens.register.RegisterActivity
import com.google.firebase.auth.FirebaseAuth
import io.jachoteam.kaska.R
import io.jachoteam.kaska.ResetPasswordActivity
import kotlinx.android.synthetic.main.activity_login.*
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEventListener
class LoginActivity : BaseActivity(), KeyboardVisibilityEventListener, View.OnClickListener {
private lateinit var mAuth: FirebaseAuth
private lateinit var mViewModel: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
Log.d(TAG, "onCreate")
KeyboardVisibilityEvent.setEventListener(this, this)
coordinateBtnAndInputs(login_btn, email_input, password_input)
login_btn.setOnClickListener(this)
reset_button.setOnClickListener(this)
create_account_text.setOnClickListener(this)
mViewModel = initViewModel()
mViewModel.goToHomeScreen.observe(this, Observer {
startActivity(Intent(this, HomeActivity::class.java))
finish()
})
mViewModel.goToRegisterScreen.observe(this, Observer {
startActivity(Intent(this, RegisterActivity::class.java))
})
mAuth = FirebaseAuth.getInstance()
}
override fun onClick(view: View) {
when (view.id) {
R.id.login_btn ->
mViewModel.onLoginClick(
email = email_input.text.toString(),
password = password_input.text.toString()
)
R.id.create_account_text -> mViewModel.onRegisterClick()
R.id.reset_button -> startActivity(Intent(this, ResetPasswordActivity::class.java))
}
}
override fun onVisibilityChanged(isKeyboardOpen: Boolean) {
if (isKeyboardOpen) {
create_account_text.visibility = View.GONE
} else {
create_account_text.visibility = View.VISIBLE
}
}
companion object {
const val TAG = "LoginActivity"
}
}
| 0
|
Kotlin
|
0
| 0
|
1aa2857144eac0a2a0a3e9aa919e8dc76981fc48
| 2,565
|
Kaska
|
MIT License
|
androidApp/src/main/java/app/opass/ccip/android/utils/CommonUtil.kt
|
CCIP-App
| 844,022,286
| false
|
{"Kotlin": 115735, "Swift": 21755}
|
package app.opass.ccip.android.utils
import android.app.Activity
import android.content.Context
import android.view.WindowManager
object CommonUtil {
fun setBrightness(context: Context, isFull: Boolean) {
val activity = context as? Activity ?: return
val layoutParams: WindowManager.LayoutParams = activity.window.attributes
layoutParams.screenBrightness =
if (isFull) 1.0F else WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
activity.window.attributes = layoutParams
}
}
| 0
|
Kotlin
|
0
| 2
|
483083cc6ab608bce7b6cd7be3d9d479fe14d8a3
| 532
|
CCIP-KMP
|
Apache License 2.0
|
feature-staking-impl/src/main/java/jp/co/soramitsu/staking/impl/domain/validations/unbond/ControllerCanPayFeeValidation.kt
|
soramitsu
| 278,060,397
| false
|
{"Kotlin": 5738459, "Java": 18796}
|
package jp.co.soramitsu.staking.impl.domain.validations.unbond
import jp.co.soramitsu.common.validation.DefaultFailureLevel
import jp.co.soramitsu.common.validation.Validation
import jp.co.soramitsu.common.validation.ValidationStatus
import jp.co.soramitsu.wallet.impl.domain.validation.AmountProducer
class ControllerCanPayFeeValidation<P, E>(
private val feeExtractor: AmountProducer<P>,
private val availableControllerBalanceProducer: AmountProducer<P>,
private val errorProducer: () -> E
) : Validation<P, E> {
override suspend fun validate(value: P): ValidationStatus<E> {
return if (feeExtractor(value) < availableControllerBalanceProducer(value)) {
ValidationStatus.Valid()
} else {
ValidationStatus.NotValid(DefaultFailureLevel.ERROR, errorProducer())
}
}
}
| 15
|
Kotlin
|
30
| 89
|
1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2
| 836
|
fearless-Android
|
Apache License 2.0
|
app/src/main/java/ru/ekbtrees/treemap/domain/entity/Entity.kt
|
dienyaaa
| 355,126,052
| true
|
{"Kotlin": 8056}
|
package ru.ekbtrees.treemap
data class ClusterTreesEntity(val count: Int, val coord: LatLonEntity)
data class TreeEntity(val id: String, val diameter: Float, val species: SpeciesEntity, val coord: LatLonEntity)
data class SpeciesEntity(val id: String, val color: String, val name: String)
data class LatLonEntity(val lat: Float, val lon: Float)
| 0
|
Kotlin
|
0
| 0
|
c6097eea7daf2e51906453c39fdca25029c98b97
| 350
|
ekbtrees-android
|
MIT License
|
apps/teacher/src/androidTest/java/com/instructure/teacher/ui/e2e/DiscussionsE2ETest.kt
|
instructure
| 179,290,947
| false
|
{"Kotlin": 16415961, "Dart": 4454406, "HTML": 185120, "Ruby": 35686, "Java": 24752, "Shell": 19157, "Groovy": 11717, "JavaScript": 9505, "Objective-C": 7431, "Python": 2438, "CSS": 1356, "Swift": 807, "Dockerfile": 112}
|
/*
* Copyright (C) 2021 - present Instructure, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.instructure.teacher.ui.e2e
import android.util.Log
import androidx.test.espresso.Espresso
import com.instructure.canvas.espresso.E2E
import com.instructure.canvas.espresso.FeatureCategory
import com.instructure.canvas.espresso.Priority
import com.instructure.canvas.espresso.TestCategory
import com.instructure.canvas.espresso.TestMetaData
import com.instructure.dataseeding.api.DiscussionTopicsApi
import com.instructure.teacher.ui.utils.TeacherTest
import com.instructure.teacher.ui.utils.seedData
import com.instructure.teacher.ui.utils.tokenLogin
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Test
import java.lang.Thread.sleep
@HiltAndroidTest
class DiscussionsE2ETest : TeacherTest() {
override fun displaysPageObjects() = Unit
override fun enableAndConfigureAccessibilityChecks() = Unit
@E2E
@Test
@TestMetaData(Priority.MANDATORY, FeatureCategory.DISCUSSIONS, TestCategory.E2E)
fun testDiscussionE2E() {
Log.d(PREPARATION_TAG, "Seeding data.")
val data = seedData(students = 1, teachers = 1, courses = 1, discussions = 2)
val teacher = data.teachersList[0]
val student = data.studentsList[0]
val course = data.coursesList[0]
val discussion = data.discussionsList[0]
val discussion2 = data.discussionsList[1]
val discussionEntryMessage = "Discussion entry test message"
val testDiscussionTopicEntry = DiscussionTopicsApi.createEntryToDiscussionTopic(student.token, course.id, discussion.id, discussionEntryMessage)
val testDiscussionEntryReplyMessage = "This is a reply for the entry for testing purposes!"
DiscussionTopicsApi.createReplyToDiscussionTopicEntry(student.token, course.id, discussion.id, testDiscussionTopicEntry.id, testDiscussionEntryReplyMessage)
Log.d(STEP_TAG, "Login with user: '${teacher.name}', login id: '${teacher.loginId}'.")
tokenLogin(teacher)
dashboardPage.waitForRender()
Log.d(STEP_TAG,"Open '${course.name}' course.")
dashboardPage.openCourse(course.name)
courseBrowserPage.waitForRender()
Log.d(STEP_TAG,"Open Discussions Page and assert has discussions: '${discussion.title}' and '${discussion2.title}'.")
courseBrowserPage.openDiscussionsTab()
discussionsListPage.assertHasDiscussion(discussion)
discussionsListPage.assertHasDiscussion(discussion2)
Log.d(STEP_TAG,"Click on '${discussion.title}' discussion.")
discussionsListPage.clickDiscussion(discussion)
Log.d(STEP_TAG, "Assert that the 'Reply' button is displayed on the discussion details (web view) page.")
discussionDetailsPage.waitForReplyButtonDisplayed()
discussionDetailsPage.assertReplyButtonDisplayed()
Log.d(STEP_TAG, "Assert that the toolbar's title is the '${discussion.title}' discussion's title.")
discussionDetailsPage.assertToolbarDiscussionTitle(discussion.title)
Log.d(STEP_TAG, "Click on the more menu of the announcement and assert if the more menu items are all displayed.")
discussionDetailsPage.clickOnDiscussionMoreMenu()
discussionDetailsPage.assertMoreMenuButtonDisplayed("Mark All as Read")
discussionDetailsPage.assertMoreMenuButtonDisplayed("Mark All as Unread")
discussionDetailsPage.assertMoreMenuButtonDisplayed("Edit")
discussionDetailsPage.assertMoreMenuButtonDisplayed("Delete")
discussionDetailsPage.assertMoreMenuButtonDisplayed("Close for Comments")
discussionDetailsPage.assertMoreMenuButtonDisplayed("Send To...")
discussionDetailsPage.assertMoreMenuButtonDisplayed("Copy To...")
discussionDetailsPage.assertMoreMenuButtonDisplayed("Share to Commons")
Log.d(STEP_TAG, "Assert that the '$discussionEntryMessage' discussion entry message is displayed.")
discussionDetailsPage.assertDiscussionEntryMessageDisplayed(discussionEntryMessage)
Log.d(STEP_TAG, "Assert that there is 1 reply and that is unread.")
discussionDetailsPage.assertReplyCounter(1, 1)
Log.d(STEP_TAG, "Expand the replies and wait for the reply to be displayed. Assert that it's displayed.")
discussionDetailsPage.clickOnExpandRepliesButton()
discussionDetailsPage.waitForReplyDisplayed(testDiscussionEntryReplyMessage)
discussionDetailsPage.assertReplyDisplayed(testDiscussionEntryReplyMessage)
Log.d(STEP_TAG, "Navigate back to Discussion List Page. Select 'Pin' overflow menu of '${discussion2.title}' discussion and assert that it has became Pinned.")
Espresso.pressBack()
discussionsListPage.clickDiscussionOverFlowMenu(discussion2.title)
discussionsListPage.selectOverFlowMenu("Pin")
discussionsListPage.assertGroupDisplayed("Pinned")
discussionsListPage.assertDiscussionInGroup("Pinned", discussion2.title)
discussionsListPage.assertDiscussionNotInGroup("Discussions", discussion2.title)
Log.d(STEP_TAG, "Select 'Unpin' overflow menu of '${discussion2.title}' discussion and assert that it has became Unpinned, so it will be displayed (again) in the 'Discussions' group.")
discussionsListPage.clickDiscussionOverFlowMenu(discussion2.title)
discussionsListPage.selectOverFlowMenu("Unpin")
discussionsListPage.assertDiscussionInGroup("Discussions", discussion2.title)
discussionsListPage.assertDiscussionNotInGroup("Pinned", discussion2.title)
Log.d(STEP_TAG, "Assert that both of the discussions, '${discussion.title}' and '${discussion2.title}' discussions are displayed.")
discussionsListPage.assertHasDiscussion(discussion)
discussionsListPage.assertHasDiscussion(discussion2)
Log.d(STEP_TAG, "Select 'Closed for Comments' overflow menu of '${discussion.title}' discussion and assert that it has became 'Closed for Comments'.")
discussionsListPage.clickDiscussionOverFlowMenu(discussion.title)
discussionsListPage.selectOverFlowMenu("Close for Comments")
discussionsListPage.assertGroupDisplayed("Closed for Comments")
discussionsListPage.assertDiscussionInGroup("Closed for Comments", discussion.title)
Log.d(STEP_TAG, "Assert that the 'Discussions' group will be still displayed despite it has no items in it. Assert that the '${discussion2.title}' discussion is not in the 'Discussions' group any more.")
discussionsListPage.assertGroupDisplayed("Discussions")
discussionsListPage.assertDiscussionNotInGroup("Discussions", discussion.title)
Log.d(STEP_TAG, "Select 'Open for Comments' overflow menu of '${discussion.title}' discussion and assert that it will be (again) displayed under the 'Discussions' group.")
discussionsListPage.clickDiscussionOverFlowMenu(discussion.title)
discussionsListPage.selectOverFlowMenu("Open for Comments")
discussionsListPage.assertDiscussionInGroup("Discussions", discussion.title)
Log.d(STEP_TAG, "Assert that the '${discussion2.title}' discussion is not in the 'Closed for Comments' group any more.")
discussionsListPage.assertDiscussionNotInGroup("Closed for Comments", discussion.title)
Log.d(STEP_TAG,"Click on more menu of '${discussion.title}' discussion and delete it.")
discussionsListPage.deleteDiscussionFromOverflowMenu(discussion.title)
Log.d(STEP_TAG,"Assert that the previously deleted '${discussion.title}' discussion is not displayed, but the other, '${discussion2.title}' discussion is.")
sleep(2000) //Allow the deletion to propagate
discussionsListPage.assertDiscussionDoesNotExist(discussion.title)
discussionsListPage.assertHasDiscussion(discussion2)
Log.d(STEP_TAG,"Click on '+' icon on the UI to create a new discussion.")
discussionsListPage.createNewDiscussion()
val newDiscussionTitle = "Test Discussion Mobile UI"
Log.d(STEP_TAG,"Set '$newDiscussionTitle' as the discussion's title and set some description as well.")
editDiscussionsDetailsPage.editDiscussionTitle(newDiscussionTitle)
editDiscussionsDetailsPage.editDiscussionDescription("Mobile UI Discussion description")
Log.d(STEP_TAG,"Toggle 'Publish' checkbox and save the page.")
editDiscussionsDetailsPage.togglePublished()
editDiscussionsDetailsPage.clickSendNewDiscussion()
Log.d(STEP_TAG,"Assert that '$newDiscussionTitle' discussion is displayed and published.")
discussionsListPage.assertHasDiscussion(newDiscussionTitle)
discussionsListPage.clickDiscussion(newDiscussionTitle)
Log.d(STEP_TAG, "Assert that the toolbar's title is the '$newDiscussionTitle' discussion's title.")
discussionDetailsPage.assertToolbarDiscussionTitle(newDiscussionTitle)
Espresso.pressBack()
Log.d(STEP_TAG,"Click on the Search icon and type some search query string which matches only with the previously created discussion's title.")
discussionsListPage.searchable.clickOnSearchButton()
discussionsListPage.searchable.typeToSearchBar("Test Discussion")
Log.d(STEP_TAG,"Assert that the '$newDiscussionTitle' discussion is displayed and it is the only one.")
discussionsListPage.assertDiscussionCount(1)
discussionsListPage.assertHasDiscussion(newDiscussionTitle)
discussionsListPage.searchable.clickOnClearSearchButton()
Log.d(STEP_TAG, "Quit from Searching mechanism.")
Espresso.pressBack()
Log.d(STEP_TAG,"Click on more menu of '${discussion2.title}' discussion and delete it.")
discussionsListPage.deleteDiscussionFromOverflowMenu(discussion2.title)
Log.d(STEP_TAG,"Assert that the previously deleted '${discussion2.title}' discussion is not displayed.")
sleep(2000) //Allow the deletion to propagate
discussionsListPage.assertDiscussionDoesNotExist(discussion2.title)
Log.d(STEP_TAG,"Collapse the discussion list and assert that the '$newDiscussionTitle' discussion can NOT be seen.")
discussionsListPage.toggleCollapseExpandIcon()
discussionsListPage.assertDiscussionCount(0) // header only
discussionsListPage.assertDiscussionDoesNotExist(newDiscussionTitle)
Log.d(STEP_TAG,"Expand the discussion list and assert that the '$newDiscussionTitle' discussion can be seen.")
discussionsListPage.toggleCollapseExpandIcon()
discussionsListPage.assertDiscussionCount(1)
discussionsListPage.assertHasDiscussion(newDiscussionTitle)
}
}
| 7
|
Kotlin
|
102
| 127
|
ca6e2aeaeedb851003af5497e64c22e02dbf0db8
| 11,243
|
canvas-android
|
Apache License 2.0
|
app/src/androidTest/java/eu/caraus/appsflastfm/data/local/LastFmDbTest.kt
|
alexandrucaraus
| 144,028,779
| false
|
{"Kotlin": 202701}
|
package eu.caraus.appsflastfm.data.local
import android.arch.persistence.room.Room
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import eu.caraus.appsflastfm.data.remote.lastFm.LastFmApi
import eu.caraus.appsflastfm.data.remote.lastFm.LastFmApiClient
import eu.caraus.appsflastfm.data.remote.lastFm.LastFmApiKeyInterceptor
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.not
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
@RunWith(AndroidJUnit4::class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class LastFmDbTest {
private val lastFmApi : LastFmApi? = LastFmApiClient(LastFmApiKeyInterceptor.LAST_FM_API_KEY).client.create( LastFmApi::class.java )
private lateinit var database : Database
@Before
fun setup() {
database = Room.inMemoryDatabaseBuilder ( InstrumentationRegistry.getTargetContext(),
Database::class.java
//, Database.DATABASE_NAME
)
.fallbackToDestructiveMigration()
.build()
}
@Test
fun testInsertAlbums() {
lastFmApi?.getArtistAlbumInfo("Metallica", "Metallica")
?.subscribe({
assertEquals("isSuccessful","isSuccessful")
database.albumsDao().insert( it.album!! )
database.albumsDao().selectAll().let{ list ->
assertThat( list.size , `is`(1) )
}
},{
assertEquals("isSuccessful", "isFailed ${it.message}")
})
}
@Test
fun testSelectAlbums(){
lastFmApi?.getArtistAlbumInfo("Metallica", "Metallica")
?.subscribe({
assertEquals("isSuccessful","isSuccessful")
database.albumsDao().insertWhole( it.album!! )
database.albumsDao().selectAll().let { list ->
assertThat( list.size , `is`(1) )
}
database.tracksDao().getAll().subscribe { list->
assertThat( list.size, `is`( not( 0)))
}
database.artistsDao().getAll().subscribe{ list->
assertThat( list.size, `is`( not( 0)))
}
},{
assertEquals("isSuccessful", "isFailed ${it.message}")
})
}
}
| 0
|
Kotlin
|
0
| 0
|
fb9b4a218fa4c09b23b253eb75ee62456b4b47ff
| 2,814
|
ShowCase-AppsFactoryLastFmMvp
|
MIT License
|
app/src/main/java/com/composebootcamp/triviva/viewmodel/GameScreenViewModel.kt
|
tudang88
| 697,826,302
| false
|
{"Kotlin": 51107}
|
package com.composebootcamp.triviva.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
data class Question(
val text: String,
val answers: List<String>,
val key: String
)
// test data of game
private val questions = listOf(
Question(
text = "What is Android Jetpack?",
answers = listOf("all of these", "tools", "documentation", "libraries"),
key = "all of these"
),
Question(
text = "Base class for Layout?",
answers = listOf("ViewGroup", "ViewSet", "ViewCollection", "ViewRoot"),
key = "ViewGroup"
),
Question(
text = "Layout for complex Screens?",
answers = listOf("ConstraintLayout", "GridLayout", "LinearLayout", "FrameLayout"),
key = "ConstraintLayout"
),
Question(
text = "Pushing structured data into a Layout?",
answers = listOf("Data Binding", "Data Pushing", "Set Text", "OnClick"),
key = "Data Binding"
),
Question(
text = "Inflate layout in fragments?",
answers = listOf("onCreateView", "onViewCreated", "onCreateLayout", "onInflateLayout"),
key = "onCreateView"
),
Question(
text = "Build system for Android?",
answers = listOf("Gradle", "Graddle", "Grodle", "Groyle"),
key = "Gradle"
),
Question(
text = "Android vector format?",
answers = listOf(
"VectorDrawable",
"AndroidVectorDrawable",
"DrawableVector",
"AndroidVector"
),
key = "VectorDrawable"
),
Question(
text = "Android Navigation Component?",
answers = listOf("NavController", "NavCentral", "NavMaster", "NavSwitcher"),
key = "NavController"
),
Question(
text = "Registers app with launcher?",
answers = listOf("intent-filter", "app-registry", "launcher-registry", "app-launcher"),
key = "intent-filter"
),
Question(
text = "Mark a layout for Data Binding?",
answers = listOf("<layout>", "<binding>", "<data-binding>", "<dbinding>"),
key = "<layout>"
)
)
enum class FinalDestination {
GameWon,
GameOver,
None
}
class GameScreenViewModel : ViewModel() {
private var _currentQuizIndex by mutableStateOf(0)
private var _listOfIndex = mutableListOf<Int>()
private var transitionGoal by mutableStateOf(FinalDestination.None)
private var numOfQuiz = 0
private var numOfCorrect = 0;
init {
reset()
}
fun getQuiz(): Question {
return questions[_currentQuizIndex]
}
fun submitAnswer(answer: String, question: Question) {
if (answer == question.key) {
correctedAnswer()
} else {
gameOver()
}
}
private fun correctedAnswer() {
// increase num of correct
++numOfCorrect
when {
(numOfQuiz > 1) -> {
// update remain list and next question index
_listOfIndex.remove(_currentQuizIndex)
_listOfIndex.apply { shuffle() }
_currentQuizIndex = _listOfIndex[0]
}
else -> {
gameWon()
}
}
// decrease remaining quiz
--numOfQuiz
}
fun getTotalQuiz() = questions.size
fun reset() {
questions.forEach() { item ->
_listOfIndex.add(questions.indexOf(item))
}
numOfQuiz = getTotalQuiz()
numOfCorrect = 0
transitionGoal = FinalDestination.None
}
fun getDestination() = transitionGoal
fun getNumOfCorrect() = numOfCorrect
private fun gameWon() {
transitionGoal = FinalDestination.GameWon
}
private fun gameOver() {
transitionGoal = FinalDestination.GameOver
}
}
| 0
|
Kotlin
|
0
| 0
|
f35eee212632fbc409866679306167c60f2e031d
| 3,940
|
jetpack-compose-triviva
|
Apache License 2.0
|
app/src/main/java/com/w2solo/android/ui/webview/WebViewFragment.kt
|
w2solo
| 330,132,683
| false
| null |
package com.w2solo.android.ui.webview
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import android.widget.ProgressBar
import android.widget.Toast
import com.w2solo.android.R
import com.w2solo.android.ui.base.fragment.BaseFragment
import com.w2solo.android.utils.AppLog
import com.w2solo.android.utils.FunctionUtils
/**
* Created by github.com/litang0908 on 1/8/16.
*/
class WebViewFragment : BaseFragment() {
var webView: WebView? = null
var progressBar: ProgressBar? = null
override fun getLayout() = R.layout.frag_webview
override fun initViews() {
webView = fview(R.id.webview)
progressBar = fview(R.id.webview_progress)
initWebView()
}
private fun initWebView() {
val settings = webView!!.settings
if (settings != null) {
settings.javaScriptEnabled = true
//兼容 https页面的http地址图片无法下载的问题
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
}
// settings.setUseWideViewPort(true);//加上此句会导致 web页面无法自适应 移动端
// settings.setSupportMultipleWindows(true);
settings.loadWithOverviewMode = true
settings.blockNetworkImage = false
settings.domStorageEnabled = true //不加载此句,部分网页不展示图片 比如一点资讯
//设置UA
val userAgent = settings.userAgentString + getWebUserAgent()
settings.userAgentString = userAgent
if (AppLog.isEnabled()) {
AppLog.d(TAG, "UserAgent=$userAgent")
}
}
WebView.setWebContentsDebuggingEnabled(AppLog.isEnabled())
webView!!.setWebChromeClient(object : WebChromeClient() {
override fun onProgressChanged(
view: WebView,
newProgress: Int
) {
super.onProgressChanged(view, newProgress)
progressBar!!.progress = newProgress
progressBar!!.visibility = View.VISIBLE
if (newProgress >= 95) {
progressBar!!.visibility = View.INVISIBLE
}
if (onWebListener != null) {
onWebListener!!.onProgressChanged(view, newProgress)
}
}
override fun onReceivedTitle(
view: WebView,
title: String
) {
super.onReceivedTitle(view, title)
AppLog.d(TAG, "tang----onReceivedTitle $title")
if (onWebListener != null) {
onWebListener!!.onReceivedTitle(view, title)
}
}
})
webView!!.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, urlStr: String): Boolean {
AppLog.d(TAG, "tang---shouldOverrideUrlLoading $urlStr")
//如果可以处理,则返回false
return loadUrl(urlStr)
}
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
super.onPageStarted(view, url, favicon)
AppLog.d(TAG, "tang-----onPageStarted $url")
}
override fun onPageFinished(view: WebView, url: String) {
AppLog.d(
"WebViewFragment",
"tang----onPageFinished 111 " + url + " " + webView!!.url
)
super.onPageFinished(view, url)
AppLog.d(
"WebViewFragment",
"tang----onPageFinished 222 " + url + " " + webView!!.url
)
// addImageClickListener();
}
override fun onReceivedError(
view: WebView,
request: WebResourceRequest,
error: WebResourceError
) {
super.onReceivedError(view, request, error)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AppLog.d(
"WebViewFragment",
"tang----onReceivedError " + error.errorCode + " " + error.description
)
}
if (onWebListener != null) {
onWebListener!!.onReceivedError(view, request, error)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//部分翻墙的梯子,直接不显示错误信息
// if (!needTizi(request.getUrl().toString())) {
// onPageError(view.getUrl());
// }
} else {
// onPageError(view.getUrl());
}
}
}
webView!!.setDownloadListener { url: String, _: String?, _: String?, _: String?, _: Long ->
AppLog.d(TAG, "onDownloadStart 下载文件 $url")
if (canDownload()) {
try {
val uri = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, uri)
startActivity(intent)
} catch (thr: Throwable) {
thr.printStackTrace()
}
} else {
Toast.makeText(context, "不能下载文件", Toast.LENGTH_SHORT).show()
}
}
}
fun getWebUserAgent() = ";w2soloand=w2solo"
private fun canDownload() = true
private fun validateUrl(urlStr: String): Boolean {
return if (TextUtils.isEmpty(urlStr)) {
false
} else urlStr.startsWith("http://")
|| urlStr.startsWith("https://")
|| urlStr.startsWith("ftp://")
}
private fun validateSchema(urlString: String): Boolean {
return urlString.startsWith("sinaweibo://") ||
urlString.startsWith("market://")
}
/**
* 是否进行拦截处理 如果为true,则使用 Jsoup 拦截内容
*
* @param urlStr
*/
fun loadUrl(urlStr: String): Boolean {
var urlStr = urlStr
AppLog.d(TAG, "tang----loadUrl $urlStr")
if (webView == null || TextUtils.isEmpty(urlStr)) {
return false
}
//固定Scheme,则打开微博
if (validateSchema(urlStr)) {
if (!FunctionUtils.openScheme(context, urlStr)) {
}
//means stop webview to process this urlStr
return true
}
if (!validateUrl(urlStr)) {
AppLog.e(TAG, "tang----loadUrl() 非法Url 不加载")
return false
}
AppLog.d(TAG, "tang------不拦截处理 $urlStr")
webView!!.loadUrl(urlStr)
return true
}
val url: String get() = if (webView != null) webView!!.url else ""
fun canGoback(): Boolean {
return webView != null && webView!!.canGoBack() && !TextUtils.equals(
webView!!.url,
"about:blank"
)
}
fun goBack(): Boolean {
if (webView != null) {
webView!!.goBack()
return true
}
return false
}
fun scrollTo(x: Int, y: Int) {
webView!!.scrollTo(x, y)
}
/**
* 正确的WebView释放内存
*/
private fun release() {
if (webView != null) {
webView!!.removeAllViews()
if (webView!!.parent != null) {
val group = webView!!.parent as ViewGroup
group.removeView(webView)
}
webView!!.destroy()
webView = null
}
}
override fun onDestroy() {
super.onDestroy()
release()
}
private var onWebListener: OnWebListener? = null
fun setOnWebListener(onWebListener: OnWebListener?) {
this.onWebListener = onWebListener
}
open class OnWebListener {
fun onProgressChanged(view: WebView?, newProgress: Int) {}
open fun onReceivedTitle(
view: WebView?,
title: String?
) {
}
fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
}
}
companion object {
private val TAG = WebViewFragment::class.java.simpleName
}
}
| 1
|
Kotlin
|
1
| 11
|
791040ba585d8d5952474ee664a5c9a988038dfa
| 8,484
|
dreamland-android
|
MIT License
|
blockchain-development-kit/accelerators/corda/cordapps/chat/cordapp/src/main/kotlin/net/corda/workbench/chat/flow/workbench/FSMCurrentStateFlow.kt
|
corda
| 158,275,332
| true
|
{"HTML": 3979585, "Python": 1081109, "Java": 880816, "Kotlin": 599568, "C#": 491991, "JavaScript": 161542, "PowerShell": 94018, "CSS": 48236, "Shell": 17585, "PLpgSQL": 16377, "Batchfile": 8685, "Dockerfile": 4248, "Scala": 840, "ASP": 105}
|
package net.corda.workbench.chat.flow.workbench
import co.paralleluniverse.fibers.Suspendable
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.flows.FlowLogic
import net.corda.core.flows.InitiatingFlow
import net.corda.core.flows.StartableByRPC
import net.corda.core.node.services.queryBy
import net.corda.core.node.services.vault.QueryCriteria
import net.corda.reflections.annotations.Description
import net.corda.reflections.annotations.fsm.FSMCurrentState
import net.corda.workbench.chat.Message
@InitiatingFlow
@StartableByRPC
@Description("The current FSM state")
@FSMCurrentState
class FSMCurrentStateFlow(private val linearId: UniqueIdentifier) : FlowLogic<String>() {
@Suspendable
override fun call(): String {
// Retrieve the shipment from the vault.
val queryCriteria = QueryCriteria.LinearStateQueryCriteria(linearId = listOf(linearId))
val items = serviceHub.vaultService.queryBy<Message>(queryCriteria).states
return if (items.isEmpty()) {
"NotStarted"
} else {
if (items.single().state.data.message.equals("bye", ignoreCase = true)) {
States.Completed.name
} else {
States.Chatting.name
}
}
}
}
| 0
|
HTML
|
1
| 0
|
c8686c9d1be88750522cd775c52d36fd9f489b62
| 1,276
|
blockchain
|
MIT License
|
app/src/main/java/com/mjrt/app/allebooks/ui/reading/ReadingFragment.kt
|
gabrielmjr
| 792,882,049
| false
|
{"Kotlin": 18470, "Java": 2045}
|
package com.mjrt.app.allebooks.ui.reading
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.mjrt.app.allebooks.databinding.FragmentReadingBinding
class ReadingFragment : Fragment() {
private var _binding: FragmentReadingBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val readingViewModel =
ViewModelProvider(this).get(ReadingViewModel::class.java)
_binding = FragmentReadingBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textReading
readingViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 2
|
099fbe04bc6dcf9cc57010482e24f32e7150e397
| 1,201
|
AllEBooks
|
Apache License 2.0
|
src/main/kotlin/br/com/lucascm/mangaeasy/micro_api_monolito/features/achievements/controllers/AchievementsController.kt
|
manga-easy
| 627,169,031
| false
|
{"Kotlin": 232817, "Dockerfile": 130}
|
package br.com.lucascm.mangaeasy.micro_api_monolito.features.achievements.controllers
import br.com.lucascm.mangaeasy.micro_api_monolito.core.entities.BusinessException
import br.com.lucascm.mangaeasy.micro_api_monolito.core.entities.UserAuth
import br.com.lucascm.mangaeasy.micro_api_monolito.core.service.HandlerPermissionUser
import br.com.lucascm.mangaeasy.micro_api_monolito.features.achievements.entities.AchievementsEntity
import br.com.lucascm.mangaeasy.micro_api_monolito.features.achievements.entities.CreateAchievementsDto
import br.com.lucascm.mangaeasy.micro_api_monolito.features.achievements.repositories.AchievementsRepository
import br.com.lucascm.mangaeasy.micro_api_monolito.features.achievements.repositories.BucketAchievementsRepository
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Sort
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.util.*
import kotlin.jvm.optionals.getOrNull
@RestController
@RequestMapping("/achievements")
@Tag(name = "Achievements")
class AchievementsController {
@Autowired
lateinit var achievementsRepository: AchievementsRepository
@Autowired
lateinit var bucketAchievementsRepository: BucketAchievementsRepository
@Autowired
lateinit var handlerPermissionUser: HandlerPermissionUser
@GetMapping("/v1")
fun list(@RequestParam available: Boolean?): List<AchievementsEntity> {
return achievementsRepository.findAll(
Sort.by(
Sort.Direction.DESC,
AchievementsEntity::updatedAt.name
)
)
}
@GetMapping("/v1/users/{userId}")
fun listByUser(@PathVariable userId: String): List<AchievementsEntity> {
return achievementsRepository.findByUser(userId)
}
@GetMapping("/v1/{id}")
fun getOne(@PathVariable id: String): AchievementsEntity {
return achievementsRepository.findById(id).getOrNull()
?: throw BusinessException("Emblema não encontrado")
}
@PostMapping("/v1")
fun create(
@RequestBody body: CreateAchievementsDto,
@AuthenticationPrincipal userAuth: UserAuth
): AchievementsEntity {
handlerPermissionUser.handleIsAdmin(userAuth)
body.handlerValidateEntity()
return achievementsRepository.save(
AchievementsEntity(
createdAt = Date().time,
updatedAt = Date().time,
name = body.name,
benefits = body.benefits,
category = body.category,
description = body.description,
percentRarity = 0.0,
rarity = body.rarity,
reclaim = body.reclaim,
totalAcquired = 0
)
)
}
@PutMapping("/v1/{id}")
fun update(
@RequestBody body: CreateAchievementsDto,
@AuthenticationPrincipal userAuth: UserAuth,
@PathVariable id: String,
): AchievementsEntity {
handlerPermissionUser.handleIsAdmin(userAuth)
body.handlerValidateEntity()
val resultFind = achievementsRepository.findById(id).getOrNull()
?: throw BusinessException("Emblema não encontrado")
return achievementsRepository.save(
resultFind.copy(
updatedAt = Date().time,
name = body.name,
benefits = body.benefits,
category = body.category,
description = body.description,
reclaim = body.reclaim,
rarity = body.rarity
)
)
}
@PutMapping("/v1/{id}/image")
fun uploadImage(
@RequestPart file: MultipartFile,
@PathVariable id: String,
@AuthenticationPrincipal userAuth: UserAuth
): AchievementsEntity {
handlerPermissionUser.handleIsAdmin(userAuth)
val find: AchievementsEntity = achievementsRepository.findById(id).getOrNull()
?: throw BusinessException("Emblema não encontrado")
bucketAchievementsRepository.saveImage(id, file, file.contentType!!)
val imageResult = bucketAchievementsRepository.getLinkImage(id)
return achievementsRepository.save(find.copy(url = imageResult, updatedAt = Date().time))
}
}
| 0
|
Kotlin
|
1
| 3
|
f5118df03be9f689620733999c5aae2de6bf75be
| 4,461
|
manga_easy_micro_api_monolito
|
MIT License
|
raw-assets/src/main/java/me/thierrylee/fe3hdb/assets/model/transformer/MagicRequirementAssetTransformer.kt
|
thierrylee
| 201,639,277
| false
| null |
package me.thierrylee.fe3hdb.assets.model.transformer
import me.thierrylee.fe3hdb.assets.model.MagicRequirementAsset
internal object MagicRequirementAssetTransformer : AbstractAssetTransformer<MagicRequirementAsset>() {
override fun getAssetFile() = "magic_req_personallearn"
override fun getColumnCount() = 4
override fun internalBuildAsset(rawValues: List<String>) = MagicRequirementAsset(
magicId = rawValues[0].toId(),
requiredSkill = rawValues[1].toSkillAsset(),
requiredRank = rawValues[2].toRankAsset(),
characterIds = rawValues[3].split().map { it.toId() }
)
}
| 0
|
Kotlin
|
0
| 4
|
22583d1c4cec0a37c671c51a69587cd99ee91540
| 621
|
FE3H-AssetsDB
|
MIT License
|
app/src/main/java/oliveira/br/consultacepmvvm/di/annotations/ForApplication.kt
|
oliveiradev27
| 165,511,274
| false
| null |
package oliveira.br.consultacepmvvm.di.annotations
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ForApplication
| 0
|
Kotlin
|
0
| 0
|
f7be19eac57bfa42cc564533b4c94ec26e2568e3
| 165
|
Consulta-CEP-MVVM-AAC
|
MIT License
|
platform/statistics/src/com/intellij/internal/statistic/utils/PluginInfoDetector.kt
|
hieuprogrammer
| 284,920,751
| false
| 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 com.intellij.internal.statistic.utils
import com.intellij.ide.plugins.PluginInfoProvider
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.internal.statistic.utils.PluginInfoDetector.isPluginFromOfficialJbPluginRepo
import com.intellij.internal.statistic.utils.PluginInfoDetector.isSafeToReportFrom
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.Getter
import com.intellij.openapi.util.TimeoutCachedValue
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository,
* so API from it may be reported
*/
fun getPluginInfo(clazz: Class<*>): PluginInfo {
val classLoader = clazz.classLoader
return when {
classLoader is PluginClassLoader -> {
getPluginInfoByDescriptor(classLoader.pluginDescriptor ?: return unknownPlugin)
}
PluginManagerCore.isRunningFromSources() && !PluginManagerCore.isUnitTestMode -> {
builtFromSources
}
else -> {
getPluginInfo(clazz.name)
}
}
}
fun getPluginInfo(className: String): PluginInfo {
if (className.startsWith("java.") || className.startsWith("javax.") ||
className.startsWith("kotlin.") || className.startsWith("groovy.")) {
return platformPlugin
}
val plugin = PluginManagerCore.getPluginDescriptorOrPlatformByClassName(className) ?: return unknownPlugin
return getPluginInfoByDescriptor(plugin)
}
/**
* Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository,
* so API from it may be reported.
*
* Use only if you don't have [PluginDescriptor].
*/
fun getPluginInfoById(pluginId: PluginId?): PluginInfo {
if (pluginId == null) {
return unknownPlugin
}
val plugin = PluginManagerCore.getPlugin(pluginId)
@Suppress("FoldInitializerAndIfToElvis")
if (plugin == null) {
// we can't load plugin descriptor for a not installed plugin but we can check if it's from JB repo
return if (isPluginFromOfficialJbPluginRepo(pluginId)) PluginInfo(PluginType.LISTED, pluginId.idString, null) else unknownPlugin
}
return getPluginInfoByDescriptor(plugin)
}
/**
* Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository,
* so API from it may be reported
*/
fun getPluginInfoByDescriptor(plugin: PluginDescriptor): PluginInfo {
if (PluginManagerCore.CORE_ID == plugin.pluginId) {
return platformPlugin
}
val id = plugin.pluginId.idString
val version = plugin.version
if (PluginManager.getInstance().isDevelopedByJetBrains(plugin)) {
val pluginType = when {
plugin.isBundled -> PluginType.JB_BUNDLED
PluginManagerCore.isUpdatedBundledPlugin(plugin) -> PluginType.JB_UPDATED_BUNDLED
else -> PluginType.JB_NOT_BUNDLED
}
return PluginInfo(pluginType, id, version)
}
// only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance -
// they are also considered bundled) would be reported
val listed = !plugin.isBundled && !PluginManagerCore.isUpdatedBundledPlugin(plugin) && isSafeToReportFrom(plugin)
return if (listed) PluginInfo(PluginType.LISTED, id, version) else notListedPlugin
}
enum class PluginType {
PLATFORM, JB_BUNDLED, JB_NOT_BUNDLED, LISTED, NOT_LISTED, UNKNOWN, FROM_SOURCES, JB_UPDATED_BUNDLED;
private fun isPlatformOrJBBundled(): Boolean {
return this == PLATFORM || this == JB_BUNDLED || this == FROM_SOURCES || this == JB_UPDATED_BUNDLED
}
fun isDevelopedByJetBrains(): Boolean {
return isPlatformOrJBBundled() || this == JB_NOT_BUNDLED
}
fun isSafeToReport(): Boolean {
return isDevelopedByJetBrains() || this == LISTED
}
}
fun findPluginTypeByValue(value: String): PluginType? {
for (type in PluginType.values()) {
if (type.name == value) {
return type
}
}
return null
}
data class PluginInfo(val type: PluginType, val id: String?, val version: String?) {
/**
* @return true if code is from IntelliJ platform or JB plugin.
*/
fun isDevelopedByJetBrains(): Boolean {
return type.isDevelopedByJetBrains()
}
/**
* @return true if code is from IntelliJ platform, JB plugin or plugin from JB plugin repository.
*/
fun isSafeToReport(): Boolean {
return type.isSafeToReport()
}
}
val platformPlugin: PluginInfo = PluginInfo(PluginType.PLATFORM, null, null)
val unknownPlugin: PluginInfo = PluginInfo(PluginType.UNKNOWN, null, null)
val notListedPlugin: PluginInfo = PluginInfo(PluginType.NOT_LISTED, null, null)
// Mock plugin info used when we can't detect plugin by class loader because IDE is built from sources
val builtFromSources: PluginInfo = PluginInfo(PluginType.FROM_SOURCES, null, null)
object PluginInfoDetector {
private val pluginIdsFromOfficialJbPluginRepo: Getter<Set<PluginId>> = TimeoutCachedValue(1, TimeUnit.HOURS) {
// before loading default repository plugins lets check it's not changed, and is really official JetBrains repository
try {
val cached = getPluginInfoProvider()?.loadCachedPlugins()
if (cached != null) {
return@TimeoutCachedValue cached.toSet()
}
}
catch (ignored: IOException) {
}
// schedule plugins loading, will take them the next time
ApplicationManager.getApplication().executeOnPooledThread {
try {
getPluginInfoProvider()?.loadPlugins(null) ?: emptySet<PluginId>()
}
catch (ignored: IOException) {
}
}
//report nothing until repo plugins loaded
emptySet<PluginId>()
}
private fun getPluginInfoProvider(): PluginInfoProvider? {
return ApplicationManager.getApplication()?.let { ServiceManager.getService(PluginInfoProvider::class.java) }
}
/**
* Checks this plugin is created by JetBrains or from official repository, so API from it may be reported
*/
internal fun isSafeToReportFrom(descriptor: PluginDescriptor): Boolean {
if (PluginManager.getInstance().isDevelopedByJetBrains(descriptor)) {
return true
}
else if (descriptor.isBundled) {
// bundled, but not from JetBrains, so, some custom unknown plugin
return false
}
// only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance -
// they are also considered bundled) would be reported
val pluginId = descriptor.pluginId ?: return false
return isPluginFromOfficialJbPluginRepo(pluginId)
}
internal fun isPluginFromOfficialJbPluginRepo(pluginId: PluginId?): Boolean {
return getPluginIdsFromJbPluginRepository().contains(pluginId)
}
private fun getPluginIdsFromJbPluginRepository(): Set<PluginId> {
// not official JetBrains repository - is used, so, not safe to report
if (!ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
return emptySet()
}
// if in official JetBrains repository, then it is safe to report
return pluginIdsFromOfficialJbPluginRepo.get()
}
}
| 1
| null |
1
| 2
|
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 7,611
|
intellij-community
|
Apache License 2.0
|
ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/providers/BasicAuthProvider.kt
|
danbrough
| 527,165,659
| false
| null |
/*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.plugins.auth.providers
import io.ktor.client.plugins.auth.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.auth.*
import io.ktor.util.*
import io.ktor.utils.io.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
/**
* Installs the client's [BasicAuthProvider].
*/
@KtorDsl
public fun AuthConfig.basic(block: BasicAuthConfig.() -> Unit) {
with(BasicAuthConfig().apply(block)) {
this@basic.providers.add(BasicAuthProvider(_credentials, realm, _sendWithoutRequest))
}
}
/**
* A configuration for [BasicAuthProvider].
*/
@KtorDsl
public class BasicAuthConfig {
/**
* Required: The username of the basic auth.
*/
@Deprecated("Please use `credentials {}` function instead", level = DeprecationLevel.ERROR)
public lateinit var username: String
/**
* Required: The password of the basic auth.
*/
@Deprecated("Please use `credentials {}` function instead", level = DeprecationLevel.ERROR)
public lateinit var password: String
/**
* Send credentials in without waiting for [HttpStatusCode.Unauthorized].
*/
@Deprecated("Please use `sendWithoutRequest {}` function instead", level = DeprecationLevel.ERROR)
public var sendWithoutRequest: Boolean = false
/**
* (Optional) Specifies the realm of the current provider.
*/
public var realm: String? = null
@Suppress("DEPRECATION_ERROR")
internal var _sendWithoutRequest: (HttpRequestBuilder) -> Boolean = { sendWithoutRequest }
@Suppress("DEPRECATION_ERROR")
internal var _credentials: suspend () -> BasicAuthCredentials? = {
BasicAuthCredentials(username = username, password = password)
}
/**
* Sends credentials without waiting for [HttpStatusCode.Unauthorized].
*/
public fun sendWithoutRequest(block: (HttpRequestBuilder) -> Boolean) {
_sendWithoutRequest = block
}
/**
* Allows you to specify authentication credentials.
*/
public fun credentials(block: suspend () -> BasicAuthCredentials?) {
_credentials = block
}
}
/**
* Contains credentials for [BasicAuthProvider].
*/
public class BasicAuthCredentials(
public val username: String,
public val password: String
)
/**
* An authentication provider for the Basic HTTP authentication scheme.
* The Basic authentication scheme can be used for logging in users.
*
* You can learn more from [Basic authentication](https://ktor.io/docs/basic-client.html).
*/
public class BasicAuthProvider(
private val credentials: suspend () -> BasicAuthCredentials?,
private val realm: String? = null,
private val sendWithoutRequestCallback: (HttpRequestBuilder) -> Boolean = { false }
) : AuthProvider {
@Deprecated("Consider using constructor with credentials provider instead", level = DeprecationLevel.ERROR)
public constructor(
username: String,
password: String,
realm: String? = null,
sendWithoutRequest: Boolean = false
) : this(
credentials = { BasicAuthCredentials(username, password) },
realm = realm,
sendWithoutRequestCallback = { sendWithoutRequest }
)
private val tokensHolder = AuthTokenHolder(credentials)
@Suppress("OverridingDeprecatedMember")
@Deprecated("Please use sendWithoutRequest function instead", level = DeprecationLevel.ERROR)
override val sendWithoutRequest: Boolean
get() = error("Deprecated")
override fun sendWithoutRequest(request: HttpRequestBuilder): Boolean = sendWithoutRequestCallback(request)
override fun isApplicable(auth: HttpAuthHeader): Boolean {
if (!AuthScheme.Basic.equals(auth.authScheme, ignoreCase = true)) {
LOGGER.trace("Basic Auth Provider is not applicable for $auth")
return false
}
val isSameRealm = when {
realm == null -> true
auth !is HttpAuthHeader.Parameterized -> false
else -> auth.parameter("realm") == realm
}
if (!isSameRealm) {
LOGGER.trace("Basic Auth Provider is not applicable for this realm")
}
return isSameRealm
}
override suspend fun addRequestHeaders(request: HttpRequestBuilder, authHeader: HttpAuthHeader?) {
val credentials = tokensHolder.loadToken() ?: return
request.headers[HttpHeaders.Authorization] = constructBasicAuthValue(credentials)
}
override suspend fun refreshToken(response: HttpResponse): Boolean {
tokensHolder.setToken(credentials)
return true
}
}
internal fun constructBasicAuthValue(credentials: BasicAuthCredentials): String {
val authString = "${credentials.username}:${credentials.password}"
val authBuf = authString.toByteArray(Charsets.UTF_8).encodeBase64()
return "Basic $authBuf"
}
| 5
| null |
962
| 2
|
f6f34582a36ee2f950ea672c4908498680cc24b2
| 5,026
|
ktor
|
Apache License 2.0
|
src/commonTest/kotlin/MenuSceneTest.kt
|
EternalJourneyman1
| 434,406,296
| false
|
{"Kotlin": 7160, "Shell": 1210}
|
import com.soywiz.korge.tests.ViewsForTesting
import kotlin.test.Test
class MenuSceneTest : ViewsForTesting() {
@Test
fun `menuScreen`() = sceneTest<MenuScene> {
val log = listOf<String>()
}
}
| 0
|
Kotlin
|
0
| 0
|
9e8fbc457ddef88f1282a011cdd62e3252b84595
| 219
|
korge-game
|
MIT License
|
app/src/main/java/com/fourteenrows/p2pcs/services/RequesConfermationtListener.kt
|
FourteenRows
| 185,977,617
| false
| null |
package com.fourteenrows.p2pcs.services
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import com.fourteenrows.p2pcs.R
import com.fourteenrows.p2pcs.activities.reservation.ReservationActivity
import com.fourteenrows.p2pcs.model.database.ModelFirebase
import com.fourteenrows.p2pcs.model.utility.ModelDates
import com.google.firebase.Timestamp
import com.google.firebase.firestore.FirebaseFirestore
import java.util.*
class RequesConfermationtListener(private val context: Context) {
private val appContext = context.applicationContext
fun initalize() {
FirebaseFirestore.getInstance()
.collection("Requests")
.addSnapshotListener { querySnapshot, _ ->
if (!querySnapshot!!.metadata.isFromCache) {
querySnapshot.documents.forEach { req ->
if (req != null && req["applicant"] as String == ModelFirebase().getUid()!!) {
FirebaseFirestore.getInstance()
.collection("Requests")
.document(req.id)
.addSnapshotListener { documentSnapshot, _ ->
if (documentSnapshot != null && documentSnapshot["accepted"] != null) {
notifyRequestPermission(
documentSnapshot["accepted"] as Boolean,
documentSnapshot["model"] as String,
ModelDates.toLocaleTimeFormat((documentSnapshot["startDate"] as Timestamp).toDate()),
ModelDates.toTinyTimeSpanFormat(
Date(
(documentSnapshot["startDate"] as Timestamp).toDate().time -
(documentSnapshot["endDate"] as Timestamp).toDate().time
)
)
)
ModelFirebase().removeRequest(req.id)
}
}
}
}
}
}
}
private fun notifyRequestPermission(result: Boolean, model: String, date: String, timeSlot: String) {
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val bigText = NotificationCompat.BigTextStyle()
if (result) {
bigText.setSummaryText("Prenotazione confermata")
bigText.setBigContentTitle("Richiesta di prenotazione accettata")
} else {
bigText.setSummaryText("Prenotazione rigettata")
bigText.setBigContentTitle("Richiesta di prenotazione rifiutata")
}
val intent = Intent(appContext, ReservationActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
val mBuilder = NotificationCompat.Builder(appContext, "notify_001")
.setStyle(bigText)
.setContentText("Modello: $model \nIl $date\nSlot: $timeSlot")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setPriority(Notification.PRIORITY_HIGH)
.setVibrate(longArrayOf(500, 0, 500, 500))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
if (Build.VERSION.SDK_INT >= 26) {
val channelId = "Your_channel_id"
val channel = NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH
)
mNotificationManager.createNotificationChannel(channel)
mBuilder.setChannelId(channelId)
}
mNotificationManager.notify(0, mBuilder.build())
}
}
| 0
|
Kotlin
|
0
| 0
|
b88364cb6775aa24ef005845943d1086a7f76bbe
| 4,359
|
P2PCS
|
MIT License
|
core/src/main/kotlin/net/corda/flows/FetchDataFlow.kt
|
evisoft
| 75,185,334
| false
| null |
package net.corda.flows
import co.paralleluniverse.fibers.Suspendable
import net.corda.core.contracts.NamedByHash
import net.corda.core.crypto.Party
import net.corda.core.crypto.SecureHash
import net.corda.core.flows.FlowLogic
import net.corda.core.utilities.UntrustworthyData
import net.corda.flows.FetchDataFlow.DownloadedVsRequestedDataMismatch
import net.corda.flows.FetchDataFlow.HashNotFound
import java.util.*
/**
* An abstract flow for fetching typed data from a remote peer.
*
* Given a set of hashes (IDs), either loads them from local disk or asks the remote peer to provide them.
*
* A malicious response in which the data provided by the remote peer does not hash to the requested hash results in
* [DownloadedVsRequestedDataMismatch] being thrown. If the remote peer doesn't have an entry, it results in a
* [HashNotFound] exception being thrown.
*
* By default this class does not insert data into any local database, if you want to do that after missing items were
* fetched then override [maybeWriteToDisk]. You *must* override [load]. If the wire type is not the same as the
* ultimate type, you must also override [convert].
*
* @param T The ultimate type of the data being fetched.
* @param W The wire type of the data being fetched, for when it isn't the same as the ultimate type.
*/
abstract class FetchDataFlow<T : NamedByHash, in W : Any>(
protected val requests: Set<SecureHash>,
protected val otherSide: Party) : FlowLogic<FetchDataFlow.Result<T>>() {
open class BadAnswer : Exception()
class HashNotFound(val requested: SecureHash) : BadAnswer()
class DownloadedVsRequestedDataMismatch(val requested: SecureHash, val got: SecureHash) : BadAnswer()
data class Request(val hashes: List<SecureHash>)
data class Result<out T : NamedByHash>(val fromDisk: List<T>, val downloaded: List<T>)
@Suspendable
override fun call(): Result<T> {
// Load the items we have from disk and figure out which we're missing.
val (fromDisk, toFetch) = loadWhatWeHave()
return if (toFetch.isEmpty()) {
Result(fromDisk, emptyList())
} else {
logger.trace("Requesting ${toFetch.size} dependency(s) for verification")
// TODO: Support "large message" response streaming so response sizes are not limited by RAM.
val maybeItems = sendAndReceive<ArrayList<W?>>(otherSide, Request(toFetch))
// Check for a buggy/malicious peer answering with something that we didn't ask for.
val downloaded = validateFetchResponse(maybeItems, toFetch)
maybeWriteToDisk(downloaded)
Result(fromDisk, downloaded)
}
}
protected open fun maybeWriteToDisk(downloaded: List<T>) {
// Do nothing by default.
}
private fun loadWhatWeHave(): Pair<List<T>, List<SecureHash>> {
val fromDisk = ArrayList<T>()
val toFetch = ArrayList<SecureHash>()
for (txid in requests) {
val stx = load(txid)
if (stx == null)
toFetch += txid
else
fromDisk += stx
}
return Pair(fromDisk, toFetch)
}
protected abstract fun load(txid: SecureHash): T?
@Suppress("UNCHECKED_CAST")
protected open fun convert(wire: W): T = wire as T
private fun validateFetchResponse(maybeItems: UntrustworthyData<ArrayList<W?>>,
requests: List<SecureHash>): List<T> =
maybeItems.unwrap { response ->
if (response.size != requests.size)
throw BadAnswer()
for ((index, resp) in response.withIndex()) {
if (resp == null) throw HashNotFound(requests[index])
}
val answers = response.requireNoNulls().map { convert(it) }
// Check transactions actually hash to what we requested, if this fails the remote node
// is a malicious flow violator or buggy.
for ((index, item) in answers.withIndex())
if (item.id != requests[index])
throw DownloadedVsRequestedDataMismatch(requests[index], item.id)
answers
}
}
| 4
| null |
1
| 1
|
4a9f5cafc1f2f09e8f612a09f30f9dfffd985a6c
| 4,263
|
corda
|
Apache License 2.0
|
wear/watchface/watchface-editor/samples/src/main/java/androidx/wear/watchface/editor/sample/ConfigFragment.kt
|
JetBrains
| 351,708,598
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface.editor.sample
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.graphics.drawable.Icon
import android.graphics.drawable.LayerDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.wearable.watchface.Constants
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.recyclerview.widget.RecyclerView
import androidx.wear.watchface.complications.ComplicationDataSourceInfoRetriever
import androidx.wear.watchface.editor.samples.R
import androidx.wear.watchface.style.UserStyleSetting
import androidx.wear.widget.SwipeDismissFrameLayout
import androidx.wear.widget.WearableLinearLayoutManager
import androidx.wear.widget.WearableRecyclerView
import kotlinx.coroutines.launch
/**
* Lets the user select whether they want to select a complication to configure, configure a
* background complication or select an option from a user style setting. Should only be used if
* theres's at least two items from that list.
*
* Note hierarchical UserStyleSchemas are supported.
*/
internal class ConfigFragment : Fragment() {
private val watchFaceConfigActivity: WatchFaceConfigActivity
get() = activity as WatchFaceConfigActivity
/** Ids for the [androidx.wear.watchface.style.UserStyleSetting]s to select from. */
private lateinit var settingIds: java.util.ArrayList<String>
private lateinit var view: SwipeDismissFrameLayout
private lateinit var configViewAdapter: ConfigViewAdapter
companion object {
const val SETTINGS_ID = "SETTINGS_ID"
fun newInstance(
settingIds: ArrayList<String>
) = ConfigFragment().apply {
arguments = Bundle().apply {
this.putStringArrayList(SETTINGS_ID, settingIds)
}
}
}
private var lifecycleObserver = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_START) {
initConfigOptions()
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
lifecycle.addObserver(lifecycleObserver)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedState: Bundle?
): View {
settingIds = requireArguments().getStringArrayList(SETTINGS_ID)!!
view = inflater.inflate(R.layout.config_layout, container, false) as
SwipeDismissFrameLayout
view.addCallback(object : SwipeDismissFrameLayout.Callback() {
override fun onDismissed(layout: SwipeDismissFrameLayout) {
parentFragmentManager.popBackStackImmediate()
}
})
return view
}
private fun initConfigOptions() {
val editingSession = watchFaceConfigActivity.editorSession
val hasBackgroundComplication = editingSession.backgroundComplicationSlotId != null
val numComplications = editingSession.complicationSlotsState.value.size
val hasNonBackgroundComplication =
numComplications > if (hasBackgroundComplication) 1 else 0
val configOptions = ArrayList<ConfigOption>()
if (hasNonBackgroundComplication) {
configOptions.add(
ConfigOption(
id = Constants.KEY_COMPLICATIONS_SETTINGS,
icon = Icon.createWithResource(
context,
R.drawable.ic_elements_settings_complications
),
title = resources.getString(R.string.settings_complications),
summary = "",
highlight = false
)
)
}
if (hasBackgroundComplication) {
configOptions.add(createBackgroundConfigOption())
}
for (settingId in settingIds) {
val styleCategory = editingSession.userStyleSchema[UserStyleSetting.Id(settingId)]!!
configOptions.add(
ConfigOption(
id = styleCategory.id.value,
icon = styleCategory.watchFaceEditorData?.icon ?: styleCategory.icon,
title = styleCategory.displayName.toString(),
summary = styleCategory.description.toString(),
highlight = false
)
)
}
configViewAdapter = ConfigViewAdapter(
requireContext(),
configOptions,
this::onItemClick
)
view.findViewById<WearableRecyclerView>(R.id.configOptionsList).apply {
adapter = configViewAdapter
isEdgeItemsCenteringEnabled = true
layoutManager = WearableLinearLayoutManager(context)
}
lifecycle.removeObserver(lifecycleObserver)
}
private fun createBackgroundConfigOption(): ConfigOption {
// Initially assume there is no background image data source.
val backgroundConfigOption = ConfigOption(
id = Constants.KEY_BACKGROUND_IMAGE_SETTINGS,
icon = Icon.createWithResource(
context,
R.drawable.ic_elements_comps_bg
),
title = getResources().getString(R.string.settings_background_image),
summary = resources.getString(R.string.none_background_image_provider),
highlight = false
)
// Update the summary with the actual background complication data source name, if there is
// one.
watchFaceConfigActivity.coroutineScope.launch {
val dataSourceInfoRetriever =
ComplicationDataSourceInfoRetriever(activity as WatchFaceConfigActivity)
val infoArray = dataSourceInfoRetriever.retrieveComplicationDataSourceInfo(
watchFaceConfigActivity.editorSession.watchFaceComponentName,
intArrayOf(watchFaceConfigActivity.editorSession.backgroundComplicationSlotId!!)
)
infoArray?.let {
it[0].info?.apply {
backgroundConfigOption.summary = name
}
configViewAdapter.notifyDataSetChanged()
}
dataSourceInfoRetriever.close()
}
return backgroundConfigOption
}
override fun onDestroy() {
super.onDestroy()
}
private fun onItemClick(configOption: ConfigOption) {
val editingSession = watchFaceConfigActivity.editorSession
when (configOption.id) {
Constants.KEY_COMPLICATIONS_SETTINGS ->
watchFaceConfigActivity.fragmentController.showComplicationConfigSelectionFragment()
Constants.KEY_BACKGROUND_IMAGE_SETTINGS -> {
watchFaceConfigActivity.coroutineScope.launch {
watchFaceConfigActivity.fragmentController.showComplicationConfig(
editingSession.backgroundComplicationSlotId!!
)
}
}
else -> {
watchFaceConfigActivity.fragmentController.showStyleConfigFragment(
configOption.id,
editingSession.userStyleSchema,
editingSession.userStyle.value
)
}
}
}
}
internal data class ConfigOption(
val id: String,
val icon: Icon?,
val title: String,
var summary: String,
var highlight: Boolean
)
internal class ConfigViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var configOption: ConfigOption? = null
}
internal class Helper {
companion object {
/**
* Wraps a given [Drawable] with a standard background to match the normal preference icon
* styling. The wrapping is idempotent, calling it multiple times will only wrap the icon
* once.
*
* @param context the current [Context], used for resolving resources.
* @param icon the icon to wrap.
* @return the wrapped icon.
*/
fun wrapIcon(
context: Context,
icon: Drawable
): Drawable {
if (icon is LayerDrawable && icon.findDrawableByLayerId(R.id.nested_icon) != null) {
return icon // icon was already wrapped, return the icon without modifying it
}
val wrappedDrawable =
(context.getDrawable(R.drawable.preference_wrapped_icon) as LayerDrawable)
wrappedDrawable.setDrawableByLayerId(R.id.nested_icon, icon)
return wrappedDrawable
}
}
}
/** Adapter for top level config options. */
internal class ConfigViewAdapter(
private val context: Context,
private val configOptions: List<ConfigOption>,
val clickListener: (ConfigOption) -> Unit
) : RecyclerView.Adapter<ConfigViewHolder>() {
private val handler = Handler(Looper.getMainLooper())
fun clearAllHighlights() {
for (configOption in configOptions) {
configOption.highlight = false
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ConfigViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.configlist_item_layout,
parent,
false
)
).apply {
itemView.setOnClickListener { clickListener(configOption!!) }
}
override fun onBindViewHolder(holder: ConfigViewHolder, position: Int) {
val configOption = configOptions[position]
holder.configOption = configOption
val textView = holder.itemView as TextView
textView.setBackgroundColor(
if (configOption.highlight) Color.rgb(20, 40, 60) else Color.BLACK
)
textView.textSize = 16f
val builder = SpannableStringBuilder()
builder.append(configOption.title)
builder.setSpan(StyleSpan(Typeface.BOLD), 0, configOption.title.length, 0)
builder.append("\n")
builder.append(configOption.summary)
textView.text = builder
configOption.icon?.loadDrawableAsync(
context,
{ drawable ->
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(
Helper.wrapIcon(context, drawable),
/* top = */ null,
/* end = */ null,
/* bottom = */ null
)
},
handler
)
}
override fun getItemCount() = configOptions.size
}
| 29
| null |
16
| 59
|
3fbd775007164912b34a1d59a923ad3387028b97
| 11,472
|
androidx
|
Apache License 2.0
|
storage/src/main/java/com/shevelev/wizard_camera/storage/repositories/LastUsedFilterRepository.kt
|
AlShevelev
| 262,626,159
| false
| null |
package com.shevelev.wizard_camera.storage.repositories
import com.shevelev.wizard_camera.common_entities.entities.LastUsedFilter
interface LastUsedFilterRepository {
fun update(filter: LastUsedFilter)
fun remove(filter: LastUsedFilter)
fun read(): List<LastUsedFilter>
}
| 0
|
Kotlin
|
4
| 40
|
ca008839fb157bac0f9b914243ef2a9d7c6a72fa
| 287
|
WizardCamera
|
Apache License 2.0
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ecs/Cluster.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 137826907}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.ecs
import io.cloudshiftdev.awscdk.Resource
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.services.autoscaling.AutoScalingGroup
import io.cloudshiftdev.awscdk.services.autoscaling.IAutoScalingGroup
import io.cloudshiftdev.awscdk.services.cloudwatch.Metric
import io.cloudshiftdev.awscdk.services.cloudwatch.MetricOptions
import io.cloudshiftdev.awscdk.services.ec2.Connections
import io.cloudshiftdev.awscdk.services.ec2.IVpc
import io.cloudshiftdev.awscdk.services.iam.Grant
import io.cloudshiftdev.awscdk.services.iam.IGrantable
import io.cloudshiftdev.awscdk.services.servicediscovery.INamespace
import kotlin.Any
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* A regional grouping of one or more container instances on which you can run tasks and services.
*
* Example:
*
* ```
* IVpc vpc = Vpc.fromLookup(this, "Vpc", VpcLookupOptions.builder()
* .isDefault(true)
* .build());
* Cluster cluster = Cluster.Builder.create(this, "ECSCluster").vpc(vpc).build();
* TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TD")
* .compatibility(Compatibility.FARGATE)
* .cpu("256")
* .memoryMiB("512")
* .build();
* taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
* .image(ContainerImage.fromRegistry("foo/bar"))
* .build());
* EcsRunTask runTask = EcsRunTask.Builder.create(this, "Run")
* .integrationPattern(IntegrationPattern.RUN_JOB)
* .cluster(cluster)
* .taskDefinition(taskDefinition)
* .launchTarget(new EcsFargateLaunchTarget())
* .cpu("1024")
* .memoryMiB("1048")
* .build();
* ```
*/
public open class Cluster(
cdkObject: software.amazon.awscdk.services.ecs.Cluster,
) : Resource(cdkObject),
ICluster {
public constructor(scope: CloudshiftdevConstructsConstruct, id: String) :
this(software.amazon.awscdk.services.ecs.Cluster(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap),
id)
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: ClusterProps,
) :
this(software.amazon.awscdk.services.ecs.Cluster(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap),
id, props.let(ClusterProps.Companion::unwrap))
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: ClusterProps.Builder.() -> Unit,
) : this(scope, id, ClusterProps(props)
)
/**
* This method adds an Auto Scaling Group Capacity Provider to a cluster.
*
* @param provider the capacity provider to add to this cluster.
* @param options
*/
public open fun addAsgCapacityProvider(provider: AsgCapacityProvider) {
unwrap(this).addAsgCapacityProvider(provider.let(AsgCapacityProvider.Companion::unwrap))
}
/**
* This method adds an Auto Scaling Group Capacity Provider to a cluster.
*
* @param provider the capacity provider to add to this cluster.
* @param options
*/
public open fun addAsgCapacityProvider(provider: AsgCapacityProvider,
options: AddAutoScalingGroupCapacityOptions) {
unwrap(this).addAsgCapacityProvider(provider.let(AsgCapacityProvider.Companion::unwrap),
options.let(AddAutoScalingGroupCapacityOptions.Companion::unwrap))
}
/**
* This method adds an Auto Scaling Group Capacity Provider to a cluster.
*
* @param provider the capacity provider to add to this cluster.
* @param options
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("1c74a4478bede1d52015e9dc4bf676fe09fc1f0be1804838cfcf8e063da3af6d")
public open fun addAsgCapacityProvider(provider: AsgCapacityProvider,
options: AddAutoScalingGroupCapacityOptions.Builder.() -> Unit): Unit =
addAsgCapacityProvider(provider, AddAutoScalingGroupCapacityOptions(options))
/**
* It is highly recommended to use `Cluster.addAsgCapacityProvider` instead of this method.
*
* This method adds compute capacity to a cluster by creating an AutoScalingGroup with the
* specified options.
*
* Returns the AutoScalingGroup so you can add autoscaling settings to it.
*
* @param id
* @param options
*/
public open fun addCapacity(id: String, options: AddCapacityOptions): AutoScalingGroup =
unwrap(this).addCapacity(id,
options.let(AddCapacityOptions.Companion::unwrap)).let(AutoScalingGroup::wrap)
/**
* It is highly recommended to use `Cluster.addAsgCapacityProvider` instead of this method.
*
* This method adds compute capacity to a cluster by creating an AutoScalingGroup with the
* specified options.
*
* Returns the AutoScalingGroup so you can add autoscaling settings to it.
*
* @param id
* @param options
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("a2ea6c7c87f52c2eb69d478a48b59f7d56b2895a61e8468323013844476400cb")
public open fun addCapacity(id: String, options: AddCapacityOptions.Builder.() -> Unit):
AutoScalingGroup = addCapacity(id, AddCapacityOptions(options))
/**
* Add default capacity provider strategy for this cluster.
*
* @param defaultCapacityProviderStrategy cluster default capacity provider strategy. This takes
* the form of a list of CapacityProviderStrategy objects.
*/
public open
fun addDefaultCapacityProviderStrategy(defaultCapacityProviderStrategy: List<CapacityProviderStrategy>) {
unwrap(this).addDefaultCapacityProviderStrategy(defaultCapacityProviderStrategy.map(CapacityProviderStrategy.Companion::unwrap))
}
/**
* Add default capacity provider strategy for this cluster.
*
* @param defaultCapacityProviderStrategy cluster default capacity provider strategy. This takes
* the form of a list of CapacityProviderStrategy objects.
*/
public open fun addDefaultCapacityProviderStrategy(vararg
defaultCapacityProviderStrategy: CapacityProviderStrategy): Unit =
addDefaultCapacityProviderStrategy(defaultCapacityProviderStrategy.toList())
/**
* Add an AWS Cloud Map DNS namespace for this cluster.
*
* NOTE: HttpNamespaces are supported only for use cases involving Service Connect. For use cases
* involving both Service-
* Discovery and Service Connect, customers should manage the HttpNamespace outside of the
* Cluster.addDefaultCloudMapNamespace method.
*
* @param options
*/
public open fun addDefaultCloudMapNamespace(options: CloudMapNamespaceOptions): INamespace =
unwrap(this).addDefaultCloudMapNamespace(options.let(CloudMapNamespaceOptions.Companion::unwrap)).let(INamespace::wrap)
/**
* Add an AWS Cloud Map DNS namespace for this cluster.
*
* NOTE: HttpNamespaces are supported only for use cases involving Service Connect. For use cases
* involving both Service-
* Discovery and Service Connect, customers should manage the HttpNamespace outside of the
* Cluster.addDefaultCloudMapNamespace method.
*
* @param options
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("ed70f7db87ce0166be021e27b40ff2ea1c055a2bd9664c7d70a82227c473e981")
public open fun addDefaultCloudMapNamespace(options: CloudMapNamespaceOptions.Builder.() -> Unit):
INamespace = addDefaultCloudMapNamespace(CloudMapNamespaceOptions(options))
/**
* Returns an ARN that represents all tasks within the cluster that match the task pattern
* specified.
*
* To represent all tasks, specify `"*"`.
*
* @param keyPattern Task id pattern.
*/
public open fun arnForTasks(keyPattern: String): String = unwrap(this).arnForTasks(keyPattern)
/**
* Getter for autoscaling group added to cluster.
*/
public override fun autoscalingGroup(): IAutoScalingGroup? =
unwrap(this).getAutoscalingGroup()?.let(IAutoScalingGroup::wrap)
/**
* Getter for _capacityProviderNames added to cluster.
*/
public open fun capacityProviderNames(): List<String> = unwrap(this).getCapacityProviderNames()
/**
* The Amazon Resource Name (ARN) that identifies the cluster.
*/
public override fun clusterArn(): String = unwrap(this).getClusterArn()
/**
* The name of the cluster.
*/
public override fun clusterName(): String = unwrap(this).getClusterName()
/**
* Manage the allowed network connections for the cluster with Security Groups.
*/
public override fun connections(): Connections =
unwrap(this).getConnections().let(Connections::wrap)
/**
* Getter for _defaultCapacityProviderStrategy.
*
* This is necessary to correctly create Capacity Provider Associations.
*/
public open fun defaultCapacityProviderStrategy(): List<CapacityProviderStrategy> =
unwrap(this).getDefaultCapacityProviderStrategy().map(CapacityProviderStrategy::wrap)
/**
* Getter for namespace added to cluster.
*/
public override fun defaultCloudMapNamespace(): INamespace? =
unwrap(this).getDefaultCloudMapNamespace()?.let(INamespace::wrap)
/**
* Enable the Fargate capacity providers for this cluster.
*/
public open fun enableFargateCapacityProviders() {
unwrap(this).enableFargateCapacityProviders()
}
/**
* Getter for execute command configuration associated with the cluster.
*/
public override fun executeCommandConfiguration(): ExecuteCommandConfiguration? =
unwrap(this).getExecuteCommandConfiguration()?.let(ExecuteCommandConfiguration::wrap)
/**
* Grants an ECS Task Protection API permission to the specified grantee.
*
* This method provides a streamlined way to assign the 'ecs:UpdateTaskProtection'
* permission, enabling the grantee to manage task protection in the ECS cluster.
*
* @param grantee The entity (e.g., IAM role or user) to grant the permissions to.
*/
public open fun grantTaskProtection(grantee: IGrantable): Grant =
unwrap(this).grantTaskProtection(grantee.let(IGrantable.Companion::unwrap)).let(Grant::wrap)
/**
* Whether the cluster has EC2 capacity associated with it.
*/
public override fun hasEc2Capacity(): Boolean = unwrap(this).getHasEc2Capacity()
/**
* This method returns the specifed CloudWatch metric for this cluster.
*
* @param metricName
* @param props
*/
public open fun metric(metricName: String): Metric =
unwrap(this).metric(metricName).let(Metric::wrap)
/**
* This method returns the specifed CloudWatch metric for this cluster.
*
* @param metricName
* @param props
*/
public open fun metric(metricName: String, props: MetricOptions): Metric =
unwrap(this).metric(metricName, props.let(MetricOptions.Companion::unwrap)).let(Metric::wrap)
/**
* This method returns the specifed CloudWatch metric for this cluster.
*
* @param metricName
* @param props
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("629ccc2b9ed0d0686ac72be3c432836a76a92f56ab45dae83dc2e318f17ba80c")
public open fun metric(metricName: String, props: MetricOptions.Builder.() -> Unit): Metric =
metric(metricName, MetricOptions(props))
/**
* This method returns the CloudWatch metric for this clusters CPU reservation.
*
* Default: average over 5 minutes
*
* @param props
*/
public open fun metricCpuReservation(): Metric =
unwrap(this).metricCpuReservation().let(Metric::wrap)
/**
* This method returns the CloudWatch metric for this clusters CPU reservation.
*
* Default: average over 5 minutes
*
* @param props
*/
public open fun metricCpuReservation(props: MetricOptions): Metric =
unwrap(this).metricCpuReservation(props.let(MetricOptions.Companion::unwrap)).let(Metric::wrap)
/**
* This method returns the CloudWatch metric for this clusters CPU reservation.
*
* Default: average over 5 minutes
*
* @param props
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("b1cccb28a8fbf5b804bd79a934ea306a3f8e9603732c81019144c8647693f16f")
public open fun metricCpuReservation(props: MetricOptions.Builder.() -> Unit): Metric =
metricCpuReservation(MetricOptions(props))
/**
* This method returns the CloudWatch metric for this clusters CPU utilization.
*
* Default: average over 5 minutes
*
* @param props
*/
public open fun metricCpuUtilization(): Metric =
unwrap(this).metricCpuUtilization().let(Metric::wrap)
/**
* This method returns the CloudWatch metric for this clusters CPU utilization.
*
* Default: average over 5 minutes
*
* @param props
*/
public open fun metricCpuUtilization(props: MetricOptions): Metric =
unwrap(this).metricCpuUtilization(props.let(MetricOptions.Companion::unwrap)).let(Metric::wrap)
/**
* This method returns the CloudWatch metric for this clusters CPU utilization.
*
* Default: average over 5 minutes
*
* @param props
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("06a38048efcdd43000e7f66d74001004b818625d95136f460bf350a2397a31d0")
public open fun metricCpuUtilization(props: MetricOptions.Builder.() -> Unit): Metric =
metricCpuUtilization(MetricOptions(props))
/**
* This method returns the CloudWatch metric for this clusters memory reservation.
*
* Default: average over 5 minutes
*
* @param props
*/
public open fun metricMemoryReservation(): Metric =
unwrap(this).metricMemoryReservation().let(Metric::wrap)
/**
* This method returns the CloudWatch metric for this clusters memory reservation.
*
* Default: average over 5 minutes
*
* @param props
*/
public open fun metricMemoryReservation(props: MetricOptions): Metric =
unwrap(this).metricMemoryReservation(props.let(MetricOptions.Companion::unwrap)).let(Metric::wrap)
/**
* This method returns the CloudWatch metric for this clusters memory reservation.
*
* Default: average over 5 minutes
*
* @param props
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("d18b296d9f033d318edae2425d2187f6d1a2e9d3d4df88141e3cf3bbe4407cd9")
public open fun metricMemoryReservation(props: MetricOptions.Builder.() -> Unit): Metric =
metricMemoryReservation(MetricOptions(props))
/**
* This method returns the CloudWatch metric for this clusters memory utilization.
*
* Default: average over 5 minutes
*
* @param props
*/
public open fun metricMemoryUtilization(): Metric =
unwrap(this).metricMemoryUtilization().let(Metric::wrap)
/**
* This method returns the CloudWatch metric for this clusters memory utilization.
*
* Default: average over 5 minutes
*
* @param props
*/
public open fun metricMemoryUtilization(props: MetricOptions): Metric =
unwrap(this).metricMemoryUtilization(props.let(MetricOptions.Companion::unwrap)).let(Metric::wrap)
/**
* This method returns the CloudWatch metric for this clusters memory utilization.
*
* Default: average over 5 minutes
*
* @param props
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("920fdd548a5bd9f6f382929d6f52aa6b867238ab20350ec7f65f1d26154d7844")
public open fun metricMemoryUtilization(props: MetricOptions.Builder.() -> Unit): Metric =
metricMemoryUtilization(MetricOptions(props))
/**
* The VPC associated with the cluster.
*/
public override fun vpc(): IVpc = unwrap(this).getVpc().let(IVpc::wrap)
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.ecs.Cluster].
*/
@CdkDslMarker
public interface Builder {
/**
* The ec2 capacity to add to the cluster.
*
* Default: - no EC2 capacity will be added, you can use `addCapacity` to add capacity later.
*
* @param capacity The ec2 capacity to add to the cluster.
*/
public fun capacity(capacity: AddCapacityOptions)
/**
* The ec2 capacity to add to the cluster.
*
* Default: - no EC2 capacity will be added, you can use `addCapacity` to add capacity later.
*
* @param capacity The ec2 capacity to add to the cluster.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("1747d0a15bfbde19321a2d8d7aab5ad188daf08bbad720ff8cd78f71bc5d0c30")
public fun capacity(capacity: AddCapacityOptions.Builder.() -> Unit)
/**
* The name for the cluster.
*
* Default: CloudFormation-generated name
*
* @param clusterName The name for the cluster.
*/
public fun clusterName(clusterName: String)
/**
* If true CloudWatch Container Insights will be enabled for the cluster.
*
* Default: - Container Insights will be disabled for this cluster.
*
* @param containerInsights If true CloudWatch Container Insights will be enabled for the
* cluster.
*/
public fun containerInsights(containerInsights: Boolean)
/**
* The service discovery namespace created in this cluster.
*
* Default: - no service discovery namespace created, you can use `addDefaultCloudMapNamespace`
* to add a
* default service discovery namespace later.
*
* @param defaultCloudMapNamespace The service discovery namespace created in this cluster.
*/
public fun defaultCloudMapNamespace(defaultCloudMapNamespace: CloudMapNamespaceOptions)
/**
* The service discovery namespace created in this cluster.
*
* Default: - no service discovery namespace created, you can use `addDefaultCloudMapNamespace`
* to add a
* default service discovery namespace later.
*
* @param defaultCloudMapNamespace The service discovery namespace created in this cluster.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("86fad33d93456dd392654e74eedbe276ef8687f3da3062b59797356804ca9d7d")
public
fun defaultCloudMapNamespace(defaultCloudMapNamespace: CloudMapNamespaceOptions.Builder.() -> Unit)
/**
* Whether to enable Fargate Capacity Providers.
*
* Default: false
*
* @param enableFargateCapacityProviders Whether to enable Fargate Capacity Providers.
*/
public fun enableFargateCapacityProviders(enableFargateCapacityProviders: Boolean)
/**
* The execute command configuration for the cluster.
*
* Default: - no configuration will be provided.
*
* @param executeCommandConfiguration The execute command configuration for the cluster.
*/
public fun executeCommandConfiguration(executeCommandConfiguration: ExecuteCommandConfiguration)
/**
* The execute command configuration for the cluster.
*
* Default: - no configuration will be provided.
*
* @param executeCommandConfiguration The execute command configuration for the cluster.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f0f4f83939edf7aed5681a9f9f8be14a1bb3bcc72ded205cab8950d1b23aed33")
public
fun executeCommandConfiguration(executeCommandConfiguration: ExecuteCommandConfiguration.Builder.() -> Unit)
/**
* The VPC where your ECS instances will be running or your ENIs will be deployed.
*
* Default: - creates a new VPC with two AZs
*
* @param vpc The VPC where your ECS instances will be running or your ENIs will be deployed.
*/
public fun vpc(vpc: IVpc)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder: software.amazon.awscdk.services.ecs.Cluster.Builder =
software.amazon.awscdk.services.ecs.Cluster.Builder.create(scope, id)
/**
* The ec2 capacity to add to the cluster.
*
* Default: - no EC2 capacity will be added, you can use `addCapacity` to add capacity later.
*
* @param capacity The ec2 capacity to add to the cluster.
*/
override fun capacity(capacity: AddCapacityOptions) {
cdkBuilder.capacity(capacity.let(AddCapacityOptions.Companion::unwrap))
}
/**
* The ec2 capacity to add to the cluster.
*
* Default: - no EC2 capacity will be added, you can use `addCapacity` to add capacity later.
*
* @param capacity The ec2 capacity to add to the cluster.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("1747d0a15bfbde19321a2d8d7aab5ad188daf08bbad720ff8cd78f71bc5d0c30")
override fun capacity(capacity: AddCapacityOptions.Builder.() -> Unit): Unit =
capacity(AddCapacityOptions(capacity))
/**
* The name for the cluster.
*
* Default: CloudFormation-generated name
*
* @param clusterName The name for the cluster.
*/
override fun clusterName(clusterName: String) {
cdkBuilder.clusterName(clusterName)
}
/**
* If true CloudWatch Container Insights will be enabled for the cluster.
*
* Default: - Container Insights will be disabled for this cluster.
*
* @param containerInsights If true CloudWatch Container Insights will be enabled for the
* cluster.
*/
override fun containerInsights(containerInsights: Boolean) {
cdkBuilder.containerInsights(containerInsights)
}
/**
* The service discovery namespace created in this cluster.
*
* Default: - no service discovery namespace created, you can use `addDefaultCloudMapNamespace`
* to add a
* default service discovery namespace later.
*
* @param defaultCloudMapNamespace The service discovery namespace created in this cluster.
*/
override fun defaultCloudMapNamespace(defaultCloudMapNamespace: CloudMapNamespaceOptions) {
cdkBuilder.defaultCloudMapNamespace(defaultCloudMapNamespace.let(CloudMapNamespaceOptions.Companion::unwrap))
}
/**
* The service discovery namespace created in this cluster.
*
* Default: - no service discovery namespace created, you can use `addDefaultCloudMapNamespace`
* to add a
* default service discovery namespace later.
*
* @param defaultCloudMapNamespace The service discovery namespace created in this cluster.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("86fad33d93456dd392654e74eedbe276ef8687f3da3062b59797356804ca9d7d")
override
fun defaultCloudMapNamespace(defaultCloudMapNamespace: CloudMapNamespaceOptions.Builder.() -> Unit):
Unit = defaultCloudMapNamespace(CloudMapNamespaceOptions(defaultCloudMapNamespace))
/**
* Whether to enable Fargate Capacity Providers.
*
* Default: false
*
* @param enableFargateCapacityProviders Whether to enable Fargate Capacity Providers.
*/
override fun enableFargateCapacityProviders(enableFargateCapacityProviders: Boolean) {
cdkBuilder.enableFargateCapacityProviders(enableFargateCapacityProviders)
}
/**
* The execute command configuration for the cluster.
*
* Default: - no configuration will be provided.
*
* @param executeCommandConfiguration The execute command configuration for the cluster.
*/
override
fun executeCommandConfiguration(executeCommandConfiguration: ExecuteCommandConfiguration) {
cdkBuilder.executeCommandConfiguration(executeCommandConfiguration.let(ExecuteCommandConfiguration.Companion::unwrap))
}
/**
* The execute command configuration for the cluster.
*
* Default: - no configuration will be provided.
*
* @param executeCommandConfiguration The execute command configuration for the cluster.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f0f4f83939edf7aed5681a9f9f8be14a1bb3bcc72ded205cab8950d1b23aed33")
override
fun executeCommandConfiguration(executeCommandConfiguration: ExecuteCommandConfiguration.Builder.() -> Unit):
Unit = executeCommandConfiguration(ExecuteCommandConfiguration(executeCommandConfiguration))
/**
* The VPC where your ECS instances will be running or your ENIs will be deployed.
*
* Default: - creates a new VPC with two AZs
*
* @param vpc The VPC where your ECS instances will be running or your ENIs will be deployed.
*/
override fun vpc(vpc: IVpc) {
cdkBuilder.vpc(vpc.let(IVpc.Companion::unwrap))
}
public fun build(): software.amazon.awscdk.services.ecs.Cluster = cdkBuilder.build()
}
public companion object {
public fun fromClusterArn(
scope: CloudshiftdevConstructsConstruct,
id: String,
clusterArn: String,
): ICluster =
software.amazon.awscdk.services.ecs.Cluster.fromClusterArn(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap),
id, clusterArn).let(ICluster::wrap)
public fun fromClusterAttributes(
scope: CloudshiftdevConstructsConstruct,
id: String,
attrs: ClusterAttributes,
): ICluster =
software.amazon.awscdk.services.ecs.Cluster.fromClusterAttributes(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap),
id, attrs.let(ClusterAttributes.Companion::unwrap)).let(ICluster::wrap)
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("54fbf9e293c46c81fc7b01109faa86bd7c632a14b9eee35f533a39b6ecf90964")
public fun fromClusterAttributes(
scope: CloudshiftdevConstructsConstruct,
id: String,
attrs: ClusterAttributes.Builder.() -> Unit,
): ICluster = fromClusterAttributes(scope, id, ClusterAttributes(attrs))
public fun isCluster(x: Any): Boolean = software.amazon.awscdk.services.ecs.Cluster.isCluster(x)
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): Cluster {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return Cluster(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.ecs.Cluster): Cluster =
Cluster(cdkObject)
internal fun unwrap(wrapped: Cluster): software.amazon.awscdk.services.ecs.Cluster =
wrapped.cdkObject as software.amazon.awscdk.services.ecs.Cluster
}
}
| 4
|
Kotlin
|
0
| 4
|
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
| 26,348
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
datalogger/src/main/java/org/obd/graphs/bl/trip/TripModelSerializers.kt
|
tzebrowski
| 326,375,780
| false
| null |
package org.obd.graphs.bl.trip
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.obd.graphs.preferences.Prefs
import org.obd.metrics.transport.message.ConnectorResponse
import org.obd.metrics.transport.message.ConnectorResponseFactory
import java.io.IOException
private val EMPTY_CONNECTOR_RESPONSE = ConnectorResponseFactory.wrap(byteArrayOf())
private class ConnectorResponseSerializer() :
StdSerializer<ConnectorResponse>(ConnectorResponse::class.java) {
@Throws(IOException::class)
override fun serialize(
value: ConnectorResponse,
gen: JsonGenerator,
provider: SerializerProvider
) {
gen.writeString(value.message)
}
}
private class NopeConnectorResponseSerializer() :
StdSerializer<ConnectorResponse>(ConnectorResponse::class.java) {
@Throws(IOException::class)
override fun serialize(
value: ConnectorResponse,
gen: JsonGenerator,
provider: SerializerProvider
) {
gen.writeString("")
}
}
private class ConnectorResponseDeserializer() :
StdDeserializer<ConnectorResponse>(String::class.java) {
override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): ConnectorResponse {
return EMPTY_CONNECTOR_RESPONSE
}
}
class TripModelSerializer {
val serializer: ObjectMapper by lazy { serializer() }
val deserializer: ObjectMapper by lazy { deserializer() }
private fun serializer(): ObjectMapper =
jacksonObjectMapper().apply {
val module = SimpleModule()
val serializeConnectorResponse =
Prefs.getBoolean("pref.debug.trip.save.connector_response", false)
if (serializeConnectorResponse) {
module.addSerializer(
ConnectorResponse::class.java,
ConnectorResponseSerializer()
)
} else {
module.addSerializer(
ConnectorResponse::class.java,
NopeConnectorResponseSerializer()
)
}
module.addDeserializer(
ConnectorResponse::class.java,
ConnectorResponseDeserializer()
)
registerModule(module)
}
private fun deserializer(): ObjectMapper =
jacksonObjectMapper().apply {
val module = SimpleModule()
module.addSerializer(
ConnectorResponse::class.java,
ConnectorResponseSerializer()
)
module.addDeserializer(
ConnectorResponse::class.java,
ConnectorResponseDeserializer()
)
registerModule(module)
}
}
| 1
|
Kotlin
|
2
| 8
|
61f19f1f8bcba21906e15d4d49b9dc3012cccf41
| 3,179
|
ObdGraphs
|
Apache License 2.0
|
mobzy-pathfinding/src/main/kotlin/com/mineinabyss/mobzy/ecs/goals/minecraft/FollowParentBehaviour.kt
|
MineInAbyss
| 142,800,887
| false
| null |
package com.mineinabyss.mobzy.ecs.goals.minecraft
import com.mineinabyss.mobzy.api.nms.aliases.NMSPathfinderGoal
import com.mineinabyss.mobzy.api.nms.aliases.toNMS
import com.mineinabyss.mobzy.ecs.components.initialization.pathfinding.PathfinderComponent
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import net.minecraft.server.v1_16_R2.EntityAnimal
import net.minecraft.server.v1_16_R2.PathfinderGoalFollowParent
import org.bukkit.entity.Mob
@Serializable
@SerialName("minecraft:behavior.follow_parent")
class FollowParentBehaviour(
private val speedModifier: Double = 1.0,
) : PathfinderComponent() {
override fun build(mob: Mob): NMSPathfinderGoal = PathfinderGoalFollowParent(
mob.toNMS<EntityAnimal>(),
speedModifier
)
}
| 13
| null |
8
| 29
|
6fdf955a0bc906f297eb91340fcdcabf5031beef
| 793
|
Mobzy
|
MIT License
|
mobzy-pathfinding/src/main/kotlin/com/mineinabyss/mobzy/ecs/goals/minecraft/FollowParentBehaviour.kt
|
MineInAbyss
| 142,800,887
| false
| null |
package com.mineinabyss.mobzy.ecs.goals.minecraft
import com.mineinabyss.mobzy.api.nms.aliases.NMSPathfinderGoal
import com.mineinabyss.mobzy.api.nms.aliases.toNMS
import com.mineinabyss.mobzy.ecs.components.initialization.pathfinding.PathfinderComponent
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import net.minecraft.server.v1_16_R2.EntityAnimal
import net.minecraft.server.v1_16_R2.PathfinderGoalFollowParent
import org.bukkit.entity.Mob
@Serializable
@SerialName("minecraft:behavior.follow_parent")
class FollowParentBehaviour(
private val speedModifier: Double = 1.0,
) : PathfinderComponent() {
override fun build(mob: Mob): NMSPathfinderGoal = PathfinderGoalFollowParent(
mob.toNMS<EntityAnimal>(),
speedModifier
)
}
| 13
| null |
8
| 29
|
6fdf955a0bc906f297eb91340fcdcabf5031beef
| 793
|
Mobzy
|
MIT License
|
model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/Lambda.kt
|
kohesive
| 81,814,921
| false
| null |
package uy.kohesive.iac.model.aws.cloudformation.resources.builders
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.services.lambda.model.*
import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder
import uy.kohesive.iac.model.aws.cloudformation.resources.Lambda
class LambdaVersionResourcePropertiesBuilder : ResourcePropertiesBuilder<PublishVersionRequest> {
override val requestClazz = PublishVersionRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as PublishVersionRequest).let {
Lambda.Version(
CodeSha256 = it.codeSha256,
FunctionName = it.functionName,
Description = it.description
)
}
}
class LambdaPermissionResourcePropertiesBuilder : ResourcePropertiesBuilder<AddPermissionRequest> {
override val requestClazz = AddPermissionRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as AddPermissionRequest).let {
Lambda.Permission(
Action = it.action,
Principal = it.principal,
FunctionName = it.functionName,
SourceAccount = it.sourceAccount,
SourceArn = it.sourceArn
)
}
}
class LambdaAliasResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateAliasRequest> {
override val requestClazz = CreateAliasRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateAliasRequest).let {
Lambda.Alias(
Description = request.description,
FunctionName = request.functionName,
FunctionVersion = request.functionVersion,
Name = request.name
)
}
}
class LambdaEventSourceMappingResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateEventSourceMappingRequest> {
override val requestClazz = CreateEventSourceMappingRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateEventSourceMappingRequest).let {
Lambda.EventSourceMapping(
BatchSize = request.batchSize?.toString(),
Enabled = request.enabled?.toString(),
EventSourceArn = request.eventSourceArn,
FunctionName = request.functionName,
StartingPosition = request.startingPosition
)
}
}
class LambdaFunctionResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateFunctionRequest> {
override val requestClazz = CreateFunctionRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateFunctionRequest).let {
Lambda.Function(
Code = request.code.let {
Lambda.Function.CodeProperty(
S3Key = it.s3Key,
S3Bucket = it.s3Bucket,
S3ObjectVersion = it.s3ObjectVersion,
ZipFile = it.zipFile?.let {
String(it.array())
}
)
},
Description = request.description,
Environment = request.environment?.let {
Lambda.Function.EnvironmentProperty(
Variables = it.variables
)
},
FunctionName = request.functionName,
Handler = request.handler,
KmsKeyArn = request.kmsKeyArn,
MemorySize = request.memorySize?.toString(),
Role = request.role,
Runtime = request.runtime,
Timeout = request.timeout?.toString(),
VpcConfig = request.vpcConfig?.let {
Lambda.Function.VPCConfigProperty(
SecurityGroupIds = it.securityGroupIds,
SubnetIds = it.subnetIds
)
}
)
}
}
| 0
|
Kotlin
|
1
| 3
|
c52427c99384396ea60f436750932ed12aad4e6d
| 4,358
|
kohesive-iac
|
MIT License
|
app/src/main/java/com/thecode/cryptomania/presentation/splash/SplashActivity.kt
|
gabriel-TheCode
| 375,033,948
| false
|
{"Kotlin": 89192}
|
package com.thecode.cryptomania.presentation.splash
import android.content.Intent
import android.os.Bundle
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.thecode.cryptomania.R
import com.thecode.cryptomania.databinding.ActivitySplashBinding
import com.thecode.cryptomania.presentation.main.MainActivity
import com.thecode.cryptomania.presentation.onboarding.OnboardingActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SplashActivity : AppCompatActivity() {
private val viewModel: SplashViewModel by viewModels()
private lateinit var binding: ActivitySplashBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySplashBinding.inflate(layoutInflater)
setContentView(binding.root)
setUpObserver()
setUpAnimation()
}
private fun setUpAnimation() {
binding.layoutImageContent.animation = AnimationUtils.loadAnimation(this, R.anim.up_to_down)
binding.layoutText.animation = AnimationUtils.loadAnimation(this, R.anim.down_to_up)
val rotate = RotateAnimation(
0f,
720f,
Animation.RELATIVE_TO_SELF,
0.5f,
Animation.RELATIVE_TO_SELF,
0.5f
)
rotate.duration = 3000
rotate.interpolator = LinearInterpolator()
binding.imageLogo.startAnimation(rotate)
rotate.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) = Unit
override fun onAnimationRepeat(animation: Animation?) = Unit
override fun onAnimationEnd(animation: Animation?) {
viewModel.getOnboardingStatus()
}
})
}
private fun setUpObserver() {
viewModel.state.observe(this) { isOnboardingCompleted ->
intent = if (isOnboardingCompleted == true) {
Intent(applicationContext, MainActivity::class.java)
} else {
Intent(applicationContext, OnboardingActivity::class.java)
}
finish()
startActivity(intent)
}
}
}
| 1
|
Kotlin
|
6
| 26
|
c45130092bd4f73b92b47a3eb57b57ba3978dd82
| 2,426
|
CryptoMania
|
Apache License 2.0
|
api/src/test/kotlin/glimpse/shaders/ProgramBuilderSpec.kt
|
glimpse-graphics
| 44,015,157
| false
|
{"Kotlin": 207226, "GLSL": 7035}
|
package glimpse.shaders
import com.nhaarman.mockito_kotlin.*
import glimpse.gles.GLES
import glimpse.test.GlimpseSpec
class ProgramBuilderSpec : GlimpseSpec() {
init {
"Program builder" should {
"create both shaders" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).createShader(ShaderType.VERTEX)
verify(glesMock).createShader(ShaderType.FRAGMENT)
}
"compile both shaders" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).compileShader(ShaderHandle(1), "vertex shader code")
verify(glesMock).compileShader(ShaderHandle(2), "fragment shader code")
}
"cause exception if compilation fails" {
glesMock {
on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2)
on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true
on { getShaderCompileStatus(ShaderHandle(2)) } doReturn false
on { getShaderLog(ShaderHandle(2)) } doReturn "Error"
}
shouldThrow<ShaderCompileException> {
buildShaderProgram()
}
}
"create a program" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).createProgram()
}
"attach both shaders to program" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).attachShader(ProgramHandle(3), ShaderHandle(1))
verify(glesMock).attachShader(ProgramHandle(3), ShaderHandle(2))
}
"link a program" {
val glesMock = glesMock()
buildShaderProgram()
verify(glesMock).linkProgram(ProgramHandle(3))
}
"return a program with correct data" {
val glesMock = glesMock()
val program = buildShaderProgram()
program.gles shouldBe glesMock
program.handle shouldBe ProgramHandle(3)
program.shaders should haveSize(2)
program.shaders.map { it.gles }.filter { it != glesMock } should beEmpty()
program.shaders.map { it.type } should containInAnyOrder(*ShaderType.values())
program.shaders.map { it.handle } should containInAnyOrder(ShaderHandle(1), ShaderHandle(2))
}
"cause exception if linking fails" {
glesMock {
on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2)
on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true
on { getShaderCompileStatus(ShaderHandle(2)) } doReturn true
on { createProgram() } doReturn ProgramHandle(3)
on { getProgramLinkStatus(ProgramHandle(3)) } doReturn false
on { getProgramLog(ProgramHandle(3)) } doReturn "Error"
}
shouldThrow<ProgramLinkException> {
buildShaderProgram()
}
}
}
}
private fun glesMock(): GLES = glesMock {
on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2)
on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true
on { getShaderCompileStatus(ShaderHandle(2)) } doReturn true
on { createProgram() } doReturn ProgramHandle(3)
on { getProgramLinkStatus(ProgramHandle(3)) } doReturn true
}
private fun buildShaderProgram(): Program = shaderProgram {
vertexShader {
"vertex shader code"
}
fragmentShader {
"fragment shader code"
}
}
}
| 0
|
Kotlin
|
0
| 16
|
5069cc1c3f2d8cb344740f3d33bcf11848f94583
| 3,104
|
glimpse-framework
|
Apache License 2.0
|
android/src/main/java/com/reactnativerangersapplogreactnativeplugin/RangersApplogReactnativePluginPackage.kt
|
bashen1
| 384,293,703
| false
|
{"Kotlin": 16124, "Objective-C": 12044, "JavaScript": 6720, "Ruby": 1240}
|
package com.reactnativerangersapplogreactnativeplugin
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class RangersApplogReactnativePluginPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(RangersApplogReactnativePluginModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
| 0
|
Kotlin
|
0
| 2
|
76d1833f724c2b46a6630702a4e78523d60a91fe
| 624
|
react-native-mrangers-log
|
MIT License
|
src/main/kotlin/org/xbery/artbeams/common/mailer/service/Mailer.kt
|
beranradek
| 354,546,253
| false
|
{"Kotlin": 573095, "JavaScript": 286267, "FreeMarker": 109973, "CSS": 12906, "Procfile": 109}
|
package org.xbery.artbeams.common.mailer.service
import org.apache.http.HttpEntity
import org.apache.http.NameValuePair
import org.apache.http.StatusLine
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.xbery.artbeams.common.mailer.config.MailerConfig
/**
* Mailer for sending e-mails.
* @author Radek Beran
*/
@Service
open class Mailer(private val mailerConfig: MailerConfig) {
private val logger: Logger = LoggerFactory.getLogger(this::class.java)
open fun sendMail(subject: String, body: String, to: String) {
logger.info("Sending email ${subject} to ${to}")
val mailerApiUrl =
"https://api:${mailerConfig.apiKey}@api.mailgun.net/v2/${mailerConfig.domain}/messages"
HttpClients.createDefault().use { httpClient ->
val httpPost = HttpPost(mailerApiUrl)
val params = mutableListOf<NameValuePair>()
params.add(BasicNameValuePair("from", mailerConfig.from))
params.add(BasicNameValuePair("to", to))
params.add(BasicNameValuePair("subject", subject))
params.add(BasicNameValuePair("text", body))
params.add(BasicNameValuePair("html", body))
httpPost.entity = UrlEncodedFormEntity(params)
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct de-allocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
httpClient.execute(httpPost).use { response ->
val statusLine: StatusLine = response.statusLine
val status: Int = statusLine.statusCode
val responseEntity: HttpEntity = response.entity
logger.info("Response status: ${statusLine}")
if (status in 200..299) {
EntityUtils.consume(responseEntity)
logger.info("Email $subject to $to was successfully sent.")
} else {
val responseString: String =
if (responseEntity != null) EntityUtils.toString(responseEntity) else ""
logger.error("Error while sending email $subject to ${to}. Unexpected response status $status with response $responseString")
}
}
}
}
}
| 0
|
Kotlin
|
1
| 2
|
8e0a0b4dd464e0735a2d2f3f6931ff4638b6d023
| 2,949
|
artbeams
|
Apache License 2.0
|
app/src/test/kotlin/de/markusfisch/android/binaryeye/actions/web/WebTest.kt
|
markusfisch
| 101,552,674
| false
| null |
package de.markusfisch.android.binaryeye.actions.web
import junit.framework.TestCase.*
import org.junit.Test
class WebTest {
@Test
fun correct() {
val urls = listOf(
"https://google.com",
"https://markusfisch.de",
"http://markusfisch.de",
"http://www.markusfisch.de",
"http://www.markusfisch.de/",
"http://www.markusfisch.de/?",
"http://www.markusfisch.de/?foo=bar",
"https://markusfisch.de/foo",
"https://markusfisch.de/foo#bar",
"https://foo.example.com/",
"http://example.com/",
)
for (url in urls) {
assertEquals(url, resolve(url))
}
}
@Test
fun colloquial() {
val urls = listOf(
"google.com",
"GOOGLE.com",
"GOOGLE.COM",
" foo.com",
"foo.com ",
" foo.com ",
" foo.com ",
"foo.com",
"foo.com/bar",
"foo.com?bar",
"foo.com#bar",
)
for (url in urls) {
assertEquals(url, resolve(url))
}
}
@Test
fun noUrls() {
val urls = listOf(
"",
"foo",
"foo . bar",
"exa mple.com",
"example.co m",
"some string",
"some string.",
".foo",
"..foo",
"...foo",
"foo.",
"foo..",
"foo...",
"foo. foo",
)
for (url in urls) {
assertEquals(null, resolve(url))
}
}
}
private fun resolve(s: String) = if (
WebAction.canExecuteOn(s.toByteArray())
) s else null
| 83
|
Kotlin
|
97
| 992
|
e99e2d7dccba2f6ffb6d7d6d2e6428288834dcf5
| 1,294
|
BinaryEye
|
MIT License
|
src/main/kotlin/net/polvott/kotlinnats/PublishMessageController.kt
|
jankb
| 721,622,202
| false
|
{"Kotlin": 1505}
|
package net.polvott.kotlinnats
import io.nats.client.Nats
import io.nats.client.Options
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
@RestController
class PublishMessageController {
@GetMapping("/publish/{message}")
fun publishMessage(@PathVariable message: String) {
val protoSampe = SampleOuterClass.Sample.newBuilder()
.setMTid("MTid")
.setMTsampnt("MTsampnt")
.setMTmessage(message)
.build()
val credsFile = Nats.credentials("/home/jankb/Downloads/sample-dev-jankb.creds")
val options = Options.Builder()
.server("tls://connect.nats.mattilsynet.io:4222")
.connectionName("kotlinnats")
.authHandler(credsFile)
.build()
val nc = Nats.connect(options)
nc.publish("jankbtest", protoSampe.toByteArray())
nc.close()
}
}
| 0
|
Kotlin
|
0
| 0
|
1f58ea8d8e12f7dcaf3f53df00c805cdcf35ae36
| 1,011
|
kotlinnats
|
MIT License
|
src/nl/hannahsten/texifyidea/intentions/LatexDisplayMathIntention.kt
|
Hannah-Sten
| 62,398,769
| false
| null |
package nl.hannahsten.texifyidea.intentions
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.lang.DefaultEnvironment
import nl.hannahsten.texifyidea.psi.LatexBeginCommand
import nl.hannahsten.texifyidea.util.files.isLatexFile
import nl.hannahsten.texifyidea.util.parser.endCommand
import nl.hannahsten.texifyidea.util.parser.environmentName
import nl.hannahsten.texifyidea.util.parser.parentOfType
import nl.hannahsten.texifyidea.util.replaceString
/**
* @author Hannah Schellekens
*/
open class LatexDisplayMathIntention : TexifyIntentionBase("Change equation*/displaymath environment to '\\[..\\]'") {
private val affectedEnvironments = setOf(DefaultEnvironment.DISPLAYMATH.environmentName, DefaultEnvironment.EQUATION_STAR.environmentName)
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
if (editor == null || file == null || !file.isLatexFile()) {
return false
}
val selected = file.findElementAt(editor.caretModel.offset) ?: return false
val begin = selected.parentOfType(LatexBeginCommand::class) ?: return false
val name = begin.environmentName() ?: return false
return affectedEnvironments.contains(name)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (editor == null || file == null || !file.isLatexFile()) {
return
}
val selected = file.findElementAt(editor.caretModel.offset) ?: return
val begin = selected.parentOfType(LatexBeginCommand::class) ?: return
val end = begin.endCommand() ?: return
val document = editor.document
runWriteAction {
document.replaceString(end.textRange, "\\]")
document.replaceString(begin.textRange, "\\[")
}
}
}
| 99
| null |
87
| 891
|
986550410e2fea91d1e93abfc683db1c8527c9d9
| 1,968
|
TeXiFy-IDEA
|
MIT License
|
CAP-10/MyRoom/app/src/main/java/es/javiercarrasco/myroom/ui/EditorialActivity.kt
|
KotlinStuff
| 601,574,601
| false
| null |
package es.javiercarrasco.myroom.ui
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.room.CoroutinesRoom
import es.javiercarrasco.myroom.MyRoomApplication
import es.javiercarrasco.myroom.R
import es.javiercarrasco.myroom.data.SupersDatabase
import es.javiercarrasco.myroom.data.model.Editorial
import es.javiercarrasco.myroom.databinding.ActivityEditorialBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class EditorialActivity : AppCompatActivity() {
private lateinit var binding: ActivityEditorialBinding
private lateinit var db: SupersDatabase
companion object {
fun navigate(activity: AppCompatActivity) {
activity.startActivity(
Intent(
activity,
EditorialActivity::class.java
).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
ActivityOptions.makeSceneTransitionAnimation(activity).toBundle()
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditorialBinding.inflate(layoutInflater)
setContentView(binding.root)
db = (application as MyRoomApplication).supersDatabase
supportActionBar!!.title = getString(R.string.txt_editorial)
binding.button.setOnClickListener {
if (binding.etEditorial.text.isNullOrBlank())
binding.labelEtEditorial.error = getString(R.string.warning_empty_field)
else {
binding.labelEtEditorial.error = null
val name = binding.etEditorial.text!!.trim().toString()
val newEditorial = Editorial(name = name)
CoroutineScope(Dispatchers.IO).launch {
db.supersDAO().insertEditorial(newEditorial)
}
finish()
}
}
}
}
| 0
| null |
0
| 1
|
2469656f963c4cdc2888b69a6d4427f23487b65e
| 2,091
|
DMKotlin-v2023
|
MIT License
|
src/main/kotlin/no/nav/syfo/aktivitetskrav/api/AktivitetskravResponseDTO.kt
|
navikt
| 554,767,872
| false
|
{"Kotlin": 394337, "Dockerfile": 226}
|
package no.nav.syfo.aktivitetskrav.api
import no.nav.syfo.aktivitetskrav.domain.AktivitetskravStatus
import no.nav.syfo.aktivitetskrav.domain.VurderingArsak
import java.time.LocalDate
import java.time.LocalDateTime
data class AktivitetskravResponseDTO(
val uuid: String,
val createdAt: LocalDateTime,
val status: AktivitetskravStatus,
val stoppunktAt: LocalDate,
val vurderinger: List<AktivitetskravVurderingResponseDTO>,
)
data class AktivitetskravVurderingResponseDTO(
val uuid: String,
val createdAt: LocalDateTime,
val createdBy: String,
val status: AktivitetskravStatus,
val beskrivelse: String?,
val arsaker: List<VurderingArsak>,
val frist: LocalDate?,
val varsel: VarselResponseDTO?
)
data class VarselResponseDTO(
val uuid: String,
val createdAt: LocalDateTime,
val svarfrist: LocalDate,
)
| 2
|
Kotlin
|
1
| 0
|
f3be9861b8c74cb60aee92cfffe38e7ac8a8c5ca
| 867
|
isaktivitetskrav
|
MIT License
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/lambda/eventsources/SnsEventSourceDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.lambda.eventsources
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import kotlin.collections.Map
import software.amazon.awscdk.services.lambda.eventsources.SnsEventSource
import software.amazon.awscdk.services.sns.FilterOrPolicy
import software.amazon.awscdk.services.sns.ITopic
import software.amazon.awscdk.services.sns.SubscriptionFilter
import software.amazon.awscdk.services.sqs.IQueue
/**
* Use an Amazon SNS topic as an event source for AWS Lambda.
*
* Example:
*
* ```
* import software.amazon.awscdk.services.sns.*;
* import software.amazon.awscdk.services.lambda.eventsources.SnsEventSource;
* Topic topic;
* Function fn;
* Queue deadLetterQueue = new Queue(this, "deadLetterQueue");
* fn.addEventSource(SnsEventSource.Builder.create(topic)
* .filterPolicy(Map.of())
* .deadLetterQueue(deadLetterQueue)
* .build());
* ```
*/
@CdkDslMarker
public class SnsEventSourceDsl(
topic: ITopic,
) {
private val cdkBuilder: SnsEventSource.Builder = SnsEventSource.Builder.create(topic)
/**
* Queue to be used as dead letter queue.
*
* If not passed no dead letter queue is enabled.
*
* Default: - No dead letter queue enabled.
*
* @param deadLetterQueue Queue to be used as dead letter queue.
*/
public fun deadLetterQueue(deadLetterQueue: IQueue) {
cdkBuilder.deadLetterQueue(deadLetterQueue)
}
/**
* The filter policy.
*
* Default: - all messages are delivered
*
* @param filterPolicy The filter policy.
*/
public fun filterPolicy(filterPolicy: Map<String, SubscriptionFilter>) {
cdkBuilder.filterPolicy(filterPolicy)
}
/**
* The filter policy that is applied on the message body.
*
* To apply a filter policy to the message attributes, use `filterPolicy`. A maximum of one of
* `filterPolicyWithMessageBody` and `filterPolicy` may be used.
*
* Default: - all messages are delivered
*
* @param filterPolicyWithMessageBody The filter policy that is applied on the message body.
*/
public fun filterPolicyWithMessageBody(filterPolicyWithMessageBody: Map<String, FilterOrPolicy>) {
cdkBuilder.filterPolicyWithMessageBody(filterPolicyWithMessageBody)
}
public fun build(): SnsEventSource = cdkBuilder.build()
}
| 3
| null |
0
| 3
|
256ad92aebe2bcf9a4160089a02c76809dbbedba
| 2,474
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/java/com/keithsmyth/ecommerce/ui/product/ProductViewModel.kt
|
keithsmyth
| 610,826,987
| false
| null |
package com.keithsmyth.ecommerce.ui.product
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.keithsmyth.ecommerce.domain.ProductController
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ProductViewModel @Inject constructor(
private val state: SavedStateHandle,
private val productController: ProductController,
) : ViewModel() {
private val mutableViewState = MutableStateFlow("")
val viewState: StateFlow<String> = mutableViewState.asStateFlow()
init {
viewModelScope.launch {
val productId = ProductArguments.retrieveProductId(state)
val product = productController.product(productId)
mutableViewState.emit(product.toString())
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ec7bdfb62f768f70a456949d1a4ad381f6b97382
| 1,016
|
Ecommerce
|
Apache License 2.0
|
app/src/main/java/com/battlelancer/seriesguide/lists/ListManageDialogFragment.kt
|
UweTrottmann
| 1,990,682
| false
| null |
package com.battlelancer.seriesguide.lists
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.databinding.DialogListManageBinding
import com.battlelancer.seriesguide.provider.SeriesGuideContract
import com.battlelancer.seriesguide.util.safeShow
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.launch
/**
* Dialog to rename or remove a list.
*/
class ListManageDialogFragment : AppCompatDialogFragment() {
private var binding: DialogListManageBinding? = null
private lateinit var listId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// hide title, use custom theme
setStyle(STYLE_NO_TITLE, 0)
listId = requireArguments().getString(ARG_LIST_ID)!!
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DialogListManageBinding.inflate(layoutInflater)
this.binding = binding
// buttons
binding.buttonNegative.isEnabled = false
binding.buttonNegative.setText(R.string.list_remove)
binding.buttonNegative.setOnClickListener {
// remove list and items
ListsTools.removeList(requireContext(), listId)
dismiss()
}
binding.buttonPositive.setText(android.R.string.ok)
binding.buttonPositive.setOnClickListener {
val editText = this.binding?.textInputLayoutListManageListName?.editText
?: return@setOnClickListener
// update title
val listName = editText.text.toString().trim()
ListsTools.renameList(requireContext(), listId, listName)
dismiss()
}
// Delay loading data for views to after this function
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
configureViews()
}
}
return MaterialAlertDialogBuilder(requireContext())
.setView(binding.getRoot())
.create()
}
private fun configureViews() {
// pre-populate list title
val list = requireContext().contentResolver
.query(
SeriesGuideContract.Lists.buildListUri(listId), arrayOf(
SeriesGuideContract.Lists.NAME
), null, null, null
)
if (list == null) {
// list might have been removed, or query failed
dismiss()
return
}
if (!list.moveToFirst()) {
// list not found
list.close()
dismiss()
return
}
val listName = list.getString(0)
list.close()
val binding = this@ListManageDialogFragment.binding
if (binding == null) {
dismiss()
return
}
val textInputLayoutName = binding.textInputLayoutListManageListName
val editTextName = textInputLayoutName.editText!!
editTextName.setText(listName)
editTextName.addTextChangedListener(
AddListDialogFragment.ListNameTextWatcher(
requireContext(), textInputLayoutName,
binding.buttonPositive, listName
)
)
// do only allow removing if this is NOT the last list
val lists = requireContext().contentResolver.query(
SeriesGuideContract.Lists.CONTENT_URI, arrayOf(
SeriesGuideContract.Lists._ID
), null, null, null
)
if (lists != null) {
if (lists.count > 1) {
binding.buttonNegative.isEnabled = true
}
lists.close()
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
companion object {
private const val TAG = "listmanagedialog"
private const val ARG_LIST_ID = "listId"
private fun newInstance(listId: String): ListManageDialogFragment {
val f = ListManageDialogFragment()
val args = Bundle()
args.putString(ARG_LIST_ID, listId)
f.arguments = args
return f
}
/**
* Display a dialog which allows to edit the title of this list or remove it.
*/
fun show(listId: String, fm: FragmentManager) {
// replace any currently showing list dialog (do not add it to the back stack)
val ft = fm.beginTransaction()
val prev = fm.findFragmentByTag(TAG)
if (prev != null) {
ft.remove(prev)
}
newInstance(listId).safeShow(fm, ft, TAG)
}
}
}
| 56
| null |
403
| 1,966
|
c7bc6445ecc58b841c1887a56146dc2d2f817007
| 4,988
|
SeriesGuide
|
Apache License 2.0
|
code/jvm/main/kotlin/com/isel/leic/ps/ionClassCode/domain/input/ApplyInput.kt
|
i-on-project
| 607,828,295
| false
| null |
package com.isel.leic.ps.ionClassCode.domain.input
/**
* Apply Input Interface
*/
data class ApplyInput(
val pendingTeacherId: Int,
) {
fun isNotValid(): Boolean {
return pendingTeacherId <= 0
}
}
| 2
|
Kotlin
|
0
| 2
|
3daeed28d8a2ce9cb90ec642698b9ecb2eb9fe0d
| 220
|
repohouse
|
Apache License 2.0
|
src/main/kotlin/dev/sterner/common/entity/AbstractCultistEntity.kt
|
mrsterner
| 854,711,582
| false
| null |
package dev.sterner.common.entity
import net.minecraft.nbt.CompoundTag
import net.minecraft.sounds.SoundEvent
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.DifficultyInstance
import net.minecraft.world.damagesource.DamageSource
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.Mob
import net.minecraft.world.entity.MobSpawnType
import net.minecraft.world.entity.SpawnGroupData
import net.minecraft.world.entity.ai.goal.*
import net.minecraft.world.entity.ai.goal.target.HurtByTargetGoal
import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal
import net.minecraft.world.entity.ai.navigation.GroundPathNavigation
import net.minecraft.world.entity.ai.navigation.PathNavigation
import net.minecraft.world.entity.monster.Monster
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.Items
import net.minecraft.world.level.Level
import net.minecraft.world.level.ServerLevelAccessor
abstract class AbstractCultistEntity(entityType: EntityType<out Monster>, level: Level) : Monster(entityType, level) {
override fun finalizeSpawn(
level: ServerLevelAccessor,
difficulty: DifficultyInstance,
reason: MobSpawnType,
spawnData: SpawnGroupData?,
dataTag: CompoundTag?
): SpawnGroupData? {
val spawnGroupData = super.finalizeSpawn(level, difficulty, reason, spawnData, dataTag)
(getNavigation() as GroundPathNavigation).setCanOpenDoors(true)
val randomSource = level.random
this.populateDefaultEquipmentSlots(randomSource, difficulty)
this.populateDefaultEquipmentEnchantments(randomSource, difficulty)
return spawnGroupData
}
open fun getArmPose(): CrimsonArmPose {
if (this.isHolding(Items.CROSSBOW)) {
return CrimsonArmPose.CROSSBOW_HOLD
}
if (this.isAggressive) {
return CrimsonArmPose.ATTACKING
}
return CrimsonArmPose.NEUTRAL
}
override fun createNavigation(level: Level): PathNavigation {
return super.createNavigation(level)
}
override fun getAmbientSound(): SoundEvent {
return SoundEvents.VINDICATOR_AMBIENT
}
override fun getDeathSound(): SoundEvent {
return SoundEvents.VINDICATOR_DEATH
}
override fun getHurtSound(damageSource: DamageSource?): SoundEvent {
return SoundEvents.VINDICATOR_HURT
}
override fun registerGoals() {
super.registerGoals()
goalSelector.addGoal(0, FloatGoal(this))
goalSelector.addGoal(2, OpenDoorGoal(this, false))
goalSelector.addGoal(7, WaterAvoidingRandomStrollGoal(this, 1.0))
goalSelector.addGoal(8, LookAtPlayerGoal(this, Player::class.java, 8.0f))
goalSelector.addGoal(8, RandomLookAroundGoal(this))
targetSelector.addGoal(
1, HurtByTargetGoal(
this,
AbstractCultistEntity::class.java
).setAlertOthers(*arrayOfNulls(0))
)
targetSelector.addGoal(
2, NearestAttackableTargetGoal(
this as Mob,
Player::class.java, true
)
)
}
enum class CrimsonArmPose {
ATTACKING,
SPELLCASTING,
BOW_AND_ARROW,
CROSSBOW_HOLD,
CROSSBOW_CHARGE,
NEUTRAL,
BLOCK
}
}
| 0
| null |
0
| 1
|
6ae8ea7a62e6deb2326662e9498c7d31466db9e4
| 3,381
|
voidbound
|
MIT License
|
core/src/main/kotlin/restaurant/internal/undertow/Undertow.kt
|
christophsturm
| 360,472,665
| false
| null |
package restaurant.internal.undertow
import io.undertow.Undertow
import io.undertow.server.HttpServerExchange
import io.undertow.server.RoutingHandler
import io.undertow.server.handlers.error.SimpleErrorPageHandler
import io.undertow.util.HttpString
import io.undertow.util.Methods
import restaurant.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
fun Route.methodToHttpString(): HttpString = when (method) {
Method.GET -> Methods.GET
Method.PUT -> Methods.PUT
Method.POST -> Methods.POST
Method.DELETE -> Methods.DELETE
}
class UndertowRequest(private val exchange: HttpServerExchange) : Request {
private var requestWithBody: RequestWithBody? = null
override suspend fun withBody(): RequestWithBody {
if (requestWithBody != null)
return requestWithBody!!
val body: ByteArray = suspendCoroutine {
exchange.requestReceiver.receiveFullBytes { _, body ->
it.resume(body)
}
}
requestWithBody = UndertowRequestWithBody(this, body)
return requestWithBody!!
}
override val requestPath: String = exchange.requestPath
override val queryString: String = exchange.queryString
override val headers: HeaderMap = HeaderMap(exchange.requestHeaders)
override val method: Method = when (val method = exchange.requestMethod) {
Methods.GET -> Method.GET
Methods.POST -> Method.POST
Methods.PUT -> Method.PUT
Methods.DELETE -> Method.DELETE
else -> throw RestaurantException("unknown request method: $method")
}
override val queryParameters: Map<String, Collection<String>> = exchange.queryParameters
override fun toString(): String =
if (queryString.isEmpty())
"Request(method:$method, path:$requestPath)"
else
"Request(method:$method, path:$requestPath?$queryString)"
}
class UndertowRequestWithBody(private val undertowRequest: UndertowRequest, override val body: ByteArray?) :
RequestWithBody, Request by undertowRequest {
override suspend fun withBody(): RequestWithBody = this
override fun toString(): String {
val withoutBody = undertowRequest.toString()
val body = body?.let { String(it) }
return if (body != null)
withoutBody.dropLast(1) + ", body:" + body + ")"
else
withoutBody
}
}
internal fun buildUndertow(
rootHandlers: List<Pair<SuspendingHandler, Route>>,
defaultHandler: SuspendingHandler,
port: Int,
host: String
): Undertow {
val routingHandler = rootHandlers.fold(RoutingHandler()) { routingHandler, (handler, route) ->
val httpHandler = CoroutinesHandler(handler)
routingHandler.add(route.methodToHttpString(), route.path, httpHandler)
}
routingHandler.fallbackHandler = CoroutinesHandler(defaultHandler)
return Undertow.builder()
// .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
.addHttpListener(port, host).setHandler(SimpleErrorPageHandler(routingHandler)).build()
}
| 9
| null |
0
| 5
|
7491c3346aef3bc4bb823022c6db219880d01db9
| 3,093
|
restaurant
|
MIT License
|
src/main/kotlin/solve/SolveApp.kt
|
prime-slam
| 542,695,410
| false
|
{"Kotlin": 372628, "GLSL": 8458}
|
package solve
import javafx.stage.Stage
import solve.main.MainView
import tornadofx.App
import tornadofx.launch
class SolveApp : App(MainView::class) {
override fun start(stage: Stage) {
with(stage) {
width = 1000.0
height = 600.0
isMaximized = true
}
super.start(stage)
}
}
fun main(args: Array<String>) = launch<SolveApp>(args)
| 50
|
Kotlin
|
0
| 8
|
c7151d6ec19eea84920bcc9d9857f37726f0c813
| 401
|
SOLVE
|
MIT License
|
app/src/main/java/com/example/mydiagnosis/database/dao/EvidencesDao.kt
|
VishwaP98
| 190,676,831
| false
| null |
package com.example.mydiagnosis.database.dao
import android.arch.persistence.room.*
import com.example.mydiagnosis.model.Evidence
@Dao
interface EvidencesDao {
@Query("SELECT * from Evidences where evidenceId = :id")
fun getEvidenceIfPresent(id : String) : Evidence
@Query("SELECT * from Evidences")
fun getAllEvidences() : List<Evidence>
@Query("SELECT * from Evidences where choice_id = :present")
fun getAllPresentEvidences(present : String) : List<Evidence>
@Query("SELECT * from Evidences where choice_id = :absent")
fun getAllAbsentEvidences(absent : String) : List<Evidence>
@Update
fun updateEvidence(evidence: Evidence)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertEvidence(evidence: Evidence)
@Insert
fun insertEvidences(evidences: List<Evidence>)
}
| 1
|
Kotlin
|
1
| 0
|
ccd4ae5cfa2ca7e081ab029943f4c12438def024
| 838
|
MyDiagnosis
|
MIT License
|
src/main/kotlin/com/khekrn/demo/workflow/WorkflowBeamConfiguration.kt
|
khekrncs
| 459,418,233
| false
|
{"Kotlin": 7372}
|
package com.khekrn.demo.workflow
import com.cs.beam.engine.workflow.executor.service.WorkflowExecutorService
import com.cs.beam.engine.workflow.runtime.config.BeamEngineConfig
import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.Resource
import org.springframework.stereotype.Component
import javax.annotation.PostConstruct
import javax.annotation.PreDestroy
@Component
class WorkflowBeamConfiguration(private val workflowExecutorService: WorkflowExecutorService) {
@PostConstruct
fun initialize() {
val resourceSet = setOf<Resource>(
ClassPathResource("workflows/sample.json"),
ClassPathResource("workflows/withconditions.json")
)
val beamEngineConfig = BeamEngineConfig(resourceSet, 1)
workflowExecutorService.initiate(beamEngineConfig)
}
@PreDestroy
fun shutDown() {
workflowExecutorService.shutDown()
}
}
| 0
|
Kotlin
|
0
| 0
|
b0fc27dd9a8649633bb85b2f3415ce8a818d96a0
| 936
|
beam-demo
|
Apache License 2.0
|
core/src/main/kotlin/com/github/icarohs7/unoxandroidarch/extensions/StateViewExtensions.kt
|
icarohs7
| 168,861,268
| false
| null |
package com.github.icarohs7.unoxandroidarch.extensions
import com.umutbey.stateviews.StateView
/**
* Display the loading state if the parameter
* is true of hide all states if false
*/
fun StateView.toggleLoading(isLoading: Boolean) {
if (isLoading) displayLoadingState()
else hideStates()
}
| 0
|
Kotlin
|
0
| 0
|
22ab4cd951974741a235698a5cdb57342ce7325b
| 304
|
unox-android-arch
|
MIT License
|
core/src/main/java/com/infinitepower/newquiz/core/math/evaluator/internal/TokenType.kt
|
joaomanaia
| 443,198,327
| false
| null |
package com.agadimi.calculator.exprk.internal
internal enum class TokenType {
// Basic operators
PLUS,
MINUS,
STAR,
SLASH,
MODULO,
EXPONENT,
SQUARE_ROOT,
ASSIGN,
// Logical operators
EQUAL_EQUAL,
NOT_EQUAL,
GREATER,
GREATER_EQUAL,
LESS,
LESS_EQUAL,
BAR_BAR,
AMP_AMP,
// Other
COMMA,
// Parentheses
LEFT_PAREN,
RIGHT_PAREN,
// Literals
NUMBER,
IDENTIFIER,
EOF
}
| 388
| null |
30
| 99
|
4741a80f1db8073c7d33499523117b446489bbf0
| 476
|
newquiz
|
Apache License 2.0
|
platform/lang-impl/src/com/intellij/ide/bookmark/providers/InvalidBookmark.kt
|
JetBrains
| 2,489,216
| false
| null |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.providers
import com.intellij.ide.bookmark.Bookmark
import java.util.Objects
internal class InvalidBookmark(override val provider: LineBookmarkProvider, val url: String, val line: Int) : Bookmark {
override val attributes: Map<String, String>
get() = mapOf("url" to url, "line" to line.toString())
override fun createNode() = UrlNode(provider.project, this)
override fun canNavigate() = false
override fun canNavigateToSource() = false
override fun navigate(requestFocus: Boolean) = Unit
override fun hashCode() = Objects.hash(provider, url, line)
override fun equals(other: Any?) = other === this || other is InvalidBookmark
&& other.provider == provider
&& other.url == url
&& other.line == line
override fun toString() = "InvalidBookmark(line=$line,url=$url,provider=$provider)"
}
| 214
| null |
4829
| 15,129
|
5578c1c17d75ca03071cc95049ce260b3a43d50d
| 1,115
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/ir/apptune/antispam/features/callog/adapter/CallLogsDiffUtils.kt
|
SirLordPouya
| 241,154,265
| false
| null |
package ir.apptune.antispam.features.callog.adapter
import androidx.recyclerview.widget.DiffUtil
import ir.apptune.antispam.pojos.CallModel
/**
* DiffUtils for call logs
*
*/
class CallLogsDiffUtils : DiffUtil.ItemCallback<CallModel>() {
override fun areItemsTheSame(oldItem: CallModel, newItem: CallModel) =
oldItem.number == newItem.number && oldItem.callDate == newItem.callDate && oldItem.callStatus == newItem.callStatus
override fun areContentsTheSame(oldItem: CallModel, newItem: CallModel) =
oldItem.number == newItem.number && oldItem.callDate == newItem.callDate && oldItem.callStatus == newItem.callStatus
}
| 0
|
Kotlin
|
1
| 9
|
fb620efe5ac319057f854ca91e810887d295feb6
| 656
|
AntiSpam
|
Apache License 2.0
|
src/main/java/com/worksap/nlp/elasticsearch/sudachi/index/SudachiStopTokenFilterFactory.kt
|
WorksApplications
| 110,100,447
| false
|
{"Kotlin": 205751, "Java": 76537, "Groovy": 18805, "Python": 12600, "Shell": 5542}
|
/*
* Copyright (c) 2017-2023 Works Applications Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.worksap.nlp.elasticsearch.sudachi.index
import com.worksap.nlp.lucene.sudachi.ja.SudachiAnalyzer
import com.worksap.nlp.search.aliases.AbstractTokenFilterFactory
import com.worksap.nlp.search.aliases.Environment
import com.worksap.nlp.search.aliases.IndexSettings
import com.worksap.nlp.search.aliases.Settings
import com.worksap.nlp.search.aliases.parseWords
import org.apache.lucene.analysis.TokenStream
import org.apache.lucene.analysis.core.StopFilter
import org.apache.lucene.search.suggest.analyzing.SuggestStopFilter
class SudachiStopTokenFilterFactory(
indexSettings: IndexSettings?,
env: Environment?,
name: String?,
settings: Settings
) : AbstractTokenFilterFactory(indexSettings, env, name, settings) {
private val ignoreCase = settings.getAsBoolean("ignore_case", false)
private val removeTrailing = settings.getAsBoolean("remove_trailing", true)
private val stopWords =
parseWords(
env,
settings,
"stopwords",
SudachiAnalyzer.getDefaultStopSet(),
NAMED_STOP_WORDS,
ignoreCase,
)
override fun create(tokenStream: TokenStream?): TokenStream {
return if (removeTrailing) {
StopFilter(tokenStream, stopWords)
} else {
SuggestStopFilter(tokenStream, stopWords)
}
}
companion object {
private val NAMED_STOP_WORDS =
mapOf(
"_japanese_" to SudachiAnalyzer.getDefaultStopSet(),
)
}
}
| 3
|
Kotlin
|
41
| 183
|
df617af023e9ab5b834b07170eb860c9b1c6af6b
| 2,085
|
elasticsearch-sudachi
|
Apache License 2.0
|
src/main/kotlin/solve/importer/model/FileInfo.kt
|
prime-slam
| 542,695,410
| false
|
{"Kotlin": 442756}
|
package solve.importer.model
data class FileInfo(
val name: String = "",
val isLeaf: Boolean = false,
val errors: MutableList<String> = mutableListOf()
)
| 52
|
Kotlin
|
0
| 8
|
67352bd0ed1f437fad6b151400898f57ae926c67
| 167
|
SOLVE
|
MIT License
|
src/main/kotlin/org/kamiblue/client/manager/managers/KamiMojiManager.kt
|
NotMonika
| 509,486,355
| false
|
{"Kotlin": 1389924, "Java": 110277, "Shell": 15180, "GLSL": 3626}
|
/*
* This file is adapted from 2b2t-Utilities/emoji-api which is licensed under MIT.
* You can find a copy of the original license here: https://github.com/2b2t-Utilities/emoji-api/blob/35b0683/LICENSE
*/
package org.kamiblue.client.manager.managers
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kamiblue.client.KamiMod
import org.kamiblue.client.manager.Manager
import org.kamiblue.client.util.graphics.texture.MipmapTexture
import org.kamiblue.client.util.threads.defaultScope
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL12.GL_CLAMP_TO_EDGE
import org.lwjgl.opengl.GL14.GL_TEXTURE_LOD_BIAS
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.util.zip.ZipInputStream
import javax.imageio.ImageIO
object KamiMojiManager : Manager {
private const val directory = "${KamiMod.DIRECTORY}emojis"
private const val versionURL = "https://raw.githubusercontent.com/2b2t-Utilities/emojis/master/version.json"
private const val zipUrl = "https://github.com/2b2t-Utilities/emojis/archive/master.zip"
private val parser = JsonParser()
private val emojiMap = HashMap<String, MipmapTexture>()
private val fileMap = HashMap<String, File>()
private val job = defaultScope.launch(Dispatchers.IO) {
val directory = File(directory)
if (!directory.exists()) {
directory.mkdir()
}
try {
checkEmojiUpdate()
} catch (e: Exception) {
KamiMod.LOG.warn("Failed to check emoji update", e)
}
directory.listFiles()?.forEach {
if (it.isFile && it.extension == "png") {
fileMap[it.nameWithoutExtension] = it
}
}
KamiMod.LOG.info("KamiMoji Initialized")
}
private fun checkEmojiUpdate() {
val localVersion = File("$directory/version.json")
if (!localVersion.exists()) {
updateEmojis()
} else {
val globalVer = streamToJson(URL(versionURL).openStream())
val localVer = streamToJson(FileInputStream(localVersion))
if (globalVer != null) {
if (!globalVer.has("version")) {
updateEmojis()
} else if (globalVer["version"].asInt != localVer?.get("version")?.asInt ?: 8) {
updateEmojis()
}
}
}
}
private fun streamToJson(stream: InputStream): JsonObject? {
return try {
parser.parse(stream.reader()).asJsonObject
} catch (e: Exception) {
KamiMod.LOG.warn("Failed to parse emoji version Json", e)
null
}
}
private fun updateEmojis() {
val zip = ZipInputStream(URL(zipUrl).openStream())
var entry = zip.nextEntry
while (entry != null) {
if (!entry.isDirectory) {
val path = "$directory/${entry.name.substringAfterLast('/')}"
File(path).apply {
if (!exists()) createNewFile()
writeBytes(zip.readBytes())
}
}
zip.closeEntry()
entry = zip.nextEntry
}
zip.close()
}
fun getEmoji(name: String?): MipmapTexture? {
if (name == null) return null
// Returns null if still loading
if (job.isActive) {
return null
}
// Loads emoji on demand
if (!emojiMap.containsKey(name)) {
loadEmoji(name)
}
return emojiMap[name]
}
fun isEmoji(name: String?) = getEmoji(name) != null
private fun loadEmoji(name: String) {
val file = fileMap[name] ?: return
if (!file.exists()) return
try {
val image = ImageIO.read(file)
val texture = MipmapTexture(image, GL_RGBA, 3)
texture.bindTexture()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, -0.5f)
texture.unbindTexture()
emojiMap[name] = texture
} catch (e: IOException) {
KamiMod.LOG.warn("Failed to load emoji", e)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
88dc5a7e96ba358898b03681bfdf760e93f94812
| 4,621
|
__AntiZhangZongZe__
|
Do What The F*ck You Want To Public License
|
commons/src/commonMain/kotlin/org/jetbrains/letsPlot/commons/geometry/DoubleRectangles.kt
|
JetBrains
| 176,771,727
| false
| null |
/*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.commons.geometry
import kotlin.math.max
import kotlin.math.min
object DoubleRectangles {
/*
Returns null if point collection is empty
*/
fun boundingBox(points: Iterable<DoubleVector>): DoubleRectangle? {
return calculateBoundingBox(points, DoubleVector::x, DoubleVector::y)
{ minX, minY, maxX, maxY ->
DoubleRectangle.span(
DoubleVector(minX, minY),
DoubleVector(maxX, maxY)
)
}
}
fun <PointT, BoxT> calculateBoundingBox(
points: Iterable<PointT>,
getX: (PointT) -> Double,
getY: (PointT) -> Double,
factory: (minX: Double, minY: Double, maxX: Double, maxY: Double) -> BoxT
): BoxT? {
if (!points.iterator().hasNext()) {
return null
}
val first = points.iterator().next()
var minLon = getX(first)
var minLat = getY(first)
var maxLon = minLon
var maxLat = minLat
for (point in points) {
minLon = min(minLon, getX(point))
maxLon = max(maxLon, getX(point))
minLat = min(minLat, getY(point))
maxLat = max(maxLat, getY(point))
}
return factory(minLon, minLat, maxLon, maxLat)
}
}
| 97
|
Kotlin
|
47
| 889
|
c5c66ceddc839bec79b041c06677a6ad5f54e416
| 1,442
|
lets-plot
|
MIT License
|
2 Layouts/AboutMe/app/src/main/java/com/android/example/AboutMe/MyName.kt
|
Android-SrA-2020
| 232,567,525
| false
| null |
package com.android.example.AboutMe
| 0
|
Kotlin
|
0
| 0
|
3f1481b37aad553ebe529eabc40692edecd837ae
| 37
|
homework-KhoiRyanNguyen
|
MIT License
|
app/src/main/java/com/github/cfogrady/vitalwear/character/mood/MoodBroadCastReceiver.kt
|
cfogrady
| 619,941,986
| false
|
{"Kotlin": 573795}
|
package com.github.cfogrady.vitalwear.character.mood
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import java.time.LocalDateTime
class MoodBroadcastReceiver(
private val moodService: MoodService) : BroadcastReceiver() {
companion object {
const val MOOD_UPDATE = "MOOD_UPDATE_INTENT"
const val TAG = "MoodBroadcastReceiver"
}
override fun onReceive(context: Context?, intent: Intent?) {
if(intent?.action == MOOD_UPDATE) {
Log.i(TAG, "MOOD_UPDATE_INTENT broadcast intent received")
moodService.updateMood(LocalDateTime.now())
}
}
}
| 21
|
Kotlin
|
0
| 4
|
2d56228325fd0e6a68456173a28f880dea3e0cb3
| 691
|
VitalWear
|
MIT License
|
editor-plugins/src/main/kotlin/ru/ilyasshafigin/openrndr/editor/plugin/ShaderPlugin.kt
|
ilyasshafigin
| 258,325,328
| false
| null |
package ru.ilyasshafigin.openrndr.editor.plugin
import ru.ilyasshafigin.openrndr.editor.Canvas
import ru.ilyasshafigin.openrndr.editor.Editor
import ru.ilyasshafigin.openrndr.editor.EditorPlugin
import mu.KotlinLogging
import org.openrndr.color.ColorRGBa
import org.openrndr.draw.ArrayTexture
import org.openrndr.draw.BlendMode
import org.openrndr.draw.ColorBuffer
import org.openrndr.draw.Cubemap
import org.openrndr.draw.DepthBuffer
import org.openrndr.draw.DepthTestPass
import org.openrndr.draw.DrawPrimitive
import org.openrndr.draw.DrawStyle
import org.openrndr.draw.Drawer
import org.openrndr.draw.RenderTarget
import org.openrndr.draw.Session
import org.openrndr.draw.Shader
import org.openrndr.draw.StencilTest
import org.openrndr.draw.VertexBuffer
import org.openrndr.draw.isolatedWithTarget
import org.openrndr.draw.renderTarget
import org.openrndr.draw.vertexFormat
import org.openrndr.extra.glslify.preprocessGlslify
import org.openrndr.extra.glslify.preprocessGlslifyFromUrl
import org.openrndr.extra.parameters.BooleanParameter
import org.openrndr.extra.parameters.Description
import org.openrndr.internal.Driver
import org.openrndr.math.Matrix44
import org.openrndr.math.Matrix55
import org.openrndr.math.Vector2
import org.openrndr.math.Vector3
import org.openrndr.math.Vector4
import org.openrndr.math.transforms.ortho
/**
* Plugin for shader drawing.
*
* Available shader parameters and attributes:
* - `uniform mat4 projectionMatrix;`
* - `uniform vec2 resolution;` - viewport resolution in pixels
* - `uniform float time;` - current running time in seconds
* - `uniform vec2 mouse;` - mouse pixel coords. xy: current, zw: mouse button down position, otherwise negative values
* - `uniform sampler2D canvas;` - current canvas texture
* - `uniform sampler2D source;` - current source texture
* - `uniform vec2 sourceSize;`
* - `uniform vec2 sourceOffset;`
* - `in vec2 texCoord;` - pixel uv position (0..1)
*/
class ShaderPlugin : EditorPlugin {
override val settings = Settings()
/** Path to GLSL shader files */
var glslPath = "data/shader"
var glslifyPath = "data/shader/glslify"
/** If [realTime] is true, then [time] will be real time, otherwise [time] will be calculated from [frameRate] */
var realTime = true
/** Frame rate (fps). It applies if [realTime] is true */
var frameRate = 60
private var time: Double = 0.0
private var previewScale: Double = 1.0
private var mouseButtonDownPosition: Vector2? = null
private val logger = KotlinLogging.logger { }
private val shaders = LinkedHashMap<String, FragmentShader>()
private lateinit var canvas: Canvas
override fun setup(editor: Editor<*>) {
logger.info { "Setup ShaderPlugin" }
canvas = editor.canvas
previewScale = editor.config.previewScale
editor.mouse.buttonDown.listen {
mouseButtonDownPosition = it.position
}
editor.mouse.buttonUp.listen {
mouseButtonDownPosition = null
}
}
override fun reset(editor: Editor<*>) {
time = 0.0
}
override fun beforeDraw(drawer: Drawer, editor: Editor<*>) {
if (settings.isUpdateEnabled) {
time += if (realTime) editor.deltaTime else (1.0 / frameRate)
}
val sourcePlugin = if (editor.isPluginInstalled<SourcePlugin>()) editor.source else null
val canvasTarget = canvas.target
val sourceColorBuffer = sourcePlugin?.image?.colorBuffer ?: canvasTarget.colorBuffer(0)
val sourceOffset = sourcePlugin?.area?.corner ?: Vector2.ZERO
val sourceSize = Vector2(sourceColorBuffer.width.toDouble(), sourceColorBuffer.height.toDouble())
val resolution = Vector2(canvasTarget.width.toDouble(), canvasTarget.height.toDouble())
val projectionMatrix = ortho(0.0, resolution.x, resolution.y, 0.0, -1.0, 1.0)
val mouseDownPosition = mouseButtonDownPosition?.let { position ->
Vector2(position.x / previewScale, resolution.y - position.y / previewScale)
}
val mousePosition = Vector4(
x = editor.mouse.position.x / previewScale,
y = resolution.y - editor.mouse.position.y / previewScale,
z = mouseDownPosition?.x ?: -1.0,
w = mouseDownPosition?.y ?: -1.0
)
shaders.values.forEach { shader ->
shader.projectionMatrix = projectionMatrix
shader.resolution = resolution
shader.targetSize = resolution
shader.time = time
shader.mouse = mousePosition
shader.source = sourceColorBuffer
shader.sourceSize = sourceSize
shader.sourceOffset = sourceOffset
shader.beforeDraw(canvas.width, canvas.height)
}
}
override fun afterDraw(drawer: Drawer, editor: Editor<*>) {
shaders.values.reversed().forEach { shader ->
shader.afterDraw(drawer, canvas.target, editor.width, editor.height)
}
}
fun addShader(name: String, shader: FragmentShader): FragmentShader {
shaders[name] = shader
logger.info { "Added shader '$name' from instance '$shader'" }
return shader
}
fun addShader(name: String, shader: FragmentShader, config: FragmentShader.() -> Unit) {
addShader(name, shader).config()
}
fun addShaderFromPath(name: String, path: String): FragmentShader {
val shaderUrl = shaderUrl(path)
val shaderCode = preprocessGlslifyFromUrl(shaderUrl, glslifyPath = glslifyPath)
val shader = FragmentShader(name, shaderCode)
shaders[name] = shader
logger.info { "Added shader '$name' from path '$path'" }
return shader
}
fun addShaderFromPath(name: String, path: String, config: FragmentShader.() -> Unit) {
addShaderFromPath(name, path).config()
}
fun addShaderFromCode(name: String, code: String): FragmentShader {
val shaderCode = preprocessGlslify(code, glslifyPath = glslifyPath)
val shader = FragmentShader(name, shaderCode)
shaders[name] = shader
logger.info { "Added shader '$name' from code" }
return shader
}
fun addShaderFromCode(name: String, code: String, config: FragmentShader.() -> Unit) {
addShaderFromCode(name, code).config()
}
private fun shaderUrl(path: String) = "file:$glslPath/$path"
@Description(title = "Shader")
class Settings {
@BooleanParameter(label = "Update")
var isUpdateEnabled = true
}
}
open class FragmentShader(private val shader: Shader) {
constructor(name: String, fragmentCode: String) :
this(Shader.createFromCode(vsCode = filterVertexCode, fsCode = fragmentCode, name = name))
constructor(name: String, vertexCode: String, fragmentCode: String) :
this(Shader.createFromCode(vsCode = vertexCode, fsCode = fragmentCode, name = name))
/**
* parameter map
*/
val parameters = mutableMapOf<String, Any>()
var projectionMatrix: Matrix44 by parameters
var resolution: Vector2 by parameters
var targetSize: Vector2 by parameters
var time: Double by parameters
var mouse: Vector4 by parameters
var source: ColorBuffer by parameters
var sourceSize: Vector2 by parameters
var sourceOffset: Vector2 by parameters
private var filteredTarget: RenderTarget? = null
private fun apply(canvas: ColorBuffer, target: RenderTarget) {
var textureIndex = 0
target.bind()
shader.begin()
canvas.bind(textureIndex)
shader.uniform("canvas", textureIndex++)
parameters.forEach { (uniform, value) ->
@Suppress("UNCHECKED_CAST")
when (value) {
is Boolean -> shader.uniform(uniform, value)
is Float -> shader.uniform(uniform, value)
is Double -> shader.uniform(uniform, value.toFloat())
is Matrix44 -> shader.uniform(uniform, value)
is Vector2 -> shader.uniform(uniform, value)
is Vector3 -> shader.uniform(uniform, value)
is Vector4 -> shader.uniform(uniform, value)
is ColorRGBa -> shader.uniform(uniform, value)
is Int -> shader.uniform(uniform, value)
is Matrix55 -> shader.uniform(uniform, value.floatArray)
is FloatArray -> shader.uniform(uniform, value)
// EJ: this is not so nice but I have no other ideas for this
is Array<*> -> if (value.size > 0) when (value[0]) {
is Vector2 -> shader.uniform(uniform, value as Array<Vector2>)
is Vector3 -> shader.uniform(uniform, value as Array<Vector3>)
is Vector4 -> shader.uniform(uniform, value as Array<Vector4>)
else -> throw IllegalArgumentException("unsupported array value: ${value[0]!!::class.java}")
}
is DepthBuffer -> {
shader.uniform(uniform, textureIndex)
value.bind(textureIndex++)
}
is ColorBuffer -> {
shader.uniform(uniform, textureIndex)
value.bind(textureIndex++)
}
is Cubemap -> {
shader.uniform(uniform, textureIndex)
value.bind(textureIndex++)
}
is ArrayTexture -> {
shader.uniform(uniform, textureIndex)
value.bind(textureIndex++)
}
}
}
Driver.instance.setState(filterDrawStyle)
Driver.instance.drawVertexBuffer(shader, listOf(filterQuad), DrawPrimitive.TRIANGLES, 0, 6)
shader.end()
target.unbind()
}
fun beforeDraw(canvasWidth: Int, canvasHeight: Int) {
if (filteredTarget == null ||
filteredTarget?.width != canvasWidth ||
filteredTarget?.height != canvasHeight
) {
filteredTarget?.detachColorBuffers()
filteredTarget?.detachDepthBuffer()
filteredTarget?.destroy()
filteredTarget = renderTarget(canvasWidth, canvasHeight) {
colorBuffer()
depthBuffer()
}
}
}
fun afterDraw(drawer: Drawer, canvasTarget: RenderTarget, editorWidth: Int, editorHeight: Int) {
filteredTarget?.let { filtered ->
apply(canvasTarget.colorBuffer(0), filtered)
drawer.isolatedWithTarget(canvasTarget) {
ortho()
view = Matrix44.IDENTITY
model = Matrix44.IDENTITY
image(filtered.colorBuffer(0), 0.0, 0.0, editorWidth * 1.0, editorHeight * 1.0)
}
}
}
fun untrack() {
Session.active.untrack(shader)
}
companion object {
private val filterDrawStyle = DrawStyle().apply {
blendMode = BlendMode.REPLACE
depthWrite = false
depthTestPass = DepthTestPass.ALWAYS
stencil.stencilTest = StencilTest.DISABLED
}
private val filterQuad: VertexBuffer by lazy {
VertexBuffer.createDynamic(filterQuadFormat, 6, Session.root).apply {
shadow.writer().apply {
write(Vector2(0.0, 1.0)); write(Vector2(0.0, 0.0))
write(Vector2(0.0, 0.0)); write(Vector2(0.0, 1.0))
write(Vector2(1.0, 0.0)); write(Vector2(1.0, 1.0))
write(Vector2(0.0, 1.0)); write(Vector2(0.0, 0.0))
write(Vector2(1.0, 1.0)); write(Vector2(1.0, 0.0))
write(Vector2(1.0, 0.0)); write(Vector2(1.0, 1.0))
}
shadow.upload()
shadow.destroy()
}
}
private val filterQuadFormat = vertexFormat {
position(2)
textureCoordinate(2)
}
private val filterVertexCode = """
|#version 330
|
|in vec2 a_texCoord0;
|in vec2 a_position;
|
|uniform vec2 targetSize;
|uniform mat4 projectionMatrix;
|
|out vec2 texCoord;
|
|void main() {
| texCoord = a_texCoord0;
| vec2 transformed = a_position * targetSize;
| gl_Position = projectionMatrix * vec4(transformed, 0.0, 1.0);
|}
""".trimMargin()
}
}
val Editor<*>.shaders: ShaderPlugin
get() = getPlugin()
| 0
|
Kotlin
|
0
| 1
|
7166d40e19687da68b2cf7d9c40b322daa17864e
| 12,627
|
openrndr-editor
|
MIT License
|
data/src/main/java/team/msg/data/dto/notice/response/getDetailNotice/Path.kt
|
GSM-MSG
| 637,641,666
| false
| null |
package team.msg.data.dto.notice.response.getDetailNotice
import team.msg.domain.model.notice.response.getDetailNotice.PathModel
import java.util.UUID
data class Path(
val id: UUID
)
fun Path.asPathModel() = PathModel(id)
| 0
|
Kotlin
|
0
| 10
|
782ebaa545a6aa2f21b5cb91efbd4371c4875d65
| 229
|
Hi-v2-Android
|
MIT License
|
app/src/main/java/com/charlesmuchene/kotlin/learn/models/Country.kt
|
StevenKatabalwa
| 191,611,390
| true
|
{"Kotlin": 21641}
|
package com.charlesmuchene.kotlin.learn.models
import android.os.Parcelable
import com.charlesmuchene.kotlin.learn.utilities.orDash
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
/**
* Country class
*/
@Parcelize
data class Country(
@SerializedName("name") val name: String,
@SerializedName("capital") val capital: String,
@SerializedName("region") val region: String,
@SerializedName("subregion") val subregion: String,
@SerializedName("flag") val flag: String,
@SerializedName("nativeName") val nativeName: String,
@SerializedName("population") val population: Int,
@SerializedName("demonym") val demonym: String,
@SerializedName("timezones") val timezones: Array<String>,
@SerializedName("currencies") val currencies: Array<Currency>,
@SerializedName("languages") val languages: Array<Language>
) :
Parcelable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Country
if (name != other.name) return false
if (capital != other.capital) return false
if (region != other.region) return false
if (subregion != other.subregion) return false
if (flag != other.flag) return false
if (nativeName != other.nativeName) return false
if (population != other.population) return false
if (demonym != other.demonym) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + capital.hashCode()
result = 31 * result + region.hashCode()
result = 31 * result + subregion.hashCode()
result = 31 * result + flag.hashCode()
result = 31 * result + nativeName.hashCode()
result = 31 * result + population
result = 31 * result + demonym.hashCode()
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
6c1648fccf3e61f940e176cf3f7fbe8f66c6d469
| 1,966
|
learn-kotlin-app
|
Apache License 2.0
|
app/src/main/java/com/leehendryp/stoneandroidchallenge/feed/data/dependencyinjection/DataModule.kt
|
leehendryp
| 258,582,373
| false
| null |
package com.leehendryp.stoneandroidchallenge.feed.data.dependencyinjection
import android.content.Context
import com.leehendryp.stoneandroidchallenge.core.utils.NetworkUtils
import com.leehendryp.stoneandroidchallenge.feed.data.JokeRepositoryImpl
import com.leehendryp.stoneandroidchallenge.feed.data.local.LocalDataSource
import com.leehendryp.stoneandroidchallenge.feed.data.local.LocalDataSourceImpl
import com.leehendryp.stoneandroidchallenge.feed.data.local.database.JokeDatabase
import com.leehendryp.stoneandroidchallenge.feed.data.local.database.JokeDatabase.Companion.getDatabase
import com.leehendryp.stoneandroidchallenge.feed.data.local.database.RoomJokeDao
import com.leehendryp.stoneandroidchallenge.feed.data.remote.JokesApi
import com.leehendryp.stoneandroidchallenge.feed.data.remote.RemoteDataSource
import com.leehendryp.stoneandroidchallenge.feed.data.remote.RemoteDataSourceImpl
import com.leehendryp.stoneandroidchallenge.feed.domain.JokeRepository
import dagger.Module
import dagger.Provides
import hu.akarnokd.rxjava3.retrofit.RxJava3CallAdapterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
@Module
class DataModule {
@Provides
fun provideHttpClient(): OkHttpClient =
OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.build()
@Singleton
@Provides
fun provideNetworkService(okHttpClient: OkHttpClient): JokesApi = Retrofit.Builder()
.baseUrl(JokesApi.BASE_URL)
.client(okHttpClient)
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(JokesApi::class.java)
@Singleton
@Provides
fun provideDatabase(context: Context): JokeDatabase = getDatabase(context)
@Singleton
@Provides
fun provideDao(database: JokeDatabase): RoomJokeDao = database.roomJokeDao()
@Provides
fun provideRemoteDataSource(api: JokesApi): RemoteDataSource = RemoteDataSourceImpl(api)
@Provides
fun provideLocalDataSource(dao: RoomJokeDao): LocalDataSource = LocalDataSourceImpl(dao)
@Provides
fun provideNetworkUtils(context: Context): NetworkUtils = NetworkUtils(context)
@Singleton
@Provides
fun provideRepository(
networkUtils: NetworkUtils,
remoteDataSource: RemoteDataSource,
localDataSource: LocalDataSource
): JokeRepository = JokeRepositoryImpl(networkUtils, remoteDataSource, localDataSource)
}
| 2
|
Kotlin
|
0
| 0
|
3f165de843abe9ec89eaaf9e93144ac4e6f56f7f
| 2,659
|
stone_android_challenge
|
MIT License
|
revcrm-server/src/main/kotlin/org/revcrm/db/EntityStoredPropertyPersister.kt
|
RevCRM
| 78,327,204
| false
|
{"JavaScript": 1795259, "Kotlin": 243670, "TypeScript": 181730, "CSS": 40221, "HTML": 6649, "Dockerfile": 278, "Shell": 89}
|
package org.revcrm.db
import com.mongodb.DBObject
import org.revcrm.annotations.Stored
import xyz.morphia.AbstractEntityInterceptor
import xyz.morphia.mapping.Mapper
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.javaField
class EntityStoredPropertyPersister : AbstractEntityInterceptor() {
override fun prePersist(ent: Any, dbObj: DBObject, mapper: Mapper) {
// Scan for members tagged with @Stored that do NOT have a backing field
// (these members are not automatically persisted by morpia)
val clazz = ent.javaClass.kotlin
clazz.memberProperties.forEach { prop ->
if (
prop.javaField == null &&
prop.findAnnotation<Stored>() != null
) {
val value = prop.get(ent)
dbObj.put(prop.name, value)
}
}
}
}
| 5
|
JavaScript
|
1
| 3
|
4e9682e0e6919ea59105adc9522084f91b2cfb50
| 921
|
kotlin-prototype
|
Apache License 2.0
|
src/main/kotlin/de/neusta/ncc/infrastructure/mapper/CsvImportMapper.kt
|
larmic
| 123,574,305
| false
| null |
package de.neusta.ncc.infrastructure.mapper
import com.fasterxml.jackson.databind.MappingIterator
import com.fasterxml.jackson.dataformat.csv.CsvMapper
import com.fasterxml.jackson.dataformat.csv.CsvParser
import de.neusta.ncc.domain.Room
import de.neusta.ncc.infrastructure.mapper.exception.CsvPersonNotValidException
import de.neusta.ncc.infrastructure.mapper.exception.EmptyFileImportException
import de.neusta.ncc.infrastructure.mapper.exception.FileImportException
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
import java.lang.AssertionError
import java.util.*
/**
* Maps a given {@link MultipartFile} to list of {@link Room}. Does not validate any content of given file.
*/
@Component
class CsvImportMapper(private val csvPersonToPersonMapper: CsvPersonToPersonMapper) {
private val log = LoggerFactory.getLogger(this.javaClass)
@Throws(FileImportException::class, EmptyFileImportException::class, AssertionError::class)
fun map(file: MultipartFile): List<Room> {
try {
return file
.loadBytes()
.mapToSimpleImportModel()
.convertCsvImportRooms()
} catch (e: IOException) {
log.error("Could not import {}", file.originalFilename, e)
throw FileImportException(e)
}
}
@Throws(IOException::class)
private fun MultipartFile.loadBytes(): ByteArray {
if (this.isEmpty) {
log.error("File %s is empty", this.originalFilename)
throw EmptyFileImportException()
}
return this.bytes
}
@Throws(IOException::class)
private fun ByteArray.mapToSimpleImportModel(): List<SimpleImportRoom> {
val dataModel = ArrayList<SimpleImportRoom>()
val it = readCsvValues(this)
while (it.hasNext()) {
val csvRow = it.next()
val roomNumber = csvRow[0]
val persons = listOf(*csvRow).subList(1, csvRow.size)
dataModel.add(SimpleImportRoom(roomNumber, persons.filter { it.isNotEmpty() }))
}
return dataModel
}
@Throws(IOException::class)
private fun readCsvValues(csvData: ByteArray): MappingIterator<Array<String>> {
val mapper = CsvMapper()
mapper.enable(CsvParser.Feature.WRAP_AS_ARRAY)
return mapper.readerFor(Array<String>::class.java).readValues(csvData)
}
@Throws(CsvPersonNotValidException::class, AssertionError::class)
private fun List<SimpleImportRoom>.convertCsvImportRooms(): List<Room> {
return this.map { it.convertToRoom() }
}
private inner class SimpleImportRoom(private val room: String, private val persons: List<String>) {
@Throws(CsvPersonNotValidException::class, AssertionError::class)
fun convertToRoom(): Room {
val people = persons.map { csvPersonToPersonMapper.map(it) }
return Room(roomNumber = room, persons = people)
}
}
}
| 3
| null |
0
| 2
|
69fb7e7bb82cd4a29bf6b790fecf05a86965a00b
| 3,065
|
neusta-code-challange-kotlin
|
Apache License 2.0
|
cmm/src/main/java/com/benli/cmm/network/CacheInterceptor.kt
|
beilly
| 98,971,871
| false
| null |
package com.benli.cmm.network
import android.content.Context
import android.util.Log
import com.benli.cmm.utils.NetworkUtils
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.CacheControl
/**
* Created by lvruheng on 2017/7/4.
*/
class CacheInterceptor(context: Context) : Interceptor{
val context = context
override fun intercept(chain: Interceptor.Chain?): Response? {
var request = chain?.request()
if (NetworkUtils.isNetConneted(context)) {
val response = chain?.proceed(request)
// read from cache for 60 s
val maxAge = 6
val cacheControl = request?.cacheControl().toString()
Log.e("CacheInterceptor", "6s load cahe" + cacheControl)
return response?.newBuilder()?.removeHeader("Pragma")?.removeHeader("Cache-Control")?.header("Cache-Control", "public, max-age=" + maxAge)?.build()
} else {
Log.e("CacheInterceptor", " no network load cahe")
request = request?.newBuilder()?.cacheControl(CacheControl.FORCE_CACHE)?.build()
val response = chain?.proceed(request)
//set cahe times is 3 days
val maxStale = 60 * 60 * 24 * 3
return response?.newBuilder()?.removeHeader("Pragma")?.removeHeader("Cache-Control")?.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)?.build()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
74ad306c941d49a22012d67aa6c05309a81c0452
| 1,409
|
KotlinWeather
|
Apache License 2.0
|
app/src/main/java/de/seemoo/at_tracking_detection/ui/scan/ScanFragment.kt
|
seemoo-lab
| 385,199,222
| false
| null |
package de.seemoo.at_tracking_detection.ui.scan
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import de.seemoo.at_tracking_detection.ATTrackingDetectionApplication
import de.seemoo.at_tracking_detection.R
import de.seemoo.at_tracking_detection.database.models.device.DeviceManager
import de.seemoo.at_tracking_detection.databinding.FragmentScanBinding
import de.seemoo.at_tracking_detection.util.Util
import timber.log.Timber
@AndroidEntryPoint
class ScanFragment : Fragment() {
private val scanViewModel: ScanViewModel by viewModels()
private var bluetoothManager: BluetoothManager? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding: FragmentScanBinding =
DataBindingUtil.inflate(inflater, R.layout.fragment_scan, container, false)
val bluetoothDeviceAdapter = BluetoothDeviceAdapter(childFragmentManager)
binding.adapter = bluetoothDeviceAdapter
binding.lifecycleOwner = viewLifecycleOwner
binding.vm = scanViewModel
scanViewModel.bluetoothDeviceList.observe(viewLifecycleOwner) {
bluetoothDeviceAdapter.submitList(it)
// Ugly workaround because i don't know why this adapter only displays items after a screen wake up...
bluetoothDeviceAdapter.notifyDataSetChanged()
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
startBluetoothScan()
}
private val scanCallback: ScanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult?) {
super.onScanResult(callbackType, result)
result?.let {
scanViewModel.addScanResult(it)
}
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
Timber.e("BLE Scan failed. $errorCode")
view?.let {
Snackbar.make(
it,
R.string.ble_service_connection_error,
Snackbar.LENGTH_LONG
)
}
}
}
private fun startBluetoothScan() {
bluetoothManager =
ATTrackingDetectionApplication.getAppContext()
.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val scanSettings =
ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
bluetoothManager?.let {
val isBluetoothEnabled = it.adapter.state == BluetoothAdapter.STATE_ON
val hasScanPermission =
Build.VERSION.SDK_INT < Build.VERSION_CODES.S || Util.checkAndRequestPermission(
Manifest.permission.BLUETOOTH_SCAN
)
if (isBluetoothEnabled && hasScanPermission) {
it.adapter.bluetoothLeScanner.startScan(DeviceManager.scanFilter, scanSettings, scanCallback)
Handler(Looper.getMainLooper()).postDelayed({
// Stop scanning if no device was detected
if (scanViewModel.isListEmpty.value == true) {
scanViewModel.scanFinished.postValue(true)
stopBluetoothScan()
}
}, SCAN_DURATION)
}
}
}
@SuppressLint("MissingPermission")
private fun stopBluetoothScan() {
bluetoothManager?.let {
if (it.adapter.state == BluetoothAdapter.STATE_ON) {
it.adapter.bluetoothLeScanner.stopScan(scanCallback)
}
}
}
override fun onResume() {
super.onResume()
startBluetoothScan()
}
override fun onPause() {
super.onPause()
stopBluetoothScan()
}
override fun onDestroyView() {
super.onDestroyView()
stopBluetoothScan()
}
companion object {
private const val SCAN_DURATION = 10000L
}
}
| 34
| null |
85
| 1,608
|
a53fb9e7d4706d8d03a6da30273f648e6015a765
| 4,818
|
AirGuard
|
Apache License 2.0
|
collections-extensions/src/main/kotlin/org/knowledger/collections/CollectionsExtensions.kt
|
andrediogo92
| 122,662,386
| false
|
{"Kotlin": 795385, "Rust": 9666, "Python": 228}
|
package org.knowledger.collections
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
fun <T> emptySortedList(comparator: Comparator<T>): SortedList<T> =
DelegatedSortedList(comparator)
fun <T : Comparable<T>> emptySortedList(): SortedList<T> =
emptySortedList { o1, o2 -> o1.compareTo(o2) }
fun <T> mutableSortedListOf(
comparator: Comparator<T>, vararg elements: T,
): MutableSortedList<T> = elements.asIterable().toMutableSortedList(comparator)
fun <T : Comparable<T>> mutableSortedListOf(vararg elements: T): MutableSortedList<T> =
elements.asIterable().toMutableSortedList()
fun <T> sortedListOf(comparator: Comparator<T>, vararg elements: T): SortedList<T> =
elements.asIterable().toSortedList(comparator)
fun <T : Comparable<T>> sortedListOf(vararg elements: T): SortedList<T> =
elements.asIterable().toSortedList()
fun <T : Comparable<T>> Sequence<T>.toMutableSortedListFromPreSorted(): MutableSortedList<T> =
asIterable().toMutableSortedListFromPreSorted()
fun <T : Comparable<T>> Iterable<T>.toMutableSortedListFromPreSorted(): MutableSortedList<T> =
toMutableSortedListFromPreSorted { o1, o2 -> o1.compareTo(o2) }
fun <T : Any> Iterable<T>.toMutableSortedListFromPreSorted(
comparator: Comparator<T>,
): MutableSortedList<T> = DelegatedSortedList(comparator, toMutableList())
fun <T : Comparable<T>> Array<T>.toMutableSortedList(): MutableSortedList<T> =
asIterable().toMutableSortedList()
fun <T : Comparable<T>> Sequence<T>.toMutableSortedList(): MutableSortedList<T> =
asIterable().toMutableSortedList()
fun <T> Iterable<T>.toMutableSortedList(comparator: Comparator<T>): MutableSortedList<T> =
DelegatedSortedList(comparator, this)
fun <T : Comparable<T>> Iterable<T>.toMutableSortedList(): MutableSortedList<T> =
toMutableSortedList { o1, o2 -> o1.compareTo(o2) }
fun <T : Comparable<T>> Sequence<T>.toSortedListFromPreSorted(): SortedList<T> =
asIterable().toSortedListFromPreSorted()
fun <T : Comparable<T>> Iterable<T>.toSortedListFromPreSorted(): SortedList<T> =
toSortedListFromPreSorted { o1, o2 -> o1.compareTo(o2) }
fun <T> Iterable<T>.toSortedListFromPreSorted(comparator: Comparator<T>): SortedList<T> =
DelegatedSortedList(comparator, toMutableList())
fun <T : Comparable<T>> Array<T>.toSortedList(): SortedList<T> =
asIterable().toSortedList()
fun <T : Comparable<T>> Sequence<T>.toSortedList(): SortedList<T> =
asIterable().toSortedList()
fun <T : Comparable<T>> Iterable<T>.toSortedList(): SortedList<T> =
toSortedList { o1, o2 -> o1.compareTo(o2) }
fun <T> Iterable<T>.toSortedList(comparator: Comparator<T>): SortedList<T> =
DelegatedSortedList(comparator, this)
fun <T> SortedList<T>.binarySearch(element: T): Int =
binarySearch(element, comparator)
inline fun <T : Comparable<T>, R : Comparable<R>> SortedList<T>.searchAndGet(
key: R, crossinline selector: (T) -> R,
): T? = getOrNull(binarySearchBy(key = key, selector = selector))
/**
* Similar to [kotlin.collections.slice] but unsafe.
* Builds an exactly sized [ArrayList] in place with elements from [from] index
* up until [toExclusive] index.
* Does no bounds checking whatsoever.
*/
fun <T> List<T>.fastSlice(from: Int, toExclusive: Int): List<T> =
ArrayList<T>(toExclusive - from).apply {
for (i in from until toExclusive) {
add(this@fastSlice[i])
}
}
/**
* Similar to [kotlin.collections.slice] but unsafe.
* Builds an exactly sized [Array] in place with elements from [from] index
* up until [toExclusive] index.
* Does no bounds checking whatsoever.
*/
inline fun <reified T> Array<T>.fastSlice(from: Int, toExclusive: Int): Array<T> =
Array(toExclusive - from) {
this@fastSlice[it + from]
}
inline fun <T, R : Comparable<R>> Sequence<T>.mapSorted(map: (T) -> R): SortedList<R> =
asIterable().mapSorted(map)
inline fun <T, R : Comparable<R>> Iterable<T>.mapSorted(map: (T) -> R): SortedList<R> =
map(map).toSortedList()
inline fun <reified T> Sequence<T>.toSizedArray(i: Int): Array<T> {
val iter = iterator()
return Array(i) { iter.next() }
}
inline fun <reified T> Iterable<T>.toSizedArray(i: Int): Array<T> {
val iter = iterator()
return Array(i) { iter.next() }
}
inline fun <T, reified R> List<T>.mapToArray(transform: (T) -> R): Array<R> {
contract {
callsInPlace(transform, InvocationKind.UNKNOWN)
}
return Array(size) { transform(this[it]) }
}
inline fun <T, reified R> Array<out T>.mapToArray(transform: (T) -> R): Array<R> {
contract {
callsInPlace(transform, InvocationKind.UNKNOWN)
}
return Array(size) { transform(this[it]) }
}
inline fun <reified T> Array<out T>.fastPrefixAdd(prefix: T): Array<T> =
if (isEmpty())
arrayOf(prefix)
else {
val result = Array(size + 1) {
this[(it + size - 1) % size]
}
result[0] = prefix
result
}
inline fun <T, reified R> Array<out T>.mapAndPrefixAdd(transform: (T) -> R, toAdd: T): Array<R> {
contract {
callsInPlace(transform, kind = InvocationKind.AT_LEAST_ONCE)
}
return if (isEmpty()) {
arrayOf(transform(toAdd))
} else {
val result = Array(size + 1) { transform(this[(it + size - 1) % size]) }
result[0] = transform(toAdd)
result
}
}
inline fun <T, reified R> Array<out T>.mapAndSuffixAdd(transform: (T) -> R, toAdd: T): Array<R> {
contract {
callsInPlace(transform, kind = InvocationKind.AT_LEAST_ONCE)
}
return if (isEmpty()) {
arrayOf(transform(toAdd))
} else {
val result = Array(size + 1) { transform(this[it % size]) }
result[size] = transform(toAdd)
result
}
}
inline fun <T> List<T>.filterByIndex(predicate: (Int) -> Boolean): List<T> {
contract {
callsInPlace(predicate, InvocationKind.UNKNOWN)
}
val mutList = ArrayList<T>(size / 2)
forEachIndexed { i, elem ->
if (predicate(i)) {
mutList += elem
}
}
return mutList
}
inline fun <T> Sequence<T>.filterByIndex(predicate: (Int) -> Boolean): List<T> =
asIterable().filterByIndex(predicate)
inline fun <T> Iterable<T>.filterByIndex(predicate: (Int) -> Boolean): List<T> {
contract {
callsInPlace(predicate, InvocationKind.UNKNOWN)
}
return with(iterator()) {
val mutList = mutableListOf<T>()
var i = 0
while (hasNext()) {
if (predicate(i)) {
mutList += next()
}
i++
}
mutList
}
}
inline fun <E> MutableIterable<E>.removeByUnique(predicate: (E) -> Boolean): Boolean {
contract {
callsInPlace(predicate, InvocationKind.UNKNOWN)
}
val it = iterator()
while (it.hasNext()) {
if (predicate(it.next())) {
it.remove()
return true
}
}
return false
}
inline fun <T, R> Collection<T>.mapMutableList(map: (T) -> R): MutableList<R> {
contract {
callsInPlace(map, InvocationKind.UNKNOWN)
}
val list = ArrayList<R>(size)
forEach { list += map(it) }
return list
}
inline fun <T, R> Collection<T>.mapMutableSet(map: (T) -> R): MutableSet<R> {
contract {
callsInPlace(map, InvocationKind.UNKNOWN)
}
val set = LinkedHashSet<R>(size)
forEach { set += map(it) }
return set
}
inline fun <T, R, S> Map<T, R>.mapMutable(map: (R) -> S): MutableMap<T, S> {
contract {
callsInPlace(map, InvocationKind.UNKNOWN)
}
val hashMap = LinkedHashMap<T, S>(size)
forEach {
hashMap[it.key] = map(it.value)
}
return hashMap
}
inline fun <T, R> Collection<T>.mapToSet(map: (T) -> R): Set<R> =
mapMutableSet(map)
inline fun <T> Collection<T>.copy(clone: (T) -> T): List<T> =
map(clone)
inline fun <T> Collection<T>.copyMutableList(clone: (T) -> T): MutableList<T> =
mapMutableList(clone)
inline fun <T> Collection<T>.copySet(clone: (T) -> T): Set<T> =
mapToSet(clone)
inline fun <T> Collection<T>.copyMutableSet(clone: (T) -> T): MutableSet<T> =
mapMutableSet(clone)
inline fun <T : Comparable<T>> Collection<T>.copySortedList(clone: (T) -> T): SortedList<T> =
map(clone).toSortedListFromPreSorted()
inline fun <T : Comparable<T>> Collection<T>.copyMutableSortedList(
clone: (T) -> T,
): MutableSortedList<T> =
map(clone).toMutableSortedListFromPreSorted()
| 0
|
Kotlin
|
1
| 3
|
0e5121243b9faf101b6d2ccf5bce60a657a31b4e
| 8,481
|
KnowLedger
|
MIT License
|
app/src/main/java/com/johnlennonlobo/appilunne/ui/activity/login/AuthResponse.kt
|
john-lobo
| 382,523,866
| false
| null |
package com.johnlennonlobo.appilunne.ui.activity.login
interface AuthResponse {
fun hideProgressBar(hide:Boolean)
fun onSuccess(message: String)
fun onFailure(message: String)
}
| 0
|
Kotlin
|
0
| 2
|
62b08c90c425eb53f033c60a47bbe697781f35d9
| 190
|
AppIlunne
|
MIT License
|
testapp/src/main/java/name/wildswift/testapp/readwrite/TestReadWriteModesViewDelegate.kt
|
wild-swift
| 153,925,818
| 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 name.wildswift.testapp.readwrite
import android.widget.LinearLayout
import name.wildswift.android.kannotations.*
import name.wildswift.android.kannotations.interfaces.ViewDelegate
import name.wildswift.testapp.IdRNames
/**
* Created by swift
*/
@ViewWithDelegate(
parent = LinearLayout::class
)
@Fields(
ViewField(name = "count", rwType = ReadWriteMode.Field, type = Int::class),
ViewField(name = "title", rwType = ReadWriteMode.Private, childName = IdRNames.vtrwmTitle, byProperty = ViewProperty.text),
ViewField(name = "roText", rwType = ReadWriteMode.Property, childName = IdRNames.vtrwmROEditor, byProperty = ViewProperty.text, activeChild = true),
ViewField(name = "check", rwType = ReadWriteMode.ObservableProperty, childName = IdRNames.vtrwmCheckbox, byProperty = ViewProperty.checked, activeChild = true),
ViewField(name = "radioSelect", rwType = ReadWriteMode.ObservableField, childName = IdRNames.vtrwmSelector, byProperty = ViewProperty.radioSelect, activeChild = true),
ViewField(name = "rwText", rwType = ReadWriteMode.FullObservableField, childName = IdRNames.vtrwmRWEditor, byProperty = ViewProperty.text, activeChild = true)
)
@Events(
ViewEvent(name = "reset", childName = IdRNames.vtrwmButton, listener = ViewListener.onClick),
ViewEvent(name = "editorAction", childName = IdRNames.vtrwmROEditor, listener = ViewListener.onEditorAction)
)
class TestReadWriteModesViewDelegate(view: TestReadWriteModesView) : ViewDelegate<TestReadWriteModesView, TestReadWriteModesViewIntState>(view) {
override fun setupView() {
view.orientation = LinearLayout.VERTICAL
}
override fun validateStateForNewInput(data: TestReadWriteModesViewIntState): TestReadWriteModesViewIntState {
return data.copy(title = String.format("321 %d", data.count))
}
}
| 12
|
Kotlin
|
1
| 1
|
43b67b1c0fec28f17c55f28a62cf314506f7e2a6
| 2,459
|
ws-android-annotations
|
Apache License 2.0
|
wpi/src/main/kotlin/frc/team4069/saturn/lib/util/CoroutineUtils.kt
|
FRCTeam4069
| 152,143,141
| false
| null |
/*
* Copyright 2019 Lo-Ellen Robotics
*
* 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 frc.team4069.saturn.lib.util
/* ktlint-disable no-wildcard-imports */
import frc.team4069.saturn.lib.mathematics.units.SIUnit
import frc.team4069.saturn.lib.mathematics.units.derived.Hertz
import frc.team4069.saturn.lib.mathematics.units.hertz
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
fun CoroutineScope.launchFrequency(
frequency: SIUnit<Hertz> = 50.hertz,
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
if (frequency.value <= 0) throw IllegalArgumentException("Frequency cannot be lower then 1!")
return launch(context, start) {
loopFrequency(frequency.value.toInt(), block)
}
}
suspend fun CoroutineScope.loopFrequency(
frequency: Int,
block: suspend CoroutineScope.() -> Unit
) {
val notifier = SaturnNotifier(frequency)
notifier.updateAlarm()
while(isActive) {
notifier.waitForAlarm()
block(this)
notifier.updateAlarm()
}
notifier.close()
}
inline fun disposableHandle(crossinline block: () -> Unit) = object : DisposableHandle {
override fun dispose() {
block()
}
}
fun disposableHandle(vararg handles: DisposableHandle) = disposableHandle(handles.asList())
fun disposableHandle(handles: Collection<DisposableHandle>) = disposableHandle {
handles.forEach { it.dispose() }
}
| 0
|
Kotlin
|
0
| 5
|
cafa7ae6dbd39177f807d5aaa5ef17c98f057826
| 2,101
|
SaturnLibrary
|
Apache License 2.0
|
src/main/kotlin/com/sourcegraph/cody/agent/protocol/ProtocolTextDocument.kt
|
sourcegraph
| 702,947,607
| false
|
{"Kotlin": 578448, "Java": 231040, "Shell": 4404, "TypeScript": 2153, "Nix": 1122, "JavaScript": 436, "HTML": 294}
|
package com.sourcegraph.cody.agent.protocol
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.vfs.VirtualFile
import com.sourcegraph.cody.agent.protocol.util.Rfc3986UriEncoder
class ProtocolTextDocument
private constructor(
var uri: String,
var content: String?,
var selection: Range?,
) {
companion object {
private fun getSelection(editor: Editor): Range {
val selectionModel = editor.selectionModel
val selectionStartPosition =
selectionModel.selectionStartPosition?.let { editor.visualToLogicalPosition(it) }
val selectionEndPosition =
selectionModel.selectionEndPosition?.let { editor.visualToLogicalPosition(it) }
if (selectionStartPosition != null && selectionEndPosition != null) {
return Range(
Position(selectionStartPosition.line, selectionStartPosition.column),
Position(selectionEndPosition.line, selectionEndPosition.column))
}
val caret = editor.caretModel.primaryCaret
val position = Position(caret.logicalPosition.line, caret.logicalPosition.column)
// A single-offset caret is a selection where end == start.
return Range(position, position)
}
@JvmStatic
@JvmOverloads
fun fromVirtualFile(
fileEditorManager: FileEditorManager,
file: VirtualFile,
): ProtocolTextDocument {
val rfc3986Uri = Rfc3986UriEncoder.encode(file.url)
val text = FileDocumentManager.getInstance().getDocument(file)?.text
val selection = fileEditorManager.selectedTextEditor?.let { getSelection(it) }
return ProtocolTextDocument(rfc3986Uri, text, selection)
}
}
}
| 278
|
Kotlin
|
9
| 33
|
5a9f9fc4986b6dabf8fba00c8c07ba5d37a68b98
| 1,785
|
jetbrains
|
Apache License 2.0
|
src/main/kotlin/dev/vndx/SMF.kt
|
viandoxdev
| 786,055,582
| false
|
{"Rust": 78111, "Kotlin": 20036, "Java": 7932, "GLSL": 289}
|
package dev.vndx
import dev.vndx.bindings.*
import net.minecraft.client.Minecraft
import net.minecraftforge.fml.common.Mod
import net.minecraftforge.fml.common.event.FMLInitializationEvent
import org.apache.logging.log4j.LogManager
import java.nio.ByteBuffer
@Mod(modid = "smf", useMetadata = true)
class SMF {
@Mod.EventHandler
fun init(event: FMLInitializationEvent) {
val logger = LogManager.getLogger()
loadNativeLibrary(logger)
GlobalConfig(atlasSize = 4096, glyphPadding = 8, sinAlpha = 0.03, coloringSeed = 6942012345678980085).use()
}
}
| 0
|
Rust
|
0
| 0
|
a91e1a4fb31a9dbee8fe8a5aa459e9e5c0de4a19
| 583
|
smf
|
The Unlicense
|
app/src/main/java/com/example/instabus/Constants.kt
|
Dramaix
| 238,223,346
| false
| null |
package com.example.instabus
const val WEB_SERVICE_URL="http://barcelonaapi.marcpous.com"
| 2
|
Kotlin
|
0
| 0
|
b242078c8893a07b6d7f55c872fecd81613014ce
| 90
|
InstaBus
|
MIT License
|
client/app/src/main/java/com/hao/heji/ui/setting/export/ExportViewModel.kt
|
RUANHAOANDROID
| 324,589,079
| false
| null |
package com.hao.heji.ui.setting.export
import android.os.Environment
import com.blankj.utilcode.util.LogUtils
import com.hao.heji.App
import com.hao.heji.network.HttpManager
import com.hao.heji.ui.base.BaseViewModel
import com.hao.heji.ui.setting.export.ExportAction.ExportExcel
import com.hao.heji.utils.MyUtils
import com.hao.heji.utils.launchIO
import okio.buffer
import okio.sink
import java.io.File
internal class ExportViewModel : BaseViewModel<ExportAction, ExportUiState>() {
override fun doAction(action: ExportAction) {
super.doAction(action)
when (action) {
is ExportExcel -> {
exportExcel(action.fileName)
}
}
}
private fun exportExcel(fileName: String) {
launchIO({
var response = HttpManager.getInstance().billExport()
if (response.isSuccessful && response.code() == 200) {
val filesDir =
App.context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
var attachment = response.headers()["Content-Disposition"]
var subFileName = attachment?.substringAfterLast(
"attachment; filename=",
System.currentTimeMillis().toString() + ".xlsx"
)
val excelFile = File(filesDir, subFileName)
try {
val sink = excelFile.sink().buffer()
response.body()?.source()?.let { sink.writeAll(it) }
sink.flush()
sink.close()
send(ExportUiState.Success(excelFile.absolutePath))
LogUtils.d("下载成功:${excelFile.absolutePath}")
MyUtils.galleryAddPic(App.context, excelFile.absolutePath)
} catch (e: Exception) {
e.printStackTrace()
send(ExportUiState.Error(e))
}
} else {
send(ExportUiState.Error(RuntimeException("导入失败 code :${response.code()} ${response.message()}")))
}
}, {
send(ExportUiState.Error(it))
})
}
}
| 0
| null |
7
| 36
|
c5491871ebbe68bca3684d1a7db3f1f78c870d68
| 2,154
|
heji
|
Apache License 2.0
|
couchbase-lite/src/nativeMain/kotlin/kotbase/internal/DbContext.kt
|
jeffdgr8
| 518,984,559
| false
|
{"Kotlin": 2266831, "Python": 294}
|
/*
* Copyright 2022-2023 <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 kotbase.internal
import kotbase.*
internal class DbContext(var database: Database?) {
// need to avoid calling expensive Blob.hashCode()
// so using === comparison with List instead of Set
private val streamBlobs = mutableListOf<Blob>()
// can't unify with internal interface without making mergeSavedBlobs() public
private val streamBlobDocs = mutableListOf<MutableDocument>()
private val streamBlobDicts = mutableListOf<MutableDictionary>()
private val streamBlobArrays = mutableListOf<MutableArray>()
internal fun addStreamBlob(blob: Blob) {
streamBlobs.identityAdd(blob)
}
internal fun addStreamBlobDoc(doc: MutableDocument) {
streamBlobDocs.identityAdd(doc)
}
internal fun removeStreamBlobDoc(doc: MutableDocument) {
streamBlobDocs.identityRemove(doc)
}
internal fun addStreamBlobDict(dict: MutableDictionary) {
streamBlobDicts.identityAdd(dict)
}
internal fun removeStreamBlobDict(dict: MutableDictionary) {
streamBlobDicts.identityRemove(dict)
}
internal fun addStreamBlobArray(array: MutableArray) {
streamBlobArrays.identityAdd(array)
}
internal fun removeStreamBlobArray(array: MutableArray) {
streamBlobArrays.identityRemove(array)
}
private fun <T> MutableList<T>.identityAdd(value: T) {
find { it === value } ?: add(value)
}
private fun <T> MutableList<T>.identityRemove(value: T) {
// avoid calling equals() with remove()
run loop@{
forEachIndexed { i, v ->
if (value === v) {
removeAt(i)
return@loop
}
}
}
}
internal fun willSave(db: Database) {
streamBlobs.forEach { blob ->
blob.saveToDb(db)
}
streamBlobs.clear()
streamBlobDocs.forEach { doc ->
doc.mergeSavedBlobs()
}
streamBlobDocs.clear()
streamBlobDicts.forEach { dict ->
dict.mergeSavedBlobs()
}
streamBlobDicts.clear()
streamBlobArrays.forEach { array ->
array.mergeSavedBlobs()
}
streamBlobArrays.clear()
}
}
| 0
|
Kotlin
|
0
| 7
|
ec8fbeb0d3e6c487ec8fb48ba2ba5388c71a29b1
| 2,837
|
kotbase
|
Apache License 2.0
|
avro-kotlin-serialization/src/main/kotlin/serializer/DoubleLogicalTypeSerializer.kt
|
toolisticon
| 493,962,736
| false
|
{"Kotlin": 474632, "Java": 1511}
|
package io.toolisticon.kotlin.avro.serialization.serializer
import com.github.avrokotlin.avro4k.AvroDecoder
import com.github.avrokotlin.avro4k.AvroEncoder
import io.toolisticon.kotlin.avro.logical.DoubleLogicalType
import io.toolisticon.kotlin.avro.logical.conversion.DoubleLogicalTypeConversion
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.descriptors.PrimitiveKind
@OptIn(ExperimentalSerializationApi::class)
abstract class DoubleLogicalTypeSerializer<LOGICAL : DoubleLogicalType, CONVERTED_TYPE : Any>(
conversion: DoubleLogicalTypeConversion<LOGICAL, CONVERTED_TYPE>
) : AvroLogicalTypeSerializer<LOGICAL, Double, CONVERTED_TYPE>(
conversion = conversion,
primitiveKind = PrimitiveKind.DOUBLE,
encode = AvroEncoder::encodeDouble,
decode = AvroDecoder::decodeDouble
)
| 12
|
Kotlin
|
0
| 4
|
d45b8fc3300205d4bf278a53ebfa53d3c46d0a48
| 826
|
avro-kotlin
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/presta/customer/network/signHome/model/Details.kt
|
morgan4080
| 726,765,347
| false
|
{"Kotlin": 2170913, "Swift": 2162, "Ruby": 382, "Shell": 228}
|
package com.presta.customer.network.signHome.model
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
@Serializable
data class Details @OptIn(ExperimentalSerializationApi::class) constructor(
@EncodeDefault val value: String?=null,
@EncodeDefault val meta: Map<String, String> = emptyMap(),
@EncodeDefault val type: String?=null
)
| 0
|
Kotlin
|
0
| 0
|
0850928853c87390a97953cfec2d21751904d3a9
| 437
|
kmp
|
Apache License 2.0
|
server/src/main/kotlin/org/ivdnt/galahad/util/StringExtensions.kt
|
INL
| 808,669,682
| false
|
{"Kotlin": 407350, "Vue": 251252, "TypeScript": 81103, "Shell": 24857, "JavaScript": 2290, "Dockerfile": 2176, "HTML": 777, "XSLT": 362}
|
package org.ivdnt.galahad.util
fun String.matchesUpTo(textToMatch: String): Int {
var matchingIndex = 0
for (i in 1 until this.length + 1) {
if (textToMatch.startsWith(this.substring(0, i))) matchingIndex = i
else break
}
return matchingIndex
}
fun Any?.toNonEmptyString(default: String): String {
return if (this == null || this.toString().isEmpty()) default else this.toString()
}
| 0
|
Kotlin
|
0
| 0
|
84a7fb40da99bd1b9ebada112e6958086d034b50
| 420
|
galahad
|
Apache License 2.0
|
proj.android/app/src/main/java/com/lh/kete/threadpool/KeteExec.kt
|
tienlocbui1110
| 175,465,509
| false
|
{"Markdown": 2, "Gradle": 13, "Java Properties": 8, "Shell": 5, "Ignore List": 9, "Batchfile": 5, "Proguard": 2, "Java": 95, "XML": 37, "Kotlin": 72, "JSON": 14, "Text": 13, "INI": 3, "JavaScript": 16, "CSS": 2, "EJS": 3}
|
package com.lh.kete.threadpool
import android.os.Process
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
interface KeteExec {
companion object {
private val NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors()
private val threadPool: ThreadPoolExecutor
init {
threadPool = ThreadPoolExecutor(
NUMBER_OF_CORES * 2,
NUMBER_OF_CORES * 2,
10L,
TimeUnit.SECONDS,
LinkedBlockingQueue<Runnable>(),
PriorityThreadFactory(Thread.MAX_PRIORITY)
)
}
fun doBackground(what: Runnable) {
threadPool.execute(what)
}
}
class PriorityThreadFactory(private val mThreadPriority: Int) : ThreadFactory {
override fun newThread(runnable: Runnable): Thread {
val wrapperRunnable = Runnable {
try {
Process.setThreadPriority(mThreadPriority)
} catch (t: Throwable) {
}
runnable.run()
}
return Thread(wrapperRunnable)
}
}
}
| 1
| null |
1
| 1
|
1b18ca584ab3d8f0c27f2180388b7cf3043efe42
| 1,293
|
Kele
|
MIT License
|
src/main/kotlin/com/intershop/gradle/scm/utils/Utils.kt
|
IntershopCommunicationsAG
| 62,041,957
| false
| null |
/*
* Copyright 2019 Intershop Communications AG.
*
* 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.intershop.gradle.jaxb.utils
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
import kotlin.reflect.KProperty
/**
* Provides 'set' functional extension for the Property object.
*/
operator fun <T> Property<T>.setValue(receiver: Any?, property: KProperty<*>, value: T) = set(value)
/**
* Provides 'get' functional extension for the Property object.
*/
operator fun <T> Property<T>.getValue(receiver: Any?, property: KProperty<*>): T = get()
/**
* Provides 'set' functional extension for the SetProperty object.
*/
operator fun <T> SetProperty<T>.setValue(receiver: Any?, property: KProperty<*>, value: Set<T>) = set(value)
/**
* Provides 'get' functional extension for the SetProperty object.
*/
operator fun <T> SetProperty<T>.getValue(receiver: Any?, property: KProperty<*>): Set<T> = get()
/**
* Provides 'set' functional extension for the ListProperty object.
*/
operator fun <T> ListProperty<T>.setValue(receiver: Any?, property: KProperty<*>, value: List<T>) = set(value)
/**
* Provides 'get' functional extension for the ListProperty object.
*/
operator fun <T> ListProperty<T>.getValue(receiver: Any?, property: KProperty<*>): List<T> = get()
/**
* Provides functional extension for primitive objects.
*/
inline fun <reified T> ObjectFactory.property(): Property<T> = property(T::class.java)
| 9
| null |
5
| 9
|
76c55233ff8c09a0f8972550a4660068d202d421
| 2,065
|
scmversion-gradle-plugin
|
Apache License 2.0
|
komapper-core/src/main/kotlin/org/komapper/core/dsl/query/RelationSetOperationQuery.kt
|
komapper
| 349,909,214
| false
| null |
package org.komapper.core.dsl.query
import kotlinx.coroutines.flow.Flow
import org.komapper.core.dsl.context.SetOperationContext
import org.komapper.core.dsl.expression.SortExpression
import org.komapper.core.dsl.expression.SubqueryExpression
import org.komapper.core.dsl.metamodel.EntityMetamodel
import org.komapper.core.dsl.options.SelectOptions
import org.komapper.core.dsl.visitor.FlowQueryVisitor
import org.komapper.core.dsl.visitor.QueryVisitor
/**
* Represents a set operation query.
*
* @param ENTITY the entity type
*/
interface RelationSetOperationQuery<ENTITY : Any> : FlowSetOperationQuery<ENTITY>
internal data class RelationSetOperationQueryImpl<ENTITY : Any>(
override val context: SetOperationContext,
private val metamodel: EntityMetamodel<ENTITY, *, *>
) : RelationSetOperationQuery<ENTITY> {
private val support: SetOperationQuerySupport<ENTITY> = SetOperationQuerySupport(context)
override fun <VISIT_RESULT> accept(visitor: FlowQueryVisitor<VISIT_RESULT>): VISIT_RESULT {
return visitor.setOperationQuery(context, metamodel)
}
override fun <R> collect(collect: suspend (Flow<ENTITY>) -> R): Query<R> = object : Query<R> {
override fun <VISIT_RESULT> accept(visitor: QueryVisitor<VISIT_RESULT>): VISIT_RESULT {
return visitor.setOperationQuery(context, metamodel, collect)
}
}
override fun except(other: SubqueryExpression<ENTITY>): FlowSetOperationQuery<ENTITY> {
return copy(context = support.except(other))
}
override fun intersect(other: SubqueryExpression<ENTITY>): FlowSetOperationQuery<ENTITY> {
return copy(context = support.intersect(other))
}
override fun union(other: SubqueryExpression<ENTITY>): FlowSetOperationQuery<ENTITY> {
return copy(context = support.union(other))
}
override fun unionAll(other: SubqueryExpression<ENTITY>): FlowSetOperationQuery<ENTITY> {
return copy(context = support.unionAll(other))
}
override fun orderBy(vararg aliases: CharSequence): FlowSetOperationQuery<ENTITY> {
return copy(context = support.orderBy(*aliases))
}
override fun orderBy(vararg expressions: SortExpression): FlowSetOperationQuery<ENTITY> {
return copy(context = support.orderBy(*expressions))
}
override fun options(configure: (SelectOptions) -> SelectOptions): FlowSetOperationQuery<ENTITY> {
val newContext = context.copy(options = configure(context.options))
return copy(context = newContext)
}
}
| 8
| null |
4
| 97
|
851b313c66645d60f2e86934a5036efbe435396a
| 2,533
|
komapper
|
Apache License 2.0
|
app/src/main/java/ca/bc/gov/bchealth/ui/healthpass/add/FetchVaccineRecordViewModel.kt
|
bcgov
| 414,797,174
| false
|
{"Kotlin": 1307307, "Java": 582146}
|
package ca.bc.gov.bchealth.ui.healthpass.add
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import ca.bc.gov.bchealth.R
import ca.bc.gov.common.const.SERVER_ERROR_DATA_MISMATCH
import ca.bc.gov.common.const.SERVER_ERROR_INCORRECT_PHN
import ca.bc.gov.common.exceptions.MyHealthException
import ca.bc.gov.common.exceptions.NetworkConnectionException
import ca.bc.gov.common.exceptions.ServiceDownException
import ca.bc.gov.common.model.ErrorData
import ca.bc.gov.common.model.relation.PatientWithVaccineAndDosesDto
import ca.bc.gov.repository.FetchVaccineRecordRepository
import ca.bc.gov.repository.model.PatientVaccineRecord
import ca.bc.gov.repository.patient.PatientRepository
import ca.bc.gov.repository.qr.VaccineRecordState
import ca.bc.gov.repository.worker.MobileConfigRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* @author Pinakin Kansara
*/
@HiltViewModel
class FetchVaccineRecordViewModel @Inject constructor(
private val fetchVaccineRecordRepository: FetchVaccineRecordRepository,
private val patientRepository: PatientRepository,
private val mobileConfigRepository: MobileConfigRepository
) : ViewModel() {
companion object {
private const val TAG = "FetchVaccineRecordViewModel"
}
private val _uiState =
MutableSharedFlow<FetchVaccineRecordUiState>(replay = 0, extraBufferCapacity = 1)
val uiState: SharedFlow<FetchVaccineRecordUiState> = _uiState.asSharedFlow()
fun fetchVaccineRecord(phn: String, dateOfBirth: String, dateOfVaccine: String) =
viewModelScope.launch {
_uiState.tryEmit(FetchVaccineRecordUiState(onLoading = true))
try {
mobileConfigRepository.refreshMobileConfiguration()
val vaccineRecord = fetchVaccineRecordRepository.fetchVaccineRecord(
phn,
dateOfBirth,
dateOfVaccine
)
_uiState.tryEmit(
FetchVaccineRecordUiState(
onLoading = false,
vaccineRecord = vaccineRecord
)
)
} catch (e: Exception) {
when (e) {
is NetworkConnectionException -> {
_uiState.tryEmit(
FetchVaccineRecordUiState(
onLoading = false,
isConnected = false
)
)
}
is ServiceDownException -> _uiState.tryEmit(
FetchVaccineRecordUiState(isHgServicesUp = false, onLoading = false)
)
is MyHealthException -> {
when (e.errCode) {
SERVER_ERROR_DATA_MISMATCH, SERVER_ERROR_INCORRECT_PHN -> {
_uiState.tryEmit(
FetchVaccineRecordUiState(
errorData = ErrorData(
R.string.error_data_mismatch_title,
R.string.error_vaccine_data_mismatch_message
)
)
)
}
else -> {
_uiState.tryEmit(
FetchVaccineRecordUiState(
errorData = ErrorData(
R.string.error,
R.string.error_message
)
)
)
}
}
}
}
}
}
fun getPatientWithVaccineRecord(patientId: Long) = viewModelScope.launch {
val record = patientRepository.getPatientWithVaccineAndDoses(patientId)
_uiState.tryEmit(
FetchVaccineRecordUiState(onLoading = false, patientDataDto = record)
)
}
fun resetUiState() {
_uiState.tryEmit(
FetchVaccineRecordUiState(
isHgServicesUp = true,
onLoading = false,
patientDataDto = null,
vaccineRecord = null,
errorData = null,
isConnected = true
)
)
}
}
data class FetchVaccineRecordUiState(
val isHgServicesUp: Boolean = true,
val onLoading: Boolean = false,
val patientDataDto: PatientWithVaccineAndDosesDto? = null,
val vaccineRecord: Pair<VaccineRecordState, PatientVaccineRecord?>? = null,
val errorData: ErrorData? = null,
val isConnected: Boolean = true
)
| 7
|
Kotlin
|
5
| 5
|
77f398a01b468267c1b3a61d124bbf1f49ef1d9b
| 5,147
|
myhealthBC-android
|
Apache License 2.0
|
libs/etterlatte-ktor/src/main/kotlin/no/nav/etterlatte/libs/ktorobo/Models.kt
|
navikt
| 417,041,535
| false
|
{"Kotlin": 5224679, "TypeScript": 1253274, "Handlebars": 21854, "Shell": 10666, "HTML": 1776, "CSS": 598, "Dockerfile": 587}
|
package no.nav.etterlatte.libs.ktorobo
import com.fasterxml.jackson.databind.JsonNode
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Result
import io.ktor.client.call.body
import io.ktor.client.statement.HttpResponse
import no.nav.etterlatte.libs.common.feilhaandtering.InternfeilException
data class Resource(
val clientId: String,
val url: String,
val additionalHeaders: Map<String, String>? = null,
val response: Any? = null,
) {
fun addResponse(response: Any?): Resource = this.copy(response = response)
}
data class ThrowableErrorMessage(
override val message: String,
override val cause: Throwable? = null,
val response: HttpResponse? = null,
) : InternfeilException(message, cause)
internal fun Throwable.toErr(url: String): Result<JsonNode, ThrowableErrorMessage> {
return Err(
ThrowableErrorMessage(
message = "An unexpected error occured when calling $url",
cause = this,
),
)
}
internal suspend fun HttpResponse.toErr(): Result<JsonNode, ThrowableErrorMessage> {
return Err(
ThrowableErrorMessage(
message = "Received response with status ${status.value} from downstream api with error: ${this.body<String>()}",
response = this,
),
)
}
| 18
|
Kotlin
|
0
| 6
|
aa6b1757cdd96526892ad4a04d3886037f968735
| 1,311
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
app/src/main/java/com/necatisozer/bloom/ui/components/BloomCard.kt
|
necatisozer
| 349,928,694
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.screens.home.components
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun BloomCard(
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Card(
modifier = modifier,
elevation = 1.dp,
content = content,
backgroundColor = MaterialTheme.colors.surface
)
}
| 1
| null |
1
| 4
|
d1e8f323109642837dcb3f5705f62985b31b7cd3
| 1,141
|
Bloom
|
Apache License 2.0
|
KirraDungeonServer/src/main/kotlin/net/sakuragame/eternal/kirradungeon/server/zone/data/writer/implement/ModelWriter.kt
|
Eternalland-Server
| 569,813,142
| false
| null |
package net.sakuragame.eternal.kirradungeon.server.zone.data.writer.implement
import net.sakuragame.eternal.kirradungeon.server.zone.Zone
import net.sakuragame.eternal.kirradungeon.server.zone.ZoneLocation
import net.sakuragame.eternal.kirradungeon.server.zone.data.ZoneModelData
import net.sakuragame.eternal.kirradungeon.server.zone.data.writer.WriteHelper
object ModelWriter : WriteHelper {
fun set(zone: Zone, id: String, modelId: String, loc: ZoneLocation) {
val file = getFile(zone.id)
file["model.$id"] = "$modelId@$loc"
reload()
}
fun remove(zone: Zone, id: String) {
val file = getFile(zone.id)
file["model.$id"] = null
reload()
}
fun read(id: String): List<ZoneModelData> {
val models = mutableListOf<ZoneModelData>()
val file = getFile(id)
val sections = file.getConfigurationSection("model")?.getKeys(false) ?: return emptyList()
sections.forEach {
val split = file.getString("model.$it")?.split("@") ?: return@forEach
val modelId = split[0]
val loc = ZoneLocation.parseToZoneLocation(split[1]) ?: return@forEach
models += ZoneModelData(it, modelId, loc)
}
return models
}
}
| 0
|
Kotlin
|
0
| 0
|
537f062f32d1b14cf26c89161a8efc178e596d14
| 1,259
|
KirraDungeon
|
Creative Commons Zero v1.0 Universal
|
omnia/src/javaMain/omnia/reference/WeakReference.kt
|
StrangePan
| 224,343,744
| false
|
{"Kotlin": 475894}
|
package omnia.reference
actual class WeakReference<T : Any> private constructor(value: T? = null) {
private val weakReference = java.lang.ref.WeakReference(value)
actual companion object {
actual fun <T : Any> of(value: T) = WeakReference<T>(value)
actual fun <T : Any> empty() = WeakReference<T>()
}
actual fun clear() = weakReference.clear()
actual val value: T? = weakReference.get()
}
| 0
|
Kotlin
|
0
| 1
|
b7bb7a1c9d1deb40a3ce7544d6dfd117fdac052e
| 411
|
omnia
|
The Unlicense
|
Base/src/main/java/com/xy/base/utils/permission/PermissionRequestMode.kt
|
xiuone
| 291,512,847
| false
| null |
package com.xy.base.utils.permission
class PermissionRequestMode(val permission:Array<String>,val permissionInfo:String?)
| 0
|
Kotlin
|
1
| 2
|
a91666c064e6843511094727503687a1ade12f3f
| 123
|
ajinlib
|
Apache License 2.0
|
platform/android/goldengate/GoldenGateConnectionManager/src/test/java/com/fitbit/goldengate/bt/gatt/server/services/gattcache/GattCacheServiceEventListenerTest.kt
|
Fitbit
| 252,750,226
| false
|
{"C": 2519513, "Kotlin": 897890, "Swift": 806092, "C++": 805305, "CMake": 121256, "Python": 115131, "Objective-C": 88567, "JavaScript": 20929, "HTML": 13841, "Shell": 2041, "Dockerfile": 1379, "Ruby": 252}
|
package com.fitbit.goldengate.bt.gatt.server.services.gattcache
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import com.fitbit.bluetooth.fbgatt.FitbitBluetoothDevice
import com.fitbit.bluetooth.fbgatt.GattServerConnection
import com.fitbit.bluetooth.fbgatt.TransactionResult
import com.fitbit.bluetooth.fbgatt.rx.server.GattServerResponseSender
import com.fitbit.bluetooth.fbgatt.rx.server.GattServerResponseSenderProvider
import com.fitbit.goldengate.bt.gatt.util.toByteArray
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.UUID
class GattCacheServiceEventListenerTest {
private val device1 = mock<BluetoothDevice> {
on { address } doReturn "1"
}
private val unknownUuid = UUID.fromString("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF")
private val mockGattServerConnection = mock<GattServerConnection>()
private val mockGattServerResponseSender = mock<GattServerResponseSender>()
private val mockGattServerResponseSenderProvider = mock<GattServerResponseSenderProvider> {
on { provide(mockGattServerConnection) } doReturn mockGattServerResponseSender
}
private val listener = GattCacheServiceEventListener(
Schedulers.trampoline(),
mockGattServerResponseSenderProvider
)
private fun mockGattServerResponse() {
whenever(mockGattServerResponseSender.send(any(), any(), any(), any(), any(), anyOrNull()))
.thenReturn(Completable.complete())
}
@Before
fun setUp() {
mockGattServerResponse()
}
@After
fun tearDown() {
}
@Test
fun `Read EphemeralCharacteristicPointer successfully`() {
listener.onServerCharacteristicReadRequest(
device1,
mockTransactionResult(
characteristicId = EphemeralCharacteristicPointer.uuid
),
mockGattServerConnection
)
verifyResponseSent(value = EphemeralCharacteristic.uuid.toByteArray())
}
@Test
fun `Read request to undefined service UUID`() {
listener.onServerCharacteristicReadRequest(
device1,
mockTransactionResult(
serviceId = unknownUuid,
characteristicId = EphemeralCharacteristicPointer.uuid
),
mockGattServerConnection
)
verifyNoResponseSent()
}
@Test
fun `Read request to undefined characteristic UUID`() {
listener.onServerCharacteristicReadRequest(
device1,
mockTransactionResult(
characteristicId = unknownUuid
),
mockGattServerConnection
)
verifyFailureSent()
}
@Test
fun `Write EphemeralCharacteristic successfully`() {
listener.onServerCharacteristicWriteRequest(
device1,
mockTransactionResult(
characteristicId = EphemeralCharacteristic.uuid,
value = byteArrayOf(0)),
mockGattServerConnection
)
verifyResponseSent(BluetoothGatt.GATT_SUCCESS)
}
@Test
fun `Write request to undefined service UUID`() {
listener.onServerCharacteristicWriteRequest(
device1,
mockTransactionResult(
serviceId = unknownUuid,
characteristicId = EphemeralCharacteristic.uuid,
value = byteArrayOf(1)),
mockGattServerConnection
)
verifyNoResponseSent()
}
@Test
fun `Write request to undefined characteristic UUID`() {
listener.onServerCharacteristicWriteRequest(
device1,
mockTransactionResult(
characteristicId = unknownUuid,
value = byteArrayOf(1)),
mockGattServerConnection
)
verifyFailureSent()
}
@Test
fun `Write EphemeralCharacteristic with wrong data`() {
listener.onServerCharacteristicWriteRequest(
device1,
mockTransactionResult(
characteristicId = EphemeralCharacteristic.uuid,
value = byteArrayOf(1)),
mockGattServerConnection
)
verifyFailureSent()
}
private fun mockTransactionResult(
serviceId: UUID = GattCacheService.uuid,
characteristicId: UUID,
responseNeeded: Boolean = true,
value: ByteArray? = null
): TransactionResult {
return mock {
on { requestId } doReturn 1
on { serviceUuid } doReturn serviceId
on { characteristicUuid} doReturn characteristicId
on { isResponseRequired } doReturn responseNeeded
on { data } doReturn value
}
}
private fun verifyResponseSent(
status: Int = BluetoothGatt.GATT_SUCCESS,
value: ByteArray? = null
){
verify(mockGattServerResponseSender).send(
device = FitbitBluetoothDevice(device1),
requestId = 1,
status = status,
value = value
)
}
private fun verifyFailureSent() {
verify(mockGattServerResponseSender).send(
device = FitbitBluetoothDevice(device1),
requestId = 1,
status = BluetoothGatt.GATT_FAILURE
)
}
private fun verifyNoResponseSent() {
verify(mockGattServerResponseSender, never()).send(any(), any(), any(), any(), any(), anyOrNull())
}
}
| 14
|
C
|
32
| 290
|
417aad0080bdc8b20c27cf8fff2455c20e6f3adb
| 5,844
|
golden-gate
|
Apache License 2.0
|
src/main/kotlin/com/github/oduig/auctionswindler/blizzard/generated/Links.kt
|
Oduig
| 201,813,155
| false
| null |
package com.github.oduig.auctionswindler.blizzard.generated
data class Links(
val self: Self
)
| 0
|
Kotlin
|
0
| 0
|
fbe50b740e65280122d5677b7ca33d4c760539eb
| 99
|
auction-swindler
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.