repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kiruto/debug-bottle | views/src/main/java/com/exyui/android/debugbottle/views/__DisplayLeakConnectorView.kt | 1 | 3541 | package com.exyui.android.debugbottle.views
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
/**
* Created by yuriel on 8/25/16.
*/
class __DisplayLeakConnectorView(context: Context, attrs: AttributeSet) : View(context, attrs) {
enum class Type {
START, NODE, END
}
private var type: Type? = null
private var cache: Bitmap? = null
init {
type = Type.NODE
}
@SuppressWarnings("SuspiciousNameCombination")
override fun onDraw(canvas: Canvas) {
val width = width
val height = height
if (cache != null && (cache!!.width != width || cache!!.height != height)) {
cache!!.recycle()
cache = null
}
if (cache == null) {
cache = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val cacheCanvas = Canvas(cache!!)
val halfWidth = width / 2f
val halfHeight = height / 2f
val thirdWidth = width / 3f
val strokeSize = LeakCanaryUi.dpToPixel(4f, resources)
iconPaint.strokeWidth = strokeSize
rootPaint.strokeWidth = strokeSize
when (type) {
Type.NODE -> {
cacheCanvas.drawLine(halfWidth, 0f, halfWidth, height.toFloat(), iconPaint)
cacheCanvas.drawCircle(halfWidth, halfHeight, halfWidth, iconPaint)
cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, clearPaint)
}
Type.START -> {
val radiusClear = halfWidth - strokeSize / 2f
cacheCanvas.drawRect(0f, 0f, width.toFloat(), radiusClear, rootPaint)
cacheCanvas.drawCircle(0f, radiusClear, radiusClear, clearPaint)
cacheCanvas.drawCircle(width.toFloat(), radiusClear, radiusClear, clearPaint)
cacheCanvas.drawLine(halfWidth, 0f, halfWidth, halfHeight, rootPaint)
cacheCanvas.drawLine(halfWidth, halfHeight, halfWidth, height.toFloat(), iconPaint)
cacheCanvas.drawCircle(halfWidth, halfHeight, halfWidth, iconPaint)
cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, clearPaint)
}
else -> {
cacheCanvas.drawLine(halfWidth, 0f, halfWidth, halfHeight, iconPaint)
cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, leakPaint)
}
}
}
canvas.drawBitmap(cache!!, 0f, 0f, null)
}
fun setType(type: Type) {
if (type != this.type) {
this.type = type
if (cache != null) {
cache!!.recycle()
cache = null
}
invalidate()
}
}
companion object {
private val iconPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val rootPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val leakPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val clearPaint = Paint(Paint.ANTI_ALIAS_FLAG)
init {
iconPaint.color = LeakCanaryUi.LIGHT_GREY
rootPaint.color = LeakCanaryUi.ROOT_COLOR
leakPaint.color = LeakCanaryUi.LEAK_COLOR
clearPaint.color = Color.TRANSPARENT
clearPaint.xfermode = LeakCanaryUi.CLEAR_XFER_MODE
}
}
} | apache-2.0 | bec4f15d81ee1d80a4664798dfccaf50 | 33.38835 | 103 | 0.589099 | 4.653088 | false | false | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/rewards/RewardDashboardFragment.kt | 1 | 6285 | /*
* Copyright 2020 Google 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.app.playhvz.screens.rewards
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.playhvz.R
import com.app.playhvz.app.EspressoIdlingResource
import com.app.playhvz.common.globals.SharedPreferencesConstants
import com.app.playhvz.firebase.classmodels.Game
import com.app.playhvz.firebase.classmodels.Player
import com.app.playhvz.firebase.classmodels.Reward
import com.app.playhvz.firebase.operations.RewardDatabaseOperations
import com.app.playhvz.firebase.viewmodels.GameViewModel
import com.app.playhvz.firebase.viewmodels.RewardListViewModel
import com.app.playhvz.navigation.NavigationUtil
import com.app.playhvz.utils.SystemUtils
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.coroutines.runBlocking
/** Fragment for showing a list of rewards.*/
class RewardDashboardFragment : Fragment() {
companion object {
val TAG = RewardDashboardFragment::class.qualifiedName
}
lateinit var gameViewModel: GameViewModel
lateinit var rewardViewModel: RewardListViewModel
lateinit var fab: FloatingActionButton
lateinit var recyclerView: RecyclerView
lateinit var adapter: RewardDashboardAdapter
var gameId: String? = null
var playerId: String? = null
var game: Game? = null
var player: Player? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sharedPrefs = activity?.getSharedPreferences(
SharedPreferencesConstants.PREFS_FILENAME,
0
)!!
gameViewModel = GameViewModel()
rewardViewModel = RewardListViewModel()
gameId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_GAME_ID, null)
playerId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_PLAYER_ID, null)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = inflater.inflate(R.layout.fragment_reward_dashboard, container, false)
fab = activity?.findViewById(R.id.floating_action_button)!!
recyclerView = view.findViewById(R.id.reward_list)
adapter = RewardDashboardAdapter(
requireActivity(),
gameId!!,
listOf(),
requireContext(),
findNavController(),
{ rewardId -> triggerAmountSelector(rewardId) })
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
setupObservers()
setupToolbar()
return view
}
fun setupToolbar() {
val toolbar = (activity as AppCompatActivity).supportActionBar
if (toolbar != null) {
toolbar.title = requireContext().getString(R.string.navigation_drawer_rewards)
}
}
private fun setupFab(isAdmin: Boolean) {
if (!isAdmin) {
fab.visibility = View.GONE
return
}
fab.visibility = View.VISIBLE
fab.setOnClickListener {
createReward()
}
fab.visibility = View.VISIBLE
}
private fun setupObservers() {
if (gameId == null || playerId == null) {
return
}
gameViewModel.getGameAndAdminObserver(this, gameId!!, playerId!!)
.observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverGameAndAdminStatus ->
updateGame(serverGameAndAdminStatus)
})
rewardViewModel.getAllRewardsInGame(gameId!!)
.observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverRewardList ->
updateRewardList(serverRewardList)
})
}
private fun updateGame(serverUpdate: GameViewModel.GameWithAdminStatus?) {
if (serverUpdate == null) {
NavigationUtil.navigateToGameList(findNavController(), requireActivity())
}
game = serverUpdate!!.game
setupFab(serverUpdate.isAdmin)
adapter.setIsAdmin(serverUpdate.isAdmin)
adapter.notifyDataSetChanged()
}
private fun updateRewardList(updatedRewardList: List<Reward>) {
adapter.setData(updatedRewardList)
adapter.notifyDataSetChanged()
}
private fun createReward() {
NavigationUtil.navigateToRewardSettings(findNavController(), null)
}
private fun triggerAmountSelector(rewardId: String) {
val amountSelectorDialog =
AmountSelectorDialog(requireContext().getString(R.string.reward_claim_code_dialog))
amountSelectorDialog.setPositiveButtonCallback { selectedNumber ->
runBlocking {
EspressoIdlingResource.increment()
RewardDatabaseOperations.asyncGenerateClaimCodes(
gameId!!,
rewardId,
selectedNumber,
{
SystemUtils.showToast(
requireContext(),
"Created claim codes! Click the count to refresh it"
)
},
{ SystemUtils.showToast(requireContext(), "Claim code generation failed") })
EspressoIdlingResource.decrement()
}
}
activity?.supportFragmentManager?.let { amountSelectorDialog.show(it, TAG) }
}
} | apache-2.0 | aa0bee9070b78886612f751fe0353934 | 36.416667 | 98 | 0.6786 | 5.2375 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/TextFieldsInDialogDemo.kt | 3 | 5354 | /*
* Copyright 2022 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.
*/
@file:OptIn(ExperimentalComposeUiApi::class)
package androidx.compose.foundation.demos.text
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.integration.demos.common.ComposableDemo
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ListItem
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
private val dialogDemos = listOf(
ComposableDemo("Full screen dialog, multiple fields") { onNavigateUp ->
Dialog(onDismissRequest = onNavigateUp) {
InputFieldDemo()
}
},
ComposableDemo(
"Small dialog, single field (platform default width, decor fits system windows)"
) { onNavigateUp ->
Dialog(
onDismissRequest = onNavigateUp,
properties = DialogProperties(
usePlatformDefaultWidth = true,
decorFitsSystemWindows = true
)
) { SingleTextFieldDialog() }
},
ComposableDemo(
"Small dialog, single field (decor fits system windows)"
) { onNavigateUp ->
Dialog(
onDismissRequest = onNavigateUp,
properties = DialogProperties(
usePlatformDefaultWidth = false,
decorFitsSystemWindows = true
)
) { SingleTextFieldDialog() }
},
ComposableDemo(
"Small dialog, single field (platform default width)"
) { onNavigateUp ->
Dialog(
onDismissRequest = onNavigateUp,
properties = DialogProperties(
usePlatformDefaultWidth = true,
decorFitsSystemWindows = false
)
) { SingleTextFieldDialog() }
},
ComposableDemo(
"Small dialog, single field"
) { onNavigateUp ->
Dialog(
onDismissRequest = onNavigateUp,
properties = DialogProperties(
usePlatformDefaultWidth = false,
decorFitsSystemWindows = false
)
) { SingleTextFieldDialog() }
},
ComposableDemo("Show keyboard automatically") { onNavigateUp ->
Dialog(onDismissRequest = onNavigateUp) {
AutoFocusTextFieldDialog()
}
}
)
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun TextFieldsInDialogDemo() {
val listState = rememberLazyListState()
val (currentDemoIndex, setDemoIndex) = rememberSaveable { mutableStateOf(-1) }
if (currentDemoIndex == -1) {
LazyColumn(state = listState) {
itemsIndexed(dialogDemos) { index, demo ->
ListItem(Modifier.clickable { setDemoIndex(index) }) {
Text(demo.title)
}
}
}
} else {
val currentDemo = dialogDemos[currentDemoIndex]
Text(
currentDemo.title,
modifier = Modifier
.fillMaxSize()
.wrapContentSize(),
textAlign = TextAlign.Center
)
Layout(
content = { currentDemo.content(onNavigateUp = { setDemoIndex(-1) }) }
) { measurables, _ ->
check(measurables.isEmpty()) { "Dialog demo must only emit a Dialog composable." }
layout(0, 0) {}
}
}
}
@Composable
private fun SingleTextFieldDialog() {
var text by remember { mutableStateOf("") }
TextField(text, onValueChange = { text = it })
}
@Composable
private fun AutoFocusTextFieldDialog() {
var text by remember { mutableStateOf("") }
val focusRequester = remember { FocusRequester() }
LaunchedEffect(focusRequester) {
focusRequester.requestFocus()
}
TextField(
text,
onValueChange = { text = it },
modifier = Modifier.focusRequester(focusRequester)
)
} | apache-2.0 | 6442ad27796ba2548fadf621f3f0bafd | 33.10828 | 94 | 0.673328 | 5.074882 | false | false | false | false |
androidx/androidx | glance/glance/src/androidMain/kotlin/androidx/glance/layout/Spacer.kt | 3 | 1614 | /*
* 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.glance.layout
import androidx.annotation.RestrictTo
import androidx.compose.runtime.Composable
import androidx.glance.Emittable
import androidx.glance.GlanceModifier
import androidx.glance.GlanceNode
/** @suppress */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class EmittableSpacer : Emittable {
override var modifier: GlanceModifier = GlanceModifier
override fun copy(): Emittable = EmittableSpacer().also {
it.modifier = modifier
}
override fun toString(): String = "EmittableSpacer(modifier=$modifier)"
}
/**
* Component that represents an empty space layout, whose size can be defined using
* [GlanceModifier.width], [GlanceModifier.height], [GlanceModifier.size] modifiers.
*
* @param modifier Modifiers to set to this spacer
*/
@Composable
fun Spacer(modifier: GlanceModifier = GlanceModifier) {
GlanceNode(
factory = :: EmittableSpacer,
update = {
this.set(modifier) { this.modifier = it }
}
)
}
| apache-2.0 | 20b47e4bfe6af290d93e23c635022380 | 30.647059 | 84 | 0.731103 | 4.315508 | false | false | false | false |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/JavaPoetExt.kt | 3 | 7141 | /*
* Copyright (C) 2020 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.room.compiler.processing
import com.squareup.javapoet.AnnotationSpec
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import com.squareup.kotlinpoet.javapoet.JClassName
import java.lang.Character.isISOControl
import javax.lang.model.SourceVersion
import javax.lang.model.element.Modifier
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
/**
* Javapoet does not model NonType, unlike javac, which makes it hard to rely on TypeName for
* common functionality (e.g. ability to implement XType.isLong as typename() == TypeName.LONG
* instead of in the base class)
*
* For those cases, we have this hacky type so that we can always query TypeName on an XType.
*
* We should still strive to avoid these cases, maybe turn it to an error in tests.
*/
internal val JAVA_NONE_TYPE_NAME: JClassName =
JClassName.get("androidx.room.compiler.processing.error", "NotAType")
fun XAnnotation.toAnnotationSpec(): AnnotationSpec {
val builder = AnnotationSpec.builder(className)
annotationValues.forEach { builder.addAnnotationValue(it) }
return builder.build()
}
private fun AnnotationSpec.Builder.addAnnotationValue(annotationValue: XAnnotationValue) {
annotationValue.apply {
requireNotNull(value) { "value == null, constant non-null value expected for $name" }
require(SourceVersion.isName(name)) { "not a valid name: $name" }
when {
hasListValue() -> asAnnotationValueList().forEach { addAnnotationValue(it) }
hasAnnotationValue() -> addMember(name, "\$L", asAnnotation().toAnnotationSpec())
hasEnumValue() -> addMember(
name, "\$T.\$L", asEnum().enclosingElement.asClassName().java, asEnum().name
)
hasTypeValue() -> addMember(name, "\$T.class", asType().asTypeName().java)
hasStringValue() -> addMember(name, "\$S", asString())
hasFloatValue() -> addMember(name, "\$Lf", asFloat())
hasCharValue() -> addMember(
name, "'\$L'", characterLiteralWithoutSingleQuotes(asChar())
)
else -> addMember(name, "\$L", value)
}
}
}
private fun characterLiteralWithoutSingleQuotes(c: Char): String? {
// see https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6
return when (c) {
'\b' -> "\\b" /* \u0008: backspace (BS) */
'\t' -> "\\t" /* \u0009: horizontal tab (HT) */
'\n' -> "\\n" /* \u000a: linefeed (LF) */
'\u000c' -> "\\u000c" /* \u000c: form feed (FF) */
'\r' -> "\\r" /* \u000d: carriage return (CR) */
'\"' -> "\"" /* \u0022: double quote (") */
'\'' -> "\\'" /* \u0027: single quote (') */
'\\' -> "\\\\" /* \u005c: backslash (\) */
else -> if (isISOControl(c)) String.format("\\u%04x", c.code) else Character.toString(c)
}
}
internal fun TypeMirror.safeTypeName(): TypeName = if (kind == TypeKind.NONE) {
JAVA_NONE_TYPE_NAME
} else {
TypeName.get(this)
}
/**
* Adds the given element as the originating element for compilation.
* see [TypeSpec.Builder.addOriginatingElement].
*/
fun TypeSpec.Builder.addOriginatingElement(element: XElement): TypeSpec.Builder {
element.originatingElementForPoet()?.let(this::addOriginatingElement)
return this
}
internal fun TypeName.rawTypeName(): TypeName {
return if (this is ParameterizedTypeName) {
this.rawType
} else {
this
}
}
/**
* Returns the unboxed TypeName for this if it can be unboxed, otherwise, returns this.
*/
internal fun TypeName.tryUnbox(): TypeName {
return if (isBoxedPrimitive) {
unbox()
} else {
this
}
}
/**
* Returns the boxed TypeName for this if it can be unboxed, otherwise, returns this.
*/
internal fun TypeName.tryBox(): TypeName {
return try {
box()
} catch (err: AssertionError) {
this
}
}
/**
* Helper class to create overrides for XExecutableElements with final parameters and correct
* parameter names read from Kotlin Metadata.
*/
object MethodSpecHelper {
/**
* Creates an overriding [MethodSpec] for the given [XMethodElement] that
* does everything in [overriding] and also mark all parameters as final
*/
@JvmStatic
fun overridingWithFinalParams(
elm: XMethodElement,
owner: XType
): MethodSpec.Builder {
val asMember = elm.asMemberOf(owner)
return overriding(
executableElement = elm,
resolvedType = asMember,
Modifier.FINAL
)
}
/**
* Creates an overriding [MethodSpec] for the given [XMethodElement] where:
* * parameter names are copied from KotlinMetadata when available
* * [Override] annotation is added and other annotations are dropped
* * thrown types are copied if the backing element is from java
*/
@JvmStatic
fun overriding(
elm: XMethodElement,
owner: XType
): MethodSpec.Builder {
val asMember = elm.asMemberOf(owner)
return overriding(
executableElement = elm,
resolvedType = asMember
)
}
private fun overriding(
executableElement: XMethodElement,
resolvedType: XMethodType = executableElement.executableType,
vararg paramModifiers: Modifier
): MethodSpec.Builder {
return MethodSpec.methodBuilder(executableElement.jvmName).apply {
addTypeVariables(
resolvedType.typeVariableNames
)
resolvedType.parameterTypes.forEachIndexed { index, paramType ->
addParameter(
ParameterSpec.builder(
paramType.asTypeName().java,
executableElement.parameters[index].name,
*paramModifiers
).build()
)
}
if (executableElement.isPublic()) {
addModifiers(Modifier.PUBLIC)
} else if (executableElement.isProtected()) {
addModifiers(Modifier.PROTECTED)
}
addAnnotation(Override::class.java)
varargs(executableElement.isVarArgs())
executableElement.thrownTypes.forEach {
addException(it.asTypeName().java)
}
returns(resolvedType.returnType.asTypeName().java)
}
}
}
| apache-2.0 | 2f3d85d84120ef1a8c35197ee7603fa0 | 34.527363 | 96 | 0.648789 | 4.391759 | false | false | false | false |
jerkar/jerkar | samples/dev.jeka.samples.kotlin-multiplatform/jeka/def/build/Build.kt | 1 | 4279 | package build
import build.common.JkNodeJs
import build.common.KotlinJkBean
import dev.jeka.core.api.depmanagement.JkDependencySet
import dev.jeka.core.api.java.JkJavaRunner
import dev.jeka.core.api.java.JkJavaVersion
import dev.jeka.core.api.kotlin.JkKotlinModules
import dev.jeka.core.api.kotlin.JkKotlinModules.COMPILER_PLUGIN_KOTLINX_SERIALIZATION
import dev.jeka.core.api.project.JkProject
import dev.jeka.core.api.utils.JkUtilsIO
import dev.jeka.core.api.utils.JkUtilsPath
import dev.jeka.core.api.utils.JkUtilsString
import dev.jeka.core.tool.JkBean
import dev.jeka.core.tool.JkDoc
import dev.jeka.core.tool.JkInit
import java.awt.Desktop
class Build : JkBean() {
val kotlin = getBean(KotlinJkBean::class.java)
val serializationVersion = "1.2.1"
val ktorVersion = "1.6.1"
val logbackVersion = "1.2.3"
val kmongoVersion = "4.2.7"
val reactWrappersVersion = "17.0.2-pre.214-kotlin-1.5.20"
@JkDoc("Version of nodeJs to use")
var nodeJsVersion = "14.18.1"
var nodejsArgs = ""
init {
kotlin.jvm().configurators.append(this::configure)
}
fun configure(project: JkProject) {
project.simpleFacade()
.setJvmTargetVersion(JkJavaVersion.V8)
.configureCompileDeps { deps -> deps
.and("io.ktor:ktor-serialization:$ktorVersion")
.and("io.ktor:ktor-server-core:$ktorVersion")
.and("io.ktor:ktor-server-netty:$ktorVersion")
.and("ch.qos.logback:logback-classic:$logbackVersion")
.and("org.litote.kmongo:kmongo-coroutine-serialization:$kmongoVersion")
}
.configureTestDeps {deps -> deps
.and(JkKotlinModules.TEST_JUNIT5)
}
project.construction.manifest.addMainClass("ServerKt")
project.includeJavadocAndSources(false, false)
kotlin.jvm()
.useFatJarForMainArtifact()
.kotlinCompiler
.addPlugin("$COMPILER_PLUGIN_KOTLINX_SERIALIZATION:${kotlin.kotlinVersion}")
kotlin.common()
.setTestSrcDir(null).compileDependencies = JkDependencySet.of()
.and("org.jetbrains.kotlinx:kotlinx-serialization-json:$serializationVersion")
.and("io.ktor:ktor-client-core:$ktorVersion")
}
// -------------------------- End of build description --------------------------------------------------------
fun cleanPack() {
clean(); kotlin.jvm().project.pack()
}
fun run() {
val jar = kotlin.jvm().project.artifactProducer.mainArtifactPath
JkJavaRunner.runInSeparateClassloader(jar)
//JkJavaProcess.ofJavaJar(jar, null).exec()
}
fun open() {
Desktop.getDesktop().browse(JkUtilsIO.toUrl("http:localhost:9090").toURI())
}
fun npm() {
val sitePath = baseDir.resolve("jeka/.work/localsite")
JkUtilsPath.createDirectories(sitePath)
JkNodeJs.of(nodeJsVersion)
.setWorkingDir(sitePath)
.exec("npm", *JkUtilsString.translateCommandline(this.nodejsArgs))
}
fun npx() {
val sitePath = baseDir.resolve("jeka/.work/localsite")
JkUtilsPath.createDirectories(sitePath)
JkNodeJs.of(nodeJsVersion)
.setWorkingDir(sitePath)
.exec("npx", *JkUtilsString.translateCommandline(this.nodejsArgs))
}
object CleanPack {
@JvmStatic fun main(args: Array<String>) {
JkInit.instanceOf(Build::class.java, *args).cleanPack()
}
}
object RunJar {
@JvmStatic fun main(args: Array<String>) {
JkInit.instanceOf(Build::class.java, *args).run()
}
}
object Open {
@JvmStatic fun main(args: Array<String>){
JkInit.instanceOf(Build::class.java, *args).open()
}
}
object CleanCompile {
@JvmStatic fun main(args: Array<String>) {
val build = JkInit.instanceOf(Build::class.java, *args)
build.kotlin.jvm().project.construction.compilation.run()
}
}
object Npm {
@JvmStatic fun main(args: Array<String>) {
val build = JkInit.instanceOf(Build::class.java, *args)
build.npm()
}
}
} | apache-2.0 | 10eaebb9f0dd35144a2b6c6ac1e3b462 | 32.178295 | 115 | 0.620939 | 3.820536 | false | false | false | false |
adgvcxz/Diycode | app/src/main/java/com/adgvcxz/diycode/bean/Token.kt | 1 | 259 | package com.adgvcxz.diycode.bean
/**
* zhaowei
* Created by zhaowei on 2017/2/13.
*/
class Token {
val accessToken: String = ""
val tokenType: String = ""
val expiresIn: Int = 0
val refreshToken: String = ""
val createdAt: Int = 0
} | apache-2.0 | 4ffd15d041709a18fd324d9095c6fcab | 15.25 | 35 | 0.621622 | 3.647887 | false | false | false | false |
coder3101/gdgApp | gdg/src/main/java/com/softminds/gdg/utils/GdgEvents.kt | 1 | 1567 | /*
* Copyright (c) Ashar Khan 2017. <[email protected]>
* This file is part of Google Developer Group's Android Application.
* Google Developer Group 's Android Application is free software : you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* This Application is distributed in the hope that it will be useful
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this Source File.
* If not, see <http:www.gnu.org/licenses/>.
*/
package com.softminds.gdg.utils
class GdgEvents {
//data-fields
var time: Long = 0
var venue: String? = null
var name: String? = null
var author: String? = null
var agenda: String? = null
var speakers: List<String>? = null
var extraDetails: String? = null //any extra payload for event
var picsUrl: List<String>? = null //contains list of urls of current event
var headIconUrl: String? = null //contains central event url
var type: Int = 0
@Suppress("unused")
companion object {
val CONFERENCE = 1
val MEET_UP = 2
val HACK_ATHON = 3
val IDEA_THON = 4
val DISCUSSION = 5
val SEMINAR = 6
val WORKSHOP = 7
val FEST = 8
}
}
| gpl-3.0 | f3c1042ec80dfe91e95212596f4534bf | 33.822222 | 106 | 0.677728 | 3.937186 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/main/news/NewsPresenter.kt | 2 | 2484 | package ru.fantlab.android.ui.modules.main.news
import android.view.View
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.News
import ru.fantlab.android.data.dao.response.NewsResponse
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getNewsPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class NewsPresenter : BasePresenter<NewsMvp.View>(), NewsMvp.Presenter {
private var page: Int = 1
private var previousTotal: Int = 0
private var lastPage = Int.MAX_VALUE
override fun onFragmentCreated() {
onCallApi(1)
}
override fun onCallApi(page: Int, parameter: String?): Boolean = onCallApi(page)
override fun onCallApi(page: Int): Boolean {
if (page == 1) {
lastPage = Int.MAX_VALUE
sendToView { it.getLoadMore().reset() }
}
if (page > lastPage || lastPage == 0) {
sendToView { it.hideProgress() }
return false
}
setCurrentPage(page)
makeRestCall(
getNewsInternal().toObservable(),
Consumer { (responses, lastPage) ->
this.lastPage = lastPage
sendToView { it.onNotifyAdapter(responses, page) }
}
)
return true
}
private fun getNewsInternal() =
getNewsFromServer()
.onErrorResumeNext { throwable ->
if (page == 1) {
getNewsFromDb()
} else {
throw throwable
}
}
private fun getNewsFromServer(): Single<Pair<ArrayList<News>, Int>> =
DataManager.getNews(page, perPage = 15)
.map { getNews(it) }
private fun getNewsFromDb(): Single<Pair<ArrayList<News>, Int>> =
DbProvider.mainDatabase
.responseDao()
.get(getNewsPath(page, perPage = 15))
.map { it.response }
.map { NewsResponse.Deserializer(perPage = 15).deserialize(it) }
.map { getNews(it) }
private fun getNews(response: NewsResponse): Pair<ArrayList<News>, Int> =
response.news.items to response.news.last
override fun getCurrentPage(): Int = page
override fun getPreviousTotal(): Int = previousTotal
override fun setCurrentPage(page: Int) {
this.page = page
}
override fun setPreviousTotal(previousTotal: Int) {
this.previousTotal = previousTotal
}
override fun onItemClick(position: Int, v: View?, item: News) {
sendToView { it.onItemClicked(item, v) }
}
override fun onItemLongClick(position: Int, v: View?, item: News) {
sendToView { it.onItemLongClicked(position, v, item) }
}
} | gpl-3.0 | 03fbabad591dd143757df08285c004f4 | 26.921348 | 81 | 0.70934 | 3.508475 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/psi/Executable.kt | 1 | 1181 | package org.jetbrains.cabal.psi
import com.intellij.lang.ASTNode
import org.jetbrains.cabal.parser.*
import org.jetbrains.cabal.psi.Name
import org.jetbrains.cabal.highlight.ErrorMessage
import java.util.ArrayList
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
import java.lang.IllegalStateException
import com.intellij.psi.PsiElement
/**
* @author Evgeny.Kurbatsky
*/
public class Executable(node: ASTNode) : BuildSection(node) {
public fun getExecutableName(): String {
val res = getSectName()
if (res == null) throw IllegalStateException()
return res
}
public override fun check(): List<ErrorMessage> {
if (getField(javaClass<MainFileField>()) == null) return listOf(ErrorMessage(getSectTypeNode(), "main-is field is required", "error"))
return listOf()
}
public override fun getAvailableFieldNames(): List<String> {
var res = ArrayList<String>()
res.addAll(EXECUTABLE_FIELDS.keySet())
res.addAll(IF_ELSE)
return res
}
public fun getMainFile(): Path? = getField(javaClass<MainFileField>())?.getValue() as Path?
} | apache-2.0 | a71cb52cd1e81d9664d8a1e9c9330bdd | 30.105263 | 142 | 0.712108 | 4.100694 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/helpers/AutocompleteAdapter.kt | 1 | 6023 | package com.habitrpg.android.habitica.ui.helpers
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.auth.LocalAuthentication
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.models.social.FindUsernameResult
import com.habitrpg.android.habitica.models.user.Authentication
import com.habitrpg.android.habitica.models.user.Profile
import com.habitrpg.android.habitica.ui.views.UsernameLabel
import com.habitrpg.common.habitica.helpers.EmojiMap
import com.habitrpg.common.habitica.helpers.EmojiParser
import java.util.Date
class AutocompleteAdapter(
val context: Context,
val socialRepository: SocialRepository? = null,
var autocompleteContext: String? = null,
var groupID: String? = null,
val remoteAutocomplete: Boolean = false
) : BaseAdapter(), Filterable {
var chatMessages: List<ChatMessage> = arrayListOf()
private var userResults: List<FindUsernameResult> = arrayListOf()
private var emojiResults: List<String> = arrayListOf()
private var isAutocompletingUsers = true
private var lastAutocomplete: Long = 0
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val filterResults = FilterResults()
if (constraint != null && constraint.isNotEmpty()) {
if (constraint[0] == '@' && constraint.length >= 3 && socialRepository != null && remoteAutocomplete) {
if (Date().time - lastAutocomplete > 2000) {
lastAutocomplete = Date().time
userResults = arrayListOf()
isAutocompletingUsers = true
socialRepository.findUsernames(constraint.toString().drop(1), autocompleteContext, groupID).blockingSubscribe {
userResults = it
filterResults.values = userResults
filterResults.count = userResults.size
}
} else {
filterResults.values = userResults
filterResults.count = userResults.size
}
} else if (constraint[0] == '@') {
lastAutocomplete = Date().time
isAutocompletingUsers = true
userResults = chatMessages
.filter { it.isValid }
.distinctBy {
it.username
}.filter { it.username?.startsWith(constraint.toString().drop(1)) ?: false }.map { message ->
val result = FindUsernameResult()
result.authentication = Authentication()
result.authentication?.localAuthentication = LocalAuthentication()
result.authentication?.localAuthentication?.username = message.username
result.contributor = message.contributor
result.profile = Profile()
result.profile?.name = message.user
result
}
filterResults.values = userResults
filterResults.count = userResults.size
} else if (constraint[0] == ':') {
isAutocompletingUsers = false
emojiResults = EmojiMap.invertedEmojiMap.keys.filter { it.startsWith(constraint) }
filterResults.values = emojiResults
filterResults.count = emojiResults.size
}
}
return filterResults
}
override fun publishResults(contraint: CharSequence?, results: FilterResults?) {
if (results != null && results.count > 0) {
notifyDataSetChanged()
} else {
notifyDataSetInvalidated()
}
}
}
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
return if (isAutocompletingUsers) {
val view = parent?.inflate(R.layout.autocomplete_username)
val result = getItem(position) as? FindUsernameResult
val displaynameView = view?.findViewById<UsernameLabel>(R.id.display_name_view)
displaynameView?.username = result?.profile?.name
displaynameView?.tier = result?.contributor?.level ?: 0
view?.findViewById<TextView>(R.id.username_view)?.text = result?.formattedUsername
view
} else {
val view = parent?.inflate(R.layout.autocomplete_emoji)
val result = getItem(position) as? String
val emojiTextView = view?.findViewById<TextView>(R.id.emoji_textview)
emojiTextView?.text = EmojiParser.parseEmojis(result)
view?.findViewById<TextView>(R.id.label)?.text = result
view
} ?: View(context)
}
override fun getItem(position: Int): Any? {
return if (isAutocompletingUsers) userResults.getOrNull(position) else emojiResults.getOrNull(position)
}
override fun getItemId(position: Int): Long {
return getItem(position).hashCode().toLong()
}
override fun getCount(): Int {
return if (isAutocompletingUsers) userResults.size else emojiResults.size
}
}
| gpl-3.0 | c14ade37a11b0f915b1c8736a059df56 | 47.572581 | 139 | 0.589241 | 5.505484 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/user/achievements/AchievementGiver.kt | 1 | 4432 | package de.westnordost.streetcomplete.data.user.achievements
import de.westnordost.streetcomplete.data.notifications.NewUserAchievementsDao
import de.westnordost.streetcomplete.data.user.QuestStatisticsDao
import de.westnordost.streetcomplete.data.user.UserStore
import javax.inject.Inject
import javax.inject.Named
/** Grants achievements based on solved quests (or other things) and puts the links contained in
* these in the link collection */
class AchievementGiver @Inject constructor(
private val userAchievementsDao: UserAchievementsDao,
private val newUserAchievementsDao: NewUserAchievementsDao,
private val userLinksDao: UserLinksDao,
private val questStatisticsDao: QuestStatisticsDao,
@Named("Achievements") private val allAchievements: List<Achievement>,
private val userStore: UserStore
) {
/** Look at and grant all achievements */
fun updateAllAchievements(silent: Boolean = false) {
return updateAchievements(allAchievements, silent)
}
/** Look at and grant only the achievements that have anything to do with the given quest type */
fun updateQuestTypeAchievements(questType: String) {
return updateAchievements(allAchievements.filter {
when (it.condition) {
is SolvedQuestsOfTypes -> it.condition.questTypes.contains(questType)
is TotalSolvedQuests -> true
else -> false
}
})
}
/** Look at and grant only the achievements that have anything to do with days active */
fun updateDaysActiveAchievements() {
return updateAchievements(allAchievements.filter { it.condition is DaysActive })
}
private fun updateAchievements(achievements: List<Achievement>, silent: Boolean = false) {
val currentAchievementLevels = userAchievementsDao.getAll()
// look at all defined achievements
for (achievement in achievements) {
val currentLevel = currentAchievementLevels[achievement.id] ?: 0
if (achievement.maxLevel != -1 && currentLevel >= achievement.maxLevel) continue
val achievedLevel = getAchievedLevel(achievement)
if (achievedLevel > currentLevel) {
userAchievementsDao.put(achievement.id, achievedLevel)
val unlockedLinkIds = mutableListOf<String>()
for (level in (currentLevel + 1)..achievedLevel) {
achievement.unlockedLinks[level]?.map { it.id }?.let { unlockedLinkIds.addAll(it) }
if (!silent) newUserAchievementsDao.push(achievement.id to level)
}
if (unlockedLinkIds.isNotEmpty()) userLinksDao.addAll(unlockedLinkIds)
}
}
}
/** Goes through all granted achievements and gives the included links to the user if he doesn't
* have them yet. This method only needs to be called when new links have been added to already
* existing achievement levels from one StreetComplete version to another. So, this only needs
* to be done once after each app update */
fun updateAchievementLinks() {
val unlockedLinkIds = mutableListOf<String>()
val currentAchievementLevels = userAchievementsDao.getAll()
for (achievement in allAchievements) {
val currentLevel = currentAchievementLevels[achievement.id] ?: 0
for (level in 1..currentLevel) {
achievement.unlockedLinks[level]?.map { it.id }?.let { unlockedLinkIds.addAll(it) }
}
}
if (unlockedLinkIds.isNotEmpty()) userLinksDao.addAll(unlockedLinkIds)
}
private fun getAchievedLevel(achievement: Achievement): Int {
val func = achievement.pointsNeededToAdvanceFunction
var level = 0
var threshold = 0
do {
threshold += func(level)
level++
if (achievement.maxLevel != -1 && level > achievement.maxLevel) break
} while (isAchieved(threshold, achievement.condition))
return level - 1
}
private fun isAchieved(threshold: Int, condition: AchievementCondition): Boolean {
return threshold <= when (condition) {
is SolvedQuestsOfTypes -> questStatisticsDao.getAmount(condition.questTypes)
is TotalSolvedQuests -> questStatisticsDao.getTotalAmount()
is DaysActive -> userStore.daysActive
}
}
}
| gpl-3.0 | f7b3e754f0055991dca9cbbb52c5ff74 | 44.690722 | 103 | 0.675993 | 5.013575 | false | false | false | false |
android/tv-samples | ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/repository/VideoRepository.kt | 1 | 3151 | /*
* Copyright 2020 Google LLC
*
* 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.android.tv.reference.repository
import android.app.Application
import com.android.tv.reference.shared.datamodel.Video
import com.android.tv.reference.shared.datamodel.VideoType
/**
* Interface to define methods to interact with different data sources.
*/
interface VideoRepository {
val application: Application
/**
* Return all videos available from a specific source.
* @return List<Video>
*/
fun getAllVideos(): List<Video>
/**
* Returns a Video for the passed [id] or null if there is no matching video.
*/
fun getVideoById(id: String): Video?
/**
* Returns a Video for the passed [uri] or null if there is no matching video.
*/
fun getVideoByVideoUri(uri: String): Video?
/**
* Returns all TV episodes from the same TV Series.
*/
fun getAllVideosFromSeries(seriesUri: String): List<Video>
/**
* Get next episode for the same TV Series.
* - if given episode is not last episode of current season, return next episode.
* - if given episode is last episode of current season, return first episode of next season.
* Returns next episode or null if failed to find one.
*/
fun getNextEpisodeInSeries(episode: Video): Video? {
if (episode.videoType != VideoType.EPISODE) {
return null
}
// Put all episodes of the same series in a map. With season number as the key and a
// list of videos from the specified season as the value.
val tvSeasonMap = getAllVideosFromSeries(episode.seriesUri).groupBy { it.seasonNumber }
var nextEpisode: Video? = null
val nextEpisodeNumber = (episode.episodeNumber.toInt() + 1).toString()
// Searching for next episode in the same season.
tvSeasonMap[episode.seasonNumber]?.let { currentSeason ->
nextEpisode = currentSeason.firstOrNull { videoInCurrentSeason ->
videoInCurrentSeason.episodeNumber == nextEpisodeNumber
}
}
// If not found in previous step, checking if there's an episode available in next season.
if (nextEpisode == null) {
val nextSeasonNumber = (episode.seasonNumber.toInt() + 1).toString()
tvSeasonMap[nextSeasonNumber]?.let { nextSeason ->
nextEpisode = if (nextSeason.sortedBy { it.episodeNumber }.isNotEmpty()) {
nextSeason[0]
} else {
null
}
}
}
return nextEpisode
}
}
| apache-2.0 | 66605a7b8aaa7a4cf5dc09046622deb4 | 35.218391 | 98 | 0.655982 | 4.6 | false | false | false | false |
sirixdb/sirix | bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/Revisions.kt | 1 | 4286 | package org.sirix.rest.crud
import org.sirix.api.NodeCursor
import org.sirix.api.NodeReadOnlyTrx
import org.sirix.api.NodeTrx
import org.sirix.api.ResourceSession
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
class Revisions {
companion object {
fun <R, W> getRevisionsToSerialize(
startRevision: String?, endRevision: String?, startRevisionTimestamp: String?,
endRevisionTimestamp: String?, manager: ResourceSession<R, W>, revision: String?,
revisionTimestamp: String?
): IntArray
where R : NodeReadOnlyTrx,
R : NodeCursor,
W : NodeTrx,
W : NodeCursor {
return when {
startRevision != null && endRevision != null -> parseIntRevisions(startRevision, endRevision)
startRevisionTimestamp != null && endRevisionTimestamp != null -> {
val tspRevisions = parseTimestampRevisions(startRevisionTimestamp, endRevisionTimestamp)
getRevisionNumbers(manager, tspRevisions).toList().toIntArray()
}
else -> getRevisionNumber(revision, revisionTimestamp, manager)
}
}
fun <R, W> getRevisionNumber(rev: String?, revTimestamp: String?, manager: ResourceSession<R, W>): IntArray
where R : NodeReadOnlyTrx,
R : NodeCursor,
W : NodeTrx,
W : NodeCursor {
return if (rev != null) {
intArrayOf(rev.toInt())
} else if (revTimestamp != null) {
var revision = getRevisionNumber(manager, revTimestamp)
if (revision == 0)
intArrayOf(++revision)
else
intArrayOf(revision)
} else {
intArrayOf(manager.mostRecentRevisionNumber)
}
}
private fun <R, W> getRevisionNumber(manager: ResourceSession<R, W>, revision: String): Int
where R : NodeReadOnlyTrx,
R : NodeCursor,
W : NodeTrx,
W : NodeCursor {
val zdt = parseRevisionTimestamp(revision)
return manager.getRevisionNumber(zdt.toInstant())
}
fun parseRevisionTimestamp(revision: String): ZonedDateTime {
val revisionDateTime = try {
LocalDateTime.parse(revision)
} catch (e: DateTimeParseException) {
LocalDateTime.parse(revision, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
}
return revisionDateTime.atZone(ZoneOffset.UTC)
}
private fun <R, W> getRevisionNumbers(
manager: ResourceSession<R, W>,
revisions: Pair<ZonedDateTime, ZonedDateTime>
): IntArray
where R : NodeReadOnlyTrx,
R : NodeCursor,
W : NodeTrx,
W : NodeCursor {
val zdtFirstRevision = revisions.first
val zdtLastRevision = revisions.second
var firstRevisionNumber = manager.getRevisionNumber(zdtFirstRevision.toInstant())
var lastRevisionNumber = manager.getRevisionNumber(zdtLastRevision.toInstant())
if (firstRevisionNumber == 0) ++firstRevisionNumber
if (lastRevisionNumber == 0) ++lastRevisionNumber
return (firstRevisionNumber..lastRevisionNumber).toSet().toIntArray()
}
private fun parseIntRevisions(startRevision: String, endRevision: String): IntArray {
return (startRevision.toInt()..endRevision.toInt()).toSet().toIntArray()
}
private fun parseTimestampRevisions(
startRevision: String,
endRevision: String
): Pair<ZonedDateTime, ZonedDateTime> {
val firstRevisionDateTime = parseRevisionTimestamp(startRevision)
val lastRevisionDateTime = parseRevisionTimestamp(endRevision)
return Pair(firstRevisionDateTime, lastRevisionDateTime)
}
}
} | bsd-3-clause | 4de1792a377acdd299034f4332e40a0b | 40.621359 | 115 | 0.591461 | 5.377666 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/Versions.kt | 1 | 1912 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.tools.projectWizard
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
@Suppress("ClassName", "SpellCheckingInspection")
object Versions {
val KOTLIN = version("1.5.0") // used as fallback version
val GRADLE = version("7.4.2")
val KTOR = version("2.0.1")
val JUNIT = version("4.13.2")
val JUNIT5 = version("5.8.2")
val JETBRAINS_COMPOSE = version("1.1.0")
val KOTLIN_VERSION_FOR_COMPOSE = version("1.6.10")
val GRADLE_VERSION_FOR_COMPOSE = version("7.3.3")
object COMPOSE {
val ANDROID_ACTIVITY_COMPOSE = version("1.4.0")
}
object ANDROID {
val ANDROID_MATERIAL = version("1.5.0")
val ANDROIDX_APPCOMPAT = version("1.4.1")
val ANDROIDX_CONSTRAINTLAYOUT = version("2.1.3")
val ANDROIDX_KTX = version("1.7.0")
}
object KOTLINX {
val KOTLINX_HTML = version("0.7.2")
val KOTLINX_NODEJS: Version = version("0.0.7")
}
object JS_WRAPPERS {
val KOTLIN_REACT = wrapperVersion("18.0.0")
val KOTLIN_REACT_DOM = KOTLIN_REACT
val KOTLIN_EMOTION = wrapperVersion("11.9.0")
val KOTLIN_REACT_ROUTER_DOM = wrapperVersion("6.3.0")
val KOTLIN_REDUX = wrapperVersion("4.1.2")
val KOTLIN_REACT_REDUX = wrapperVersion("7.2.6")
private fun wrapperVersion(version: String): Version =
version("$version-pre.332-kotlin-1.6.21")
}
object GRADLE_PLUGINS {
val ANDROID = version("7.0.4")
}
object MAVEN_PLUGINS {
val SUREFIRE = version("2.22.2")
val FAILSAFE = SUREFIRE
}
}
private fun version(version: String) = Version.fromString(version)
| apache-2.0 | 230f76a54a7ce580ebbb8e79b8a8a299 | 30.866667 | 115 | 0.642259 | 3.527675 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/showcase/inline/Reader.kt | 1 | 1575 | @file:Suppress("EXPERIMENTAL_FEATURE_WARNING", "EXPERIMENTAL_API_USAGE")
package arcs.showcase.inline
import arcs.jvm.host.TargetHost
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.withContext
@OptIn(ExperimentalCoroutinesApi::class)
@TargetHost(arcs.android.integration.IntegrationHost::class)
class Reader0 : AbstractReader0() {
private fun Level0.fromArcs() = MyLevel0(name)
suspend fun read(): List<MyLevel0> = withContext(handles.level0.dispatcher) {
handles.level0.fetchAll().map { it.fromArcs() }
}
}
@OptIn(ExperimentalCoroutinesApi::class)
@TargetHost(arcs.android.integration.IntegrationHost::class)
class Reader1 : AbstractReader1() {
private fun Level0.fromArcs() = MyLevel0(name)
private suspend fun Level1.fromArcs() = MyLevel1(
name = name,
children = children.map { it.fromArcs() }.toSet()
)
suspend fun read(): List<MyLevel1> = withContext(handles.level1.dispatcher) {
handles.level1.fetchAll().map { it.fromArcs() }
}
}
@OptIn(ExperimentalCoroutinesApi::class)
@TargetHost(arcs.android.integration.IntegrationHost::class)
class Reader2 : AbstractReader2() {
private fun Level0.fromArcs() = MyLevel0(name)
private fun Level1.fromArcs() = MyLevel1(
name = name,
children = children.map { it.fromArcs() }.toSet()
)
private fun Level2.fromArcs() = MyLevel2(
name = name,
children = children.map { it.fromArcs() }.toSet()
)
suspend fun read(): List<MyLevel2> = withContext(handles.level2.dispatcher) {
handles.level2.fetchAll().map { it.fromArcs() }
}
}
| bsd-3-clause | 4be5e36555fd0cbee7da798896d3a06f | 29.288462 | 79 | 0.732063 | 3.612385 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinSourceSetDataService.kt | 1 | 13491 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.externalSystem.service.project.manage.SourceFolderManager
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExportableOrderEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.idea.facet.*
import org.jetbrains.kotlin.idea.gradle.configuration.KotlinSourceSetInfo
import org.jetbrains.kotlin.idea.gradle.configuration.findChildModuleById
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinAndroidSourceSets
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinSourceSetData
import org.jetbrains.kotlin.idea.gradleJava.KotlinGradleFacadeImpl
import org.jetbrains.kotlin.idea.platform.IdePlatformKindTooling
import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation
import org.jetbrains.kotlin.idea.projectModel.KotlinComponent
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform
import org.jetbrains.kotlin.idea.projectModel.KotlinSourceSet
import org.jetbrains.kotlin.idea.roots.migrateNonJvmSourceFolders
import org.jetbrains.kotlin.idea.roots.pathAsUrl
import org.jetbrains.kotlin.platform.IdePlatformKind
import org.jetbrains.kotlin.platform.SimplePlatform
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.platform.js.JsPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.platform.konan.NativePlatform
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.util.GradleConstants
class KotlinSourceSetDataService : AbstractProjectDataService<GradleSourceSetData, Void>() {
override fun getTargetDataKey() = GradleSourceSetData.KEY
private fun getProjectPlatforms(toImport: MutableCollection<out DataNode<GradleSourceSetData>>): List<KotlinPlatform> {
val platforms = HashSet<KotlinPlatform>()
for (nodeToImport in toImport) {
nodeToImport.kotlinSourceSetData?.sourceSetInfo?.also {
platforms += it.actualPlatforms.platforms
}
if (nodeToImport.parent?.children?.any { it.key.dataType.contains("Android") } == true) {
platforms += KotlinPlatform.ANDROID
}
}
return platforms.toList()
}
override fun postProcess(
toImport: MutableCollection<out DataNode<GradleSourceSetData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
val projectPlatforms = getProjectPlatforms(toImport)
for (nodeToImport in toImport) {
val mainModuleData = ExternalSystemApiUtil.findParent(
nodeToImport,
ProjectKeys.MODULE
) ?: continue
val sourceSetData = nodeToImport.data
val kotlinSourceSet = nodeToImport.kotlinSourceSetData?.sourceSetInfo ?: continue
val ideModule = modelsProvider.findIdeModule(sourceSetData) ?: continue
val platform = kotlinSourceSet.actualPlatforms
val rootModel = modelsProvider.getModifiableRootModel(ideModule)
if (platform.platforms.any { it != KotlinPlatform.JVM && it != KotlinPlatform.ANDROID }) {
migrateNonJvmSourceFolders(rootModel)
populateNonJvmSourceRootTypes(nodeToImport, ideModule)
}
configureFacet(sourceSetData, kotlinSourceSet, mainModuleData, ideModule, modelsProvider, projectPlatforms).let { facet ->
GradleProjectImportHandler.getInstances(project).forEach { it.importBySourceSet(facet, nodeToImport) }
}
if (kotlinSourceSet.isTestModule) {
assignTestScope(rootModel)
}
}
}
private fun assignTestScope(rootModel: ModifiableRootModel) {
rootModel
.orderEntries
.asSequence()
.filterIsInstance<ExportableOrderEntry>()
.filter { it.scope == DependencyScope.COMPILE }
.forEach { it.scope = DependencyScope.TEST }
}
companion object {
private val KotlinComponent.kind
get() = when (this) {
is KotlinCompilation -> KotlinModuleKind.COMPILATION_AND_SOURCE_SET_HOLDER
is KotlinSourceSet -> KotlinModuleKind.SOURCE_SET_HOLDER
else -> KotlinModuleKind.DEFAULT
}
private fun SimplePlatform.isRelevantFor(projectPlatforms: List<KotlinPlatform>): Boolean {
val jvmPlatforms = listOf(KotlinPlatform.ANDROID, KotlinPlatform.JVM, KotlinPlatform.COMMON)
return when (this) {
is JvmPlatform -> projectPlatforms.intersect(jvmPlatforms).isNotEmpty()
is JsPlatform -> KotlinPlatform.JS in projectPlatforms
is NativePlatform -> KotlinPlatform.NATIVE in projectPlatforms
else -> true
}
}
private fun IdePlatformKind.toSimplePlatforms(
moduleData: ModuleData,
isHmppModule: Boolean,
projectPlatforms: List<KotlinPlatform>
): Collection<SimplePlatform> {
if (this is JvmIdePlatformKind) {
val jvmTarget = JvmTarget.fromString(moduleData.targetCompatibility ?: "") ?: JvmTarget.DEFAULT
return JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget)
}
if (this is NativeIdePlatformKind) {
return NativePlatforms.nativePlatformByTargetNames(moduleData.konanTargets)
}
return if (isHmppModule) {
this.defaultPlatform.filter { it.isRelevantFor(projectPlatforms) }
} else {
this.defaultPlatform
}
}
fun configureFacet(
moduleData: ModuleData,
kotlinSourceSet: KotlinSourceSetInfo,
mainModuleNode: DataNode<ModuleData>,
ideModule: Module,
modelsProvider: IdeModifiableModelsProvider
) {
// TODO Review this code after AS Chipmunk released and merged to master
// In https://android.googlesource.com/platform/tools/adt/idea/+/ab31cd294775b7914ddefbe417a828b5c18acc81%5E%21/#F1
// creation of KotlinAndroidSourceSetData node was dropped, all tasks must be stored in corresponding KotlinSourceSetData nodes
val additionalRunTasks = mainModuleNode.kotlinAndroidSourceSets
?.filter { it.isTestModule }
?.flatMap { it.externalSystemRunTasks }
?.toSet()
configureFacet(
moduleData,
kotlinSourceSet,
mainModuleNode,
ideModule,
modelsProvider,
enumValues<KotlinPlatform>().toList(),
additionalRunTasks
)
}
@OptIn(ExperimentalStdlibApi::class)
fun configureFacet(
moduleData: ModuleData,
kotlinSourceSet: KotlinSourceSetInfo,
mainModuleNode: DataNode<ModuleData>,
ideModule: Module,
modelsProvider: IdeModifiableModelsProvider,
projectPlatforms: List<KotlinPlatform>,
additionalRunTasks: Collection<ExternalSystemRunTask>? = null
): KotlinFacet {
val compilerVersion = KotlinGradleFacadeImpl.findKotlinPluginVersion(mainModuleNode)
// ?: return null TODO: Fix in CLion or our plugin KT-27623
val platformKinds = kotlinSourceSet.actualPlatforms.platforms //TODO(auskov): fix calculation of jvm target
.map { IdePlatformKindTooling.getTooling(it).kind }
.flatMap { it.toSimplePlatforms(moduleData, mainModuleNode.kotlinGradleProjectDataOrFail.isHmpp, projectPlatforms) }
.distinct()
.toSet()
val platform = TargetPlatform(platformKinds)
val compilerArguments = kotlinSourceSet.lazyCompilerArguments?.value
// Used ID is the same as used in org/jetbrains/kotlin/idea/configuration/KotlinGradleSourceSetDataService.kt:280
// because this DataService was separated from KotlinGradleSourceSetDataService for MPP projects only
val id = if (compilerArguments?.multiPlatform == true) GradleConstants.SYSTEM_ID.id else null
val kotlinFacet = ideModule.getOrCreateFacet(modelsProvider, false, id)
val kotlinGradleProjectData = mainModuleNode.kotlinGradleProjectDataOrFail
kotlinFacet.configureFacet(
compilerVersion = compilerVersion,
platform = platform,
modelsProvider = modelsProvider,
hmppEnabled = kotlinGradleProjectData.isHmpp,
pureKotlinSourceFolders = if (platform.isJvm()) kotlinGradleProjectData.pureKotlinSourceFolders.toList() else emptyList(),
dependsOnList = kotlinSourceSet.dependsOn,
additionalVisibleModuleNames = kotlinSourceSet.additionalVisible
)
val defaultCompilerArguments = kotlinSourceSet.lazyDefaultCompilerArguments?.value
if (compilerArguments != null) {
applyCompilerArgumentsToFacet(
compilerArguments,
defaultCompilerArguments,
kotlinFacet,
modelsProvider
)
}
adjustClasspath(kotlinFacet, kotlinSourceSet.lazyDependencyClasspath.value)
kotlinFacet.noVersionAutoAdvance()
with(kotlinFacet.configuration.settings) {
kind = kotlinSourceSet.kotlinComponent.kind
isTestModule = kotlinSourceSet.isTestModule
externalSystemRunTasks = buildList {
addAll(kotlinSourceSet.externalSystemRunTasks)
additionalRunTasks?.let(::addAll)
}
externalProjectId = kotlinSourceSet.gradleModuleId
sourceSetNames = kotlinSourceSet.sourceSetIdsByName.values.mapNotNull { sourceSetId ->
val node = mainModuleNode.findChildModuleById(sourceSetId) ?: return@mapNotNull null
val data = node.data as? ModuleData ?: return@mapNotNull null
modelsProvider.findIdeModule(data)?.name
}
if (kotlinSourceSet.isTestModule) {
testOutputPath = (kotlinSourceSet.lazyCompilerArguments?.value as? K2JSCompilerArguments)?.outputFile
productionOutputPath = null
} else {
productionOutputPath = (kotlinSourceSet.lazyCompilerArguments?.value as? K2JSCompilerArguments)?.outputFile
testOutputPath = null
}
}
return kotlinFacet
}
}
}
private const val KOTLIN_NATIVE_TARGETS_PROPERTY = "konanTargets"
var ModuleData.konanTargets: Set<String>
get() {
val value = getProperty(KOTLIN_NATIVE_TARGETS_PROPERTY) ?: return emptySet()
return if (value.isNotEmpty()) value.split(',').toSet() else emptySet()
}
set(value) = setProperty(KOTLIN_NATIVE_TARGETS_PROPERTY, value.takeIf { it.isNotEmpty() }?.joinToString(","))
private fun populateNonJvmSourceRootTypes(sourceSetNode: DataNode<GradleSourceSetData>, module: Module) {
val sourceFolderManager = SourceFolderManager.getInstance(module.project)
val contentRootDataNodes = ExternalSystemApiUtil.findAll(sourceSetNode, ProjectKeys.CONTENT_ROOT)
val contentRootDataList = contentRootDataNodes.mapNotNull { it.data }
if (contentRootDataList.isEmpty()) return
val externalToKotlinSourceTypes = mapOf(
ExternalSystemSourceType.SOURCE to SourceKotlinRootType,
ExternalSystemSourceType.TEST to TestSourceKotlinRootType
)
externalToKotlinSourceTypes.forEach { (externalType, kotlinType) ->
val sourcesRoots = contentRootDataList.flatMap { it.getPaths(externalType) }
sourcesRoots.forEach {
if (!FileUtil.exists(it.path)) {
sourceFolderManager.addSourceFolder(module, it.pathAsUrl, kotlinType)
}
}
}
} | apache-2.0 | d9529c40998be49d011e033555cc6ed3 | 46.174825 | 139 | 0.689571 | 5.750639 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/testUtils.kt | 3 | 6669 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage
import com.google.common.collect.HashBiMap
import com.intellij.workspaceModel.storage.impl.*
import com.intellij.workspaceModel.storage.impl.containers.BidirectionalLongMultiMap
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import junit.framework.TestCase.*
import org.junit.Assert
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.function.BiPredicate
import kotlin.reflect.full.memberProperties
class TestEntityTypesResolver : EntityTypesResolver {
private val pluginPrefix = "PLUGIN___"
override fun getPluginId(clazz: Class<*>): String = pluginPrefix + clazz.name
override fun resolveClass(name: String, pluginId: String?): Class<*> {
Assert.assertEquals(pluginPrefix + name, pluginId)
if (name.startsWith("[")) return Class.forName(name)
return javaClass.classLoader.loadClass(name)
}
}
object SerializationRoundTripChecker {
fun verifyPSerializationRoundTrip(storage: EntityStorage, virtualFileManager: VirtualFileUrlManager): ByteArray {
storage as EntityStorageSnapshotImpl
storage.assertConsistency()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager)
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, storage)
val byteArray = stream.toByteArray()
val deserialized = (serializer.deserializeCache(ByteArrayInputStream(byteArray)) as MutableEntityStorageImpl).toSnapshot() as EntityStorageSnapshotImpl
deserialized.assertConsistency()
assertStorageEquals(storage, deserialized)
storage.assertConsistency()
return byteArray
}
private fun assertStorageEquals(expected: EntityStorageSnapshotImpl, actual: EntityStorageSnapshotImpl) {
// Assert entity data
assertEquals(expected.entitiesByType.size(), actual.entitiesByType.size())
for ((clazz, expectedEntityFamily) in expected.entitiesByType.entityFamilies.withIndex()) {
val actualEntityFamily = actual.entitiesByType.entityFamilies[clazz]
if (expectedEntityFamily == null || actualEntityFamily == null) {
assertNull(expectedEntityFamily)
assertNull(actualEntityFamily)
continue
}
val expectedEntities = expectedEntityFamily.entities
val actualEntities = actualEntityFamily.entities
assertOrderedEquals(expectedEntities, actualEntities) { a, b -> a == null && b == null || a != null && b != null && a.equalsIgnoringEntitySource(b) }
}
// Assert refs
assertMapsEqual(expected.refs.oneToOneContainer, actual.refs.oneToOneContainer)
assertMapsEqual(expected.refs.oneToManyContainer, actual.refs.oneToManyContainer)
assertMapsEqual(expected.refs.abstractOneToOneContainer, actual.refs.abstractOneToOneContainer)
assertMapsEqual(expected.refs.oneToAbstractManyContainer, actual.refs.oneToAbstractManyContainer)
assertMapsEqual(expected.indexes.virtualFileIndex.entityId2VirtualFileUrl, actual.indexes.virtualFileIndex.entityId2VirtualFileUrl)
assertMapsEqual(expected.indexes.virtualFileIndex.vfu2EntityId, actual.indexes.virtualFileIndex.vfu2EntityId)
// Just checking that all properties have been asserted
assertEquals(4, RefsTable::class.memberProperties.size)
// Assert indexes
assertBiLongMultiMap(expected.indexes.softLinks.index, actual.indexes.softLinks.index)
assertBiMap(expected.indexes.persistentIdIndex.index, actual.indexes.persistentIdIndex.index)
// External index should not be persisted
assertTrue(actual.indexes.externalMappings.isEmpty())
// Just checking that all properties have been asserted
assertEquals(5, StorageIndexes::class.memberProperties.size)
}
// Use UsefulTestCase.assertOrderedEquals in case it'd be used in this module
private fun <T> assertOrderedEquals(actual: Iterable<T?>, expected: Iterable<T?>, comparator: (T?, T?) -> Boolean) {
if (!equals(actual, expected, BiPredicate(comparator))) {
val expectedString: String = expected.toString()
val actualString: String = actual.toString()
Assert.assertEquals("", expectedString, actualString)
Assert.fail(
"Warning! 'toString' does not reflect the difference.\nExpected: $expectedString\nActual: $actualString")
}
}
private fun <T> equals(a1: Iterable<T?>, a2: Iterable<T?>, predicate: BiPredicate<in T?, in T?>): Boolean {
val it1 = a1.iterator()
val it2 = a2.iterator()
while (it1.hasNext() || it2.hasNext()) {
if (!it1.hasNext() || !it2.hasNext() || !predicate.test(it1.next(), it2.next())) {
return false
}
}
return true
}
private fun assertMapsEqual(expected: Map<*, *>, actual: Map<*, *>) {
val local = HashMap(expected)
for ((key, value) in actual) {
val expectedValue = local.remove(key)
if (expectedValue == null) {
Assert.fail(String.format("Expected to find '%s' -> '%s' mapping but it doesn't exist", key, value))
}
if (expectedValue != value) {
Assert.fail(
String.format("Expected to find '%s' value for the key '%s' but got '%s'", expectedValue, key, value))
}
}
if (local.isNotEmpty()) {
Assert.fail("No mappings found for the following keys: " + local.keys)
}
}
private fun <B> assertBiLongMultiMap(expected: BidirectionalLongMultiMap<B>, actual: BidirectionalLongMultiMap<B>) {
val local = expected.copy()
actual.keys.forEach { key ->
val value = actual.getValues(key)
val expectedValue = local.getValues(key)
local.removeKey(key)
assertOrderedEquals(expectedValue.sortedBy { it.toString() }, value.sortedBy { it.toString() }) { a, b -> a == b }
}
if (!local.isEmpty()) {
Assert.fail("No mappings found for the following keys: " + local.keys)
}
}
private fun <T> assertBiMap(expected: HashBiMap<EntityId, T>, actual: HashBiMap<EntityId, T>) {
val local = HashBiMap.create(expected)
for (key in actual.keys) {
val value = actual.getValue(key)
val expectedValue = local.remove(key)
if (expectedValue == null) {
Assert.fail(String.format("Expected to find '%s' -> '%s' mapping but it doesn't exist", key, value))
}
if (expectedValue != value) {
Assert.fail(
String.format("Expected to find '%s' value for the key '%s' but got '%s'", expectedValue, key, value))
}
}
if (local.isNotEmpty()) {
Assert.fail("No mappings found for the following keys: " + local.keys)
}
}
}
| apache-2.0 | 2761624136a52016e1622f5de80f205b | 41.75 | 155 | 0.721547 | 4.589814 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/module/ModuleString.kt | 1 | 13131 | package com.bajdcc.LALR1.interpret.module
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.*
import com.bajdcc.LALR1.grammar.runtime.data.RuntimeArray
import com.bajdcc.util.ResourceLoader
import java.util.regex.Pattern
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
/**
* 【模块】字符串模块
*
* @author bajdcc
*/
class ModuleString : IInterpreterModule {
private var runtimeCodePage: RuntimeCodePage? = null
override val moduleName: String
get() = "sys.string"
override val moduleCode: String
get() = ResourceLoader.load(javaClass)
override val codePage: RuntimeCodePage
@Throws(Exception::class)
get() {
if (runtimeCodePage != null)
return runtimeCodePage!!
val base = ResourceLoader.load(javaClass)
val grammar = Grammar(base)
val page = grammar.codePage
val info = page.info
buildStringUtils(info)
runtimeCodePage = page
return page
}
private fun buildStringUtils(info: IRuntimeDebugInfo) {
info.addExternalFunc("g_string_replace",
RuntimeDebugExec("字符串替换", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kString, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val pat = args[1].string
val sub = args[2].string
RuntimeObject(str.replace(pat.toRegex(), sub))
}
})
info.addExternalFunc("g_string_split",
RuntimeDebugExec("字符串分割", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val split = args[1].string
RuntimeObject(RuntimeArray(str.split(split.toRegex(), Integer.MAX_VALUE).toTypedArray().map { RuntimeObject(it) }))
}
})
info.addExternalFunc("g_string_splitn",
RuntimeDebugExec("字符串分割", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kString, RuntimeObjectType.kInt))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val split = args[1].string
val n = args[1].long.toInt()
RuntimeObject(RuntimeArray(str.split(split.toRegex(), n.coerceAtLeast(0)).toTypedArray().map { RuntimeObject(it) }))
}
})
info.addExternalFunc("g_string_trim",
RuntimeDebugExec("字符串去除头尾空白", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
RuntimeObject(str.trim { it <= ' ' })
}
})
info.addExternalFunc("g_string_length",
RuntimeDebugExec("字符串长度", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
RuntimeObject(str.length.toLong())
}
})
info.addExternalFunc("g_string_empty",
RuntimeDebugExec("字符串是否为空", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus -> RuntimeObject(args[0].string.isEmpty()) })
info.addExternalFunc("g_string_get",
RuntimeDebugExec("字符串查询", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kInt))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val index = args[1].long
RuntimeObject(str[index.toInt()])
}
})
info.addExternalFunc("g_string_regex",
RuntimeDebugExec("字符串正则匹配", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val regex = args[1].string
val m = Pattern.compile(regex).matcher(str)
val arr = RuntimeArray()
if (m.find()) {
for (i in 0..m.groupCount()) {
arr.add(RuntimeObject(m.group(i)))
}
}
RuntimeObject(arr)
}
})
info.addExternalFunc("g_string_build",
RuntimeDebugExec("从字节数组构造字符串", arrayOf(RuntimeObjectType.kArray))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val array = args[0].array
val sb = StringBuilder()
for (obj in array.toList()) {
sb.append(obj)
}
RuntimeObject(sb.toString())
}
})
info.addExternalFunc("g_string_atoi",
RuntimeDebugExec("字符串转换成数字", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
try {
RuntimeObject(java.lang.Long.parseLong(str))
} catch (e: NumberFormatException) {
RuntimeObject(-1L)
}
}
})
info.addExternalFunc("g_string_atoi_s",
RuntimeDebugExec("字符串转换成数字(安全版本)", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
try {
RuntimeObject(java.lang.Long.parseLong(str))
} catch (e: NumberFormatException) {
null
}
}
})
info.addExternalFunc("g_string_join_array",
RuntimeDebugExec("字符串数组连接", arrayOf(RuntimeObjectType.kArray, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val arr = args[0].array
val delim = args[1].string
RuntimeObject(arr.toStringList().joinToString(delim))
}
})
info.addExternalFunc("g_string_toupper",
RuntimeDebugExec("字符串大写", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val delim = args[0].string
RuntimeObject(delim.toUpperCase())
}
})
info.addExternalFunc("g_string_tolower",
RuntimeDebugExec("字符串小写", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val delim = args[0].string
RuntimeObject(delim.toLowerCase())
}
})
info.addExternalFunc("g_string_rep",
RuntimeDebugExec("字符串重复构造", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kInt))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val dup = args[1].long
val n = dup.toInt()
val sb = StringBuilder()
for (i in 0 until n) {
sb.append(str)
}
RuntimeObject(sb.toString())
}
})
info.addExternalFunc("g_string_to_number",
RuntimeDebugExec("字符串转换数字", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
try {
RuntimeObject(java.lang.Long.parseLong(str))
} catch (e1: Exception) {
try {
RuntimeObject(java.lang.Double.parseDouble(str))
} catch (e2: Exception) {
null
}
}
}
})
info.addExternalFunc("g_string_equal",
RuntimeDebugExec("字符串相等比较", arrayOf(RuntimeObjectType.kObject, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
if (args[0].type === RuntimeObjectType.kString) {
val str = args[0].string
val cmp = args[1].string
RuntimeObject(str.compareTo(cmp) == 0)
} else RuntimeObject(false)
}
})
info.addExternalFunc("g_string_not_equal",
RuntimeDebugExec("字符串不等比较", arrayOf(RuntimeObjectType.kObject, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
if (args[0].type === RuntimeObjectType.kString) {
val str = args[0].string
val cmp = args[1].string
RuntimeObject(str.compareTo(cmp) != 0)
} else RuntimeObject(true)
}
})
info.addExternalFunc("g_string_start_with",
RuntimeDebugExec("字符串开头比较", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val cmp = args[1].string
RuntimeObject(str.startsWith(cmp))
}
})
info.addExternalFunc("g_string_end_with",
RuntimeDebugExec("字符串结尾比较", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val cmp = args[1].string
RuntimeObject(str.endsWith(cmp))
}
})
info.addExternalFunc("g_string_substr",
RuntimeDebugExec("字符串子串", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kInt, RuntimeObjectType.kInt))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val a = args[1].long
val b = args[2].long
RuntimeObject(str.substring(a.toInt(), b.toInt()))
}
})
info.addExternalFunc("g_string_left",
RuntimeDebugExec("字符串左子串", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kInt))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val a = args[1].long
RuntimeObject(str.substring(0, a.toInt()))
}
})
info.addExternalFunc("g_string_right",
RuntimeDebugExec("字符串右子串", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kInt))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val str = args[0].string
val a = args[1].long
RuntimeObject(str.substring(a.toInt()))
}
})
}
companion object {
val instance = ModuleString()
}
}
| mit | 9b483e4243fa751ce1edb14a7aa34a2e | 44.717857 | 140 | 0.474494 | 5.696929 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day04.kt | 1 | 1094 | package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.head
import nl.jstege.adventofcode.aoccommon.utils.extensions.isPrefixedWithZeroes
import java.security.MessageDigest
/**
*
* @author Jelle Stege
*/
class Day04 : Day(title = "The Ideal Stucking Stuffer") {
private companion object Configuration {
private const val STARTING_ZEROES_FIRST = 5
private const val STARTING_ZEROES_SECOND = 6
}
override fun first(input: Sequence<String>): Any = input.head
.bruteforce(STARTING_ZEROES_FIRST)
override fun second(input: Sequence<String>): Any = input.head
.bruteforce(STARTING_ZEROES_SECOND)
private fun String.bruteforce(zeroes: Int): Int = MessageDigest.getInstance("MD5")
.let { md5 ->
(0 until Int.MAX_VALUE)
.asSequence()
.map { md5.digest("$this$it".toByteArray()) }
.withIndex()
.first { (_, d) -> d.isPrefixedWithZeroes(zeroes) }.index
}
}
| mit | 8b2b634c3c5d20a68c2759206c94d61b | 32.151515 | 86 | 0.66362 | 4.051852 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/autoassociative/NewRecirculationLayer.kt | 1 | 3049 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.autoassociative
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.activations.Sigmoid
import com.kotlinnlp.simplednn.core.layers.Layer
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceHelper
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
* The Feedforward Layer Structure.
*
* @property inputArray the input array of the layer
* @property outputArray the output array of the layer
* @property params the parameters which connect the input to the output
* @property activationFunction the activation function of the output (can be null, default: Sigmoid)
* @property lambda the partition factor for the reconstruction (default = 0.75)
* @property dropout the probability of dropout
*/
internal class NewRecirculationLayer(
inputArray: AugmentedArray<DenseNDArray>,
outputArray: AugmentedArray<DenseNDArray>,
override val params: NewRecirculationLayerParameters,
activationFunction: ActivationFunction? = Sigmoid,
val lambda: Double = 0.75,
dropout: Double
) : Layer<DenseNDArray>(
inputArray = inputArray,
inputType = LayerType.Input.Dense,
outputArray = outputArray,
params = params,
activationFunction = activationFunction,
dropout = dropout
) {
/**
*
*/
val realInput = inputArray
/**
*
*/
val imaginaryInput = outputArray
/**
*
*/
val realOutput = AugmentedArray(values = DenseNDArrayFactory.zeros(Shape(this.params.hiddenSize)))
/**
*
*/
val imaginaryOutput = AugmentedArray(values = DenseNDArrayFactory.zeros(Shape(this.params.hiddenSize)))
/**
* The helper which executes the forward
*/
override val forwardHelper = NewRecirculationForwardHelper(this)
/**
* The helper which executes the backward
*/
override val backwardHelper = NewRecirculationBackwardHelper(this)
/**
* The helper which calculates the relevance
*/
override val relevanceHelper: RelevanceHelper? = null
/**
* Initialization: set the activation function of the outputArray
*/
init {
require(this.inputArray.size == this.outputArray.size) {
"The inputArray and the outputArray must have the same size."
}
if (activationFunction != null) {
this.realOutput.setActivation(activationFunction)
this.imaginaryOutput.setActivation(activationFunction)
}
}
}
| mpl-2.0 | ba649e6b3342b0053ca70c58860cef1d | 30.760417 | 105 | 0.739587 | 4.537202 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/events/ui/NotifyUser.kt | 1 | 375 | package com.kelsos.mbrc.events.ui
class NotifyUser {
val message: String
val resId: Int
var isFromResource: Boolean = false
private set
constructor(message: String) {
this.message = message
this.isFromResource = false
this.resId = -1
}
constructor(resId: Int) {
this.resId = resId
this.isFromResource = true
this.message = ""
}
}
| gpl-3.0 | 5c2f4e26c4325c1debea847c11153654 | 17.75 | 37 | 0.666667 | 3.787879 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/memberInfoUtils.kt | 1 | 3272 | // 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 org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiNamedElement
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.javaResolutionFacade
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
fun PsiNamedElement.getClassDescriptorIfAny(resolutionFacade: ResolutionFacade? = null): ClassDescriptor? {
return when (this) {
is KtClassOrObject -> resolutionFacade?.resolveToDescriptor(this) ?: resolveToDescriptorIfAny(BodyResolveMode.FULL)
is PsiClass -> getJavaClassDescriptor()
else -> null
} as? ClassDescriptor
}
// Applies to JetClassOrObject and PsiClass
@NlsSafe
fun PsiNamedElement.qualifiedClassNameForRendering(): String {
val fqName = when (this) {
is KtClassOrObject -> fqName?.asString()
is PsiClass -> qualifiedName
else -> throw AssertionError("Not a class: ${getElementTextWithContext()}")
}
return fqName ?: name ?: KotlinBundle.message("text.anonymous")
}
fun KotlinMemberInfo.getChildrenToAnalyze(): List<PsiElement> {
val member = member
val childrenToCheck = member.allChildren.toMutableList()
if (isToAbstract && member is KtCallableDeclaration) {
when (member) {
is KtNamedFunction -> childrenToCheck.remove(member.bodyExpression as PsiElement?)
is KtProperty -> {
childrenToCheck.remove(member.initializer as PsiElement?)
childrenToCheck.remove(member.delegateExpression as PsiElement?)
childrenToCheck.removeAll(member.accessors)
}
}
}
return childrenToCheck
}
internal fun KtNamedDeclaration.resolveToDescriptorWrapperAware(resolutionFacade: ResolutionFacade? = null): DeclarationDescriptor {
if (this is KtPsiClassWrapper) {
(resolutionFacade ?: psiClass.javaResolutionFacade())
?.let { psiClass.getJavaClassDescriptor(it) }
?.let { return it }
}
return resolutionFacade?.resolveToDescriptor(this) ?: unsafeResolveToDescriptor()
}
internal fun PsiMember.toKtDeclarationWrapperAware(): KtNamedDeclaration? {
if (this is PsiClass && this !is KtLightClass) return KtPsiClassWrapper(this)
return namedUnwrappedElement as? KtNamedDeclaration
} | apache-2.0 | e61ff702bffaec5083be005826843f3f | 44.458333 | 158 | 0.767726 | 5.1125 | false | false | false | false |
DanielGrech/anko | dsl/testData/functional/21s/SimpleListenerTest.kt | 3 | 8571 | public fun android.gesture.GestureOverlayView.onGesturePerformed(l: (overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit): Unit = addOnGesturePerformedListener(l)
public fun android.media.tv.TvView.onUnhandledInputEvent(l: (event: android.view.InputEvent?) -> Boolean): Unit = setOnUnhandledInputEventListener(l)
public fun android.support.v4.app.FragmentTabHost.onTabChanged(l: (tabId: String?) -> Unit): Unit = setOnTabChangedListener(l)
public fun android.support.v4.widget.SwipeRefreshLayout.onRefresh(l: () -> Unit): Unit = setOnRefreshListener(l)
public fun android.support.v7.widget.ActionMenuView.onMenuItemClick(l: (item: android.view.MenuItem?) -> Boolean): Unit = setOnMenuItemClickListener(l)
public fun android.support.v7.widget.SearchView.onClose(l: () -> Boolean): Unit = setOnCloseListener(l)
public fun android.support.v7.widget.SearchView.onQueryTextFocusChange(l: (v: android.view.View, hasFocus: Boolean) -> Unit): Unit = setOnQueryTextFocusChangeListener(l)
public fun android.support.v7.widget.SearchView.onSearchClick(l: (v: android.view.View) -> Unit): Unit = setOnSearchClickListener(l)
public fun android.support.v7.widget.Toolbar.onMenuItemClick(l: (item: android.view.MenuItem?) -> Boolean): Unit = setOnMenuItemClickListener(l)
public fun android.view.View.onLayoutChange(l: (v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit): Unit = addOnLayoutChangeListener(l)
public fun android.view.View.onApplyWindowInsets(l: (v: android.view.View?, insets: android.view.WindowInsets?) -> android.view.WindowInsets?): Unit = setOnApplyWindowInsetsListener(l)
public fun android.view.View.onClick(l: (v: android.view.View) -> Unit): Unit = setOnClickListener(l)
public fun android.view.View.onCreateContextMenu(l: (menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit): Unit = setOnCreateContextMenuListener(l)
public fun android.view.View.onDrag(l: (v: android.view.View, event: android.view.DragEvent) -> Boolean): Unit = setOnDragListener(l)
public fun android.view.View.onFocusChange(l: (v: android.view.View, hasFocus: Boolean) -> Unit): Unit = setOnFocusChangeListener(l)
public fun android.view.View.onGenericMotion(l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean): Unit = setOnGenericMotionListener(l)
public fun android.view.View.onHover(l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean): Unit = setOnHoverListener(l)
public fun android.view.View.onKey(l: (v: android.view.View, keyCode: Int, event: android.view.KeyEvent) -> Boolean): Unit = setOnKeyListener(l)
public fun android.view.View.onLongClick(l: (v: android.view.View) -> Boolean): Unit = setOnLongClickListener(l)
public fun android.view.View.onSystemUiVisibilityChange(l: (visibility: Int) -> Unit): Unit = setOnSystemUiVisibilityChangeListener(l)
public fun android.view.View.onTouch(l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean): Unit = setOnTouchListener(l)
public fun android.view.ViewStub.onInflate(l: (stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit): Unit = setOnInflateListener(l)
public fun android.widget.ActionMenuView.onMenuItemClick(l: (item: android.view.MenuItem?) -> Boolean): Unit = setOnMenuItemClickListener(l)
public fun android.widget.AdapterView<out android.widget.Adapter?>.onClick(l: (v: android.view.View) -> Unit): Unit = setOnClickListener(l)
public fun android.widget.AdapterView<out android.widget.Adapter?>.onItemClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit): Unit = setOnItemClickListener(l)
public fun android.widget.AdapterView<out android.widget.Adapter?>.onItemLongClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Boolean): Unit = setOnItemLongClickListener(l)
public fun android.widget.AutoCompleteTextView.onClick(l: (v: android.view.View) -> Unit): Unit = setOnClickListener(l)
public fun android.widget.AutoCompleteTextView.onDismiss(l: () -> Unit): Unit = setOnDismissListener(l)
public fun android.widget.AutoCompleteTextView.onItemClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit): Unit = setOnItemClickListener(l)
public fun android.widget.CalendarView.onDateChange(l: (view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit): Unit = setOnDateChangeListener(l)
public fun android.widget.Chronometer.onChronometerTick(l: (chronometer: android.widget.Chronometer?) -> Unit): Unit = setOnChronometerTickListener(l)
public fun android.widget.CompoundButton.onCheckedChange(l: (buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit): Unit = setOnCheckedChangeListener(l)
public fun android.widget.ExpandableListView.onChildClick(l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Boolean): Unit = setOnChildClickListener(l)
public fun android.widget.ExpandableListView.onGroupClick(l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Boolean): Unit = setOnGroupClickListener(l)
public fun android.widget.ExpandableListView.onGroupCollapse(l: (groupPosition: Int) -> Unit): Unit = setOnGroupCollapseListener(l)
public fun android.widget.ExpandableListView.onGroupExpand(l: (groupPosition: Int) -> Unit): Unit = setOnGroupExpandListener(l)
public fun android.widget.ExpandableListView.onItemClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit): Unit = setOnItemClickListener(l)
public fun android.widget.NumberPicker.onScroll(l: (view: android.widget.NumberPicker?, scrollState: Int) -> Unit): Unit = setOnScrollListener(l)
public fun android.widget.NumberPicker.onValueChanged(l: (picker: android.widget.NumberPicker, oldVal: Int, newVal: Int) -> Unit): Unit = setOnValueChangedListener(l)
public fun android.widget.RadioGroup.onCheckedChange(l: (group: android.widget.RadioGroup?, checkedId: Int) -> Unit): Unit = setOnCheckedChangeListener(l)
public fun android.widget.RatingBar.onRatingBarChange(l: (ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit): Unit = setOnRatingBarChangeListener(l)
public fun android.widget.SearchView.onClose(l: () -> Boolean): Unit = setOnCloseListener(l)
public fun android.widget.SearchView.onQueryTextFocusChange(l: (v: android.view.View, hasFocus: Boolean) -> Unit): Unit = setOnQueryTextFocusChangeListener(l)
public fun android.widget.SearchView.onSearchClick(l: (v: android.view.View) -> Unit): Unit = setOnSearchClickListener(l)
public fun android.widget.SlidingDrawer.onDrawerClose(l: () -> Unit): Unit = setOnDrawerCloseListener(l)
public fun android.widget.SlidingDrawer.onDrawerOpen(l: () -> Unit): Unit = setOnDrawerOpenListener(l)
public fun android.widget.Spinner.onItemClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit): Unit = setOnItemClickListener(l)
public fun android.widget.TabHost.onTabChanged(l: (tabId: String?) -> Unit): Unit = setOnTabChangedListener(l)
public fun android.widget.TextView.onEditorAction(l: (v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Boolean): Unit = setOnEditorActionListener(l)
public fun android.widget.TimePicker.onTimeChanged(l: (view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit): Unit = setOnTimeChangedListener(l)
public fun android.widget.Toolbar.onMenuItemClick(l: (item: android.view.MenuItem?) -> Boolean): Unit = setOnMenuItemClickListener(l)
public fun android.widget.VideoView.onCompletion(l: (mp: android.media.MediaPlayer?) -> Unit): Unit = setOnCompletionListener(l)
public fun android.widget.VideoView.onError(l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean): Unit = setOnErrorListener(l)
public fun android.widget.VideoView.onInfo(l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean): Unit = setOnInfoListener(l)
public fun android.widget.VideoView.onPrepared(l: (mp: android.media.MediaPlayer) -> Unit): Unit = setOnPreparedListener(l)
public fun android.widget.ZoomControls.onZoomInClick(l: (v: android.view.View) -> Unit): Unit = setOnZoomInClickListener(l)
public fun android.widget.ZoomControls.onZoomOutClick(l: (v: android.view.View) -> Unit): Unit = setOnZoomOutClickListener(l) | apache-2.0 | 577fbe8a70385b033291724878637941 | 74.858407 | 225 | 0.773772 | 3.804261 | false | false | false | false |
android/play-billing-samples | ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/network/firebase/SubscriptionMessageService.kt | 1 | 2677 | /*
* Copyright 2018 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.subscriptions.data.network.firebase
import android.util.Log
import com.example.subscriptions.SubApp
import com.example.subscriptions.data.SubscriptionStatusList
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
class SubscriptionMessageService : FirebaseMessagingService() {
private val gson: Gson = GsonBuilder().create()
private val externalScope: CoroutineScope =
CoroutineScope(SupervisorJob() + Dispatchers.Default)
override fun onMessageReceived(remoteMessage: RemoteMessage) {
remoteMessage.data.let { data ->
if (data.isNotEmpty()) {
var result: SubscriptionStatusList? = null
if (REMOTE_MESSAGE_SUBSCRIPTIONS_KEY in data) {
result = gson.fromJson(
data[REMOTE_MESSAGE_SUBSCRIPTIONS_KEY],
SubscriptionStatusList::class.java
)
}
if (result == null) {
Log.e(TAG, "Invalid subscription data")
} else {
Log.i(TAG, "onMessageReceived - ${result.subscriptions} ")
val app = application as SubApp
externalScope.launch {
try {
app.repository.updateSubscriptionsFromNetwork(result.subscriptions)
} catch (e: Exception) {
Log.e(TAG, e.localizedMessage ?: "Failed to update subscription!")
}
}
}
}
}
}
companion object {
private val TAG = SubscriptionMessageService::class.java.simpleName
private const val REMOTE_MESSAGE_SUBSCRIPTIONS_KEY = "currentStatus"
}
} | apache-2.0 | 18e3f7a89cd239b42af9c14445195d3c | 38.970149 | 95 | 0.64139 | 5.138196 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/card/desfire/DesfireApplication.kt | 1 | 2557 | /*
* DesfireApplication.kt
*
* Copyright (C) 2011 Eric Butler
*
* Authors:
* Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.card.desfire
import au.id.micolous.metrodroid.card.desfire.files.DesfireFile
import au.id.micolous.metrodroid.card.desfire.files.RawDesfireFile
import au.id.micolous.metrodroid.serializers.XMLId
import au.id.micolous.metrodroid.serializers.XMLListIdx
import au.id.micolous.metrodroid.ui.ListItem
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
@Serializable
data class DesfireApplication(
@XMLListIdx("id")
private val files: Map<Int, RawDesfireFile>,
@XMLId("auth-log")
private val authLog: List<DesfireAuthLog> = emptyList(),
private val dirListLocked: Boolean = false) {
@Transient
val interpretedFiles: Map<Int, DesfireFile> = files.mapValues { (_, v) -> DesfireFile.create(v) }
@Transient
val rawData: List<ListItem>
get() = interpretedFiles.map { (k, v) -> v.getRawData(k) } + authLog.map { it.rawData }
fun getFile(fileId: Int) = interpretedFiles[fileId]
companion object {
/**
* Converts the MIFARE DESFire application into a MIFARE Classic Application Directory AID,
* according to the process described in NXP AN10787.
* @return A Pair of (aid, sequence) if the App ID is encoded per AN10787, or null otherwise.
*/
fun getMifareAID(appid: Int): Pair<Int, Int>? {
if ((appid and 0xf0) != 0xf0) {
// Not a MIFARE AID
return null
}
// 0x1234f6 == 0x6341 seq 0x2
val aid = ((appid and 0xf00000) shr 20) or
((appid and 0xff00) shr 4) or
((appid and 0xf) shl 12)
val seq = (appid and 0x0f0000) shr 16
return Pair(aid, seq)
}
}
}
| gpl-3.0 | f2972bbc7bf479ffd78756d43e236ba1 | 36.057971 | 101 | 0.667188 | 3.909786 | false | false | false | false |
darkoverlordofdata/entitas-kotlin | entitas/src/main/java/com/darkoverlordofdata/entitas/Entity.kt | 1 | 8034 | package com.darkoverlordofdata.entitas
import java.util.*
/**
*
* Use pool.CreateEntity() to create a new entity and pool.DestroyEntity() to destroy it.
*/
class Entity(totalComponents:Int) {
val totalComponents = totalComponents
val creationIndex:Int get() = _creationIndex
val refCount:Int get() = _refCount
val name:String get() = _name
val isEnabled:Boolean get() = _isEnabled
val onEntityReleased = Event<EntityReleasedArgs>()
val onComponentAdded = Event<EntityChangedArgs>()
val onComponentRemoved = Event<EntityChangedArgs>()
val onComponentReplaced = Event<ComponentReplacedArgs>()
private var _name = ""
private var _refCount = 0
private var _isEnabled = false
private var _creationIndex = 0
private var toStringCache = ""
private val components: Array<IComponent?> = Array(totalComponents, { i-> null })
private val componentsCache: MutableList<IComponent> = ArrayList(listOf())
fun initialize(name:String, creationIndex:Int) {
_name = name
_creationIndex = creationIndex
_isEnabled = true
}
/**
* Adds a component at a certain index. You can only have one component at an index.
* Each component type must have its own constant index.
* The preferred way is to use the generated methods from the code generator.
*
* @param[index] the components ordinal index
* @param[component] the component object to add
* @return this entity
*/
fun addComponent(index:Int, component: IComponent): Entity {
if (!isEnabled)
throw EntityIsNotEnabledException("Cannot add component!")
if (hasComponent(index)) {
val errorMsg = "Cannot add component at index $index to ${toString()}"
throw EntityAlreadyHasComponentException(errorMsg, index)
}
components[index] = component
componentsCache.clear()
toStringCache = ""
onComponentAdded(EntityChangedArgs(this, index, component))
return this
}
/**
* Removes a component at a certain index. You can only remove a component at an index if it exists.
* The preferred way is to use the generated methods from the code generator.
*
* @param[index] the components ordinal index
* @return this entity
*/
fun removeComponent(index:Int): Entity {
if (!isEnabled)
throw EntityIsNotEnabledException("Entity is disabled, cannot remove component")
if (!hasComponent(index)) {
val errorMsg = "Cannot remove component at index $index from ${toString()}"
throw EntityDoesNotHaveComponentException(errorMsg, index)
}
_replaceComponent(index, null)
return this
}
/**
* Replaces an existing component at a certain index or adds it if it doesn't exist yet.
* The preferred way is to use the generated methods from the code generator.
*
* @param[index] the components ordinal index
* @param[component] the replacement component object
* @return this entity
*/
fun replaceComponent(index:Int, component: IComponent?): Entity {
if (!isEnabled)
throw EntityIsNotEnabledException("Entity is disabled, cannot replace at index $index, ${toString()}")
if (hasComponent(index)) {
_replaceComponent(index, component)
} else if (component != null) {
addComponent(index, component)
}
return this
}
/**
* Returns a component at a certain index. You can only get a component at an index if it exists.
* The preferred way is to use the generated methods from the code generator.
*
* @param[index] the components ordinal index
* @return the compoment
*/
fun getComponent(index:Int): IComponent? {
if (!hasComponent(index)) {
val errorMsg = "Cannot get component at index $index from ${toString()}"
throw EntityDoesNotHaveComponentException(errorMsg, index)
}
return components[index]
}
/**
* Returns all added components.
*
* @return an array of components
*/
fun getComponents():MutableList<IComponent> {
if (componentsCache.size == 0) {
componentsCache.addAll(components.filterNotNull().toMutableList())
}
return componentsCache//.toTypedArray()
}
/**
* Determines whether this entity has a component at the specified index.
*
* @param[index] the components ordinal index
* @return true if the component is available
*/
fun hasComponent(index:Int):Boolean {
return components[index] != null
}
/**
* Determines whether this entity has components at all the specified indices.
*
* @param[indices] an arry of components ordinal index's
* @return true if all components in indices are available
*/
fun hasComponents(indices:IntArray):Boolean {
for (index in indices)
if (components[index] == null) return false
return true
}
/**
* Determines whether this entity has a component at any of the specified indices.
*
* @param[indices] an arry of components ordinal index's
* @return true if any components in indices are available
*/
fun hasAnyComponent(indices:IntArray):Boolean {
for (index in indices)
if (components[index] != null) return true
return false
}
/**
*
* Removes all components.
*/
fun removeAllComponents() {
for (index in 0..totalComponents-1)
if (components[index] != null)
_replaceComponent(index, null)
}
fun retain(): Entity {
_refCount += 1
return this
}
fun release() {
_refCount -= 1
if (_refCount == 0) {
onEntityReleased(EntityReleasedArgs(this))
} else if (_refCount < 0)
throw Exception("Entity is already released ${toString()}")
}
/**
* Returns a cached string to describe the entity with the following format:
* Entity_{name|creationIndex}(*{retainCount})({list of components})
*/
override fun toString():String {
if (toStringCache == "") {
val sb = StringBuilder()
sb.append("Entity_")
sb.append(if (name != "") name else creationIndex.toString())
sb.append("($_creationIndex)(")
for (i in 0..components.size-1) {
//val name = Pool.instance!!.componentName(i)
if (components[i] != null) {
//sb.append(Pool.instance!!.componentName(i))
sb.append(components[i].toString())
sb.append(",")
}
}
sb.append(")")
toStringCache = sb.toString().replace(",)", ")")
}
return toStringCache
}
fun destroy() {
removeAllComponents()
onComponentAdded.clear()
onComponentRemoved.clear()
onComponentReplaced.clear()
componentsCache.clear()
_name = ""
_isEnabled = false
}
private fun _replaceComponent(index:Int, replacement: IComponent?): Entity {
val previousComponent = components[index]
if (previousComponent != null) {
if (previousComponent.equals(replacement)) {
onComponentReplaced(ComponentReplacedArgs(this, index, previousComponent, replacement))
} else {
components[index] = replacement
componentsCache.clear()
toStringCache = ""
if (replacement == null)
onComponentRemoved(EntityChangedArgs(this, index, previousComponent))
else
onComponentReplaced(ComponentReplacedArgs(this, index, previousComponent, replacement))
}
}
return this
}
} | mit | 63ddc92fe796fc2a14e9399ff7682453 | 33.484979 | 114 | 0.608788 | 4.759479 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/notification/impl/RemindLaterManager.kt | 5 | 6980 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.notification.impl
import com.intellij.ide.DataManager
import com.intellij.notification.Notification
import com.intellij.notification.NotificationRemindLaterHandler
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectPostStartupActivity
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.wm.WindowManager
import com.intellij.util.concurrency.AppExecutorUtil
import org.jdom.Element
import java.util.concurrent.TimeUnit
/**
* @author Alexander Lobas
*/
@State(name = "NotificationRemindLaterService",
storages = [Storage(value = "notification.remind.later.xml", roamingType = RoamingType.DISABLED)])
@Service(Service.Level.APP)
internal class RemindLaterManager : SimpleModificationTracker(), PersistentStateComponent<Element> {
companion object {
@JvmStatic
fun createAction(notification: Notification, delay: Long): Runnable? {
val handlerId = notification.remindLaterHandlerId
if (handlerId == null) {
if (notification.listener != null || notification.actions.isNotEmpty() || notification.contextHelpAction != null) {
return null
}
return Runnable {
instance().addSimpleNotification(notification, delay)
}
}
val handler = NotificationRemindLaterHandler.findHandler(handlerId) ?: return null
return Runnable {
instance().addNotificationWithActions(handler, notification, delay)
}
}
@JvmStatic
fun instance(): RemindLaterManager = service()
}
private val rootElement = Element("state")
private fun addSimpleNotification(notification: Notification, delay: Long, action: ((Element) -> Unit)? = null) {
val element = createElement(notification, System.currentTimeMillis() + delay)
action?.invoke(element)
rootElement.addContent(element)
incModificationCount()
schedule(element, delay)
}
private fun addNotificationWithActions(handler: NotificationRemindLaterHandler, notification: Notification, delay: Long) {
addSimpleNotification(notification, delay) {
val element = Element("Actions")
element.setAttribute("id", handler.getID())
element.addContent(handler.getActionsState(notification))
it.addContent(element)
}
}
private fun createElement(notification: Notification, time: Long): Element {
val element = Element("Notification")
element.setAttribute("time", time.toString())
element.setAttribute("type", notification.type.name)
element.setAttribute("groupId", notification.groupId)
element.setAttribute("suggestion", notification.isSuggestionType.toString())
element.setAttribute("importantSuggestion", notification.isImportantSuggestion.toString())
val displayId = notification.displayId
if (displayId != null) {
element.setAttribute("displayId", displayId)
}
if (notification.hasTitle()) {
val title = Element("Title")
title.text = notification.title
element.addContent(title)
val subtitle = notification.subtitle
if (subtitle != null) {
val subtitleElement = Element("SubTitle")
subtitleElement.text = subtitle
element.addContent(subtitleElement)
}
}
if (notification.hasContent()) {
val content = Element("Content")
content.text = notification.content
element.addContent(content)
}
return element
}
private fun schedule(element: Element, delay: Long) {
AppExecutorUtil.getAppScheduledExecutorService().schedule({ execute(element) }, delay, TimeUnit.MILLISECONDS)
}
private fun execute(element: Element) {
rootElement.removeContent(element)
incModificationCount()
val groupId = element.getAttributeValue("groupId") ?: return
val type = NotificationType.valueOf(element.getAttributeValue("type") ?: "INFORMATION")
@NlsSafe val title = element.getChildText("Title") ?: ""
@NlsSafe val content = element.getChildText("Content") ?: ""
@NlsSafe val subtitle = element.getChildText("SubTitle")
val notification = Notification(groupId, title, content, type)
notification.subtitle = subtitle
val displayId = element.getAttributeValue("displayId")
if (displayId != null) {
notification.setDisplayId(displayId)
}
val suggestion = element.getAttributeValue("suggestion")
if (suggestion != null) {
notification.isSuggestionType = suggestion.toBoolean()
}
val importantSuggestion = element.getAttributeValue("importantSuggestion")
if (importantSuggestion != null) {
notification.isImportantSuggestion = importantSuggestion.toBoolean()
}
val actionsChild = element.getChild("Actions")
if (actionsChild != null) {
val handlerId = actionsChild.getAttributeValue("id") ?: return
val handler = NotificationRemindLaterHandler.findHandler(handlerId) ?: return
val children = actionsChild.children
if (children.size != 1) {
return
}
notification.setRemindLaterHandlerId(handlerId)
if (!handler.setActions(notification, children[0])) {
return
}
}
ApplicationManager.getApplication().invokeLater {
notification.notify(
CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(WindowManager.getInstance().mostRecentFocusedWindow)))
}
}
override fun getState(): Element {
return rootElement
}
override fun initializeComponent() {
val time = System.currentTimeMillis()
val removeList = ArrayList<Element>()
for (element in rootElement.getChildren("Notification")) {
val timeValue = element.getAttributeValue("time")
if (timeValue == null) {
removeList.add(element)
continue
}
val nextTime: Long
try {
nextTime = timeValue.toLong()
}
catch (_: Exception) {
removeList.add(element)
continue
}
val delay = nextTime - time
if (delay > 0) {
schedule(element, delay)
}
else {
execute(element)
}
}
for (element in removeList) {
rootElement.removeContent(element)
}
if (removeList.isNotEmpty()) {
incModificationCount()
}
}
override fun loadState(state: Element) {
rootElement.removeContent()
for (element in state.getChildren("Notification")) {
rootElement.addContent(element.clone())
}
}
}
internal class RemindLaterActivity : ProjectPostStartupActivity {
override suspend fun execute(project: Project) {
RemindLaterManager.instance()
}
} | apache-2.0 | 42b9f9fc5660ea4a7835fc67053dd6d9 | 30.588235 | 134 | 0.708309 | 4.877708 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/PackageVersionRangeInspection.kt | 7 | 3145 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.module.Module
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
abstract class PackageVersionRangeInspection : AbstractPackageUpdateInspectionCheck() {
override fun ProblemsHolder.checkFile(file: PsiFile, fileModule: Module) {
file.project.packageSearchProjectService.dependenciesByModuleStateFlow.value
.entries
.find { it.key.nativeModule == fileModule }
?.value
?.filter { it.dependency.coordinates.version?.let { isIvyRange(it) } ?: false }
?.mapNotNull { coordinates ->
runCatching {
coordinates.declarationIndexes
?.let { selectPsiElementIndex(it) }
?.let { PsiUtil.getElementAtOffset(file, it) }
}.getOrNull()
?.let { coordinates to it }
}
?.forEach { (coordinatesWithResolvedVersion, psiElement) ->
val message = coordinatesWithResolvedVersion.dependency.coordinates.version
?.let { PackageSearchBundle.message("packagesearch.inspection.upgrade.range.withVersion", it) }
?: PackageSearchBundle.message("packagesearch.inspection.upgrade.range")
registerProblem(psiElement, message, ProblemHighlightType.WEAK_WARNING)
}
}
private fun isIvyRange(version: String): Boolean {
// See https://ant.apache.org/ivy/history/2.1.0/ivyfile/dependency.html
val normalizedVersion = version.trimEnd()
if (normalizedVersion.endsWith('+')) return true
if (normalizedVersion.startsWith("latest.")) return true
val startsWithParenthesisOrBrackets = normalizedVersion.startsWith('(') || normalizedVersion.startsWith('[')
val endsWithParenthesisOrBrackets = normalizedVersion.endsWith(')') || normalizedVersion.endsWith(']')
if (startsWithParenthesisOrBrackets && endsWithParenthesisOrBrackets) return true
return false
}
}
| apache-2.0 | 9336362682512bf0276f4b3e7295e63f | 46.651515 | 116 | 0.663593 | 5.348639 | false | false | false | false |
jk1/intellij-community | java/java-indexing-impl/src/com/intellij/psi/impl/JavaSimplePropertyIndex.kt | 3 | 8976 | // Copyright 2000-2018 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.psi.impl
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.LighterASTNode
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiField
import com.intellij.psi.impl.cache.RecordUtil
import com.intellij.psi.impl.java.stubs.JavaStubElementTypes
import com.intellij.psi.impl.source.JavaLightStubBuilder
import com.intellij.psi.impl.source.JavaLightTreeUtil
import com.intellij.psi.impl.source.PsiMethodImpl
import com.intellij.psi.impl.source.tree.ElementType
import com.intellij.psi.impl.source.tree.JavaElementType
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stub.JavaStubImplUtil
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PropertyUtil
import com.intellij.psi.util.PropertyUtilBase
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.indexing.*
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.EnumeratorIntegerDescriptor
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.KeyDescriptor
import java.io.DataInput
import java.io.DataOutput
private val indexId = ID.create<Int, PropertyIndexValue>("java.simple.property")
private val log = Logger.getInstance(JavaSimplePropertyIndex::class.java)
private val allowedExpressions = TokenSet.create(ElementType.REFERENCE_EXPRESSION, ElementType.THIS_EXPRESSION, ElementType.SUPER_EXPRESSION)
fun getFieldOfGetter(method: PsiMethodImpl): PsiField? = resolveFieldFromIndexValue(method, true)
fun getFieldOfSetter(method: PsiMethodImpl): PsiField? = resolveFieldFromIndexValue(method, false)
private fun resolveFieldFromIndexValue(method: PsiMethodImpl, isGetter: Boolean): PsiField? {
val id = JavaStubImplUtil.getMethodStubIndex(method)
if (id != -1) {
val values = FileBasedIndex.getInstance().getValues(indexId, id, GlobalSearchScope.fileScope(method.containingFile))
when (values.size) {
0 -> return null
1 -> {
val indexValue = values[0]
if (isGetter != indexValue.getter) return null
val psiClass = method.containingClass
val project = psiClass!!.project
val expr = JavaPsiFacade.getElementFactory(project).createExpressionFromText(indexValue.propertyRefText, psiClass)
return PropertyUtil.getSimplyReturnedField(expr)
}
else -> {
log.error("multiple index values for method $method")
}
}
}
return null
}
data class PropertyIndexValue(val propertyRefText: String, val getter: Boolean)
class JavaSimplePropertyIndex : FileBasedIndexExtension<Int, PropertyIndexValue>(), PsiDependentIndex {
override fun getIndexer(): DataIndexer<Int, PropertyIndexValue, FileContent> = DataIndexer { inputData ->
val result = ContainerUtil.newHashMap<Int, PropertyIndexValue>()
val tree = (inputData as FileContentImpl).lighterASTForPsiDependentIndex
object : RecursiveLighterASTNodeWalkingVisitor(tree) {
var methodIndex = 0
override fun visitNode(element: LighterASTNode) {
if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return
if (element.tokenType === JavaElementType.METHOD) {
extractProperty(element)?.let { result.put(methodIndex, it) }
methodIndex++
}
super.visitNode(element)
}
private fun extractProperty(method: LighterASTNode): PropertyIndexValue? {
var isConstructor = true
var isGetter = true
var isBooleanReturnType = false
var isVoidReturnType = false
var setterParameterName: String? = null
var refText: String? = null
for (child in tree.getChildren(method)) {
when (child.tokenType) {
JavaElementType.TYPE -> {
val children = tree.getChildren(child)
if (children.size != 1) return null
val typeElement = children[0]
if (typeElement.tokenType == JavaTokenType.VOID_KEYWORD) isVoidReturnType = true
if (typeElement.tokenType == JavaTokenType.BOOLEAN_KEYWORD) isBooleanReturnType = true
isConstructor = false
}
JavaElementType.PARAMETER_LIST -> {
if (isGetter) {
if (LightTreeUtil.firstChildOfType(tree, child, JavaElementType.PARAMETER) != null) return null
} else {
val parameters = LightTreeUtil.getChildrenOfType(tree, child, JavaElementType.PARAMETER)
if (parameters.size != 1) return null
setterParameterName = JavaLightTreeUtil.getNameIdentifierText(tree, parameters[0])
if (setterParameterName == null) return null
}
}
JavaElementType.CODE_BLOCK -> {
refText = if (isGetter) getGetterPropertyRefText(child) else getSetterPropertyRefText(child, setterParameterName!!)
if (refText == null) return null
}
JavaTokenType.IDENTIFIER -> {
if (isConstructor) return null
val name = RecordUtil.intern(tree.charTable, child)
val flavour = PropertyUtil.getMethodNameGetterFlavour(name)
when (flavour) {
PropertyUtilBase.GetterFlavour.NOT_A_GETTER -> {
if (PropertyUtil.isSetterName(name)) {
isGetter = false
}
else {
return null
}
}
PropertyUtilBase.GetterFlavour.BOOLEAN -> if (!isBooleanReturnType) return null
else -> { }
}
if (isVoidReturnType && isGetter) return null
}
}
}
return refText?.let { PropertyIndexValue(it, isGetter) }
}
private fun getSetterPropertyRefText(codeBlock: LighterASTNode, setterParameterName: String): String? {
val assignment = tree
.getChildren(codeBlock)
.singleOrNull { ElementType.JAVA_STATEMENT_BIT_SET.contains(it.tokenType) }
?.takeIf { it.tokenType == JavaElementType.EXPRESSION_STATEMENT }
?.let { LightTreeUtil.firstChildOfType(tree, it, JavaElementType.ASSIGNMENT_EXPRESSION) }
if (assignment == null || LightTreeUtil.firstChildOfType(tree, assignment, JavaTokenType.EQ) == null) return null
val operands = LightTreeUtil.getChildrenOfType(tree, assignment, ElementType.EXPRESSION_BIT_SET)
if (operands.size != 2 || LightTreeUtil.toFilteredString(tree, operands[1], null) != setterParameterName) return null
val lhsText = LightTreeUtil.toFilteredString(tree, operands[0], null)
if (lhsText == setterParameterName) return null
return lhsText
}
private fun getGetterPropertyRefText(codeBlock: LighterASTNode): String? {
return tree
.getChildren(codeBlock)
.singleOrNull { ElementType.JAVA_STATEMENT_BIT_SET.contains(it.tokenType) }
?.takeIf { it.tokenType == JavaElementType.RETURN_STATEMENT}
?.let { LightTreeUtil.firstChildOfType(tree, it, allowedExpressions) }
?.takeIf(this::checkQulifiers)
?.let { LightTreeUtil.toFilteredString(tree, it, null) }
}
private fun checkQulifiers(expression: LighterASTNode): Boolean {
if (!allowedExpressions.contains(expression.tokenType)) {
return false
}
val qualifier = JavaLightTreeUtil.findExpressionChild(tree, expression)
return qualifier == null || checkQulifiers(qualifier)
}
}.visitNode(tree.root)
result
}
override fun getKeyDescriptor(): KeyDescriptor<Int> = EnumeratorIntegerDescriptor.INSTANCE
override fun getValueExternalizer(): DataExternalizer<PropertyIndexValue> = object: DataExternalizer<PropertyIndexValue> {
override fun save(out: DataOutput, value: PropertyIndexValue?) {
value!!
EnumeratorStringDescriptor.INSTANCE.save(out, value.propertyRefText)
out.writeBoolean(value.getter)
}
override fun read(input: DataInput): PropertyIndexValue = PropertyIndexValue(EnumeratorStringDescriptor.INSTANCE.read(input), input.readBoolean())
}
override fun getName(): ID<Int, PropertyIndexValue> = indexId
override fun getInputFilter(): FileBasedIndex.InputFilter = object : DefaultFileTypeSpecificInputFilter(JavaFileType.INSTANCE) {
override fun acceptInput(file: VirtualFile): Boolean = JavaStubElementTypes.JAVA_FILE.shouldBuildStubFor(file)
}
override fun dependsOnFileContent(): Boolean = true
override fun getVersion(): Int = 1
} | apache-2.0 | c2d52fe135d52c0d6e8c0e9de41be47e | 44.110553 | 150 | 0.702986 | 5.056901 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/widget/CheckableLinearLayout.kt | 1 | 4180 | /*
* Copyright © 2013 dvbviewer-controller Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.dvbviewer.controller.ui.widget
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.CheckBox
import android.widget.Checkable
import android.widget.ImageView
import android.widget.LinearLayout
import org.dvbviewer.controller.R
/**
* The Class CheckableLinearLayout.
*
* @author RayBa
* @date 07.04.2013
*/
class CheckableLinearLayout
/**
* Instantiates a new checkable linear layout.
*
* @param context the context
* @param attrs the attrs
* @author RayBa
* @date 07.04.2013
*/
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs), Checkable {
private var mChecked: Boolean = false
private var touchPadding: Int = 0
private var checkIndicator: CheckBox? = null
private var contextMenuButton: ImageView? = null
/* (non-Javadoc)
* @see android.view.View#onFinishInflate()
*/
override fun onFinishInflate() {
super.onFinishInflate()
touchPadding = (15 * resources.displayMetrics.density).toInt()
checkIndicator = findViewById<CheckBox>(R.id.checkIndicator)
contextMenuButton = findViewById<ImageView>(R.id.contextMenu)
}
/* (non-Javadoc)
* @see android.widget.Checkable#isChecked()
*/
override fun isChecked(): Boolean {
return mChecked
}
/* (non-Javadoc)
* @see android.widget.Checkable#setChecked(boolean)
*/
override fun setChecked(checked: Boolean) {
mChecked = checked
if (checkIndicator != null) {
checkIndicator!!.isChecked = mChecked
}
refreshDrawableState()
}
/* (non-Javadoc)
* @see android.widget.Checkable#toggle()
*/
override fun toggle() {
mChecked = !mChecked
if (checkIndicator != null) {
checkIndicator!!.isChecked = mChecked
}
refreshDrawableState()
}
/* (non-Javadoc)
* @see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
val width = width
val leftBound = width / 7
val rightbound = width / 7 * 6
if (checkIndicator != null && contextMenuButton!!.visibility == View.VISIBLE && event.x < leftBound) {
event.setLocation(1f, 1f)
checkIndicator!!.onTouchEvent(event)
return true
} else if (contextMenuButton != null && contextMenuButton!!.visibility == View.VISIBLE && event.x > rightbound) {
event.setLocation(1f, 1f)
contextMenuButton!!.onTouchEvent(event)
return true
} else {
return super.onTouchEvent(event)
}
}
/* (non-Javadoc)
* @see android.view.ViewGroup#dispatchSetPressed(boolean)
*/
override fun dispatchSetPressed(pressed: Boolean) {
/**
* Empty Override to not select the child views when the whole vie is
* selected
*/
}
/* (non-Javadoc)
* @see android.view.ViewGroup#onCreateDrawableState(int)
*/
override fun onCreateDrawableState(extraSpace: Int): IntArray {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
if (isChecked) {
View.mergeDrawableStates(drawableState, CheckedStateSet)
}
return drawableState
}
companion object {
private val CheckedStateSet = intArrayOf(R.attr.state_checked)
}
}
| apache-2.0 | ef4e790082b854760657931cf314a1eb | 28.85 | 121 | 0.670495 | 4.44102 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/MethodSideOnlyInspection.kt | 1 | 4926 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiMethod
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import org.jetbrains.annotations.Nls
class MethodSideOnlyInspection : BaseInspection() {
@Nls
override fun getDisplayName() = "Invalid usage of @SideOnly in method declaration"
override fun buildErrorString(vararg infos: Any): String {
val error = infos[0] as Error
return error.getErrorString(*SideOnlyUtil.getSubArray(infos))
}
override fun getStaticDescription(): String? {
return "A method in a class annotated for one side cannot be declared as being in the other side. For example, a class which is " +
"annotated as @SideOnly(Side.SERVER) cannot contain a method which is annotated as @SideOnly(Side.CLIENT). Since a class that " +
"is annotated with @SideOnly brings everything with it, @SideOnly annotated methods are usually useless"
}
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
val error = infos[0] as Error
val method = infos[3] as PsiMethod
return if (method.isWritable && error === Error.METHOD_IN_WRONG_CLASS) {
RemoveAnnotationInspectionGadgetsFix(method, "Remove @SideOnly annotation from method")
} else {
null
}
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitMethod(method: PsiMethod) {
val psiClass = method.containingClass ?: return
if (!SideOnlyUtil.beginningCheck(method)) {
return
}
val methodSide = SideOnlyUtil.checkMethod(method)
val returnType = method.returnType as? PsiClassType ?: return
val resolve = returnType.resolve() ?: return
val returnSide = SideOnlyUtil.getSideForClass(resolve)
if (returnSide !== Side.NONE && returnSide !== Side.INVALID && returnSide !== methodSide &&
methodSide !== Side.NONE && methodSide !== Side.INVALID) {
registerMethodError(method, Error.RETURN_TYPE_ON_WRONG_METHOD, methodSide.annotation, returnSide.annotation, method)
}
val classHierarchySides = SideOnlyUtil.checkClassHierarchy(psiClass)
for (classHierarchySide in classHierarchySides) {
if (classHierarchySide.first !== Side.NONE && classHierarchySide.first !== Side.INVALID) {
if (methodSide !== classHierarchySide.first && methodSide !== Side.NONE && methodSide !== Side.INVALID) {
registerMethodError(
method,
Error.METHOD_IN_WRONG_CLASS,
methodSide.annotation,
classHierarchySide.first.annotation,
method
)
}
if (returnSide !== Side.NONE && returnSide !== Side.INVALID) {
if (returnSide !== classHierarchySide.first) {
registerMethodError(
method,
Error.RETURN_TYPE_IN_WRONG_CLASS,
classHierarchySide.first.annotation,
returnSide.annotation,
method
)
}
}
return
}
}
}
}
}
enum class Error {
METHOD_IN_WRONG_CLASS {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot be declared inside a class annotated with " + infos[1] + "."
}
},
RETURN_TYPE_ON_WRONG_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot return a type annotated with " + infos[1] + "."
}
},
RETURN_TYPE_IN_WRONG_CLASS {
override fun getErrorString(vararg infos: Any): String {
return "Method in a class annotated with " + infos[0] +
" cannot return a type annotated with " + infos[1] + "."
}
};
abstract fun getErrorString(vararg infos: Any): String
}
}
| mit | 8c04e9a1c01d3ef2fc98c84cece5b117 | 39.04878 | 141 | 0.549127 | 5.479422 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/volumes/RAIVolume.kt | 1 | 3468 | package graphics.scenery.volumes
import bdv.tools.brightness.ConverterSetup
import graphics.scenery.Hub
import graphics.scenery.OrientedBoundingBox
import graphics.scenery.Origin
import graphics.scenery.utils.extensions.minus
import graphics.scenery.utils.extensions.times
import net.imglib2.type.numeric.integer.UnsignedByteType
import org.joml.Matrix4f
import org.joml.Vector3f
import tpietzsch.example2.VolumeViewerOptions
class RAIVolume(val ds: VolumeDataSource.RAISource<*>, options: VolumeViewerOptions, hub: Hub): Volume(ds, options, hub) {
private constructor() : this(VolumeDataSource.RAISource(UnsignedByteType(), emptyList(), ArrayList<ConverterSetup>(), 0, null), VolumeViewerOptions.options(), Hub()) {
}
init {
name = "Volume (RAI source)"
if(ds.cacheControl != null) {
logger.debug("Adding cache control")
cacheControls.addCacheControl(ds.cacheControl)
}
timepointCount = ds.numTimepoints
boundingBox = generateBoundingBox()
}
override fun generateBoundingBox(): OrientedBoundingBox {
val source = ds.sources.firstOrNull()
val sizes = if(source != null) {
val s = source.spimSource.getSource(0, 0)
val min = Vector3f(s.min(0).toFloat(), s.min(1).toFloat(), s.min(2).toFloat())
val max = Vector3f(s.max(0).toFloat(), s.max(1).toFloat(), s.max(2).toFloat())
max - min
} else {
Vector3f(1.0f, 1.0f, 1.0f)
}
return OrientedBoundingBox(this,
Vector3f(-0.0f, -0.0f, -0.0f),
sizes)
}
override fun localScale(): Vector3f {
var size = Vector3f(1.0f, 1.0f, 1.0f)
val source = ds.sources.firstOrNull()
if(source != null) {
val s = source.spimSource.getSource(0, 0)
val min = Vector3f(s.min(0).toFloat(), s.min(1).toFloat(), s.min(2).toFloat())
val max = Vector3f(s.max(0).toFloat(), s.max(1).toFloat(), s.max(2).toFloat())
size = max - min
}
logger.debug("Sizes are $size")
return Vector3f(
size.x() * pixelToWorldRatio / 10.0f,
-1.0f * size.y() * pixelToWorldRatio / 10.0f,
size.z() * pixelToWorldRatio / 10.0f
)
}
override fun createSpatial(): VolumeSpatial {
return object: VolumeSpatial(this) {
override fun composeModel() {
@Suppress("SENSELESS_COMPARISON")
if (position != null && rotation != null && scale != null) {
val source = ds.sources.firstOrNull()
val shift = if (source != null) {
val s = source.spimSource.getSource(0, 0)
val min = Vector3f(s.min(0).toFloat(), s.min(1).toFloat(), s.min(2).toFloat())
val max = Vector3f(s.max(0).toFloat(), s.max(1).toFloat(), s.max(2).toFloat())
(max - min) * (-0.5f)
} else {
Vector3f(0.0f, 0.0f, 0.0f)
}
model.translation(position)
model.mul(Matrix4f().set(this.rotation))
model.scale(scale)
model.scale(localScale())
if (origin == Origin.Center) {
model.translate(shift)
}
}
}
}
}
}
| lgpl-3.0 | 3ef8c4fe6096f2ee390a4072bbdb6803 | 35.893617 | 171 | 0.553633 | 3.914221 | false | false | false | false |
StPatrck/edac | app/src/main/java/com/phapps/elitedangerous/companion/data/entities/Module.kt | 1 | 687 | package com.phapps.elitedangerous.companion.data.entities
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.support.annotation.NonNull
@Entity(tableName = "modules")
class Module {
@PrimaryKey
var id: Long = 0
var name: String = ""
@NonNull
@ColumnInfo(name = "location_name")
var locationName: String = ""
@NonNull
@ColumnInfo(name = "location_description")
var locationDescription = ""
@NonNull
var value: Int = 0
var free: Boolean = false
var health: Long = 0
var on: Boolean = false
var priority: Int = 0
}
| gpl-3.0 | 9e985298d83519f32569c847a28cb2cc | 19.205882 | 57 | 0.692868 | 4.089286 | false | false | false | false |
RuneSuite/client | client/src/main/java/org/runestar/client/Main.kt | 1 | 1783 | @file:JvmName("Main")
package org.runestar.client
import com.google.common.base.Throwables
import org.kxtra.slf4j.getLogger
import org.runestar.client.api.Application
import org.runestar.client.common.JAV_CONFIG
import org.runestar.client.common.MANIFEST_NAME
import org.runestar.client.common.lookupClassLoader
import java.util.Locale
import java.util.jar.JarInputStream
import java.util.jar.Manifest
import javax.swing.JOptionPane
import javax.swing.JScrollPane
import javax.swing.JTextArea
import javax.swing.SwingUtilities
import kotlin.system.exitProcess
fun main() {
Thread.setDefaultUncaughtExceptionHandler(::handleUncaughtException)
Locale.setDefault(Locale.ENGLISH)
SwingUtilities.invokeLater((StarTheme)::install)
checkUpToDate()
Application.start()
}
private fun handleUncaughtException(t: Thread, e: Throwable) {
getLogger().error("Uncaught exception", e)
showErrorDialog(Throwables.getStackTraceAsString(e))
}
private fun checkUpToDate() {
val serverManifest = JarInputStream(JAV_CONFIG.gamepackUrl.openStream()).use { it.manifest }
val bundledManifest = lookupClassLoader.getResourceAsStream(MANIFEST_NAME).use { Manifest(it) }
if (serverManifest != bundledManifest) {
showErrorDialog("Client is out of date")
exitProcess(1)
}
}
private fun showErrorDialog(s: String) {
val runnable = Runnable {
val component = JScrollPane().apply {
setViewportView(JTextArea(s, 5, 40).apply {
isEditable = false
})
}
JOptionPane.showMessageDialog(null, component, "Error", JOptionPane.ERROR_MESSAGE)
}
if (SwingUtilities.isEventDispatchThread()) {
runnable.run()
} else {
SwingUtilities.invokeAndWait(runnable)
}
} | mit | ccbb3a2fbb737d43172f9c262c929b73 | 29.237288 | 99 | 0.734717 | 4.359413 | false | false | false | false |
google/intellij-community | plugins/gradle/java/src/service/project/wizard/GradleNewProjectWizardStep.kt | 2 | 6107 | // 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 org.jetbrains.plugins.gradle.service.project.wizard
import com.intellij.ide.JavaUiBundle
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logDslChanged
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkChanged
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkFinished
import com.intellij.ide.wizard.NewProjectWizardBaseData
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.service.project.wizard.MavenizedNewProjectWizardStep
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ui.DataView
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.projectRoots.impl.DependentSdkType
import com.intellij.openapi.roots.ui.configuration.sdkComboBox
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.layout.*
import com.intellij.util.lang.JavaVersion
import icons.GradleIcons
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.util.*
import javax.swing.Icon
abstract class GradleNewProjectWizardStep<ParentStep>(parent: ParentStep) :
MavenizedNewProjectWizardStep<ProjectData, ParentStep>(parent), GradleNewProjectWizardData
where ParentStep : NewProjectWizardStep,
ParentStep : NewProjectWizardBaseData {
final override val sdkProperty = propertyGraph.property<Sdk?>(null)
final override val useKotlinDslProperty = propertyGraph.property(false)
final override var sdk by sdkProperty
final override var useKotlinDsl by useKotlinDslProperty
override fun createView(data: ProjectData) = GradleDataView(data)
override fun setupUI(builder: Panel) {
with(builder) {
row(JavaUiBundle.message("label.project.wizard.new.project.jdk")) {
val sdkTypeFilter = { it: SdkTypeId -> it is JavaSdkType && it !is DependentSdkType }
sdkComboBox(context, sdkProperty, StdModuleTypes.JAVA.id, sdkTypeFilter)
.validationOnApply { validateGradleVersion() }
.columns(COLUMNS_MEDIUM)
.whenItemSelectedFromUi { logSdkChanged(sdk) }
}.bottomGap(BottomGap.SMALL)
row(GradleBundle.message("gradle.dsl.new.project.wizard")) {
val renderer: (Boolean) -> String = {
when (it) {
true -> GradleBundle.message("gradle.dsl.new.project.wizard.kotlin")
else -> GradleBundle.message("gradle.dsl.new.project.wizard.groovy")
}
}
segmentedButton(listOf(false, true), renderer)
.bind(useKotlinDslProperty)
.whenItemSelectedFromUi { logDslChanged(it) }
}.bottomGap(BottomGap.SMALL)
}
super.setupUI(builder)
}
override fun setupProject(project: Project) {
logSdkFinished(sdk)
}
override fun findAllParents(): List<ProjectData> {
val project = context.project ?: return emptyList()
return ProjectDataManager.getInstance()
.getExternalProjectsData(project, GradleConstants.SYSTEM_ID)
.mapNotNull { it.externalProjectStructure }
.map { it.data }
}
override fun ValidationInfoBuilder.validateArtifactId(): ValidationInfo? {
if (artifactId != parentStep.name) {
return error(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.and.artifact.id.is.different.error",
if (context.isCreatingNewProject) 1 else 0))
}
return null
}
private fun ValidationInfoBuilder.validateGradleVersion(): ValidationInfo? {
val javaVersion = getJavaVersion() ?: return null
if (getGradleVersion() == null) {
val preferredGradleVersion = getPreferredGradleVersion()
val errorTitle = GradleBundle.message("gradle.settings.wizard.unsupported.jdk.title", if (context.isCreatingNewProject) 0 else 1)
val errorMessage = GradleBundle.message(
"gradle.settings.wizard.unsupported.jdk.message",
javaVersion.toFeatureString(),
MINIMUM_SUPPORTED_JAVA.toFeatureString(),
MAXIMUM_SUPPORTED_JAVA.toFeatureString(),
preferredGradleVersion.version)
val dialog = MessageDialogBuilder.yesNo(errorTitle, errorMessage).asWarning()
if (!dialog.ask(component)) {
return error(errorTitle)
}
}
return null
}
private fun getJavaVersion(): JavaVersion? {
val jdk = sdk ?: return null
val versionString = jdk.versionString ?: return null
return JavaVersion.tryParse(versionString)
}
private fun getPreferredGradleVersion(): GradleVersion {
val project = context.project ?: return GradleVersion.current()
return findGradleVersion(project) ?: GradleVersion.current()
}
private fun getGradleVersion(): GradleVersion? {
val preferredGradleVersion = getPreferredGradleVersion()
val javaVersion = getJavaVersion() ?: return preferredGradleVersion
return when (isSupported(preferredGradleVersion, javaVersion)) {
true -> preferredGradleVersion
else -> suggestGradleVersion(javaVersion)
}
}
protected fun suggestGradleVersion(): GradleVersion {
return getGradleVersion() ?: getPreferredGradleVersion()
}
class GradleDataView(override val data: ProjectData) : DataView<ProjectData>() {
override val location: String = data.linkedExternalProjectPath
override val icon: Icon = GradleIcons.GradleFile
override val presentationName: String = data.externalName
override val groupId: String = data.group ?: ""
override val version: String = data.version ?: ""
}
} | apache-2.0 | d421b0901b808458ebdd1dbe2859fca0 | 42.942446 | 158 | 0.759784 | 4.877796 | false | false | false | false |
dzharkov/intellij-markdown | src/org/intellij/markdown/parser/sequentialparsers/impl/InlineLinkParser.kt | 1 | 3130 | package org.intellij.markdown.parser.sequentialparsers.impl
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil
import org.intellij.markdown.parser.sequentialparsers.TokensCache
import java.util.ArrayList
public class InlineLinkParser : SequentialParser {
override fun parse(tokens: TokensCache, rangesToGlue: Collection<Range<Int>>): SequentialParser.ParsingResult {
var result = SequentialParser.ParsingResult()
val delegateIndices = ArrayList<Int>()
val indices = SequentialParserUtil.textRangesToIndices(rangesToGlue)
var iterator: TokensCache.Iterator = tokens.ListIterator(indices, 0)
while (iterator.type != null) {
if (iterator.type == MarkdownTokenTypes.LBRACKET) {
val localDelegates = ArrayList<Int>()
val resultNodes = ArrayList<SequentialParser.Node>()
val afterLink = parseInlineLink(resultNodes, localDelegates, iterator)
if (afterLink != null) {
iterator = afterLink.advance()
result = result.withNodes(resultNodes).withFurtherProcessing(SequentialParserUtil.indicesToTextRanges(localDelegates))
continue
}
}
delegateIndices.add(iterator.index)
iterator = iterator.advance()
}
return result.withFurtherProcessing(SequentialParserUtil.indicesToTextRanges(delegateIndices))
}
companion object {
fun parseInlineLink(result: MutableCollection<SequentialParser.Node>, delegateIndices: MutableList<Int>, iterator: TokensCache.Iterator): TokensCache.Iterator? {
val startIndex = iterator.index
var it = iterator
val afterText = LinkParserUtil.parseLinkText(result, delegateIndices, it)
?: return null
it = afterText
if (it.rawLookup(1) != MarkdownTokenTypes.LPAREN) {
return null
}
it = it.advance().advance()
if (it.type == MarkdownTokenTypes.EOL) {
it = it.advance()
}
val afterDestination = LinkParserUtil.parseLinkDestination(result, it)
if (afterDestination != null) {
it = afterDestination.advance()
if (it.type == MarkdownTokenTypes.EOL) {
it = it.advance()
}
}
val afterTitle = LinkParserUtil.parseLinkTitle(result, it)
if (afterTitle != null) {
it = afterTitle.advance()
if (it.type == MarkdownTokenTypes.EOL) {
it = it.advance()
}
}
if (it.type != MarkdownTokenTypes.RPAREN) {
return null
}
result.add(SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.INLINE_LINK))
return it
}
}
}
| apache-2.0 | d9aecb208a96d09511338f862b2b7c43 | 40.733333 | 169 | 0.619808 | 5.405872 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinValuesHintsProvider.kt | 1 | 3122 | // Copyright 2000-2022 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 org.jetbrains.kotlin.idea.codeInsight.hints
import com.intellij.codeInsight.hints.ChangeListener
import com.intellij.codeInsight.hints.ImmediateConfigurable
import com.intellij.codeInsight.hints.InlayGroup
import com.intellij.codeInsight.hints.SettingsKey
import com.intellij.ui.layout.*
import com.intellij.util.castSafelyTo
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyze
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import javax.swing.JComponent
class KotlinValuesHintsProvider : KotlinAbstractHintsProvider<KotlinValuesHintsProvider.Settings>() {
data class Settings(
var ranges: Boolean = true
): HintsSettings() {
override fun isEnabled(hintType: HintType): Boolean =
when (hintType) {
HintType.RANGES -> ranges
else -> false
}
override fun enable(hintType: HintType, enable: Boolean) =
when (hintType) {
HintType.RANGES -> ranges = enable
else -> Unit
}
}
override val key: SettingsKey<Settings> = SettingsKey("kotlin.values.hints")
override val name: String = KotlinBundle.message("hints.settings.values.ranges")
override val group: InlayGroup
get() = InlayGroup.VALUES_GROUP
override fun createSettings(): Settings = Settings()
override fun createConfigurable(settings: Settings): ImmediateConfigurable = object : ImmediateConfigurable {
override fun createComponent(listener: ChangeListener): JComponent = panel {}
override val mainCheckboxText: String = KotlinBundle.message("hints.settings.common.items")
override val cases: List<ImmediateConfigurable.Case>
get() = listOf(
ImmediateConfigurable.Case(
KotlinBundle.message("hints.settings.values.ranges"),
"kotlin.values.ranges",
settings::ranges,
KotlinBundle.message("inlay.kotlin.values.hints.kotlin.values.ranges")
)
)
}
override fun isElementSupported(resolved: HintType?, settings: Settings): Boolean =
when (resolved) {
HintType.RANGES -> settings.ranges
else -> false
}
override fun isHintSupported(hintType: HintType): Boolean = hintType == HintType.RANGES
override val previewText: String? = null
override val description: String
get() = KotlinBundle.message("inlay.kotlin.values.hints")
}
| apache-2.0 | c00601387c67378196fecab4e1015866 | 40.078947 | 158 | 0.70788 | 5.003205 | false | true | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/domain/course_collection/interactor/CourseCollectionInteractor.kt | 1 | 5752 | package org.stepik.android.domain.course_collection.interactor
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles.zip
import ru.nobird.app.core.model.PagedList
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.catalog.model.CatalogAuthor
import org.stepik.android.domain.catalog.model.CatalogCourseList
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course.model.SourceTypeComposition
import org.stepik.android.domain.course_collection.model.CourseCollectionResult
import org.stepik.android.domain.course_collection.repository.CourseCollectionRepository
import org.stepik.android.domain.course_list.interactor.CourseListInteractor
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.user.repository.UserRepository
import org.stepik.android.model.CourseCollection
import javax.inject.Inject
class CourseCollectionInteractor
@Inject
constructor(
private val courseListInteractor: CourseListInteractor,
private val courseCollectionRepository: CourseCollectionRepository,
private val userRepository: UserRepository
) {
companion object {
private const val PAGE_SIZE = 20
}
fun getCourseCollectionResult(id: Long, viewSource: CourseViewSource): Flowable<CourseCollectionResult> =
Flowable
.fromArray(SourceTypeComposition.CACHE, SourceTypeComposition.REMOTE)
.concatMapSingle { sourceType ->
getCourseCollection(id, sourceType.generalSourceType)
.flatMap { collection ->
if (collection.courses.isEmpty()) {
Single.just(
CourseCollectionResult(
courseCollection = collection,
courseListDataItems = PagedList(emptyList()),
courseListItems = emptyList(),
sourceType = sourceType.generalSourceType
)
)
} else {
resolveCollectionLoading(collection, sourceType, viewSource)
}
}
}
fun getCourseListItems(
courseId: List<Long>,
courseViewSource: CourseViewSource,
sourceTypeComposition: SourceTypeComposition = SourceTypeComposition.REMOTE
): Single<PagedList<CourseListItem.Data>> =
courseListInteractor.getCourseListItems(courseId, courseViewSource, sourceTypeComposition)
private fun getCourseCollection(id: Long, dataSource: DataSourceType): Single<CourseCollection> =
courseCollectionRepository
.getCourseCollections(id, dataSource)
private fun getSimilarCourseLists(ids: List<Long>, dataSource: DataSourceType): Single<List<CatalogCourseList>> =
courseCollectionRepository
.getCourseCollections(ids, dataSource)
.map { it.map { courseCollection ->
CatalogCourseList(
id = courseCollection.id,
title = courseCollection.title,
description = courseCollection.description,
courses = courseCollection.courses,
coursesCount = courseCollection.courses.size
)
} }
private fun getSimilarAuthorLists(ids: List<Long>, dataSource: DataSourceType): Single<List<CatalogAuthor>> =
userRepository
.getUsers(ids, dataSource)
.map { it.map { user ->
CatalogAuthor(
id = user.id,
isOrganization = user.isOrganization,
fullName = user.fullName ?: "",
alias = null,
avatar = user.avatar ?: "",
createdCoursesCount = user.createdCoursesCount.toInt(),
followersCount = user.followersCount.toInt()
)
} }
private fun resolveCollectionLoading(collection: CourseCollection, sourceType: SourceTypeComposition, viewSource: CourseViewSource): Single<CourseCollectionResult> =
zip(
courseListInteractor.getCourseListItems(
courseIds =
if (collection.similarCourseLists.isNotEmpty() || collection.similarAuthors.isNotEmpty()) {
collection.courses
} else {
collection.courses.take(PAGE_SIZE)
},
sourceTypeComposition = sourceType,
courseViewSource = viewSource
),
getSimilarCourseLists(collection.similarCourseLists, dataSource = sourceType.generalSourceType),
getSimilarAuthorLists(collection.similarAuthors, dataSource = sourceType.generalSourceType)
) { items, similarCourses, authors ->
CourseCollectionResult(
courseCollection = collection,
courseListDataItems = items,
courseListItems = items + formHorizontalLists(authors, similarCourses),
sourceType = sourceType.generalSourceType
)
}
private fun formHorizontalLists(authors: List<CatalogAuthor>, similarCourses: List<CatalogCourseList>): List<CourseListItem> {
val list = mutableListOf<CourseListItem>()
if (authors.isNotEmpty()) {
list += CourseListItem.SimilarAuthors(authors)
}
if (similarCourses.isNotEmpty()) {
list += CourseListItem.SimilarCourses(similarCourses)
}
return list
}
} | apache-2.0 | 7f793427114294eb28c297a61d55df33 | 45.395161 | 169 | 0.634388 | 5.929897 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/course_list/CourseListCollectionPresenter.kt | 1 | 10721 | package org.stepik.android.presentation.course_list
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course.model.SourceTypeComposition
import org.stepik.android.domain.course_collection.interactor.CourseCollectionInteractor
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.user_courses.model.UserCourse
import org.stepik.android.domain.wishlist.model.WishlistOperationData
import org.stepik.android.model.Course
import org.stepik.android.model.CourseCollection
import org.stepik.android.presentation.course_continue.delegate.CourseContinuePresenterDelegate
import org.stepik.android.presentation.course_continue.delegate.CourseContinuePresenterDelegateImpl
import org.stepik.android.presentation.course_list.mapper.CourseListCollectionStateMapper
import org.stepik.android.presentation.course_list.mapper.CourseListStateMapper
import org.stepik.android.view.injection.course.EnrollmentCourseUpdates
import org.stepik.android.view.injection.course_list.UserCoursesOperationBus
import org.stepik.android.view.injection.course_list.WishlistOperationBus
import ru.nobird.app.core.model.cast
import ru.nobird.app.core.model.safeCast
import ru.nobird.app.core.model.slice
import ru.nobird.android.domain.rx.emptyOnErrorStub
import ru.nobird.android.presentation.base.PresenterBase
import ru.nobird.android.presentation.base.PresenterViewContainer
import ru.nobird.android.presentation.base.delegate.PresenterDelegate
import javax.inject.Inject
class CourseListCollectionPresenter
@Inject
constructor(
private val courseCollectionInteractor: CourseCollectionInteractor,
private val courseListStateMapper: CourseListStateMapper,
private val courseListCollectionStateMapper: CourseListCollectionStateMapper,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler,
@EnrollmentCourseUpdates
private val enrollmentUpdatesObservable: Observable<Course>,
@UserCoursesOperationBus
private val userCourseOperationObservable: Observable<UserCourse>,
@WishlistOperationBus
private val wishlistOperationObservable: Observable<WishlistOperationData>,
viewContainer: PresenterViewContainer<CourseListCollectionView>,
continueCoursePresenterDelegate: CourseContinuePresenterDelegateImpl
) : PresenterBase<CourseListCollectionView>(viewContainer),
CourseContinuePresenterDelegate by continueCoursePresenterDelegate {
companion object {
private const val PAGE_SIZE = 20
}
override val delegates: List<PresenterDelegate<in CourseListCollectionView>> =
listOf(continueCoursePresenterDelegate)
private var state: CourseListCollectionView.State = CourseListCollectionView.State.Idle
set(value) {
field = value
view?.setState(value)
}
private val paginationDisposable = CompositeDisposable()
init {
compositeDisposable += paginationDisposable
subscribeForEnrollmentUpdates()
subscribeForUserCourseOperationUpdates()
subscribeForWishlistOperationUpdates()
}
override fun attachView(view: CourseListCollectionView) {
super.attachView(view)
view.setState(state)
}
fun fetchCourses(courseCollectionId: Long, forceUpdate: Boolean = false) {
if (state != CourseListCollectionView.State.Idle && !forceUpdate) return
paginationDisposable.clear()
val viewSource = CourseViewSource.Collection(courseCollectionId)
state = CourseListCollectionView.State.Loading
paginationDisposable += courseCollectionInteractor
.getCourseCollectionResult(courseCollectionId, viewSource)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onNext = { courseCollectionResult ->
val newState = courseListCollectionStateMapper.mapCourseCollectionResultToState(courseCollectionResult)
val isNeedLoadNextPage = courseListCollectionStateMapper.isNeedLoadNextPage(newState)
state = newState
if (isNeedLoadNextPage) {
fetchNextPage()
}
},
onError = {
when (val oldState = state.safeCast<CourseListCollectionView.State.Data>()?.courseListViewState) {
is CourseListView.State.Content -> {
state = state.cast<CourseListCollectionView.State.Data>()
.copy(
courseListViewState = oldState.copy(oldState.courseListDataItems, oldState.courseListItems),
sourceType = null
)
view?.showNetworkError()
}
else ->
state = CourseListCollectionView.State.NetworkError
}
}
)
}
fun fetchNextPage() {
val oldState = state as? CourseListCollectionView.State.Data
?: return
val oldCourseListState = oldState.courseListViewState as? CourseListView.State.Content
?: return
val lastItem = oldCourseListState.courseListItems.last()
if (lastItem is CourseListItem.SimilarAuthors || lastItem is CourseListItem.SimilarCourses) {
return
}
val ids = getNextPageCourseIds(oldState.courseCollection, oldCourseListState)
?.takeIf { it.isNotEmpty() }
?: return
state = oldState.copy(courseListViewState = courseListStateMapper.mapToLoadMoreState(oldCourseListState))
if (oldState.sourceType != DataSourceType.CACHE) {
paginationDisposable += courseCollectionInteractor
.getCourseListItems(ids, courseViewSource = CourseViewSource.Collection(oldState.courseCollection.id))
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = {
if (oldState.sourceType == null) {
state = oldState.copy(courseListViewState = CourseListView.State.Content(it, it), sourceType = DataSourceType.REMOTE)
fetchNextPage()
} else {
state = oldState.copy(courseListViewState = courseListStateMapper.mapFromLoadMoreToSuccess(oldCourseListState, it))
}
},
onError = {
state = oldState.copy(courseListViewState = courseListStateMapper.mapFromLoadMoreToError(oldCourseListState))
view?.showNetworkError()
}
)
}
}
private fun getNextPageCourseIds(courseCollection: CourseCollection, courseListViewState: CourseListView.State.Content): List<Long>? {
if ((courseListViewState.courseListItems.last() as? CourseListItem.PlaceHolder)?.courseId == -1L) {
return null
}
val offset = courseListViewState.courseListItems.size
return courseCollection
.courses
.slice(offset, offset + PAGE_SIZE)
.map { it }
}
/**
* Enrollment updates
*/
private fun subscribeForEnrollmentUpdates() {
compositeDisposable += enrollmentUpdatesObservable
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onNext = { enrolledCourse ->
val oldState = (state as? CourseListCollectionView.State.Data)
?: return@subscribeBy
state = oldState.copy(courseListViewState = courseListStateMapper.mapToEnrollmentUpdateState(oldState.courseListViewState, enrolledCourse))
fetchForEnrollmentUpdate(enrolledCourse)
},
onError = emptyOnErrorStub
)
}
private fun fetchForEnrollmentUpdate(course: Course) {
val oldState = (state as? CourseListCollectionView.State.Data)
?: return
compositeDisposable += courseCollectionInteractor
.getCourseListItems(listOf(course.id), courseViewSource = CourseViewSource.Collection(oldState.courseCollection.id), sourceTypeComposition = SourceTypeComposition.CACHE)
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { courses ->
state = oldState.copy(courseListViewState = courseListStateMapper.mapToEnrollmentUpdateState(oldState.courseListViewState, courses.first()))
},
onError = emptyOnErrorStub
)
}
/**
* UserCourse updates
*/
private fun subscribeForUserCourseOperationUpdates() {
compositeDisposable += userCourseOperationObservable
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onNext = { userCourse ->
val oldState = (state as? CourseListCollectionView.State.Data)
?: return@subscribeBy
state = oldState.copy(courseListViewState = courseListStateMapper.mapToUserCourseUpdate(oldState.courseListViewState, userCourse))
},
onError = emptyOnErrorStub
)
}
/**
* Wishlist updates
*/
private fun subscribeForWishlistOperationUpdates() {
compositeDisposable += wishlistOperationObservable
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onNext = {
val oldState = (state as? CourseListCollectionView.State.Data)
?: return@subscribeBy
state = oldState.copy(courseListViewState = courseListStateMapper.mapToWishlistUpdate(oldState.courseListViewState, it))
},
onError = emptyOnErrorStub
)
}
public override fun onCleared() {
super.onCleared()
}
} | apache-2.0 | d8f07a6a48fb689acacb0311fb36ce7c | 42.585366 | 181 | 0.668035 | 5.939612 | false | false | false | false |
exercism/xkotlin | exercises/practice/yacht/.meta/src/reference/kotlin/Yacht.kt | 1 | 1098 | import YachtCategory.*
object Yacht {
fun solve(category: YachtCategory, vararg dices: Int): Int = when (category) {
YACHT -> if (dices.distinct().size == 1) 50 else 0
ONES -> dices.filter { it == 1 }.sum()
TWOS -> dices.filter { it == 2 }.sum()
THREES -> dices.filter { it == 3 }.sum()
FOURS -> dices.filter { it == 4 }.sum()
FIVES -> dices.filter { it == 5 }.sum()
SIXES -> dices.filter { it == 6 }.sum()
FULL_HOUSE -> {
val counts = dices.groupBy { it }.map { it.key to it.value.count() }.sortedByDescending { it.second }
if (counts.size >= 2 && counts[0].second >= 3 && counts[1].second >= 2) {
counts[0].first * counts[0].second + counts[1].first * counts[1].second
} else 0
}
FOUR_OF_A_KIND -> dices.groupBy { it }.filter { it.value.size >= 4 }.keys.sumOf { it * 4 }
LITTLE_STRAIGHT -> if ((1..5).all { dices.contains(it) }) 30 else 0
BIG_STRAIGHT -> if ((2..6).all { dices.contains(it) }) 30 else 0
CHOICE -> dices.sum()
}
}
| mit | e17692c7f63bdb36748e3c8e5e33c9f4 | 44.75 | 113 | 0.527322 | 3.317221 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/ProjectModifiableLibraryTableBridgeImpl.kt | 2 | 5718 | // 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.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.Disposer
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectEntitiesLoader
import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.findLibraryEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.mutableLibraryMap
import com.intellij.workspaceModel.ide.legacyBridge.ProjectModifiableLibraryTableBridge
import com.intellij.workspaceModel.storage.CachedValue
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer
internal class ProjectModifiableLibraryTableBridgeImpl(
originalStorage: WorkspaceEntityStorage,
private val libraryTable: ProjectLibraryTableBridgeImpl,
private val project: Project,
diff: WorkspaceEntityStorageBuilder = WorkspaceEntityStorageBuilder.from(originalStorage),
cacheStorageResult: Boolean = true
) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ProjectModifiableLibraryTableBridge {
private val myAddedLibraries = mutableListOf<LibraryBridgeImpl>()
private val librariesArrayValue = CachedValue<Array<Library>> { storage ->
storage.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }
.mapNotNull { storage.libraryMap.getDataByEntity(it) }
.toList().toTypedArray()
}
private val librariesArray: Array<Library>
get() = entityStorageOnDiff.cachedValue(librariesArrayValue)
override fun createLibrary(name: String?): Library = createLibrary(name = name, type = null)
override fun createLibrary(name: String?, type: PersistentLibraryKind<out LibraryProperties<*>>?): Library =
createLibrary(name = name, type = type, externalSource = null)
override fun createLibrary(name: String?,
type: PersistentLibraryKind<out LibraryProperties<*>>?,
externalSource: ProjectModelExternalSource?): Library {
if (name.isNullOrBlank()) error("Project Library must have a name")
assertModelIsLive()
val libraryTableId = LibraryTableId.ProjectLibraryTableId
val libraryEntity = diff.addLibraryEntity(
roots = emptyList(),
tableId = LibraryTableId.ProjectLibraryTableId,
name = name,
excludedRoots = emptyList(),
source = JpsProjectEntitiesLoader.createEntitySourceForProjectLibrary(project, externalSource)
)
if (type != null) {
diff.addLibraryPropertiesEntity(
library = libraryEntity,
libraryType = type.kindId,
propertiesXmlTag = serializeComponentAsString(JpsLibraryTableSerializer.PROPERTIES_TAG, type.createDefaultProperties())
)
}
val library = LibraryBridgeImpl(
libraryTable = libraryTable,
project = project,
initialId = LibraryId(name, libraryTableId),
initialEntityStorage = entityStorageOnDiff,
targetBuilder = this.diff
)
myAddedLibraries.add(library)
diff.mutableLibraryMap.addMapping(libraryEntity, library)
return library
}
override fun removeLibrary(library: Library) {
assertModelIsLive()
val libraryEntity = entityStorageOnDiff.current.findLibraryEntity(library as LibraryBridge)
if (libraryEntity != null) {
diff.removeEntity(libraryEntity)
if (myAddedLibraries.remove(library)) {
Disposer.dispose(library)
}
}
}
override fun commit() {
prepareForCommit()
WorkspaceModel.getInstance(project).updateProjectModel {
it.addDiff(diff)
}
}
override fun prepareForCommit() {
assertModelIsLive()
modelIsCommittedOrDisposed = true
val storage = WorkspaceModel.getInstance(project).entityStorage.current
myAddedLibraries.forEach { library ->
if (storage.resolve(library.libraryId) != null) {
// it may happen that actual library table already has a library with such name (e.g. when multiple projects are imported in parallel)
// in such case we need to skip the new library to avoid exceptions.
diff.removeEntity(diff.libraryMap.getEntities(library).first())
Disposer.dispose(library)
}
library.clearTargetBuilder()
}
}
override fun getLibraryIterator(): Iterator<Library> = librariesArray.iterator()
override fun getLibraryByName(name: String): Library? {
val libraryEntity = diff.resolve(LibraryId(name, LibraryTableId.ProjectLibraryTableId)) ?: return null
return diff.libraryMap.getDataByEntity(libraryEntity)
}
override fun getLibraries(): Array<Library> = librariesArray
override fun dispose() {
modelIsCommittedOrDisposed = true
myAddedLibraries.forEach { Disposer.dispose(it) }
myAddedLibraries.clear()
}
override fun isChanged(): Boolean = !diff.isEmpty()
}
| apache-2.0 | d59b2d5a5aad5ee6e4006c4722728096 | 41.355556 | 142 | 0.76985 | 5.236264 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/observable/properties/PropertyGraph.kt | 2 | 3183 | // Copyright 2000-2019 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.openapi.observable.properties
import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace
import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace.Companion.task
import com.intellij.openapi.util.RecursionManager
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
class PropertyGraph(debugName: String? = null) {
private val propagation = AnonymousParallelOperationTrace((if (debugName == null) "" else " of $debugName") + ": Graph propagation")
private val properties = ConcurrentHashMap<ObservableClearableProperty<*>, PropertyNode>()
private val dependencies = ConcurrentHashMap<PropertyNode, CopyOnWriteArrayList<Dependency<*>>>()
private val recursionGuard = RecursionManager.createGuard<PropertyNode>(PropertyGraph::class.java.name)
fun <T> dependsOn(child: AtomicProperty<T>, parent: ObservableClearableProperty<*>) {
addDependency(child, parent) { reset() }
}
fun <T> dependsOn(child: AtomicProperty<T>, parent: ObservableClearableProperty<*>, update: () -> T) {
addDependency(child, parent) { updateAndGet { update() } }
}
private fun <T> addDependency(child: AtomicProperty<T>, parent: ObservableClearableProperty<*>, update: AtomicProperty<T>.() -> Unit) {
val childNode = properties[child] ?: throw IllegalArgumentException("Unregistered child property")
val parentNode = properties[parent] ?: throw IllegalArgumentException("Unregistered parent property")
dependencies.putIfAbsent(parentNode, CopyOnWriteArrayList())
val children = dependencies.getValue(parentNode)
children.add(Dependency(childNode, child, update))
}
fun afterPropagation(listener: () -> Unit) {
propagation.afterOperation(listener)
}
fun register(property: ObservableClearableProperty<*>) {
val node = PropertyNode()
properties[property] = node
property.afterChange {
recursionGuard.doPreventingRecursion(node, false) {
propagation.task {
node.isPropagationBlocked = true
propagateChange(node)
}
}
}
property.afterReset {
node.isPropagationBlocked = false
}
}
private fun propagateChange(parent: PropertyNode) {
val dependencies = dependencies[parent] ?: return
for (dependency in dependencies) {
val child = dependency.node
if (child.isPropagationBlocked) continue
recursionGuard.doPreventingRecursion(child, false) {
dependency.applyUpdate()
propagateChange(child)
}
}
}
@TestOnly
fun isPropagationBlocked(property: ObservableClearableProperty<*>) =
properties.getValue(property).isPropagationBlocked
private inner class PropertyNode {
@Volatile
var isPropagationBlocked = false
}
private data class Dependency<T>(
val node: PropertyNode,
val property: AtomicProperty<T>,
val update: AtomicProperty<T>.() -> Unit
) {
fun applyUpdate() = property.update()
}
} | apache-2.0 | 93a1afc01612750375957f2eb357fb69 | 38.308642 | 140 | 0.739868 | 5.012598 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableModelCommitterServiceBridge.kt | 2 | 1930 | // 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.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.impl.ModifiableModelCommitterService
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModifiableModuleModelBridgeImpl
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
internal class ModifiableModelCommitterServiceBridge : ModifiableModelCommitterService {
override fun multiCommit(rootModels: MutableCollection<out ModifiableRootModel>, moduleModel: ModifiableModuleModel) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
// TODO Naive impl, check for existing contact in com.intellij.openapi.module.impl.ModuleManagerImpl.commitModelWithRunnable
val diffs = mutableSetOf<WorkspaceEntityStorageBuilder>()
diffs += (moduleModel as ModifiableModuleModelBridgeImpl).collectChanges()
val committedModels = ArrayList<ModifiableRootModelBridge>()
for (rootModel in rootModels) {
if (rootModel.isChanged) {
diffs += (rootModel as ModifiableRootModelBridgeImpl).collectChangesAndDispose() ?: continue
committedModels += rootModel as ModifiableRootModelBridge
}
else rootModel.dispose()
}
WorkspaceModel.getInstance(moduleModel.project).updateProjectModel { builder ->
diffs.forEach { builder.addDiff(it) }
}
for (rootModel in committedModels) {
rootModel.postCommit()
}
}
} | apache-2.0 | fa2f2f2eb53430dbb35855d0419fd52a | 48.512821 | 140 | 0.80829 | 5.34626 | false | false | false | false |
mr-max/learning-spaces | app/src/main/java/de/maxvogler/learningspaces/helpers/SequenceHelpers.kt | 1 | 952 | package de.maxvogler.learningspaces.helpers
import android.view.Menu
import android.view.MenuItem
import java.util.*
fun Menu.itemsSequence(): Sequence<MenuItem> = MenuItemsSequence(this)
private class MenuItemsSequence(private val menu: Menu) : Sequence<MenuItem> {
override fun iterator(): Iterator<MenuItem> {
return IndexBasedIterator(count = { menu.size() }, getItem = { menu.getItem(it) })
}
}
private class IndexBasedIterator<O>(
private val count: () -> Int,
private val getItem: (Int) -> O
) : Iterator<O> {
private var index = 0
private val initialCount = count()
override fun next(): O {
if (!hasNext()) {
throw NoSuchElementException()
}
return getItem(index++)
}
override fun hasNext(): Boolean {
if (initialCount != count()) {
throw ConcurrentModificationException()
}
return index < initialCount
}
}
| gpl-2.0 | cf3e683cd33859f711d10e20a49eab52 | 24.052632 | 90 | 0.636555 | 4.387097 | false | false | false | false |
code-helix/slatekit | src/apps/kotlin/slatekit-samples/src/main/kotlin/slatekit/samples/common/apis/SampleAPI.kt | 1 | 14807 | package slatekit.samples.common.apis
import slatekit.apis.*
import slatekit.apis.core.Patch
import slatekit.common.DateTime
import slatekit.common.DateTimes
import slatekit.common.requests.Request
import slatekit.context.Context
import slatekit.common.Sources
import slatekit.common.ext.toId
import slatekit.common.ext.toStringUtc
import slatekit.common.info.About
import slatekit.common.info.Build
import slatekit.common.types.Doc
import slatekit.results.Outcome
import slatekit.results.builders.Outcomes
import slatekit.samples.common.models.Movie
/**
* Sample API that can be used on both
* 1. CLI : Command line interface apps
* 2. WEB : As Http/Web API ( see postman script at /doc/samples/apis/slatekit-samples-postman.json
*
* SAMPLES:
* ROUTE | SOURCE | PURPOSE
* samples/all/about , CLI + WEB , 0 params: get version info
* samples/all/greet , CLI + WEB , 1 param : simple hello world greeting
* samples/all/outcome , CLI + WEB , 1 param : shows how to model success and failure
* samples/all/inc , CLI + WEB , 0 params: increment a accumulator
* samples/all/add , CLI + WEB , 1 param : add to a accumulator
* samples/all/value , CLI + WEB , get value of the counter
* samples/all/dec , CLI , CLI restricted access, decrement accumulator
* samples/all/inputs , CLI + WEB , 5 + params: use basic data types
* samples/all/movies , CLI + WEB , show retrieval of complex objects
* samples/all/request , CLI + WEB , show access to request object
* samples/all/response , CLI + WEB , show error handling responses
* samples/all/recent , CLI + WEB , show both inputs and complex object response
* samples/all/create , WEB , http post example
* samples/all/update , WEB , http put example
* samples/all/patch , WEB , http patch example
* samples/all/delete , WEB , http delete example
*
*
*
* NOTES:
* This has examples for showing
* 1. Basic Types : Basic data types ( bool, string, int, double, datetime )
* 2. Complex Types : Complex types such as classes/objects/lists/maps
* 3. Requests : Access to the request object
* 4. Error handling : Working with errors and exceptions
* 5. CLI Only : Configuring actions for CLI access only
* 6. WEB Only : Configuring actions for WEB access only
* 7. WEB Verbs : HTTP Verbs post, put, patch, delete actions
* 8. WEB Files : File handling with uploads / downloads
*
*/
@Api(area = "samples", name = "all", desc = "sample to test features of Slate Kit APIs", auth = AuthModes.NONE, verb = Verbs.AUTO, sources = [Sources.ALL])
class SampleAPI(context: Context) : ApiBase(context) {
// Simple value to test actions/methods
private var accumulator = 0
/*
Sample acton to show info about this app/api
Examples:
CLI: samples.all.about
WEB: curl -X POST http://localhost:5000/api/samples/all/about
*/
@Action(desc = "info about this api")
fun about(): About {
return context.info.about
}
/*
Sample acton to show build info of this app/api
Examples:
CLI: samples.all.build
WEB: curl -X POST http://localhost:5000/api/samples/all/build
*/
@Action(desc = "info about this api")
fun build(): Build {
return context.info.build
}
/*
Sample action to take in a input and return a simple response
Examples:
CLI: samples.all.greet -greeting="hey there"
WEB: curl -X POST http://localhost:5000/api/samples/all/greet -d '{ "greeting": "hello" }'
*/
@Action(desc = "simple hello world greeting")
fun greet(greeting: String): String {
return "$greeting back"
}
/*
Sample acton to show how to model success/failure values
Examples:
CLI: samples.all.about
WEB: curl -X POST http://localhost:5000/api/samples/all/about
*/
@Action(desc = "show how to model success and failure")
fun outcome(name:String): Outcome<Int> {
return when(name.toLowerCase()){
"succeeded" -> Outcomes.success(1)
"pending" -> Outcomes.pending(2)
"denied" -> Outcomes.denied("Sample denied error")
"ignored" -> Outcomes.ignored("Sample ignored error")
"invalid" -> Outcomes.invalid("Sample invalid error")
"errored" -> Outcomes.errored("Sample expected error")
"unknown" -> Outcomes.unexpected("Sample unexpected error")
else -> Outcomes.unexpected("Sample unexpected error")
}
}
/*
Sample action to increment the accumulator
Examples:
CLI: samples.all.inc
WEB: curl -X POST http://localhost:5000/api/samples/all/inc
*/
@Action(desc = "increments the accumulator")
fun inc(): Int {
accumulator += 1
return accumulator
}
/*
Sample action to show restricted access to only the CLI
CLI: samples.all.dec -value=1
WEB: Not available with this configuration
*/
@Action(desc = "subtracts a value from the accumulator", sources = [Sources.CLI])
fun dec(value:Int): Int {
accumulator += value
return accumulator
}
/*
Sample action to get value of accumulator
CLI: samples.all.value
WEB: curl -X GET http://localhost:5000/api/samples/all/value
*/
@Action(desc = "get current value of accumulator", verb = Verbs.GET)
fun value(): Int {
return accumulator
}
/*
Simple action to add 2 values
CLI: samples.all.add -a=1 -b=2
WEB: curl -X POST http://localhost:5000/api/samples/all/add -d '{ "a" : 1, "b" : 2 }'
*/
@Action(desc = "simple addition of 2 numbers")
fun add(a:Int, b:Int): Int {
return a + b
}
/*
Sample action to show accepting different basic data types
CLI: samples.all.inputs -name="jason" -isActive=true -age=32 -dept=2 -account=123 -average=2.4 -salary=120000 -date="2019-04-01T11:05:30Z"
WEB: curl -X POST http://localhost:5000/api/samples/all/inputs \
-H 'Content-Type: application/json' \
-d '{
"name" : "kishore",
"isActive" : true,
"age" : 30,
"dept" : 10,
"account" : 1234,
"average" : 3.1,
"salary" : 100000,
"date" : "2019-04-01T11:05:30Z"
}'
*/
@Action(desc = "accepts supplied basic data types from send")
fun inputs(name: String, isActive: Boolean, age: Short, dept: Int, account: Long, average: Float, salary: Double, date: DateTime): Map<String, Any> {
return mapOf(
"name" to name,
"active" to isActive,
"age" to age,
"dept" to dept,
"account" to account,
"average" to average,
"salary" to salary,
"date" to date.toStringUtc()
)
}
/*
Sample action to show retrieving complex objects
CLI: samples.all.movies
WEB: curl -X GET http://localhost:5000/api/samples/all/movies
*/
@Action(desc = "get lists of movies", verb = Verbs.GET)
fun movies(): List<Movie> {
return listOf(
Movie(
title = "Indiana Jones",
category = "action",
playing = false,
cost = 10,
rating = 4.5,
released = DateTimes.of(1985, 8, 10)
),
Movie(
title = "Contact",
category = "sci-fi",
playing = false,
cost = 10,
rating = 4.5,
released = DateTimes.of(1995, 8, 10)
)
)
}
/*
Sample action ( similar to greeting above ), but with access to the Request object
Examples:
CLI: samples.all.request -greeting="hey there"
WEB: curl -X POST http://localhost:5000/api/samples/all/request -d '{ "greeting": "hello" }'
*/
@Action(desc = "test access to the request")
fun request(request: Request, greeting: String): String {
val greetFromBody = request.data.getString("greeting")
return "Handled Request: got `$greeting` as parameter, got `$greetFromBody` from request body"
}
/*
Sample action ( similar to greeting above ), to show error handling and returning statuses
Examples:
CLI: samples.all.response -status="invalid"
WEB: curl -X POST http://localhost:5000/api/samples/all/request -d '{ "greeting": "hello" }'
*/
@Action(desc = "test wrapped result")
fun response(request: Request, status: String): Outcome<Movie> {
val sampleMovie = Movie(
title = "Sample Movie 1",
category = "action",
playing = false,
cost = 10,
rating = 4.5,
released = DateTimes.of(1985, 8, 10)
)
val result:Outcome<Movie> = when(status) {
"invalid" -> Outcomes.invalid ("test status invalid")
"ignored" -> Outcomes.ignored ("test status ignored")
"denied" -> Outcomes.denied ("test status denied ")
"errored" -> Outcomes.errored ("test status errored")
"conflict" -> Outcomes.conflict("test status conflict")
"pending" -> Outcomes.pending (sampleMovie)
"success" -> Outcomes.success (sampleMovie)
else -> Outcomes.unexpected("test status unknown")
}
return result
}
/*
Sample action to show getting list of objects
Examples:
CLI: samples.all.recent -category="sci-fi"
WEB: curl -X POST http://localhost:5000/api/samples/all/recent -d '{ "category": "sci-fi" }'
*/
@Action(desc = "test movie list", verb = Verbs.GET)
fun recent(category: String): List<Movie> {
return listOf(
Movie(
title = "Sample Movie 1",
category = category,
playing = false,
cost = 10,
rating = 4.5,
released = DateTimes.of(1985, 8, 10)
),
Movie(
title = "Sample Movie 2",
category = category,
playing = false,
cost = 10,
rating = 4.5,
released = DateTimes.of(1995, 8, 10)
)
)
}
/**
* The HTTP Verb handling is automatic or can be explicitly supplied.
* Names starting with the following match to HTTP Verbs
* 1. create -> post
* 2. update -> put
* 3. patch -> patch
* 4. delete -> delete
*/
/*
Sample action to show creating a complex object with POST, restricted to WEB only calls
Examples:
CLI: N/A
WEB: curl -X POST http://localhost:5000/api/samples/all/create \
-H 'Content-Type: application/json' \
-d '{
"movie" : {
"id": 0,
"title": "Indiana Jones",
"category": "action",
"playing": false,
"cost": 10,
"rating": 4.5,
"released": "1985-08-10T04:00:00Z"
}
}'
*/
@Action(desc = "test post", sources = [Sources.API])
fun create(movie: Movie): String {
return "movie ${movie.title} created"
}
/*
Sample action to show updating a complex object with PUT, restricted to WEB only calls
Examples:
CLI: N/A
WEB: curl -X PUT http://localhost:5000/api/samples/all/update \
-H 'Content-Type: application/json' \
-d '{
"movie" : {
"id": 0,
"title": "Indiana Jones",
"category": "action",
"playing": false,
"cost": 10,
"rating": 4.5,
"released": "1985-08-10T04:00:00Z"
}
}'
*/
@Action(desc = "test put", sources = [Sources.API])
fun update(movie: Movie): String {
return "movie ${movie.title} updated"
}
/*
Sample action to show updating a complex object with PUT, restricted to WEB only calls
Examples:
CLI: N/A
WEB: curl -X PATCH http://localhost:5000/api/samples/all/patch \
-H 'Content-Type: application/json' \
-d '{
"id": 1,
"fields" : [
{ "name" : "cost" , "value" : 12 },
{ "name" : "rating", "value" : 4.8 }
]
}'
*/
@Action(desc = "test patch", sources = [Sources.API])
fun patch(id:Long, fields: List<Patch>): String {
val info = fields.joinToString("") { i -> i.name + "=" + i.value + " " }
return "movie ${id} updated with $info"
}
/*
Sample action to show deleting a complex object with DELETE, restricted to WEB only calls
Examples:
CLI: N/A
WEB: curl -X DELETE http://localhost:5000/api/samples/all/delete \
-H 'Content-Type: application/json' \
-d '{
"movie" : {
"id": 0,
"title": "Indiana Jones",
"category": "action",
"playing": false,
"cost": 10,
"rating": 4.5,
"released": "1985-08-10T04:00:00Z"
}
}'
*/
@Action(desc = "test delete", sources = [Sources.API])
fun delete(movie: Movie): String {
return "movie ${movie.title} deleted"
}
/*
Sample action to show getting a file containing the sample text supplied
Examples:
CLI: n/a
WEB: curl -X POST http://localhost:5000/api/samples/all/download \
-H 'Content-Type: application/json' \
-d '{ "text" : "some content" }'
*/
@Action(desc = "File download", sources = [Sources.API])
fun download(text:String):Doc {
return Doc.text(DateTime.now().toStringUtc().toId() + ".txt", text)
}
@Action(desc = "File upload", sources = [Sources.API])
fun upload(file: Doc):Map<String, String> {
return mapOf(
"name" to file.name,
"type" to file.tpe.http,
"size" to file.size.toString(),
"data" to file.content
)
}
}
| apache-2.0 | b1c6fb18e1bf5f0f8f83b135e1bc7a2c | 33.758216 | 155 | 0.545215 | 4.13257 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/symbols/KtFirPropertySetterSymbol.kt | 2 | 3692 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api.fir.symbols
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyAccessor
import org.jetbrains.kotlin.idea.fir.findPsi
import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirModuleResolveState
import org.jetbrains.kotlin.idea.frontend.api.ValidityToken
import org.jetbrains.kotlin.idea.frontend.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.containsAnnotation
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.getAnnotationClassIds
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.toAnnotationsList
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.cached
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.firRef
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtPropertySetterSymbol
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtSetterParameterSymbol
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.*
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtPsiBasedSymbolPointer
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.idea.frontend.api.types.KtType
internal class KtFirPropertySetterSymbol(
fir: FirPropertyAccessor,
resolveState: FirModuleResolveState,
override val token: ValidityToken,
private val builder: KtSymbolByFirBuilder,
) : KtPropertySetterSymbol(), KtFirSymbol<FirPropertyAccessor> {
init {
require(fir.isSetter)
}
override val firRef = firRef(fir, resolveState)
override val psi: PsiElement? by firRef.withFirAndCache { fir -> fir.findPsi(fir.session) }
override val isDefault: Boolean get() = firRef.withFir { it is FirDefaultPropertyAccessor }
override val isInline: Boolean get() = firRef.withFir { it.isInline }
override val isOverride: Boolean get() = firRef.withFir { it.isOverride }
override val hasBody: Boolean get() = firRef.withFir { it.body != null }
override val modality: KtCommonSymbolModality get() = firRef.withFir(FirResolvePhase.STATUS) { it.modality.getSymbolModality() }
override val visibility: KtSymbolVisibility get() = firRef.withFir(FirResolvePhase.STATUS) { it.visibility.getSymbolVisibility() }
override val annotations: List<KtAnnotationCall> by cached { firRef.toAnnotationsList() }
override fun containsAnnotation(classId: ClassId): Boolean = firRef.containsAnnotation(classId)
override val annotationClassIds: Collection<ClassId> by cached { firRef.getAnnotationClassIds() }
override val parameter: KtSetterParameterSymbol by firRef.withFirAndCache { fir ->
builder.buildFirSetterParameter(fir.valueParameters.single())
}
override val symbolKind: KtSymbolKind
get() = firRef.withFir { fir ->
when (fir.symbol.callableId.classId) {
null -> KtSymbolKind.TOP_LEVEL
else -> KtSymbolKind.MEMBER
}
}
override val dispatchType: KtType? by cached {
firRef.dispatchReceiverTypeAndAnnotations(builder)
}
override fun createPointer(): KtSymbolPointer<KtPropertySetterSymbol> {
KtPsiBasedSymbolPointer.createForSymbolFromSource(this)?.let { return it }
TODO("Creating pointers for setters from library is not supported yet")
}
} | apache-2.0 | 95b4bb8792c6d59c9e475747127e8131 | 49.589041 | 134 | 0.775731 | 4.552404 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/index/actions/GitCommitWithStagingAreaAction.kt | 4 | 1407 | // 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 git4idea.index.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.wm.IdeFocusManager
import git4idea.index.GitStageContentProvider
import git4idea.index.isStagingAreaAvailable
import git4idea.index.showStagingArea
class GitCommitWithStagingAreaAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val project = e.project
if (project == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isEnabledAndVisible = ChangesViewContentManager.getToolWindowFor(project,
GitStageContentProvider.STAGING_AREA_TAB_NAME) != null
&& isStagingAreaAvailable(project)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
showStagingArea(project) { gitStagePanel ->
IdeFocusManager.getInstance(project).requestFocus(gitStagePanel.commitMessage.editorField, false).doWhenDone {
gitStagePanel.commitMessage.editorField.selectAll()
}
}
}
} | apache-2.0 | 7c9b0a42df9a2b523e836550ae571359 | 41.666667 | 158 | 0.717129 | 4.989362 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/KotlinChainTransformerImpl.kt | 1 | 3954 | // 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 org.jetbrains.kotlin.idea.debugger.sequence.psi.impl
import com.intellij.debugger.streams.psi.ChainTransformer
import com.intellij.debugger.streams.trace.impl.handler.type.GenericType
import com.intellij.debugger.streams.wrapper.CallArgument
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall
import com.intellij.debugger.streams.wrapper.QualifierExpression
import com.intellij.debugger.streams.wrapper.StreamChain
import com.intellij.debugger.streams.wrapper.impl.*
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.debugger.sequence.psi.CallTypeExtractor
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.callName
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
class KotlinChainTransformerImpl(private val typeExtractor: CallTypeExtractor) : ChainTransformer<KtCallExpression> {
override fun transform(callChain: List<KtCallExpression>, context: PsiElement): StreamChain {
val intermediateCalls = mutableListOf<IntermediateStreamCall>()
for (call in callChain.subList(0, callChain.size - 1)) {
val (typeBefore, typeAfter) = typeExtractor.extractIntermediateCallTypes(call)
intermediateCalls += IntermediateStreamCallImpl(
call.callName(), call.valueArguments.map { createCallArgument(call, it) },
typeBefore, typeAfter,
call.textRange
)
}
val terminationsPsiCall = callChain.last()
val (typeBeforeTerminator, resultType) = typeExtractor.extractTerminalCallTypes(terminationsPsiCall)
val terminationCall = TerminatorStreamCallImpl(
terminationsPsiCall.callName(),
terminationsPsiCall.valueArguments.map { createCallArgument(terminationsPsiCall, it) },
typeBeforeTerminator, resultType, terminationsPsiCall.textRange
)
val typeAfterQualifier =
if (intermediateCalls.isEmpty()) typeBeforeTerminator else intermediateCalls.first().typeBefore
val qualifier = createQualifier(callChain.first(), typeAfterQualifier)
return StreamChainImpl(qualifier, intermediateCalls, terminationCall, context)
}
private fun createCallArgument(callExpression: KtCallExpression, arg: KtValueArgument): CallArgument {
fun KtValueArgument.toCallArgument(): CallArgument {
val argExpression = getArgumentExpression()!!
return CallArgumentImpl(KotlinPsiUtil.getTypeName(argExpression.resolveType()!!), this.text)
}
val bindingContext = callExpression.getResolutionFacade().analyzeWithAllCompilerChecks(callExpression).bindingContext
val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return arg.toCallArgument()
val parameter = resolvedCall.getParameterForArgument(arg) ?: return arg.toCallArgument()
return CallArgumentImpl(KotlinPsiUtil.getTypeName(parameter.type), arg.text)
}
private fun createQualifier(expression: PsiElement, typeAfter: GenericType): QualifierExpression {
val parent = expression.parent as? KtDotQualifiedExpression ?: return QualifierExpressionImpl("", TextRange.EMPTY_RANGE, typeAfter)
val receiver = parent.receiverExpression
return QualifierExpressionImpl(receiver.text, receiver.textRange, typeAfter)
}
}
| apache-2.0 | 070c27d179dc76ad1c2a69d2d824013b | 54.690141 | 158 | 0.774153 | 5.005063 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/gui/rcomponents/Util.kt | 1 | 17936 | package com.cout970.modeler.gui.rcomponents
import com.cout970.modeler.api.model.ITransformation
import com.cout970.modeler.controller.usecases.scriptEngine
import com.cout970.modeler.core.model.TRSTransformation
import com.cout970.modeler.core.model.TRTSTransformation
import com.cout970.modeler.gui.leguicomp.*
import com.cout970.modeler.input.window.Loop
import com.cout970.modeler.util.disableInput
import com.cout970.modeler.util.text
import com.cout970.modeler.util.toJoml2f
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.core.RProps
import com.cout970.reactive.core.RStatelessComponent
import com.cout970.reactive.dsl.*
import com.cout970.reactive.nodes.*
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.Vector3
import org.joml.Vector2f
import org.liquidengine.legui.component.Component
import org.liquidengine.legui.component.optional.align.HorizontalAlign
import org.liquidengine.legui.event.ScrollEvent
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
data class FloatInputProps(
val getter: () -> Float,
val command: String,
val metadata: Map<String, Any>,
val enabled: Boolean,
val pos: IVector2
) : RProps
private val formatter = DecimalFormat("#.###", DecimalFormatSymbols.getInstance(Locale.ENGLISH))
class FloatInput : RStatelessComponent<FloatInputProps>() {
override fun RBuilder.render() = div("FloatInput") {
style {
transparent()
borderless()
sizeX = 75f
sizeY = 70f
position = props.pos.toJoml2f()
}
postMount {
if (!props.enabled) {
disableInput()
}
}
comp(StringInput(null)) {
style {
defaultTextColor()
fontSize = 24f
posX = 0f
posY = 16f
sizeX = 75f
sizeY = 40f
text = formatter.format(props.getter())
classes("float_input")
horizontalAlign = HorizontalAlign.CENTER
onLoseFocus = {
dispatch(this, 0f, text)
}
onEnterPress = {
dispatch(this, 0f, text)
}
}
on<ScrollEvent<StringInput>> {
val off = it.yoffset.toFloat()
dispatch(it.targetComponent, off, it.targetComponent.text)
}
}
comp(IconButton()) {
style {
sizeX = 75f
sizeY = 16f
icon = "button_up"
classes("float_input_button")
onRelease {
dispatch(this, 1f, formatter.format(props.getter()))
}
}
}
comp(IconButton()) {
style {
posY = 56f
sizeX = 75f
sizeY = 16f
icon = "button_down"
classes("float_input_button")
onRelease {
dispatch(this, -1f, formatter.format(props.getter()))
}
}
}
}
var lastTick = 0L
fun dispatch(comp: Component, offset: Float, content: String) {
// this avoid generating a million task doing the same thing
if (lastTick == Loop.currentTick) return
lastTick = Loop.currentTick
comp.apply {
metadata += props.metadata
metadata += "offset" to offset
metadata += "content" to content
dispatch(props.command)
}
}
}
data class TinyFloatInputProps(
val pos: Vector2f = Vector2f(),
val increment: Float = 0.1f,
val getter: () -> Float,
val setter: (Float) -> Unit,
val enabled: Boolean = true) : RProps
class TinyFloatInput : RStatelessComponent<TinyFloatInputProps>() {
override fun RBuilder.render() = div("TinyFloatInput") {
style {
position.set(props.pos)
width = 120f
height = 24f
classes("tiny_float_input")
if (!props.enabled) {
classes("tiny_float_input_disable")
}
}
postMount {
if (!props.enabled) {
disableInput()
}
}
+IconButton("", "button_left", 0f, 0f, 24f, 24f).apply {
classes("tiny_float_input_left")
if (!props.enabled) {
classes("tiny_float_input_left_disable")
}
onClick {
value -= props.increment
rerender()
}
}
+StringInput("", formatter.format(value), 24f, 0f, 72f, 24f).apply {
classes("tiny_float_input_field")
if (!props.enabled) {
disable()
disableInput()
classes("tiny_float_input_field_disable")
focusedStyle.background = style.background
}
onScroll {
text.toFloatValue()?.let { txt ->
value = it.yoffset.toFloat() * props.increment + txt
} ?: rerender()
}
onEnterPress = {
text.toFloatValue()?.let { txt ->
value = txt
} ?: rerender()
}
onLoseFocus = onEnterPress
}
+IconButton("", "button_right", 96f, 0f, 24f, 24f).apply {
classes("tiny_float_input_right")
if (!props.enabled) {
classes("tiny_float_input_right_disable")
}
onClick {
value += props.increment
rerender()
}
}
}
var value: Float
get() = props.getter()
set(value) {
props.setter(value)
// rerender()
}
fun String.toFloatValue(): Float? {
return try {
(scriptEngine.eval(this) as? Number)?.toFloat()
} catch (e: Exception) {
null
}
}
}
data class TransformationInputProps(val usecase: String, val transformation: ITransformation, val enable: Boolean) : RProps
class TransformationInput : RStatelessComponent<TransformationInputProps>() {
companion object {
private const val line = 0.4f
}
override fun RBuilder.render() {
val t = props.transformation
when (t) {
is TRSTransformation -> {
scale(t.scale)
position(t.translation)
rotation(t.euler.angles)
pivot(Vector3.ZERO, false)
}
is TRTSTransformation -> {
scale(t.scale)
position(t.translation)
rotation(t.rotation)
pivot(t.pivot, true)
}
}
}
fun RBuilder.position(translation: IVector3) {
div("Position") {
style {
height = 93f
classes("inputGroup")
}
postMount {
fillX()
}
div {
style {
classes("div")
}
postMount {
width = parent.width * line
fillY()
floatTop(6f, 5f)
}
label("Position X") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
label("Position Y") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
label("Position Z") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
}
div {
style {
classes("div")
}
postMount {
posX = parent.width * line
width = parent.width * (1 - line)
fillY()
floatTop(6f, 5f)
}
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { translation.xf },
setter = { cmd("pos.x", it) },
enabled = props.enable
))
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { translation.yf },
setter = { cmd("pos.y", it) },
enabled = props.enable
))
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { translation.zf },
setter = { cmd("pos.z", it) },
enabled = props.enable
))
}
}
}
fun RBuilder.rotation(rotation: IVector3) {
div("Rotation") {
style {
height = 93f
classes("inputGroup")
}
postMount {
fillX()
}
div {
style {
classes("div")
}
postMount {
width = parent.width * line
fillY()
floatTop(6f, 5f)
}
label("Rotation X") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
label("Rotation Y") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
label("Rotation Z") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
}
div {
style {
classes("div")
}
postMount {
posX = parent.width * line
width = parent.width * (1 - line)
fillY()
floatTop(6f, 5f)
}
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 15f,
getter = { rotation.xf },
setter = { cmd("rot.x", it) },
enabled = props.enable
))
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 15f,
getter = { rotation.yf },
setter = { cmd("rot.y", it) },
enabled = props.enable
))
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 15f,
getter = { rotation.zf },
setter = { cmd("rot.z", it) },
enabled = props.enable
))
}
}
}
fun RBuilder.pivot(translation: IVector3, enabled: Boolean) {
div("Pivot") {
style {
height = 93f
classes("inputGroup")
}
postMount {
fillX()
}
div {
style {
classes("div")
}
postMount {
width = parent.width * line
fillY()
floatTop(6f, 5f)
}
label("Pivot X") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
label("Pivot Y") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
label("Pivot Z") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
}
div {
style {
classes("div")
}
postMount {
posX = parent.width * line
width = parent.width * (1 - line)
fillY()
floatTop(6f, 5f)
}
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { translation.xf },
setter = { cmd("pivot.x", it) },
enabled = props.enable && enabled
))
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { translation.yf },
setter = { cmd("pivot.y", it) },
enabled = props.enable && enabled
))
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { translation.zf },
setter = { cmd("pivot.z", it) },
enabled = props.enable && enabled
))
}
}
}
fun RBuilder.scale(scale: IVector3) {
div("Scale") {
style {
height = 93f
classes("inputGroup")
}
postMount {
fillX()
}
div {
style {
classes("div")
}
postMount {
width = parent.width * line
fillY()
floatTop(6f, 5f)
}
label("Scale X") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
label("Scale Y") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
label("Scale Z") {
style {
width = 110f
height = 25f
classes("inputLabel")
}
postMount { marginX(10f) }
}
}
div {
style {
classes("div")
}
postMount {
posX = parent.width * line
width = parent.width * (1 - line)
fillY()
floatTop(6f, 5f)
}
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { scale.xf },
setter = { cmd("size.x", it) },
enabled = props.enable
))
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { scale.yf },
setter = { cmd("size.y", it) },
enabled = props.enable
))
child(TinyFloatInput::class, TinyFloatInputProps(
pos = Vector2f(5f, 0f),
increment = 1f,
getter = { scale.zf },
setter = { cmd("size.z", it) },
enabled = props.enable
))
}
}
}
fun cmd(txt: String, value: Float) {
if (props.enable) {
Panel().apply {
metadata += mapOf("command" to txt)
metadata += "offset" to 0f
metadata += "content" to value.toString()
dispatch(props.usecase)
}
}
}
} | gpl-3.0 | c07fdd6cfb80d9c17293720f31c8d852 | 27.930645 | 123 | 0.396688 | 5.23526 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/viewholders/discoverydrawer/TopFilterViewHolder.kt | 1 | 2292 | package com.kickstarter.ui.viewholders.discoverydrawer
import androidx.core.content.res.ResourcesCompat
import com.kickstarter.R
import com.kickstarter.databinding.DiscoveryDrawerTopFilterViewBinding
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.ui.adapters.data.NavigationDrawerData
import com.kickstarter.ui.viewholders.KSViewHolder
class TopFilterViewHolder(
private val binding: DiscoveryDrawerTopFilterViewBinding,
private val delegate: Delegate
) : KSViewHolder(binding.root) {
private var item: NavigationDrawerData.Section.Row? = null
interface Delegate {
fun topFilterViewHolderRowClick(viewHolder: TopFilterViewHolder, row: NavigationDrawerData.Section.Row)
}
@Throws(Exception::class)
override fun bindData(data: Any?) {
item = ObjectUtils.requireNonNull(data as NavigationDrawerData.Section.Row?, NavigationDrawerData.Section.Row::class.java)
}
override fun onBind() {
val context = context()
val textColor = when {
item?.selected() == true ->
context.resources.getColor(R.color.accent, null)
else ->
context.resources.getColor(R.color.kds_support_700, null)
}
val iconDrawable = when {
item?.selected() == true ->
ResourcesCompat.getDrawable(context.resources, R.drawable.ic_label_green, null)
else ->
ResourcesCompat.getDrawable(context.resources, R.drawable.ic_label, null)
}
val backgroundDrawable = when {
item?.selected() == true ->
ResourcesCompat.getDrawable(context.resources, R.drawable.drawer_selected, null)
else -> null
}
binding.filterTextView.apply {
val ksString = requireNotNull(environment().ksString())
text = item?.params()?.filterString(context, ksString)
setCompoundDrawablesRelativeWithIntrinsicBounds(iconDrawable, null, null, null)
setTextColor(textColor)
background = backgroundDrawable
setOnClickListener {
textViewClick()
}
}
}
private fun textViewClick() {
item?.let { delegate.topFilterViewHolderRowClick(this, it) }
}
}
| apache-2.0 | 18d08f27f17ecbf83299447bbe52276d | 35.380952 | 130 | 0.665794 | 4.993464 | false | false | false | false |
ingokegel/intellij-community | plugins/evaluation-plugin/src/com/intellij/cce/evaluation/step/SetupStatsCollectorStep.kt | 5 | 6949 | package com.intellij.cce.evaluation.step
import com.intellij.cce.evaluation.UndoableEvaluationStep
import com.intellij.cce.evaluation.features.CCEContextFeatureProvider
import com.intellij.cce.evaluation.features.CCEElementFeatureProvider
import com.intellij.cce.workspace.EvaluationWorkspace
import com.intellij.codeInsight.completion.ml.ContextFeatureProvider
import com.intellij.codeInsight.completion.ml.ElementFeatureProvider
import com.intellij.completion.ml.experiment.ExperimentInfo
import com.intellij.completion.ml.experiment.ExperimentStatus
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.stats.completion.sender.StatisticSender
import com.intellij.stats.completion.storage.FilePathProvider
import com.intellij.stats.completion.storage.UniqueFilesProvider
import java.io.File
import java.nio.file.Paths
import java.util.*
class SetupStatsCollectorStep(private val project: Project,
private val experimentGroup: Int?,
private val logLocationAndTextItem: Boolean,
private val isHeadless: Boolean) : UndoableEvaluationStep {
companion object {
private val LOG = Logger.getInstance(SetupStatsCollectorStep::class.java)
private const val SEND_LOGS_REGISTRY = "completion.stats.send.logs"
private const val STATS_COLLECTOR_ID = "com.intellij.stats.completion"
private const val COLLECT_LOGS_HEADLESS_KEY = "completion.evaluation.headless"
fun statsCollectorLogsDirectory(): String = Paths.get(PathManager.getSystemPath(), "completion-stats-data").toString()
fun deleteLogs() {
val logsDirectory = File(statsCollectorLogsDirectory())
if (logsDirectory.exists()) {
logsDirectory.deleteRecursively()
}
}
fun isStatsCollectorEnabled(): Boolean = PluginManagerCore.getPlugin(PluginId.getId(STATS_COLLECTOR_ID))?.isEnabled ?: false
}
val serviceManager = ApplicationManager.getApplication() as ComponentManagerImpl
val initFileProvider: FilePathProvider? = serviceManager.getService(FilePathProvider::class.java)
val initStatisticSender: StatisticSender? = serviceManager.getService(StatisticSender::class.java)
val initExperimentStatus: ExperimentStatus? = serviceManager.getService(ExperimentStatus::class.java)
private var initSendLogsValue = false
private var initCollectLogsInHeadlessValue = false
private lateinit var elementFeatureProvider: CCEElementFeatureProvider
private lateinit var contextFeatureProvider: CCEContextFeatureProvider
override val name: String = "Setup Stats Collector step"
override val description: String = "Configure plugin Stats Collector if needed"
override fun start(workspace: EvaluationWorkspace): EvaluationWorkspace? {
if (!isStatsCollectorEnabled()) {
println("Stats Collector plugin isn't installed. Install it, if you want to save completion logs or features.")
return null
}
deleteLogs()
val filesProvider = object : UniqueFilesProvider("chunk", PathManager.getSystemPath(), "completion-stats-data", 10) {
override fun cleanupOldFiles() = Unit
}
val statisticSender = object : StatisticSender {
override fun sendStatsData(url: String) = Unit
}
try {
initSendLogsValue = Registry.`is`(SEND_LOGS_REGISTRY)
Registry.get(SEND_LOGS_REGISTRY).setValue(false)
} catch (e: MissingResourceException) {
LOG.warn("No registry for not sending logs", e)
}
if (isHeadless) {
initCollectLogsInHeadlessValue = java.lang.Boolean.getBoolean(COLLECT_LOGS_HEADLESS_KEY)
System.setProperty(COLLECT_LOGS_HEADLESS_KEY, "true")
}
val experimentStatus = object : ExperimentStatus {
// it allows to collect logs from all sessions (need a more explicit solution in stats-collector)
override fun forLanguage(language: Language): ExperimentInfo =
ExperimentInfo(true, version = experimentGroup ?: 0, shouldRank = false, shouldShowArrows = false, shouldCalculateFeatures = true)
// it allows to ignore experiment info during ranking
override fun isDisabled(): Boolean = true
override fun disable() = Unit
}
serviceManager.replaceRegularServiceInstance(FilePathProvider::class.java, filesProvider)
serviceManager.replaceRegularServiceInstance(StatisticSender::class.java, statisticSender)
serviceManager.replaceRegularServiceInstance(ExperimentStatus::class.java, experimentStatus)
LOG.runAndLogException { registerFeatureProvidersIfNeeded() }
return workspace
}
override fun undoStep(): UndoableEvaluationStep.UndoStep {
return object : UndoableEvaluationStep.UndoStep {
override val name: String = "Undo setup Stats Collector step"
override val description: String = "Return default behaviour of Stats Collector plugin"
override fun start(workspace: EvaluationWorkspace): EvaluationWorkspace {
if (initFileProvider != null)
serviceManager.replaceRegularServiceInstance(FilePathProvider::class.java, initFileProvider)
if (initStatisticSender != null)
serviceManager.replaceRegularServiceInstance(StatisticSender::class.java, initStatisticSender)
if (initExperimentStatus != null)
serviceManager.replaceRegularServiceInstance(ExperimentStatus::class.java, initExperimentStatus)
try {
Registry.get(SEND_LOGS_REGISTRY).setValue(initSendLogsValue)
}
catch (e: MissingResourceException) {
LOG.warn("No registry for not sending logs", e)
}
if (isHeadless) {
System.setProperty(COLLECT_LOGS_HEADLESS_KEY, initCollectLogsInHeadlessValue.toString())
}
LOG.runAndLogException { unregisterFeatureProviders() }
return workspace
}
}
}
private fun registerFeatureProvidersIfNeeded() {
contextFeatureProvider = CCEContextFeatureProvider(logLocationAndTextItem)
ContextFeatureProvider.EP_NAME.addExplicitExtension(Language.ANY, contextFeatureProvider)
if (!logLocationAndTextItem) return
elementFeatureProvider = CCEElementFeatureProvider()
ElementFeatureProvider.EP_NAME.addExplicitExtension(Language.ANY, elementFeatureProvider)
}
private fun unregisterFeatureProviders() {
ContextFeatureProvider.EP_NAME.removeExplicitExtension(Language.ANY, contextFeatureProvider)
if (!logLocationAndTextItem) return
ElementFeatureProvider.EP_NAME.removeExplicitExtension(Language.ANY, elementFeatureProvider)
}
} | apache-2.0 | 31ba8d3d4573ed85b835ea558000e8f8 | 49 | 138 | 0.769463 | 4.952958 | false | false | false | false |
leafclick/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/Generator.kt | 1 | 10591 | // Copyright 2000-2018 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 org.jetbrains.protocolModelGenerator
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.isNullOrEmpty
import gnu.trove.THashMap
import org.jetbrains.io.JsonReaderEx
import org.jetbrains.jsonProtocol.*
import org.jetbrains.protocolReader.TextOutput
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.net.URL
import java.nio.file.FileSystems
import java.nio.file.Files
import java.util.*
fun main(args: Array<String>) {
val outputDir = args[0]
val roots = IntRange(3, args.size - 1).map {
val schemaUrl = args[it]
val bytes: ByteArray
if (schemaUrl.startsWith("http")) {
bytes = loadBytes(URL(schemaUrl).openStream())
}
else {
bytes = Files.readAllBytes(FileSystems.getDefault().getPath(schemaUrl))
}
val reader = JsonReaderEx(bytes.toString(Charsets.UTF_8))
reader.isLenient = true
ProtocolSchemaReaderImpl().parseRoot(reader)
}
val mergedRoot = if (roots.size == 1) roots[0] else object : ProtocolMetaModel.Root {
override val version: ProtocolMetaModel.Version?
get() = roots[0].version
override fun domains(): List<ProtocolMetaModel.Domain> {
return ContainerUtil.concat(roots.map { it.domains() })
}
}
Generator(outputDir, args[1], args[2], mergedRoot)
}
private fun loadBytes(stream: InputStream): ByteArray {
val buffer = ByteArrayOutputStream(Math.max(stream.available(), 16 * 1024))
val bytes = ByteArray(1024 * 20)
while (true) {
val n = stream.read(bytes, 0, bytes.size)
if (n <= 0) {
break
}
buffer.write(bytes, 0, n)
}
buffer.close()
return buffer.toByteArray()
}
internal class Naming(val inputPackage: String, val requestClassName: String) {
val params = ClassNameScheme.Output("", inputPackage)
val additionalParam = ClassNameScheme.Output("", inputPackage)
val outputTypedef: ClassNameScheme = ClassNameScheme.Output("Typedef", inputPackage)
val commandResult = ClassNameScheme.Input("Result", inputPackage)
val eventData = ClassNameScheme.Input("EventData", inputPackage)
val inputValue = ClassNameScheme.Input("Value", inputPackage)
val inputEnum = ClassNameScheme.Input("", inputPackage)
val inputTypedef = ClassNameScheme.Input("Typedef", inputPackage)
val commonTypedef = ClassNameScheme.Common("Typedef", inputPackage)
}
/**
* Read metamodel and generates set of files with Java classes/interfaces for the protocol.
*/
internal class Generator(outputDir: String, private val rootPackage: String, requestClassName: String, metamodel: ProtocolMetaModel.Root) {
val jsonProtocolParserClassNames = ArrayList<String>()
val parserRootInterfaceItems = ArrayList<ParserRootInterfaceItem>()
val typeMap = TypeMap()
val nestedTypeMap = THashMap<NamePath, StandaloneType>()
val fileSet = FileSet(FileSystems.getDefault().getPath(outputDir))
val naming = Naming(rootPackage, requestClassName)
init {
val domainList = metamodel.domains()
val domainGeneratorMap = THashMap<String, DomainGenerator>()
for (domain in domainList) {
if (!INCLUDED_DOMAINS.contains(domain.domain())) {
System.out.println("Domain skipped: ${domain.domain()}")
continue
}
val fileUpdater = fileSet.createFileUpdater("${StringUtil.nullize(domain.domain()) ?: "protocol"}.kt")
val out = fileUpdater.out
out.append("// Generated source").newLine().append("package ").append(getPackageName(rootPackage, domain.domain())).newLine().newLine()
out.append("import org.jetbrains.jsonProtocol.*").newLine()
out.append("import org.jetbrains.io.JsonReaderEx").newLine()
val domainGenerator = DomainGenerator(this, domain, fileUpdater)
domainGeneratorMap.put(domain.domain(), domainGenerator)
domainGenerator.registerTypes()
out.newLine()
System.out.println("Domain generated: ${domain.domain()}")
}
typeMap.domainGeneratorMap = domainGeneratorMap
for (domainGenerator in domainGeneratorMap.values) {
domainGenerator.generateCommandsAndEvents()
}
val sharedFileUpdater = if (domainGeneratorMap.size == 1) {
domainGeneratorMap.values.first().fileUpdater
}
else {
val fileUpdater = fileSet.createFileUpdater("protocol.kt")
val out = fileUpdater.out
out.append("// Generated source").newLine().append("package ").append(rootPackage).newLine().newLine()
out.append("import org.jetbrains.jsonProtocol.*").newLine()
out.append("import org.jetbrains.io.JsonReaderEx").newLine()
fileUpdater
}
typeMap.generateRequestedTypes()
generateParserInterfaceList(sharedFileUpdater.out)
generateParserRoot(parserRootInterfaceItems, sharedFileUpdater.out)
fileSet.deleteOtherFiles()
for (domainGenerator in domainGeneratorMap.values) {
domainGenerator.fileUpdater.update()
}
if (domainGeneratorMap.size != 1) {
sharedFileUpdater.update()
}
}
fun resolveType(itemDescriptor: ItemDescriptor, scope: ResolveAndGenerateScope): TypeDescriptor {
return switchByType(itemDescriptor, object : TypeVisitor<TypeDescriptor> {
override fun visitRef(refName: String) = TypeDescriptor(resolveRefType(scope.getDomainName(), refName, scope.getTypeDirection()), itemDescriptor)
override fun visitBoolean() = TypeDescriptor(BoxableType.BOOLEAN, itemDescriptor)
override fun visitEnum(enumConstants: List<String>): TypeDescriptor {
assert(scope is MemberScope)
return TypeDescriptor((scope as MemberScope).generateEnum(itemDescriptor.description, enumConstants), itemDescriptor)
}
override fun visitString() = TypeDescriptor(BoxableType.STRING, itemDescriptor)
override fun visitInteger() = TypeDescriptor(BoxableType.INT, itemDescriptor)
override fun visitNumber() = TypeDescriptor(BoxableType.NUMBER, itemDescriptor)
override fun visitMap() = TypeDescriptor(BoxableType.MAP, itemDescriptor)
override fun visitArray(items: ProtocolMetaModel.ArrayItemType): TypeDescriptor {
val type = scope.resolveType(items).type
return TypeDescriptor(ListType(type), itemDescriptor, type == BoxableType.ANY_STRING)
}
override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?) = TypeDescriptor(scope.generateNestedObject(itemDescriptor.description, properties), itemDescriptor)
override fun visitUnknown() = TypeDescriptor(BoxableType.STRING, itemDescriptor, true)
})
}
private fun generateParserInterfaceList(out: TextOutput) {
// write classes in stable order
Collections.sort(jsonProtocolParserClassNames)
out.newLine().newLine().append("val PARSER_CLASSES = arrayOf(").newLine()
for (name in jsonProtocolParserClassNames) {
out.append(" ").append(name).append("::class.java")
if (name != jsonProtocolParserClassNames.last()) {
out.append(',')
}
out.newLine()
}
out.append(')')
}
private fun generateParserRoot(parserRootInterfaceItems: List<ParserRootInterfaceItem>, out: TextOutput) {
// write classes in stable order
Collections.sort<ParserRootInterfaceItem>(parserRootInterfaceItems)
out.newLine().newLine().append("interface ").append(READER_INTERFACE_NAME).append(" : org.jetbrains.jsonProtocol.ResponseResultReader").openBlock()
for (item in parserRootInterfaceItems) {
item.writeCode(out)
out.newLine()
}
out.append("override fun readResult(methodName: String, reader: org.jetbrains.io.JsonReaderEx): Any? = ")
out.append("when (methodName)").block {
for (item in parserRootInterfaceItems) {
out.append('"')
if (!item.domain.isEmpty()) {
out.append(item.domain).append('.')
}
out.append(item.name).append('"').append(" -> ")
item.appendReadMethodName(out)
out.append("(reader)").newLine()
}
out.append("else -> null")
}
out.closeBlock()
}
/**
* Resolve absolute (DOMAIN.TYPE) or relative (TYPE) type name
*/
private fun resolveRefType(scopeDomainName: String, refName: String, direction: TypeData.Direction): BoxableType {
val pos = refName.indexOf('.')
val domainName: String
val shortName: String
if (pos == -1) {
domainName = scopeDomainName
shortName = refName
}
else {
domainName = refName.substring(0, pos)
shortName = refName.substring(pos + 1)
}
return typeMap.resolve(domainName, shortName, direction)!!
}
}
const val READER_INTERFACE_NAME: String = "ProtocolResponseReader"
private val INCLUDED_DOMAINS = arrayOf("CSS", "Debugger", "DOM", "Inspector", "Log", "Network", "Page", "Runtime", "ServiceWorker",
"Tracing", "Target", "Overlay", "Console", "DOMDebugger", "Profiler", "HeapProfiler", "NodeWorker")
fun generateMethodNameSubstitute(originalName: String, out: TextOutput): String {
if (originalName != "this") {
return originalName
}
out.append("@org.jetbrains.jsonProtocol.ProtocolName(\"").append(originalName).append("\")").newLine()
return "get${Character.toUpperCase(originalName.get(0))}${originalName.substring(1)}"
}
fun capitalizeFirstChar(s: String): String {
if (!s.isEmpty() && s.get(0).isLowerCase()) {
return s.get(0).toUpperCase() + s.substring(1)
}
return s
}
fun <R> switchByType(typedObject: ItemDescriptor, visitor: TypeVisitor<R>): R {
val refName = if (typedObject is ItemDescriptor.Referenceable) typedObject.ref else null
if (refName != null) {
return visitor.visitRef(refName)
}
val typeName = typedObject.type
return when (typeName) {
BOOLEAN_TYPE -> visitor.visitBoolean()
STRING_TYPE, BINARY_TYPE -> if (typedObject.enum == null) visitor.visitString() else visitor.visitEnum(typedObject.enum!!)
INTEGER_TYPE, "int" -> visitor.visitInteger()
NUMBER_TYPE -> visitor.visitNumber()
ARRAY_TYPE -> visitor.visitArray(typedObject.items!!)
OBJECT_TYPE -> {
if (typedObject !is ItemDescriptor.Type) {
visitor.visitObject(null)
}
else {
val properties = typedObject.properties
return if (properties.isNullOrEmpty()) visitor.visitMap() else visitor.visitObject(properties)
}
}
ANY_TYPE, UNKNOWN_TYPE -> return visitor.visitUnknown()
else -> throw RuntimeException("Unrecognized type $typeName")
}
} | apache-2.0 | 546f6df643fba6c7a9e1a8be515fb625 | 37.376812 | 184 | 0.710981 | 4.372832 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/treeUtils.kt | 1 | 2993 | // 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 org.jetbrains.kotlin.nj2k.tree
import kotlin.jvm.internal.CallableReference
import kotlin.reflect.KProperty0
inline fun <reified T : JKElement> JKElement.parentOfType(): T? {
return generateSequence(parent) { it.parent }.filterIsInstance<T>().firstOrNull()
}
private fun <T : JKElement> KProperty0<Any>.detach(element: T) {
if (element.parent == null) return
// TODO: Fix when KT-16818 is implemented
val boundReceiver = (this as CallableReference).boundReceiver
require(boundReceiver != CallableReference.NO_RECEIVER)
require(boundReceiver is JKElement)
element.detach(boundReceiver)
}
fun <T : JKElement> KProperty0<T>.detached(): T =
get().also { detach(it) }
fun <T : JKElement> KProperty0<List<T>>.detached(): List<T> =
get().also { list -> list.forEach { detach(it) } }
fun <T : JKElement> T.detached(from: JKElement): T =
also { it.detach(from) }
fun <R : JKTreeElement, T> applyRecursive(
element: R,
data: T,
onElementChanged: (JKTreeElement, JKTreeElement) -> Unit,
func: (JKTreeElement, T) -> JKTreeElement
): R {
fun <T> applyRecursiveToList(
element: JKTreeElement,
child: List<JKTreeElement>,
iter: MutableListIterator<Any>,
data: T,
func: (JKTreeElement, T) -> JKTreeElement
): List<JKTreeElement> {
val newChild = child.map {
func(it, data)
}
child.forEach { it.detach(element) }
iter.set(child)
newChild.forEach { it.attach(element) }
newChild.zip(child).forEach { (old, new) ->
if (old !== new) {
onElementChanged(new, old)
}
}
return newChild
}
val iter = element.children.listIterator()
while (iter.hasNext()) {
val child = iter.next()
if (child is List<*>) {
@Suppress("UNCHECKED_CAST")
iter.set(applyRecursiveToList(element, child as List<JKTreeElement>, iter, data, func))
} else if (child is JKTreeElement) {
val newChild = func(child, data)
if (child !== newChild) {
child.detach(element)
iter.set(newChild)
newChild.attach(element)
onElementChanged(newChild, child)
}
} else {
error("unsupported child type: ${child::class}")
}
}
return element
}
fun <R : JKTreeElement> applyRecursive(
element: R,
func: (JKTreeElement) -> JKTreeElement
): R = applyRecursive(element, null, { _, _ -> }) { it, _ -> func(it) }
inline fun <reified T : JKTreeElement> T.copyTree(): T =
copy().withFormattingFrom(this) as T
inline fun <reified T : JKTreeElement> T.copyTreeAndDetach(): T =
copyTree().also {
if (it.parent != null) it.detach(it.parent!!)
}
| apache-2.0 | bb2ff1802d1a591ba9d4a65f237b9836 | 29.85567 | 158 | 0.614434 | 4.01745 | false | false | false | false |
itachi1706/DroidEggs | app/src/main/java/com/itachi1706/droideggs/s_egg/easter_egg/widget/PaintChipsWidget.kt | 1 | 14217 | /*
* Copyright (C) 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 com.itachi1706.droideggs.s_egg.easter_egg.widget
import android.annotation.TargetApi
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.util.SizeF
import android.widget.RemoteViews
import androidx.annotation.RequiresApi
import com.itachi1706.droideggs.R
/**
* A homescreen widget to explore the current dynamic system theme.
*/
@TargetApi(Build.VERSION_CODES.Q)
class PaintChipsWidget : AppWidgetProvider() {
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
override fun onAppWidgetOptionsChanged(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int,
newOptions: Bundle?
) {
// Log.v(TAG, "onAppWidgetOptionsChanged: id=${appWidgetId}")
updateAppWidget(context, appWidgetManager, appWidgetId)
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
}
}
const val TAG = "PaintChips"
val SHADE_NUMBERS = intArrayOf(0, 10, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000)
val COLORS_NEUTRAL1 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
intArrayOf(
android.R.color.system_neutral1_0,
android.R.color.system_neutral1_10,
android.R.color.system_neutral1_50,
android.R.color.system_neutral1_100,
android.R.color.system_neutral1_200,
android.R.color.system_neutral1_300,
android.R.color.system_neutral1_400,
android.R.color.system_neutral1_500,
android.R.color.system_neutral1_600,
android.R.color.system_neutral1_700,
android.R.color.system_neutral1_800,
android.R.color.system_neutral1_900,
android.R.color.system_neutral1_1000
)
} else {
intArrayOf(
R.color.system_neutral1_0,
R.color.system_neutral1_10,
R.color.system_neutral1_50,
R.color.system_neutral1_100,
R.color.system_neutral1_200,
R.color.system_neutral1_300,
R.color.system_neutral1_400,
R.color.system_neutral1_500,
R.color.system_neutral1_600,
R.color.system_neutral1_700,
R.color.system_neutral1_800,
R.color.system_neutral1_900,
R.color.system_neutral1_1000
)
}
val COLORS_NEUTRAL2 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
intArrayOf(
android.R.color.system_neutral2_0,
android.R.color.system_neutral2_10,
android.R.color.system_neutral2_50,
android.R.color.system_neutral2_100,
android.R.color.system_neutral2_200,
android.R.color.system_neutral2_300,
android.R.color.system_neutral2_400,
android.R.color.system_neutral2_500,
android.R.color.system_neutral2_600,
android.R.color.system_neutral2_700,
android.R.color.system_neutral2_800,
android.R.color.system_neutral2_900,
android.R.color.system_neutral2_1000
)
} else {
intArrayOf(
R.color.system_neutral2_0,
R.color.system_neutral2_10,
R.color.system_neutral2_50,
R.color.system_neutral2_100,
R.color.system_neutral2_200,
R.color.system_neutral2_300,
R.color.system_neutral2_400,
R.color.system_neutral2_500,
R.color.system_neutral2_600,
R.color.system_neutral2_700,
R.color.system_neutral2_800,
R.color.system_neutral2_900,
R.color.system_neutral2_1000
)
}
var COLORS_ACCENT1 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
intArrayOf(
android.R.color.system_accent1_0,
android.R.color.system_accent1_10,
android.R.color.system_accent1_50,
android.R.color.system_accent1_100,
android.R.color.system_accent1_200,
android.R.color.system_accent1_300,
android.R.color.system_accent1_400,
android.R.color.system_accent1_500,
android.R.color.system_accent1_600,
android.R.color.system_accent1_700,
android.R.color.system_accent1_800,
android.R.color.system_accent1_900,
android.R.color.system_accent1_1000
)
} else {
intArrayOf(
R.color.system_accent1_0,
R.color.system_accent1_10,
R.color.system_accent1_50,
R.color.system_accent1_100,
R.color.system_accent1_200,
R.color.system_accent1_300,
R.color.system_accent1_400,
R.color.system_accent1_500,
R.color.system_accent1_600,
R.color.system_accent1_700,
R.color.system_accent1_800,
R.color.system_accent1_900,
R.color.system_accent1_1000
)
}
var COLORS_ACCENT2 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
intArrayOf(
android.R.color.system_accent2_0,
android.R.color.system_accent2_10,
android.R.color.system_accent2_50,
android.R.color.system_accent2_100,
android.R.color.system_accent2_200,
android.R.color.system_accent2_300,
android.R.color.system_accent2_400,
android.R.color.system_accent2_500,
android.R.color.system_accent2_600,
android.R.color.system_accent2_700,
android.R.color.system_accent2_800,
android.R.color.system_accent2_900,
android.R.color.system_accent2_1000
)
} else {
intArrayOf(
R.color.system_accent2_0,
R.color.system_accent2_10,
R.color.system_accent2_50,
R.color.system_accent2_100,
R.color.system_accent2_200,
R.color.system_accent2_300,
R.color.system_accent2_400,
R.color.system_accent2_500,
R.color.system_accent2_600,
R.color.system_accent2_700,
R.color.system_accent2_800,
R.color.system_accent2_900,
R.color.system_accent2_1000
)
}
var COLORS_ACCENT3 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
intArrayOf(
android.R.color.system_accent3_0,
android.R.color.system_accent3_10,
android.R.color.system_accent3_50,
android.R.color.system_accent3_100,
android.R.color.system_accent3_200,
android.R.color.system_accent3_300,
android.R.color.system_accent3_400,
android.R.color.system_accent3_500,
android.R.color.system_accent3_600,
android.R.color.system_accent3_700,
android.R.color.system_accent3_800,
android.R.color.system_accent3_900,
android.R.color.system_accent3_1000
)
} else {
intArrayOf(
R.color.system_accent3_0,
R.color.system_accent3_10,
R.color.system_accent3_50,
R.color.system_accent3_100,
R.color.system_accent3_200,
R.color.system_accent3_300,
R.color.system_accent3_400,
R.color.system_accent3_500,
R.color.system_accent3_600,
R.color.system_accent3_700,
R.color.system_accent3_800,
R.color.system_accent3_900,
R.color.system_accent3_1000
)
}
var COLOR_NAMES = arrayOf(
"N1", "N2", "A1", "A2", "A3"
)
var COLORS = arrayOf(
COLORS_NEUTRAL1,
COLORS_NEUTRAL2,
COLORS_ACCENT1,
COLORS_ACCENT2,
COLORS_ACCENT3
)
@RequiresApi(Build.VERSION_CODES.Q)
internal fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
// val opts = appWidgetManager.getAppWidgetOptions(appWidgetId)
// Log.v(TAG, "requested sizes=${opts[OPTION_APPWIDGET_SIZES]}")
val allSizes = mapOf(
SizeF(50f, 50f)
to buildWidget(context, 1, 1, ClickBehavior.LAUNCH),
SizeF(100f, 50f)
to buildWidget(context, 1, 2, ClickBehavior.LAUNCH),
SizeF(150f, 50f)
to buildWidget(context, 1, 3, ClickBehavior.LAUNCH),
SizeF(200f, 50f)
to buildWidget(context, 1, 4, ClickBehavior.LAUNCH),
SizeF(250f, 50f)
to buildWidget(context, 1, 5, ClickBehavior.LAUNCH),
SizeF(50f, 120f)
to buildWidget(context, 3, 1, ClickBehavior.LAUNCH),
SizeF(100f, 120f)
to buildWidget(context, 3, 2, ClickBehavior.LAUNCH),
SizeF(150f, 120f)
to buildWidget(context, 3, 3, ClickBehavior.LAUNCH),
SizeF(200f, 120f)
to buildWidget(context, 3, 4, ClickBehavior.LAUNCH),
SizeF(250f, 120f)
to buildWidget(context, 3, 5, ClickBehavior.LAUNCH),
SizeF(50f, 250f)
to buildWidget(context, 5, 1, ClickBehavior.LAUNCH),
SizeF(100f, 250f)
to buildWidget(context, 5, 2, ClickBehavior.LAUNCH),
SizeF(150f, 250f)
to buildWidget(context, 5, 3, ClickBehavior.LAUNCH),
SizeF(200f, 250f)
to buildWidget(context, 5, 4, ClickBehavior.LAUNCH),
SizeF(250f, 250f)
to buildWidget(context, 5, 5, ClickBehavior.LAUNCH),
SizeF(300f, 300f)
to buildWidget(context, SHADE_NUMBERS.size, COLORS.size, ClickBehavior.LAUNCH)
)
// Instruct the widget manager to update the widget
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
appWidgetManager.updateAppWidget(appWidgetId, RemoteViews(allSizes))
} else {
appWidgetManager.updateAppWidget(appWidgetId, RemoteViews(allSizes.entries.first().value))
}
}
@RequiresApi(Build.VERSION_CODES.Q)
fun buildFullWidget(context: Context, clickable: ClickBehavior): RemoteViews {
return buildWidget(context, SHADE_NUMBERS.size, COLORS.size, clickable)
}
@RequiresApi(Build.VERSION_CODES.Q)
fun buildWidget(context: Context, numShades: Int, numColors: Int, clickable: ClickBehavior):
RemoteViews {
val grid = RemoteViews(context.packageName, R.layout.s_paint_chips_grid)
// shouldn't be necessary but sometimes the RV instructions get played twice in launcher.
grid.removeAllViews(R.id.paint_grid)
grid.setInt(R.id.paint_grid, "setRowCount", numShades)
grid.setInt(R.id.paint_grid, "setColumnCount", numColors)
Log.v(TAG, "building widget: shade rows=$numShades, color columns=$numColors")
COLORS.forEachIndexed colorLoop@{ i, colorlist ->
when (colorlist) {
COLORS_NEUTRAL1 -> if (numColors < 2) return@colorLoop
COLORS_NEUTRAL2 -> if (numColors < 4) return@colorLoop
COLORS_ACCENT2 -> if (numColors < 3) return@colorLoop
COLORS_ACCENT3 -> if (numColors < 5) return@colorLoop
else -> {} // always do ACCENT1
}
colorlist.forEachIndexed shadeLoop@{ j, resId ->
when (SHADE_NUMBERS[j]) {
500 -> {}
300, 700 -> if (numShades < 3) return@shadeLoop
100, 900 -> if (numShades < 5) return@shadeLoop
else -> if (numShades < SHADE_NUMBERS.size) return@shadeLoop
}
val cell = RemoteViews(context.packageName, R.layout.s_paint_chip)
cell.setTextViewText(R.id.chip, "${COLOR_NAMES[i]}-${SHADE_NUMBERS[j]}")
val textColor = if (SHADE_NUMBERS[j] > 500)
colorlist[0]
else colorlist[colorlist.size - 1]
cell.setTextColor(R.id.chip, context.getColor(textColor))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
cell.setColorStateList(R.id.chip, "setBackgroundTintList", resId)
}
val text = """
${COLOR_NAMES[i]}-${SHADE_NUMBERS[j]} (@${
context.resources.getResourceName(resId) })
currently: #${ String.format("%06x", context.getColor(resId) and 0xFFFFFF) }
""".trimIndent()
when (clickable) {
ClickBehavior.SHARE -> cell.setOnClickPendingIntent(
R.id.chip,
makeTextSharePendingIntent(context, text)
)
ClickBehavior.LAUNCH -> cell.setOnClickPendingIntent(
R.id.chip,
makeActivityLaunchPendingIntent(context)
)
ClickBehavior.NONE -> { }
}
grid.addView(R.id.paint_grid, cell)
}
}
return grid
}
enum class ClickBehavior {
NONE,
SHARE,
LAUNCH
}
@RequiresApi(Build.VERSION_CODES.Q)
fun makeTextSharePendingIntent(context: Context, text: String): PendingIntent {
val shareIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, text)
type = "text/plain"
}
val chooserIntent = Intent.createChooser(shareIntent, null).apply {
identifier = text // incredible quality-of-life improvement, thanks framework team
}
return PendingIntent.getActivity(context, 0, chooserIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
}
@RequiresApi(Build.VERSION_CODES.M)
fun makeActivityLaunchPendingIntent(context: Context): PendingIntent {
return PendingIntent.getActivity(context, 0,
Intent().apply {
component = ComponentName(context, PaintChipsActivity::class.java)
action = Intent.ACTION_MAIN
},
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
}
| apache-2.0 | 7722d933b86ad91edcc2775710407934 | 34.811083 | 98 | 0.641345 | 3.629563 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/coroutines/controlFlow_finally2.kt | 4 | 1145 | /*
* Copyright 2010-2018 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 codegen.coroutines.controlFlow_finally2
import kotlin.test.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resumeWith(result: Result<Any?>) { result.getOrThrow() }
}
suspend fun s1(): Int = suspendCoroutineUninterceptedOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
fun f1(): Int {
println("f1")
return 117
}
fun f2(): Int {
println("f2")
return 1
}
fun f3(x: Int, y: Int): Int {
println("f3")
return x + y
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
@Test fun runTest() {
var result = 0
builder {
val x = try {
f1()
} catch (t: Throwable) {
f2()
} finally {
s1()
}
result = x
}
println(result)
} | apache-2.0 | e6365673169ab338eaea3ea7868a3948 | 18.758621 | 115 | 0.622707 | 3.791391 | false | true | false | false |
androidx/androidx | room/room-common/src/main/java/androidx/room/OnConflictStrategy.kt | 3 | 2984 | /*
* Copyright (C) 2017 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.room
import androidx.annotation.IntDef
/**
* Set of conflict handling strategies for various {@link Dao} methods.
*/
@Retention(AnnotationRetention.BINARY)
@Suppress("DEPRECATION")
@IntDef(
OnConflictStrategy.NONE,
OnConflictStrategy.REPLACE,
OnConflictStrategy.ROLLBACK,
OnConflictStrategy.ABORT,
OnConflictStrategy.FAIL,
OnConflictStrategy.IGNORE
)
public annotation class OnConflictStrategy {
public companion object {
/**
* OnConflict strategy constant used by default when no other strategy is set. Using it
* prevents Room from generating ON CONFLICT clause. It may be useful when there is a need
* to use ON CONFLICT clause within a trigger. The runtime behavior is the same as
* when [ABORT] strategy is applied. *The transaction is rolled back.*
*/
public const val NONE: Int = 0
/**
* OnConflict strategy constant to replace the old data and continue the transaction.
*
* An [Insert] DAO method that returns the inserted rows ids will never return -1 since
* this strategy will always insert a row even if there is a conflict.
*/
public const val REPLACE: Int = 1
/**
* OnConflict strategy constant to rollback the transaction.
*
* @deprecated Does not work with Android's current SQLite bindings. Use [ABORT] to
* roll back the transaction.
*/
@Deprecated("Use ABORT instead.")
public const val ROLLBACK: Int = 2
/**
* OnConflict strategy constant to abort the transaction. *The transaction is rolled
* back.*
*/
public const val ABORT: Int = 3
/**
* OnConflict strategy constant to fail the transaction.
*
* @deprecated Does not work as expected. The transaction is rolled back. Use
* [ABORT].
*/
@Deprecated("Use ABORT instead.")
public const val FAIL: Int = 4
/**
* OnConflict strategy constant to ignore the conflict.
*
* An [Insert] DAO method that returns the inserted rows ids will return -1 for rows
* that are not inserted since this strategy will ignore the row if there is a conflict.
*/
public const val IGNORE: Int = 5
}
}
| apache-2.0 | dc0151d9441e6f8c5db3a4640bffe01f | 37.25641 | 98 | 0.656836 | 4.867863 | false | false | false | false |
androidx/androidx | health/health-services-client/src/main/java/androidx/health/services/client/impl/ServiceBackedMeasureClient.kt | 3 | 5204 | /*
* Copyright (C) 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.health.services.client.impl
import android.content.Context
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import androidx.core.content.ContextCompat
import androidx.health.services.client.MeasureCallback
import androidx.health.services.client.MeasureClient
import androidx.health.services.client.data.DeltaDataType
import androidx.health.services.client.data.MeasureCapabilities
import androidx.health.services.client.impl.IpcConstants.MEASURE_API_BIND_ACTION
import androidx.health.services.client.impl.IpcConstants.SERVICE_PACKAGE_NAME
import androidx.health.services.client.impl.MeasureCallbackStub.MeasureCallbackCache
import androidx.health.services.client.impl.internal.HsConnectionManager
import androidx.health.services.client.impl.internal.StatusCallback
import androidx.health.services.client.impl.ipc.Client
import androidx.health.services.client.impl.ipc.ClientConfiguration
import androidx.health.services.client.impl.ipc.internal.ConnectionManager
import androidx.health.services.client.impl.request.CapabilitiesRequest
import androidx.health.services.client.impl.request.MeasureRegistrationRequest
import androidx.health.services.client.impl.request.MeasureUnregistrationRequest
import com.google.common.util.concurrent.FutureCallback
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.SettableFuture
import java.util.concurrent.Executor
/**
* [MeasureClient] implementation that is backed by Health Services.
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
public class ServiceBackedMeasureClient(
private val context: Context,
connectionManager: ConnectionManager = HsConnectionManager.getInstance(context)
) :
MeasureClient,
Client<IMeasureApiService>(
CLIENT_CONFIGURATION,
connectionManager,
{ binder -> IMeasureApiService.Stub.asInterface(binder) },
{ service -> service.apiVersion }
) {
override fun registerMeasureCallback(dataType: DeltaDataType<*, *>, callback: MeasureCallback) {
registerMeasureCallback(dataType, ContextCompat.getMainExecutor(context), callback)
}
override fun registerMeasureCallback(
dataType: DeltaDataType<*, *>,
executor: Executor,
callback: MeasureCallback
) {
val request = MeasureRegistrationRequest(context.packageName, dataType)
val callbackStub = MeasureCallbackCache.INSTANCE.getOrCreate(dataType, executor, callback)
val future =
registerListener(callbackStub.listenerKey) { service, result: SettableFuture<Void?> ->
service.registerCallback(
request,
callbackStub,
StatusCallback(result)
)
}
Futures.addCallback(
future,
object : FutureCallback<Void?> {
override fun onSuccess(result: Void?) {
callback.onRegistered()
}
override fun onFailure(t: Throwable) {
callback.onRegistrationFailed(t)
}
},
executor)
}
override fun unregisterMeasureCallbackAsync(
dataType: DeltaDataType<*, *>,
callback: MeasureCallback
): ListenableFuture<Void> {
val callbackStub =
MeasureCallbackCache.INSTANCE.remove(dataType, callback)
?: return Futures.immediateFailedFuture(
IllegalArgumentException("Given callback was not registered.")
)
val request = MeasureUnregistrationRequest(context.packageName, dataType)
return unregisterListener(callbackStub.listenerKey) { service, resultFuture ->
service.unregisterCallback(request, callbackStub, StatusCallback(resultFuture))
}
}
override fun getCapabilitiesAsync(): ListenableFuture<MeasureCapabilities> =
Futures.transform(
execute { service ->
service.getCapabilities(CapabilitiesRequest(context.packageName))
},
{ response -> response!!.measureCapabilities },
ContextCompat.getMainExecutor(context)
)
internal companion object {
internal const val CLIENT = "HealthServicesMeasureClient"
internal val CLIENT_CONFIGURATION =
ClientConfiguration(CLIENT, SERVICE_PACKAGE_NAME, MEASURE_API_BIND_ACTION)
}
}
| apache-2.0 | 51fc44dea4505517f6c42332a93785ef | 40.632 | 100 | 0.719639 | 5.047527 | false | false | false | false |
androidx/androidx | camera/integration-tests/extensionstestapp/src/main/java/androidx/camera/integration/extensions/Camera2ExtensionsActivity.kt | 3 | 45889 | /*
* Copyright 2022 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.camera.integration.extensions
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraExtensionCharacteristics
import android.hardware.camera2.CameraExtensionSession
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CameraMetadata
import android.hardware.camera2.CaptureFailure
import android.hardware.camera2.CaptureRequest
import android.hardware.camera2.params.ExtensionSessionConfiguration
import android.hardware.camera2.params.OutputConfiguration
import android.hardware.camera2.params.SessionConfiguration
import android.hardware.camera2.params.SessionConfiguration.SESSION_REGULAR
import android.media.ImageReader
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.util.Log
import android.util.Size
import android.view.Menu
import android.view.MenuItem
import android.view.Surface
import android.view.TextureView
import android.view.View
import android.view.ViewStub
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.impl.utils.futures.Futures
import androidx.camera.integration.extensions.IntentExtraKey.INTENT_EXTRA_KEY_CAMERA_ID
import androidx.camera.integration.extensions.IntentExtraKey.INTENT_EXTRA_KEY_ERROR_CODE
import androidx.camera.integration.extensions.IntentExtraKey.INTENT_EXTRA_KEY_EXTENSION_MODE
import androidx.camera.integration.extensions.IntentExtraKey.INTENT_EXTRA_KEY_IMAGE_ROTATION_DEGREES
import androidx.camera.integration.extensions.IntentExtraKey.INTENT_EXTRA_KEY_IMAGE_URI
import androidx.camera.integration.extensions.IntentExtraKey.INTENT_EXTRA_KEY_REQUEST_CODE
import androidx.camera.integration.extensions.ValidationErrorCode.ERROR_CODE_EXTENSION_MODE_NOT_SUPPORT
import androidx.camera.integration.extensions.ValidationErrorCode.ERROR_CODE_NONE
import androidx.camera.integration.extensions.ValidationErrorCode.ERROR_CODE_SAVE_IMAGE_FAILED
import androidx.camera.integration.extensions.utils.Camera2ExtensionsUtil.getCamera2ExtensionModeStringFromId
import androidx.camera.integration.extensions.utils.Camera2ExtensionsUtil.getLensFacingCameraId
import androidx.camera.integration.extensions.utils.Camera2ExtensionsUtil.isCamera2ExtensionModeSupported
import androidx.camera.integration.extensions.utils.Camera2ExtensionsUtil.pickPreviewResolution
import androidx.camera.integration.extensions.utils.Camera2ExtensionsUtil.pickStillImageResolution
import androidx.camera.integration.extensions.utils.FileUtil
import androidx.camera.integration.extensions.utils.TransformUtil.calculateRelativeImageRotationDegrees
import androidx.camera.integration.extensions.utils.TransformUtil.surfaceRotationToRotationDegrees
import androidx.camera.integration.extensions.utils.TransformUtil.transformTextureView
import androidx.camera.integration.extensions.validation.CameraValidationResultActivity
import androidx.concurrent.futures.CallbackToFutureAdapter
import androidx.concurrent.futures.CallbackToFutureAdapter.Completer
import androidx.core.util.Preconditions
import androidx.lifecycle.lifecycleScope
import androidx.test.espresso.idling.CountingIdlingResource
import com.google.common.util.concurrent.ListenableFuture
import java.text.Format
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.suspendCancellableCoroutine
private const val TAG = "Camera2ExtensionsAct~"
private const val EXTENSION_MODE_INVALID = -1
private const val FRAMES_UNTIL_VIEW_IS_READY = 10
@RequiresApi(31)
class Camera2ExtensionsActivity : AppCompatActivity() {
private lateinit var cameraManager: CameraManager
/**
* A reference to the opened [CameraDevice].
*/
private var cameraDevice: CameraDevice? = null
/**
* The current camera capture session. Use Any type to store it because it might be either a
* CameraCaptureSession instance if current is in normal mode, or, it might be a
* CameraExtensionSession instance if current is in Camera2 extension mode.
*/
private var cameraCaptureSession: Any? = null
private var currentCameraId = "0"
private lateinit var backCameraId: String
private lateinit var frontCameraId: String
private var cameraSensorRotationDegrees = 0
/**
* Still capture image reader
*/
private var stillImageReader: ImageReader? = null
/**
* Camera extension characteristics for the current camera device.
*/
private lateinit var extensionCharacteristics: CameraExtensionCharacteristics
/**
* Flag whether we should restart preview after an extension switch.
*/
private var restartPreview = false
/**
* Flag whether we should restart after an camera switch.
*/
private var restartCamera = false
/**
* Track current extension type and index.
*/
private var currentExtensionMode = EXTENSION_MODE_INVALID
private var currentExtensionIdx = -1
private val supportedExtensionModes = mutableListOf<Int>()
private lateinit var containerView: View
private lateinit var textureView: TextureView
private lateinit var previewSurface: Surface
private val surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(
surfaceTexture: SurfaceTexture,
with: Int,
height: Int
) {
previewSurface = Surface(surfaceTexture)
setupAndStartPreview(currentCameraId, currentExtensionMode)
}
override fun onSurfaceTextureSizeChanged(
surfaceTexture: SurfaceTexture,
with: Int,
height: Int
) {
}
override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean {
return true
}
override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {
if (captureProcessStartedIdlingResource.isIdleNow &&
receivedPreviewFrameCount.getAndIncrement() >= FRAMES_UNTIL_VIEW_IS_READY &&
!previewIdlingResource.isIdleNow
) {
previewIdlingResource.decrement()
}
}
}
private val captureCallbacks = object : CameraExtensionSession.ExtensionCaptureCallback() {
override fun onCaptureProcessStarted(
session: CameraExtensionSession,
request: CaptureRequest
) {
if (receivedCaptureProcessStartedCount.getAndIncrement() >=
FRAMES_UNTIL_VIEW_IS_READY && !captureProcessStartedIdlingResource.isIdleNow
) {
captureProcessStartedIdlingResource.decrement()
}
}
override fun onCaptureFailed(session: CameraExtensionSession, request: CaptureRequest) {
Log.e(TAG, "onCaptureFailed!!")
}
}
private val captureCallbacksNormalMode = object : CameraCaptureSession.CaptureCallback() {
override fun onCaptureStarted(
session: CameraCaptureSession,
request: CaptureRequest,
timestamp: Long,
frameNumber: Long
) {
if (receivedCaptureProcessStartedCount.getAndIncrement() >=
FRAMES_UNTIL_VIEW_IS_READY && !captureProcessStartedIdlingResource.isIdleNow
) {
captureProcessStartedIdlingResource.decrement()
}
}
}
private var restartOnStart = false
private var activityStopped = false
private val cameraTaskDispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
private var imageSaveTerminationFuture: ListenableFuture<Any?> = Futures.immediateFuture(null)
/**
* Used to wait for the capture session is configured.
*/
private val captureSessionConfiguredIdlingResource =
CountingIdlingResource("captureSessionConfigured").apply { increment() }
/**
* Used to wait for the ExtensionCaptureCallback#onCaptureProcessStarted is called which means
* an image is captured and extension processing is triggered.
*/
private val captureProcessStartedIdlingResource =
CountingIdlingResource("captureProcessStarted").apply { increment() }
/**
* Used to wait for the preview is ready. This will become idle after
* captureProcessStartedIdlingResource becomes idle and
* [SurfaceTextureListener#onSurfaceTextureUpdated()] is also called. It means that there has
* been images captured to trigger the extension processing and the preview's SurfaceTexture is
* also updated by [SurfaceTexture#updateTexImage()] calls.
*/
private val previewIdlingResource = CountingIdlingResource("preview").apply { increment() }
/**
* Used to trigger a picture taking action and waits for the image being saved.
*/
private val imageSavedIdlingResource = CountingIdlingResource("imageSaved")
private val receivedCaptureProcessStartedCount: AtomicLong = AtomicLong(0)
private val receivedPreviewFrameCount: AtomicLong = AtomicLong(0)
private lateinit var sessionImageUriSet: SessionMediaUriSet
/**
* Stores the request code passed from the caller activity.
*/
private var requestCode = -1
/**
* This will be true if the activity is called by other activity to request capturing an image.
*/
private var isRequestMode = false
/**
* The result intent that saves the image capture request results.
*/
private lateinit var result: Intent
private var extensionModeEnabled = true
/**
* A [HandlerThread] used for normal mode camera capture operations
*/
private val normalModeCaptureThread = HandlerThread("CameraThread").apply { start() }
/**
* [Handler] corresponding to [normalModeCaptureThread]
*/
private val normalModeCaptureHandler = Handler(normalModeCaptureThread.looper)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate()")
setContentView(R.layout.activity_camera_extensions)
cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
backCameraId = getLensFacingCameraId(cameraManager, CameraCharacteristics.LENS_FACING_BACK)
frontCameraId =
getLensFacingCameraId(cameraManager, CameraCharacteristics.LENS_FACING_FRONT)
currentCameraId = if (isCameraSupportExtensions(backCameraId)) {
backCameraId
} else if (isCameraSupportExtensions(frontCameraId)) {
frontCameraId
} else {
Toast.makeText(
this,
"Can't find camera supporting Camera2 extensions.",
Toast.LENGTH_SHORT
).show()
closeCameraAndStartActivity(CameraExtensionsActivity::class.java.name)
return
}
sessionImageUriSet = SessionMediaUriSet(contentResolver)
// Gets params from extra bundle
intent.extras?.let { bundle ->
currentCameraId = bundle.getString(INTENT_EXTRA_KEY_CAMERA_ID, currentCameraId)
currentExtensionMode =
bundle.getInt(INTENT_EXTRA_KEY_EXTENSION_MODE, currentExtensionMode)
requestCode = bundle.getInt(INTENT_EXTRA_KEY_REQUEST_CODE, -1)
isRequestMode = requestCode != -1
if (isRequestMode) {
setupForRequestMode()
}
}
updateExtensionInfo()
setupTextureView()
enableUiControl(false)
setupUiControl()
}
private fun setupForRequestMode() {
result = Intent()
result.putExtra(INTENT_EXTRA_KEY_EXTENSION_MODE, currentExtensionMode)
result.putExtra(INTENT_EXTRA_KEY_ERROR_CODE, ERROR_CODE_NONE)
setResult(requestCode, result)
if (!isCamera2ExtensionModeSupported(this, currentCameraId, currentExtensionMode)) {
result.putExtra(INTENT_EXTRA_KEY_ERROR_CODE, ERROR_CODE_EXTENSION_MODE_NOT_SUPPORT)
finish()
return
}
val lensFacing = cameraManager.getCameraCharacteristics(
currentCameraId)[CameraCharacteristics.LENS_FACING]
supportActionBar?.title = resources.getString(R.string.camera2_extensions_validator)
supportActionBar!!.subtitle =
"Camera $currentCameraId [${getLensFacingString(lensFacing!!)}][${
getCamera2ExtensionModeStringFromId(currentExtensionMode)
}]"
findViewById<Button>(R.id.PhotoToggle).visibility = View.INVISIBLE
findViewById<Button>(R.id.Switch).visibility = View.INVISIBLE
setExtensionToggleButtonResource()
findViewById<ImageButton>(R.id.ExtensionToggle).apply {
visibility = View.VISIBLE
setOnClickListener {
val cameraId = currentCameraId
val extensionMode = currentExtensionMode
restartPreview = true
lifecycleScope.launch(cameraTaskDispatcher) {
extensionModeEnabled = !extensionModeEnabled
if (cameraCaptureSession == null) {
setupAndStartPreview(cameraId, extensionMode)
} else {
closeCaptureSessionAsync()
}
val extensionEnabled = extensionModeEnabled
lifecycleScope.launch(Dispatchers.Main) {
setExtensionToggleButtonResource()
if (extensionEnabled) {
Toast.makeText(
this@Camera2ExtensionsActivity,
"Effect is enabled!",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
this@Camera2ExtensionsActivity,
"Effect is disabled!",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
}
@Suppress("DEPRECATION") // EXTENSION_BEAUTY
private fun setExtensionToggleButtonResource() {
val extensionToggleButton: ImageButton = findViewById(R.id.ExtensionToggle)
if (!extensionModeEnabled) {
extensionToggleButton.setImageResource(R.drawable.outline_block)
return
}
val resourceId = when (currentExtensionMode) {
CameraExtensionCharacteristics.EXTENSION_HDR -> R.drawable.outline_hdr_on
CameraExtensionCharacteristics.EXTENSION_BOKEH -> R.drawable.outline_portrait
CameraExtensionCharacteristics.EXTENSION_NIGHT -> R.drawable.outline_bedtime
CameraExtensionCharacteristics.EXTENSION_BEAUTY ->
R.drawable.outline_face_retouching_natural
CameraExtensionCharacteristics.EXTENSION_AUTOMATIC -> R.drawable.outline_auto_awesome
else -> throw IllegalArgumentException("Invalid extension mode!")
}
extensionToggleButton.setImageResource(resourceId)
}
private fun getLensFacingString(lensFacing: Int) = when (lensFacing) {
CameraMetadata.LENS_FACING_BACK -> "BACK"
CameraMetadata.LENS_FACING_FRONT -> "FRONT"
CameraMetadata.LENS_FACING_EXTERNAL -> "EXTERNAL"
else -> throw IllegalArgumentException("Invalid lens facing!!")
}
private fun isCameraSupportExtensions(cameraId: String): Boolean {
val characteristics = cameraManager.getCameraExtensionCharacteristics(cameraId)
return characteristics.supportedExtensions.isNotEmpty()
}
private fun updateExtensionInfo() {
Log.d(
TAG,
"updateExtensionInfo() - camera Id: $currentCameraId, current extension mode: " +
"$currentExtensionMode"
)
extensionCharacteristics = cameraManager.getCameraExtensionCharacteristics(currentCameraId)
supportedExtensionModes.clear()
supportedExtensionModes.addAll(extensionCharacteristics.supportedExtensions)
cameraSensorRotationDegrees = cameraManager.getCameraCharacteristics(
currentCameraId)[CameraCharacteristics.SENSOR_ORIENTATION] ?: 0
currentExtensionIdx = -1
// Checks whether the original selected extension mode is supported by the new target camera
if (currentExtensionMode != EXTENSION_MODE_INVALID) {
for (i in 0..supportedExtensionModes.size) {
if (supportedExtensionModes[i] == currentExtensionMode) {
currentExtensionIdx = i
break
}
}
}
// Switches to the first supported extension mode if the original selected mode is not
// supported
if (currentExtensionIdx == -1) {
currentExtensionIdx = 0
currentExtensionMode = supportedExtensionModes[0]
}
}
private fun setupTextureView() {
val viewFinderStub = findViewById<ViewStub>(R.id.viewFinderStub)
viewFinderStub.layoutResource = R.layout.full_textureview
containerView = viewFinderStub.inflate()
textureView = containerView.findViewById(R.id.textureView)
textureView.surfaceTextureListener = surfaceTextureListener
}
private fun enableUiControl(enabled: Boolean) {
findViewById<Button>(R.id.PhotoToggle).isEnabled = enabled
findViewById<Button>(R.id.Switch).isEnabled = enabled
findViewById<Button>(R.id.Picture).isEnabled = enabled
}
private fun setupUiControl() {
val extensionModeToggleButton = findViewById<Button>(R.id.PhotoToggle)
extensionModeToggleButton.text = getCamera2ExtensionModeStringFromId(currentExtensionMode)
extensionModeToggleButton.setOnClickListener {
enableUiControl(false)
currentExtensionIdx = (currentExtensionIdx + 1) % supportedExtensionModes.size
currentExtensionMode = supportedExtensionModes[currentExtensionIdx]
restartPreview = true
extensionModeToggleButton.text =
getCamera2ExtensionModeStringFromId(currentExtensionMode)
closeCaptureSessionAsync()
}
val cameraSwitchButton = findViewById<Button>(R.id.Switch)
cameraSwitchButton.setOnClickListener {
val newCameraId = if (currentCameraId == backCameraId) frontCameraId else backCameraId
if (!isCameraSupportExtensions(newCameraId)) {
Toast.makeText(
this,
"Camera of the other lens facing doesn't support Camera2 extensions.",
Toast.LENGTH_SHORT
).show()
return@setOnClickListener
}
enableUiControl(false)
currentCameraId = newCameraId
restartCamera = true
closeCameraAsync()
}
val captureButton = findViewById<Button>(R.id.Picture)
captureButton.setOnClickListener {
enableUiControl(false)
resetImageSavedIdlingResource()
takePicture()
}
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart()")
activityStopped = false
if (restartOnStart) {
restartOnStart = false
setupAndStartPreview(currentCameraId, currentExtensionMode)
}
}
override fun onStop() {
Log.d(TAG, "onStop()++")
super.onStop()
// Needs to close the camera first. Otherwise, the next activity might be failed to open
// the camera and configure the capture session.
runBlocking {
closeCaptureSessionAsync().await()
closeCameraAsync().await()
}
restartOnStart = true
activityStopped = true
Log.d(TAG, "onStop()--")
}
override fun onDestroy() {
Log.d(TAG, "onDestroy()++")
super.onDestroy()
previewSurface.release()
imageSaveTerminationFuture.addListener({ stillImageReader?.close() }, mainExecutor)
normalModeCaptureThread.quitSafely()
Log.d(TAG, "onDestroy()--")
}
private fun closeCameraAsync(): Deferred<Unit> = lifecycleScope.async(cameraTaskDispatcher) {
Log.d(TAG, "closeCamera()++")
cameraDevice?.close()
cameraDevice = null
Log.d(TAG, "closeCamera()--")
}
private fun closeCaptureSessionAsync(): Deferred<Unit> =
lifecycleScope.async(cameraTaskDispatcher) {
Log.d(TAG, "closeCaptureSession()++")
resetCaptureSessionConfiguredIdlingResource()
if (cameraCaptureSession != null) {
try {
if (cameraCaptureSession is CameraCaptureSession) {
(cameraCaptureSession as CameraCaptureSession).close()
} else {
(cameraCaptureSession as CameraExtensionSession).close()
}
cameraCaptureSession = null
} catch (e: Exception) {
Log.e(TAG, e.toString())
}
}
Log.d(TAG, "closeCaptureSession()--")
}
/**
* Sets up the UI layout settings for the specified camera and extension mode. And then,
* triggers to open the camera and capture session to start the preview with the extension mode
* enabled.
*/
@Suppress("DEPRECATION") /* defaultDisplay */
private fun setupAndStartPreview(cameraId: String, extensionMode: Int) {
if (!textureView.isAvailable) {
Toast.makeText(
this, "TextureView is invalid!!",
Toast.LENGTH_SHORT
).show()
finish()
return
}
val previewResolution = pickPreviewResolution(
cameraManager,
cameraId,
resources.displayMetrics,
extensionMode
)
if (previewResolution == null) {
Toast.makeText(
this,
"Invalid preview extension sizes!.",
Toast.LENGTH_SHORT
).show()
finish()
return
}
Log.d(TAG, "Set default buffer size to previewResolution: $previewResolution")
textureView.surfaceTexture?.setDefaultBufferSize(
previewResolution.width,
previewResolution.height
)
textureView.layoutParams =
FrameLayout.LayoutParams(previewResolution.width, previewResolution.height)
val containerViewSize = Size(containerView.width, containerView.height)
val lensFacing =
cameraManager.getCameraCharacteristics(cameraId)[CameraCharacteristics.LENS_FACING]
transformTextureView(
textureView,
containerViewSize,
previewResolution,
windowManager.defaultDisplay.rotation,
cameraSensorRotationDegrees,
lensFacing == CameraCharacteristics.LENS_FACING_BACK
)
startPreview(cameraId, extensionMode)
}
/**
* Opens the camera and capture session to start the preview with the extension mode enabled.
*/
private fun startPreview(cameraId: String, extensionMode: Int) =
lifecycleScope.launch(cameraTaskDispatcher) {
Log.d(TAG, "openCameraWithExtensionMode()++ cameraId: $cameraId")
if (cameraDevice == null || cameraDevice!!.id != cameraId) {
cameraDevice = openCamera(cameraManager, cameraId)
}
cameraCaptureSession = openCaptureSession(extensionMode)
lifecycleScope.launch(Dispatchers.Main) {
if (activityStopped) {
closeCaptureSessionAsync()
closeCameraAsync()
}
}
Log.d(TAG, "openCameraWithExtensionMode()--")
}
/**
* Opens and returns the camera (as the result of the suspend coroutine)
*/
@SuppressLint("MissingPermission")
suspend fun openCamera(
manager: CameraManager,
cameraId: String,
): CameraDevice = suspendCancellableCoroutine { cont ->
Log.d(TAG, "openCamera(): $cameraId")
manager.openCamera(
cameraId,
cameraTaskDispatcher.asExecutor(),
object : CameraDevice.StateCallback() {
override fun onOpened(device: CameraDevice) = cont.resume(device)
override fun onDisconnected(device: CameraDevice) {
Log.w(TAG, "Camera $cameraId has been disconnected")
finish()
}
override fun onClosed(camera: CameraDevice) {
Log.d(TAG, "Camera - onClosed: $cameraId")
lifecycleScope.launch(Dispatchers.Main) {
if (restartCamera) {
restartCamera = false
updateExtensionInfo()
setupAndStartPreview(currentCameraId, currentExtensionMode)
}
}
}
override fun onError(device: CameraDevice, error: Int) {
Log.d(TAG, "Camera - onError: $cameraId")
val msg = when (error) {
ERROR_CAMERA_DEVICE -> "Fatal (device)"
ERROR_CAMERA_DISABLED -> "Device policy"
ERROR_CAMERA_IN_USE -> "Camera in use"
ERROR_CAMERA_SERVICE -> "Fatal (service)"
ERROR_MAX_CAMERAS_IN_USE -> "Maximum cameras in use"
else -> "Unknown"
}
val exc = RuntimeException("Camera $cameraId error: ($error) $msg")
Log.e(TAG, exc.message, exc)
cont.resumeWithException(exc)
}
})
}
/**
* Opens and returns the extensions session (as the result of the suspend coroutine)
*/
private suspend fun openCaptureSession(extensionMode: Int): Any =
suspendCancellableCoroutine { cont ->
Log.d(TAG, "openCaptureSession")
if (stillImageReader != null) {
val imageReaderToClose = stillImageReader!!
imageSaveTerminationFuture.addListener(
{ imageReaderToClose.close() },
mainExecutor
)
}
stillImageReader = setupImageReader()
val outputConfigs = arrayListOf<OutputConfiguration>()
outputConfigs.add(OutputConfiguration(stillImageReader!!.surface))
outputConfigs.add(OutputConfiguration(previewSurface))
if (extensionModeEnabled) {
createCameraExtensionSession(cont, outputConfigs, extensionMode)
} else {
createCameraCaptureSession(cont, outputConfigs)
}
}
/**
* Creates normal mode CameraCaptureSession
*/
private fun createCameraCaptureSession(
cont: CancellableContinuation<Any>,
outputConfigs: ArrayList<OutputConfiguration>
) {
val sessionConfiguration = SessionConfiguration(
SESSION_REGULAR,
outputConfigs,
cameraTaskDispatcher.asExecutor(),
object : CameraCaptureSession.StateCallback() {
override fun onClosed(session: CameraCaptureSession) {
Log.d(TAG, "CaptureSession - onClosed: $session")
lifecycleScope.launch(Dispatchers.Main) {
if (restartPreview) {
restartPreviewWhenCaptureSessionClosed()
}
}
}
override fun onConfigured(session: CameraCaptureSession) {
Log.d(TAG, "CaptureSession - onConfigured: $session")
setRepeatingRequestWhenCaptureSessionConfigured(cont, session.device, session)
runOnUiThread {
enableUiControl(true)
if (!captureSessionConfiguredIdlingResource.isIdleNow) {
captureSessionConfiguredIdlingResource.decrement()
}
}
}
override fun onConfigureFailed(session: CameraCaptureSession) {
Log.e(TAG, "CaptureSession - onConfigureFailed: $session")
cont.resumeWithException(
RuntimeException("Configure failed when creating capture session.")
)
}
})
cameraDevice!!.createCaptureSession(sessionConfiguration)
}
/**
* Creates extension mode CameraExtensionSession
*/
private fun createCameraExtensionSession(
cont: CancellableContinuation<Any>,
outputConfigs: ArrayList<OutputConfiguration>,
extensionMode: Int
) {
val extensionConfiguration = ExtensionSessionConfiguration(
extensionMode, outputConfigs,
cameraTaskDispatcher.asExecutor(), object : CameraExtensionSession.StateCallback() {
override fun onClosed(session: CameraExtensionSession) {
Log.d(TAG, "Extension CaptureSession - onClosed: $session")
lifecycleScope.launch(Dispatchers.Main) {
if (restartPreview) {
restartPreviewWhenCaptureSessionClosed()
}
}
}
override fun onConfigured(session: CameraExtensionSession) {
Log.d(TAG, "Extension CaptureSession - onConfigured: $session")
setRepeatingRequestWhenCaptureSessionConfigured(cont, session.device, session)
runOnUiThread {
enableUiControl(true)
if (!captureSessionConfiguredIdlingResource.isIdleNow) {
captureSessionConfiguredIdlingResource.decrement()
}
}
}
override fun onConfigureFailed(session: CameraExtensionSession) {
Log.e(TAG, "Extension CaptureSession - onConfigureFailed: $session")
cont.resumeWithException(
RuntimeException("Configure failed when creating capture session.")
)
}
}
)
try {
cameraDevice!!.createExtensionSession(extensionConfiguration)
} catch (e: CameraAccessException) {
Log.e(TAG, e.toString())
cont.resumeWithException(RuntimeException("Failed to create capture session."))
}
}
private fun setRepeatingRequestWhenCaptureSessionConfigured(
cont: CancellableContinuation<Any>,
device: CameraDevice,
captureSession: Any
) {
require(
captureSession is CameraCaptureSession ||
captureSession is CameraExtensionSession
) {
"The input capture session must be either a CameraCaptureSession or a" +
" CameraExtensionSession instance."
}
try {
val captureBuilder = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
captureBuilder.addTarget(previewSurface)
if (captureSession is CameraCaptureSession) {
captureSession.setRepeatingRequest(
captureBuilder.build(),
captureCallbacksNormalMode,
normalModeCaptureHandler
)
} else {
(captureSession as CameraExtensionSession).setRepeatingRequest(
captureBuilder.build(),
cameraTaskDispatcher.asExecutor(), captureCallbacks
)
}
cont.resume(captureSession)
} catch (e: CameraAccessException) {
Log.e(TAG, e.toString())
cont.resumeWithException(
RuntimeException("Failed to create capture session.")
)
}
}
private fun restartPreviewWhenCaptureSessionClosed() {
restartPreview = false
val newExtensionMode = currentExtensionMode
lifecycleScope.launch(cameraTaskDispatcher) {
cameraCaptureSession =
openCaptureSession(newExtensionMode)
}
}
private fun setupImageReader(): ImageReader {
val (size, format) = pickStillImageResolution(
extensionCharacteristics,
currentExtensionMode
)
Log.d(TAG, "Setup image reader - size: $size, format: $format")
return ImageReader.newInstance(size.width, size.height, format, 1)
}
/**
* Takes a picture.
*/
private fun takePicture() = lifecycleScope.launch(cameraTaskDispatcher) {
Preconditions.checkState(
cameraCaptureSession != null,
"take picture button is only enabled when session is configured successfully"
)
val session = cameraCaptureSession!!
var takePictureCompleter: Completer<Any?>? = null
imageSaveTerminationFuture = CallbackToFutureAdapter.getFuture<Any?> {
takePictureCompleter = it
"imageSaveTerminationFuture"
}
stillImageReader!!.setOnImageAvailableListener(
{ reader: ImageReader ->
lifecycleScope.launch(cameraTaskDispatcher) {
val (imageUri, rotationDegrees) = acquireImageAndSave(reader)
imageUri?.let { sessionImageUriSet.add(it) }
stillImageReader!!.setOnImageAvailableListener(null, null)
takePictureCompleter?.set(null)
if (!imageSavedIdlingResource.isIdleNow) {
imageSavedIdlingResource.decrement()
}
lifecycleScope.launch(Dispatchers.Main) {
if (isRequestMode) {
if (imageUri == null) {
result.putExtra(
INTENT_EXTRA_KEY_ERROR_CODE,
ERROR_CODE_SAVE_IMAGE_FAILED
)
} else {
result.putExtra(INTENT_EXTRA_KEY_IMAGE_URI, imageUri)
result.putExtra(
INTENT_EXTRA_KEY_IMAGE_ROTATION_DEGREES,
rotationDegrees
)
}
// Closes the camera, capture session and finish the activity to return
// to the caller activity if activity is in request mode.
closeCaptureSessionAsync().await()
closeCameraAsync().await()
finish()
} else {
enableUiControl(true)
}
}
}
}, Handler(Looper.getMainLooper())
)
val device = if (session is CameraCaptureSession) {
session.device
} else {
(session as CameraExtensionSession).device
}
val captureBuilder = device.createCaptureRequest(
CameraDevice.TEMPLATE_STILL_CAPTURE
)
captureBuilder.addTarget(stillImageReader!!.surface)
if (session is CameraCaptureSession) {
session.capture(
captureBuilder.build(),
object : CameraCaptureSession.CaptureCallback() {
override fun onCaptureFailed(
session: CameraCaptureSession,
request: CaptureRequest,
failure: CaptureFailure
) {
takePictureCompleter?.set(null)
Log.e(TAG, "Failed to take picture.")
}
},
normalModeCaptureHandler
)
} else {
(session as CameraExtensionSession).capture(
captureBuilder.build(),
cameraTaskDispatcher.asExecutor(),
object : CameraExtensionSession.ExtensionCaptureCallback() {
override fun onCaptureFailed(
session: CameraExtensionSession,
request: CaptureRequest
) {
takePictureCompleter?.set(null)
Log.e(TAG, "Failed to take picture.")
}
override fun onCaptureSequenceCompleted(
session: CameraExtensionSession,
sequenceId: Int
) {
Log.v(TAG, "onCaptureProcessSequenceCompleted: $sequenceId")
}
}
)
}
}
/**
* Acquires the latest image from the image reader and save it to the Pictures folder
*/
private fun acquireImageAndSave(imageReader: ImageReader): Pair<Uri?, Int> {
var uri: Uri? = null
var rotationDegrees = 0
try {
val (fileName, suffix) = generateFileName(currentCameraId, currentExtensionMode)
val lensFacing = cameraManager.getCameraCharacteristics(
currentCameraId
)[CameraCharacteristics.LENS_FACING]
rotationDegrees = calculateRelativeImageRotationDegrees(
(surfaceRotationToRotationDegrees(display!!.rotation)),
cameraSensorRotationDegrees,
lensFacing == CameraCharacteristics.LENS_FACING_BACK
)
imageReader.acquireLatestImage().let { image ->
uri = if (isRequestMode) {
// Saves as temp file if the activity is called by other validation activity to
// capture a image.
FileUtil.saveImageToTempFile(image, fileName, suffix, null, rotationDegrees)
} else {
FileUtil.saveImage(
image,
fileName,
suffix,
"Pictures/ExtensionsPictures",
contentResolver,
rotationDegrees
)
}
image.close()
val msg = if (uri != null) {
"Saved image to $fileName.jpg"
} else {
"Failed to save image."
}
if (!isRequestMode) {
lifecycleScope.launch(Dispatchers.Main) {
Toast.makeText(this@Camera2ExtensionsActivity, msg, Toast.LENGTH_SHORT)
.show()
}
}
}
} catch (e: Exception) {
Log.e(TAG, e.toString())
}
return Pair(uri, rotationDegrees)
}
/**
* Generate the output file name and suffix depending on whether the image is requested by the
* validation activity.
*/
private fun generateFileName(cameraId: String, extensionMode: Int): Pair<String, String> {
val fileName: String
val suffix: String
if (isRequestMode) {
val lensFacing = cameraManager.getCameraCharacteristics(
cameraId
)[CameraCharacteristics.LENS_FACING]!!
fileName =
"[Camera2Extension][Camera-$cameraId][${getLensFacingStringFromInt(lensFacing)}][${
getCamera2ExtensionModeStringFromId(extensionMode)
}]${if (extensionModeEnabled) "[Enabled]" else "[Disabled]"}"
suffix = ""
} else {
val formatter: Format =
SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS", Locale.US)
fileName =
"[${formatter.format(Calendar.getInstance().time)}][Camera2]${
getCamera2ExtensionModeStringFromId(extensionMode)
}"
suffix = ".jpg"
}
return Pair(fileName, suffix)
}
private fun getLensFacingStringFromInt(lensFacing: Int): String = when (lensFacing) {
CameraMetadata.LENS_FACING_BACK -> "BACK"
CameraMetadata.LENS_FACING_FRONT -> "FRONT"
CameraMetadata.LENS_FACING_EXTERNAL -> "EXTERNAL"
else -> throw IllegalArgumentException("Invalid lens facing!!")
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (!isRequestMode) {
val inflater = menuInflater
inflater.inflate(R.menu.main_menu_camera2_extensions_activity, menu)
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_camerax_extensions -> {
closeCameraAndStartActivity(CameraExtensionsActivity::class.java.name)
return true
}
R.id.menu_validation_tool -> {
closeCameraAndStartActivity(CameraValidationResultActivity::class.java.name)
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun closeCameraAndStartActivity(className: String) {
// Needs to close the camera first. Otherwise, the next activity might be failed to open
// the camera and configure the capture session.
runBlocking {
closeCaptureSessionAsync().await()
closeCameraAsync().await()
}
val intent = Intent()
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
intent.setClassName(this, className)
startActivity(intent)
}
@VisibleForTesting
fun getCaptureSessionConfiguredIdlingResource(): CountingIdlingResource =
captureSessionConfiguredIdlingResource
@VisibleForTesting
fun getPreviewIdlingResource(): CountingIdlingResource = previewIdlingResource
@VisibleForTesting
fun getImageSavedIdlingResource(): CountingIdlingResource = imageSavedIdlingResource
private fun resetCaptureSessionConfiguredIdlingResource() {
if (captureSessionConfiguredIdlingResource.isIdleNow) {
captureSessionConfiguredIdlingResource.increment()
}
}
@VisibleForTesting
fun resetPreviewIdlingResource() {
receivedCaptureProcessStartedCount.set(0)
receivedPreviewFrameCount.set(0)
if (captureProcessStartedIdlingResource.isIdleNow) {
captureProcessStartedIdlingResource.increment()
}
if (previewIdlingResource.isIdleNow) {
previewIdlingResource.increment()
}
}
private fun resetImageSavedIdlingResource() {
if (imageSavedIdlingResource.isIdleNow) {
imageSavedIdlingResource.increment()
}
}
@VisibleForTesting
fun deleteSessionImages() {
sessionImageUriSet.deleteAllUris()
}
private class SessionMediaUriSet constructor(val contentResolver: ContentResolver) {
private val mSessionMediaUris: MutableSet<Uri> = mutableSetOf()
fun add(uri: Uri) {
synchronized(mSessionMediaUris) {
mSessionMediaUris.add(uri)
}
}
fun deleteAllUris() {
synchronized(mSessionMediaUris) {
val it =
mSessionMediaUris.iterator()
while (it.hasNext()) {
contentResolver.delete(it.next(), null, null)
it.remove()
}
}
}
}
} | apache-2.0 | 3c95371abda47623df51c43c72c3bdb6 | 37.273561 | 109 | 0.619822 | 5.726819 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/WhenNonExhaustive.fir.kt | 10 | 2527 | fun nonExhaustiveInt(x: Int) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(x) {
0 -> false
}
fun nonExhaustiveBoolean(b: Boolean) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'true' branch or 'else' branch instead">when</error>(b) {
false -> 0
}
fun nonExhaustiveNullableBoolean(b: Boolean?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'null' branch or 'else' branch instead">when</error>(b) {
false -> 0
true -> 1
}
enum class Color {
RED,
GREEN,
BLUE
}
fun nonExhaustiveEnum(c: Color) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'RED', 'BLUE' branches or 'else' branch instead">when</error>(c) {
Color.GREEN -> 0xff00
}
fun nonExhaustiveNullable(c: Color?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'GREEN', 'null' branches or 'else' branch instead">when</error>(c) {
Color.RED -> 0xff
Color.BLUE -> 0xff0000
}
fun whenOnEnum(c: Color) {
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
}
}
enum class EnumInt {
A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15
}
fun whenOnLongEnum(i: EnumInt) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', ... branches or 'else' branch instead">when</error> (i) {
EnumInt.A7 -> 7
}
sealed class Variant {
object Singleton : Variant()
class Something : Variant()
object Another : Variant()
}
fun nonExhaustiveSealed(v: Variant) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'Another', 'is Something' branches or 'else' branch instead">when</error>(v) {
Variant.Singleton -> false
}
fun nonExhaustiveNullableSealed(v: Variant?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'Another', 'null' branches or 'else' branch instead">when</error>(v) {
Variant.Singleton -> false
is Variant.Something -> true
}
sealed class Empty
fun nonExhaustiveEmpty(e: Empty) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(e) {}
fun nonExhaustiveNullableEmpty(e: Empty?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'null' branch or 'else' branch instead">when</error>(e) {}
| apache-2.0 | 13f6d7bf1b317ed1692fa011d65e2425 | 37.876923 | 216 | 0.675505 | 3.316273 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/logging/TeamCityBuildMessageLogger.kt | 6 | 5964 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl.logging
import org.jetbrains.intellij.build.BuildMessageLogger
import org.jetbrains.intellij.build.CompilationErrorsLogMessage
import org.jetbrains.intellij.build.LogMessage
import org.jetbrains.intellij.build.LogMessage.Kind.*
import org.jetbrains.intellij.build.impl.BuildUtils
import java.io.PrintStream
import java.util.concurrent.ConcurrentLinkedDeque
class TeamCityBuildMessageLogger : BuildMessageLogger() {
companion object {
@JvmField
val FACTORY: () -> BuildMessageLogger = ::TeamCityBuildMessageLogger
private const val ANT_OUTPUT_PREFIX = "###<<<>>>###:" //copied from jetbrains.buildServer.agent.ant.ServiceMessageBuildProgressLogger
private val out: PrintStream? = System.out
private fun doPrintTeamCityMessage(messageId: String, messageArguments: String) {
printMessageText("##teamcity[$messageId $messageArguments]")
}
private fun printMessageText(message: String) {
if (BuildUtils.isUnderJpsBootstrap) {
// under jps-bootstrap we're logging directly to teamcity
// so special prefixes are not required
out?.println(message)
return
}
if (message.contains(ANT_OUTPUT_PREFIX)) {
out?.println(message)
}
else {
//TeamCity will ignore an output line if it doesn't contain the prefix so we need to add it manually
out?.println("$ANT_OUTPUT_PREFIX$message")
}
}
private fun escapeChar(c: Char): Char =
when (c) {
'\n' -> 'n'
'\r' -> 'r'
'\u0085' -> 'x' // next-line character
'\u2028' -> 'l' // line-separator character
'\u2029' -> 'p' // paragraph-separator character
'|' -> '|'
'\'' -> '\''
'[' -> '['
']' -> ']'
else -> 0.toChar()
}
private fun escape(text: String): String {
val escaped = StringBuilder()
for (c: Char in text.toCharArray()) {
val escChar = escapeChar(c)
if (escChar == 0.toChar()) {
escaped.append(c)
}
else {
escaped.append('|').append(escChar)
}
}
return escaped.toString()
}
}
private val delayedBlockStartMessages = ConcurrentLinkedDeque<LogMessage>()
override fun processMessage(message: LogMessage) {
when (message.kind) {
INFO -> logPlainMessage(message, "")
WARNING -> logPlainMessage(message, " status='WARNING'")
ERROR -> {
val messageText = message.text.trim()
val lineEnd = messageText.indexOf('\n')
val firstLine: String
val details: String
if (lineEnd != -1) {
firstLine = messageText.substring(0, lineEnd)
details = " errorDetails='${escape(messageText.substring(lineEnd + 1))}'"
}
else {
firstLine = messageText
details = ""
}
printTeamCityMessage("message", "text='${escape(firstLine)}'$details status='ERROR'")
}
PROGRESS -> printTeamCityMessage("progressMessage", "'${escape(message.text)}'")
BLOCK_STARTED -> delayedBlockStartMessages.addLast(message)
BLOCK_FINISHED -> {
if (!dropDelayedBlockStartMessageIfSame(message)) {
printTeamCityMessage("blockClosed", "name='${escape(message.text)}'")
}
}
ARTIFACT_BUILT -> printTeamCityMessage("publishArtifacts", "'${escape(message.text)}'")
BUILD_STATUS -> printTeamCityMessage("buildStatus", "text='${escape(message.text)}'")
STATISTICS -> {
val index = message.text.indexOf('=')
val key = escape(message.text.substring(0, index))
val value = escape(message.text.substring(index + 1))
printTeamCityMessage("buildStatisticValue", "key='$key' value='$value'")
}
SET_PARAMETER -> {
val index = message.text.indexOf('=')
val name = escape(message.text.substring(0, index))
val value = escape(message.text.substring(index + 1))
printTeamCityMessage("setParameter", "name='$name' value='$value'")
}
COMPILATION_ERRORS -> {
val compiler = escape((message as CompilationErrorsLogMessage).compilerName)
printTeamCityMessage("compilationStarted", "compiler='$compiler']")
message.errorMessages.forEach {
val messageText = escape(it)
printTeamCityMessage("message", "text='$messageText' status='ERROR']")
}
printTeamCityMessage("compilationFinished", "compiler='$compiler']")
}
DEBUG -> {} //debug messages are printed to a separate file available in the build artifacts
}
}
private fun logPlainMessage(message: LogMessage, status: String) {
printDelayedBlockStartMessages()
if (!status.isEmpty()) {
printTeamCityMessage("message", "text='${escape(message.text)}'$status")
}
else {
printMessageText(message.text)
}
}
private fun printTeamCityMessage(messageId: String, messageArguments: String) {
printDelayedBlockStartMessages()
doPrintTeamCityMessage(messageId, messageArguments)
}
private fun printDelayedBlockStartMessages() {
var message = delayedBlockStartMessages.pollFirst()
while (message != null) {
doPrintTeamCityMessage("blockOpened", "name='${escape(message.text)}'")
message = delayedBlockStartMessages.pollFirst()
}
}
private fun dropDelayedBlockStartMessageIfSame(message: LogMessage): Boolean {
var last = delayedBlockStartMessages.peekLast()
if (last == null) return false
if (message.text != last.text) {
return false
}
last = delayedBlockStartMessages.pollLast()
if (message.text != last.text) {
// it's different since peek, return it back, hopefully no one notice that
delayedBlockStartMessages.addLast(last)
return false
}
return true
}
}
| apache-2.0 | 9bcd77fbb6f125002bf5e2e84d633e33 | 35.145455 | 137 | 0.646546 | 4.45407 | false | false | false | false |
idea4bsd/idea4bsd | platform/configuration-store-impl/src/StateMap.kt | 4 | 7433 | /*
* Copyright 2000-2015 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 com.intellij.configurationStore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.SystemProperties
import gnu.trove.THashMap
import org.iq80.snappy.SnappyInputStream
import org.iq80.snappy.SnappyOutputStream
import org.jdom.Element
import java.io.ByteArrayInputStream
import java.util.*
import java.util.concurrent.atomic.AtomicReferenceArray
fun archiveState(state: Element): BufferExposingByteArrayOutputStream {
val byteOut = BufferExposingByteArrayOutputStream()
SnappyOutputStream(byteOut).use {
serializeElementToBinary(state, it)
}
return byteOut
}
private fun unarchiveState(state: ByteArray) = SnappyInputStream(ByteArrayInputStream(state)).use { readElement(it) }
fun getNewByteIfDiffers(key: String, newState: Any, oldState: ByteArray): ByteArray? {
val newBytes: ByteArray
if (newState is Element) {
val byteOut = archiveState(newState)
if (arrayEquals(byteOut.internalBuffer, oldState, byteOut.size())) {
return null
}
newBytes = ArrayUtil.realloc(byteOut.internalBuffer, byteOut.size())
}
else {
newBytes = newState as ByteArray
if (Arrays.equals(newBytes, oldState)) {
return null
}
}
val logChangedComponents = SystemProperties.getBooleanProperty("idea.log.changed.components", false)
if (ApplicationManager.getApplication().isUnitTestMode || logChangedComponents ) {
fun stateToString(state: Any) = JDOMUtil.writeParent(state as? Element ?: unarchiveState(state as ByteArray), "\n")
val before = stateToString(oldState)
val after = stateToString(newState)
if (before == after) {
throw IllegalStateException("$key serialization error - serialized are different, but unserialized are equal")
}
else if (logChangedComponents) {
LOG.info("$key ${StringUtil.repeat("=", 80 - key.length)}\nBefore:\n$before\nAfter:\n$after")
}
}
return newBytes
}
fun stateToElement(key: String, state: Any?, newLiveStates: Map<String, Element>? = null): Element? {
if (state is Element) {
return state.clone()
}
else {
return newLiveStates?.get(key) ?: (state as? ByteArray)?.let(::unarchiveState)
}
}
class StateMap private constructor(private val names: Array<String>, private val states: AtomicReferenceArray<Any?>) {
override fun toString() = if (this == EMPTY) "EMPTY" else states.toString()
companion object {
val EMPTY = StateMap(emptyArray(), AtomicReferenceArray(0))
fun fromMap(map: Map<String, Any>): StateMap {
if (map.isEmpty()) {
return EMPTY
}
val names = map.keys.toTypedArray()
if (map !is TreeMap) {
Arrays.sort(names)
}
val states = AtomicReferenceArray<Any?>(names.size)
for (i in names.indices) {
states.set(i, map[names[i]])
}
return StateMap(names, states)
}
}
fun toMutableMap(): MutableMap<String, Any> {
val map = THashMap<String, Any>(names.size)
for (i in names.indices) {
map.put(names[i], states.get(i))
}
return map
}
/**
* Sorted by name.
*/
fun keys() = names
fun get(key: String): Any? {
val index = Arrays.binarySearch(names, key)
return if (index < 0) null else states.get(index)
}
fun getElement(key: String, newLiveStates: Map<String, Element>? = null) = stateToElement(key, get(key), newLiveStates)
fun isEmpty(): Boolean = names.isEmpty()
fun hasState(key: String) = get(key) is Element
fun hasStates(): Boolean {
if (isEmpty()) {
return false
}
for (i in names.indices) {
if (states.get(i) is Element) {
return true
}
}
return false
}
fun compare(key: String, newStates: StateMap, diffs: MutableSet<String>) {
val oldState = get(key)
val newState = newStates.get(key)
if (oldState is Element) {
if (!JDOMUtil.areElementsEqual(oldState as Element?, newState as Element?)) {
diffs.add(key)
}
}
else if (oldState == null) {
if (newState != null) {
diffs.add(key)
}
}
else if (newState == null || getNewByteIfDiffers(key, newState, oldState as ByteArray) != null) {
diffs.add(key)
}
}
fun getState(key: String, archive: Boolean = false): Element? {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return null
}
val state = states.get(index) as? Element ?: return null
if (!archive) {
return state
}
return if (states.compareAndSet(index, state, archiveState(state).toByteArray())) state else getState(key, true)
}
fun archive(key: String, state: Element?) {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return
}
states.set(index, state?.let { archiveState(state).toByteArray() })
}
}
fun setStateAndCloneIfNeed(key: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>? = null): MutableMap<String, Any>? {
val oldState = oldStates.get(key)
if (newState == null || JDOMUtil.isEmpty(newState)) {
if (oldState == null) {
return null
}
val newStates = oldStates.toMutableMap()
newStates.remove(key)
return newStates
}
newLiveStates?.put(key, newState)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return null
}
}
else if (oldState != null) {
newBytes = getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return null
}
val newStates = oldStates.toMutableMap()
newStates.put(key, newBytes ?: newState)
return newStates
}
// true if updated (not equals to previous state)
internal fun updateState(states: MutableMap<String, Any>, key: String, newState: Element?, newLiveStates: MutableMap<String, Element>? = null): Boolean {
if (newState == null || JDOMUtil.isEmpty(newState)) {
states.remove(key)
return true
}
newLiveStates?.put(key, newState)
val oldState = states.get(key)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return false
}
}
else if (oldState != null) {
newBytes = getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return false
}
states.put(key, newBytes ?: newState)
return true
}
private fun arrayEquals(a: ByteArray, a2: ByteArray, aSize: Int = a.size): Boolean {
if (a == a2) {
return true
}
val length = aSize
if (a2.size != length) {
return false
}
for (i in 0..length - 1) {
if (a[i] != a2[i]) {
return false
}
}
return true
} | apache-2.0 | 5972bda90d049314b094e86ff5bf61e8 | 27.92607 | 160 | 0.680748 | 3.951621 | false | false | false | false |
fkorotkov/k8s-kotlin-dsl | DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/coordination/v1/ClassBuilders.kt | 1 | 714 | // GENERATE
package com.fkorotkov.kubernetes.coordination.v1
import io.fabric8.kubernetes.api.model.coordination.v1.Lease as v1_Lease
import io.fabric8.kubernetes.api.model.coordination.v1.LeaseList as v1_LeaseList
import io.fabric8.kubernetes.api.model.coordination.v1.LeaseSpec as v1_LeaseSpec
fun newLease(block : v1_Lease.() -> Unit = {}): v1_Lease {
val instance = v1_Lease()
instance.block()
return instance
}
fun newLeaseList(block : v1_LeaseList.() -> Unit = {}): v1_LeaseList {
val instance = v1_LeaseList()
instance.block()
return instance
}
fun newLeaseSpec(block : v1_LeaseSpec.() -> Unit = {}): v1_LeaseSpec {
val instance = v1_LeaseSpec()
instance.block()
return instance
}
| mit | fda7ea3dd710e5f5f3478f3b22120ee2 | 24.5 | 80 | 0.726891 | 3.201794 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/data/RealmContext.kt | 1 | 994 | package ch.rmy.android.framework.data
import io.realm.ImportFlag
import io.realm.Realm
import io.realm.RealmModel
interface RealmContext {
val realmInstance: Realm
}
fun Realm.createContext() =
object : RealmContext {
override val realmInstance: Realm
get() = this@createContext
}
fun Realm.createTransactionContext() =
object : RealmTransactionContext {
override val realmInstance: Realm
get() = this@createTransactionContext
}
interface RealmTransactionContext : RealmContext {
fun <T : RealmModel> copy(`object`: T): T =
realmInstance.copyToRealm(`object`, ImportFlag.CHECK_SAME_VALUES_BEFORE_SET)
fun <T : RealmModel> copyOrUpdate(`object`: T): T =
realmInstance.copyToRealmOrUpdate(`object`, ImportFlag.CHECK_SAME_VALUES_BEFORE_SET)
fun <T : RealmModel> copyOrUpdate(objects: Iterable<T>): List<T> =
realmInstance.copyToRealmOrUpdate(objects, ImportFlag.CHECK_SAME_VALUES_BEFORE_SET)
}
| mit | cf13c225d39f6e9b170fc256864a0a47 | 30.0625 | 92 | 0.711268 | 4.378855 | false | false | false | false |
aosp-mirror/platform_frameworks_support | jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/transform/proguard/ProGuardTransformer.kt | 1 | 1873 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.jetifier.processor.transform.proguard
import com.android.tools.build.jetifier.processor.archive.ArchiveFile
import com.android.tools.build.jetifier.processor.transform.TransformationContext
import com.android.tools.build.jetifier.processor.transform.Transformer
import com.android.tools.build.jetifier.processor.transform.proguard.patterns.ReplacersRunner
import java.nio.charset.StandardCharsets
/**
* The [Transformer] responsible for ProGuard files refactoring.
*/
class ProGuardTransformer internal constructor(context: TransformationContext) : Transformer {
private val mapper = ProGuardTypesMapper(
context)
val replacer = ReplacersRunner(
listOf(
ProGuardClassSpecParser(mapper).replacer,
ProGuardClassFilterParser(mapper).replacer
))
override fun canTransform(file: ArchiveFile): Boolean {
return file.isProGuardFile()
}
override fun runTransform(file: ArchiveFile) {
val content = StringBuilder(file.data.toString(StandardCharsets.UTF_8)).toString()
val result = replacer.applyReplacers(content)
if (result == content) {
return
}
file.setNewData(result.toByteArray())
}
}
| apache-2.0 | 3fc1f30f128b44beb2b108cbe5e6e077 | 33.685185 | 94 | 0.73732 | 4.535109 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/feedback/FeedbackViewModel.kt | 1 | 1912 | package org.fossasia.openevent.general.feedback
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
class FeedbackViewModel(
private val feedbackService: FeedbackService,
private val resource: Resource
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableFeedback = MutableLiveData<List<Feedback>>()
val feedback: LiveData<List<Feedback>> = mutableFeedback
private val mutableMessage = SingleLiveEvent<String>()
val message: LiveData<String> = mutableMessage
private val mutableProgress = MutableLiveData<Boolean>(false)
val progress: LiveData<Boolean> = mutableProgress
fun getAllFeedback(eventId: Long) {
if (eventId == -1L) {
mutableMessage.value = resource.getString(R.string.error_fetching_feedback_message)
return
}
compositeDisposable += feedbackService.getFeedbackUnderEventFromDb(eventId)
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({
mutableFeedback.value = it
}, {
mutableMessage.value = resource.getString(R.string.error_fetching_feedback_message)
Timber.e(it, " Fail on fetching feedback for event ID: $eventId")
})
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| apache-2.0 | 7fa7df5588c96edb0f5bf8e84da922ac | 37.24 | 99 | 0.70659 | 5.167568 | false | false | false | false |
duftler/clouddriver | clouddriver-scattergather/src/main/kotlin/com/netflix/spinnaker/clouddriver/scattergather/reducer/DeepMergeResponseReducer.kt | 1 | 4559 | /*
* Copyright 2018 Netflix, 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.netflix.spinnaker.clouddriver.scattergather.reducer
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.netflix.spinnaker.clouddriver.scattergather.ReducedResponse
import com.netflix.spinnaker.clouddriver.scattergather.ResponseReducer
import okhttp3.Response
import org.springframework.http.HttpStatus
/**
* Performs a recursive merge across responses.
*
* Elements inside of an array will not be recursed. If two responses have the same
* key mapped to an array, the elements from the second response will be appended,
* removing any duplicate objects, but there will be no recursion of the array
* elements themselves.
*
* Conflict resolution is last-one-wins, where responses are ordered by the client.
*/
class DeepMergeResponseReducer : ResponseReducer {
private val objectMapper = ObjectMapper()
override fun reduce(responses: List<Response>): ReducedResponse {
val status = getResponseCode(responses)
val body = mergeResponseBodies(responses, status)
return ReducedResponse(
status,
mapOf(), // TODO(rz): There's no real benefit to propagate headers at this point.
"application/json",
"UTF-8",
body?.toString(),
hasErrors(responses)
)
}
/**
* Merges all response bodies into a single [JsonNode]. Uses the first response
* as a base, layering each subsequent non-null response on top.
*/
private fun mergeResponseBodies(responses: List<Response>, responseStatus: Int): JsonNode? {
val bodies = responses
.asSequence()
.map { Pair(it.body()?.string(), it) }
.filter { it.first != null }
.toList()
if (bodies.isEmpty()) {
return null
}
if (responseStatus !in (200..299)) {
// Find the highest response status and return that.
val highestResponseBody = bodies.sortedByDescending { it.second.code() }.first().first
if (highestResponseBody != null) {
return objectMapper.readTree(highestResponseBody)
}
}
val main = objectMapper.readTree(bodies.first().first)
if (bodies.size == 1) {
return main
}
bodies.subList(1, bodies.size).forEach {
mergeNodes(main, objectMapper.readTree(it.first))
}
return main
}
private fun mergeNodes(mainNode: JsonNode, updateNode: JsonNode?): JsonNode {
if (updateNode == null) {
return mainNode
}
val fieldNames = updateNode.fieldNames()
while (fieldNames.hasNext()) {
val updatedFieldName = fieldNames.next()
val valueToBeUpdated = mainNode.get(updatedFieldName)
val updatedValue = updateNode.get(updatedFieldName)
if (valueToBeUpdated != null && valueToBeUpdated is ArrayNode && updatedValue.isArray) {
updatedValue.forEach { updatedChildNode ->
if (!valueToBeUpdated.contains(updatedChildNode)) {
valueToBeUpdated.add(updatedChildNode)
}
}
} else if (valueToBeUpdated != null && valueToBeUpdated.isObject) {
mergeNodes(valueToBeUpdated, updatedValue)
} else {
if (mainNode is ObjectNode) {
mainNode.replace(updatedFieldName, updatedValue)
}
}
}
return mainNode
}
private fun getResponseCode(responses: List<Response>): Int {
if (hasErrors(responses)) {
return HttpStatus.BAD_GATEWAY.value()
}
val distinctCodes = responses.asSequence().map { it.code() }.distinct().toList()
return when {
distinctCodes.size == 1 -> distinctCodes[0]
distinctCodes.any { it == 404 } -> HttpStatus.NOT_FOUND.value()
distinctCodes.any { it == 429 } -> HttpStatus.TOO_MANY_REQUESTS.value()
else -> distinctCodes.sortedDescending().first()
}
}
private fun hasErrors(responses: List<Response>): Boolean =
responses.any { it.code() >= 500 }
}
| apache-2.0 | b37be304faf53bdae81cc165a14ce2f8 | 33.022388 | 94 | 0.695547 | 4.358509 | false | false | false | false |
Adven27/Exam | exam-core/src/main/java/io/github/adven27/concordion/extensions/exam/core/ExamExtension.kt | 1 | 7626 | @file:Suppress("TooManyFunctions")
package io.github.adven27.concordion.extensions.exam.core
import ch.qos.logback.classic.turbo.TurboFilter
import com.github.jknack.handlebars.Handlebars
import io.github.adven27.concordion.extensions.exam.core.handlebars.HANDLEBARS
import io.github.adven27.concordion.extensions.exam.core.json.DefaultObjectMapperProvider
import io.github.adven27.concordion.extensions.exam.core.logger.LoggerLevelFilter
import io.github.adven27.concordion.extensions.exam.core.logger.LoggingFormatterExtension
import io.github.adven27.concordion.extensions.exam.core.utils.After
import io.github.adven27.concordion.extensions.exam.core.utils.Before
import io.github.adven27.concordion.extensions.exam.core.utils.DateFormatMatcher
import io.github.adven27.concordion.extensions.exam.core.utils.DateWithinNow
import io.github.adven27.concordion.extensions.exam.core.utils.DateWithinParam
import io.github.adven27.concordion.extensions.exam.core.utils.XMLDateWithin
import net.javacrumbs.jsonunit.JsonAssert.`when`
import net.javacrumbs.jsonunit.core.Configuration
import net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER
import net.javacrumbs.jsonunit.providers.Jackson2ObjectMapperProvider
import org.concordion.api.extension.ConcordionExtender
import org.concordion.api.extension.ConcordionExtension
import org.concordion.api.listener.ExampleEvent
import org.hamcrest.Matcher
import org.xmlunit.diff.DefaultNodeMatcher
import org.xmlunit.diff.ElementSelectors.byName
import org.xmlunit.diff.ElementSelectors.byNameAndText
import org.xmlunit.diff.NodeMatcher
import java.util.function.Consumer
class ExamExtension constructor(private vararg var plugins: ExamPlugin) : ConcordionExtension {
private var focusOnError: Boolean = true
private var nodeMatcher: NodeMatcher = DEFAULT_NODE_MATCHER
private var skipDecider: SkipDecider = SkipDecider.NoSkip()
/**
* Attach xmlunit/jsonunit matchers.
*
* @param matcherName name to reference in placeholder.
* @param matcher implementation.
* usage: {{matcherName param1 param2}}
*/
@Suppress("unused")
fun withPlaceholderMatcher(matcherName: String, matcher: Matcher<*>): ExamExtension {
MATCHERS[matcherName] = matcher
return this
}
@Suppress("unused")
fun withXmlUnitNodeMatcher(nodeMatcher: NodeMatcher): ExamExtension {
this.nodeMatcher = nodeMatcher
return this
}
@Suppress("unused")
fun withJackson2ObjectMapperProvider(provider: Jackson2ObjectMapperProvider): ExamExtension {
JACKSON_2_OBJECT_MAPPER_PROVIDER = provider
return this
}
@Suppress("unused")
fun withHandlebar(fn: Consumer<Handlebars>): ExamExtension {
fn.accept(HANDLEBARS)
return this
}
@Suppress("unused")
fun withContentTypeConfigs(addContentTypeConfigs: Map<String, ContentTypeConfig>): ExamExtension {
CONTENT_TYPE_CONFIGS += addContentTypeConfigs
return this
}
/**
* All examples but failed will be collapsed
*/
@Suppress("unused")
fun withFocusOnFailed(enabled: Boolean): ExamExtension {
focusOnError = enabled
return this
}
@Suppress("unused")
fun runOnlyExamplesWithPathsContains(vararg substrings: String): ExamExtension {
skipDecider = object : SkipDecider {
var reason = ""
override fun test(event: ExampleEvent): Boolean {
val skips = mutableListOf<String>()
val name = event.resultSummary.specificationDescription
val noSkip = substrings.none { substring ->
if (name.contains(substring)) {
true
} else {
skips += substring
false
}
}
if (noSkip) {
reason = "specification name: \"$name\" not contains: $skips \n"
}
return noSkip
}
override fun reason(): String = reason
}
return this
}
@Suppress("unused")
fun withSkipExampleDecider(decider: SkipDecider): ExamExtension {
skipDecider = decider
return this
}
@Suppress("unused")
fun withLoggingFilter(loggerLevel: Map<String, String>): ExamExtension {
LOGGING_FILTER = LoggerLevelFilter(loggerLevel)
return this
}
override fun addTo(ex: ConcordionExtender) {
val registry = CommandRegistry(JsonVerifier(), XmlVerifier())
plugins.forEach { registry.register(it.commands()) }
registry.commands()
.filter { "example" != it.name }
.forEach { ex.withCommand(NS, it.name, it) }
CommandPrinterExtension().addTo(ex)
IncludesExtension().addTo(ex)
TopButtonExtension().addTo(ex)
CodeMirrorExtension().addTo(ex)
HighlightExtension().addTo(ex)
TocbotExtension().addTo(ex)
FontAwesomeExtension().addTo(ex)
BootstrapExtension().addTo(ex)
DetailsExtension().addTo(ex)
ResponsiveTableExtension().addTo(ex)
NomNomlExtension().addTo(ex)
LoggingFormatterExtension().addTo(ex)
ex.withDocumentParsingListener(ExamDocumentParsingListener(registry))
ex.withThrowableListener(ErrorListener())
if (focusOnError) {
ex.withSpecificationProcessingListener(FocusOnErrorsListener())
}
ex.withExampleListener(ExamExampleListener(skipDecider))
}
fun setUp() {
plugins.forEach { it.setUp() }
}
fun tearDown() {
plugins.forEach { it.tearDown() }
}
companion object {
val PARSED_COMMANDS: MutableMap<String, String> = HashMap()
const val NS = "http://exam.extension.io"
val MATCHERS: MutableMap<String, Matcher<*>> = mutableMapOf(
"formattedAs" to DateFormatMatcher(),
"formattedAndWithin" to DateWithinParam(),
"formattedAndWithinNow" to DateWithinNow(),
"xmlDateWithinNow" to XMLDateWithin(),
"after" to After(),
"before" to Before(),
)
@JvmField
var JACKSON_2_OBJECT_MAPPER_PROVIDER: Jackson2ObjectMapperProvider = DefaultObjectMapperProvider()
@JvmField
val DEFAULT_NODE_MATCHER = DefaultNodeMatcher(byNameAndText, byName)
@JvmField
val DEFAULT_JSON_UNIT_CFG: Configuration = `when`(IGNORING_ARRAY_ORDER).let { cfg ->
MATCHERS.map { cfg to it }
.reduce { acc, cur ->
acc.first
.withMatcher(acc.second.key, acc.second.value)
.withMatcher(cur.second.key, cur.second.value) to cur.second
}.first
}
val CONTENT_TYPE_CONFIGS: MutableMap<String, ContentTypeConfig> = mutableMapOf(
"json" to JsonContentTypeConfig(),
"xml" to XmlContentTypeConfig(),
"text" to TextContentTypeConfig(),
)
@JvmStatic
fun contentTypeConfig(type: String): ContentTypeConfig = CONTENT_TYPE_CONFIGS[type]
?: throw IllegalStateException(
"Content type config for type '$type' not found. " +
"Provide it via ExamExtension(...).withContentTypeConfigs(...) method."
)
@JvmStatic
fun prettyXml(text: String) = text.prettyXml()
@JvmStatic
fun prettyJson(text: String) = text.prettyJson()
var LOGGING_FILTER: TurboFilter = LoggerLevelFilter()
}
}
| mit | 66588d00ea1ba03276468ccc0627d408 | 35.84058 | 106 | 0.661815 | 4.491166 | false | true | false | false |
BenAlderfer/hand-and-foot-scores | app/src/main/java/com/alderferstudios/handandfootscores/ScoreActivity.kt | 1 | 13822 | package com.alderferstudios.handandfootscores
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.ScrollView
/**
* Hand and Foot Scores
* Main activity
* Handles navigation, updating scores, clearing, etc...
* Some things are public for testing
*
* @author Ben Alderfer
* Alderfer Studios
*/
class ScoreActivity : AppCompatActivity() {
companion object {
var shared: SharedPreferences? = null
private var editor: SharedPreferences.Editor? = null
}
var tabNum: Int = 0
private var tabLayout: TabLayout? = null
private var viewPager: ViewPager? = null
private var adapter: PagerAdapter? = null
val editTexts = arrayOfNulls<Array<EditText?>>(4) //holds all the views, first dimension is tab number
/**
* Creates the Activity and gets all the variables/listeners ready
*
* @param savedInstanceState the savedInstanceState from before
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_score)
initPrefs(this)
resetPrefs(this, false) //resets prefs only first time
editor = shared?.edit()
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
//lock orientation on phone
if (!DeviceUtils.isTablet(this)) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
}
//current tab
tabNum = 0
//set up tabs
try {
tabLayout = findViewById(R.id.tab_layout)
tabLayout?.addTab(tabLayout?.newTab()!!.setText(getString(R.string.team1) + '\n' + 0))
tabLayout?.addTab(tabLayout?.newTab()!!.setText(getString(R.string.team2) + '\n' + 0))
tabLayout?.addTab(tabLayout?.newTab()!!.setText(getString(R.string.team3) + '\n' + 0))
tabLayout?.addTab(tabLayout?.newTab()!!.setText(getString(R.string.team4) + '\n' + 0))
tabLayout?.tabGravity = TabLayout.GRAVITY_FILL
} catch (e: NullPointerException) {
Log.e("tabLayout error", "Failed to add tabLayout tabs")
e.printStackTrace()
}
//set up viewpager
viewPager = findViewById(R.id.pager)
adapter = PagerAdapter(supportFragmentManager, tabLayout?.tabCount ?: 4)
viewPager?.adapter = adapter
viewPager?.addOnPageChangeListener(object : TabLayout.TabLayoutOnPageChangeListener(tabLayout) {
override fun onPageSelected(position: Int) {
viewPager?.currentItem = position
tabNum = position
}
})
tabLayout?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager?.currentItem = tab.position
}
override fun onTabUnselected(tab: TabLayout.Tab) {}
override fun onTabReselected(tab: TabLayout.Tab) {
scrollToTop((adapter?.getItem(tab.position) as ScoreFragment).scrollView)
}
})
}
/**
* Initializes shared preferences
*/
fun initPrefs(context: Context) {
shared = PreferenceManager.getDefaultSharedPreferences(context)
}
/**
* Resets the prefs to their default values based on param
* @param reRead true: overwrite everything, false: only reset the first time this is called
*/
fun resetPrefs(context: Context, reRead: Boolean) {
PreferenceManager.setDefaultValues(context, R.xml.prefs, reRead)
}
/**
* Creates the options menu
*
* @param menu the Menu
* @return always true
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_score, menu)
return true
}
/**
* Handles toolbar/overflow options
*
* @param item the option tapped
* @return true if it matches one of the options, otherwise goes to super
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_clear_all -> {
if (editTexts[tabNum] == null) {
saveEditTexts()
}
promptClear()
return true
}
R.id.action_settings -> {
val settingsActivity = Intent(this, SettingsActivity::class.java)
startActivity(settingsActivity)
return true
}
R.id.action_instructions -> {
val instructionActivity = Intent(this, InstructionActivity::class.java)
startActivity(instructionActivity)
return true
}
R.id.help -> {
val helpActivity = Intent(this, HelpActivity::class.java)
startActivity(helpActivity)
return true
}
R.id.about -> {
val aboutActivity = Intent(this, AboutActivity::class.java)
startActivity(aboutActivity)
return true
}
}
return super.onOptionsItemSelected(item)
}
/**
* Saves all the EditTexts for later
* Only saves the EditText once
* Keeps a separate array for each tab
* Used to minimize findViewById usage
*/
private fun saveEditTexts() {
if (editTexts[tabNum] == null) {
val temp = adapter?.getItem(tabNum) as ScoreFragment?
editTexts[tabNum] = temp?.ets
}
}
/**
* Calculates the score with no bonus
*/
fun lostRound(@Suppress("UNUSED_PARAMETER") v: View) {
calculateScore(0)
}
/**
* Calculates the score with the win bonus added
*/
fun wonRound(@Suppress("UNUSED_PARAMETER") v: View) {
calculateScore(Integer.parseInt(shared?.getString("winBonus", "300")))
}
/**
* Calculates the score
* Returns the score for testing
*
* @param bonus the bonus to add if they won
*/
fun calculateScore(bonus: Int): Int {
var score = bonus
saveEditTexts()
//books
val numCleanBooks = editTexts[tabNum]?.get(0)?.text.toString()
if (numCleanBooks != "") {
score += Math.abs(Integer.parseInt(numCleanBooks) * Integer.parseInt(shared?.getString("cleanBook", "500")))
}
val numDirtyBooks = editTexts[tabNum]?.get(1)?.text.toString()
if (numDirtyBooks != "") {
score += Math.abs(Integer.parseInt(numDirtyBooks) * Integer.parseInt(shared?.getString("dirtyBook", "300")))
}
val numCleanWildBooks = editTexts[tabNum]?.get(2)?.text.toString()
if (numCleanWildBooks != "") {
score += Math.abs(Integer.parseInt(numCleanWildBooks) * Integer.parseInt(shared?.getString("cleanWildBook", "1500")))
}
val numDirtyWildBooks = editTexts[tabNum]?.get(3)?.text.toString()
if (numDirtyWildBooks != "") {
score += Math.abs(Integer.parseInt(numDirtyWildBooks) * Integer.parseInt(shared?.getString("dirtyWildBook", "1300")))
}
//3's, three values are positive because they are being subtracted from score
val redThreeValue = Math.abs(Integer.parseInt(shared?.getString("redThree", "300")))
val numRedThrees = editTexts[tabNum]?.get(4)?.text.toString()
if (numRedThrees != "") {
score -= Math.abs(Integer.parseInt(numRedThrees) * redThreeValue)
}
val blackThreeValue = Math.abs(Integer.parseInt(shared?.getString("blackThree", "100")))
val numBlackThrees = editTexts[tabNum]?.get(5)?.text.toString()
if (numBlackThrees != "") {
score -= Math.abs(Integer.parseInt(numBlackThrees) * blackThreeValue)
}
//additional points
val fourNineValue = Math.abs(Integer.parseInt(shared?.getString("fourNine", "5")))
val numFourNines = editTexts[tabNum]?.get(6)?.text.toString()
if (numFourNines != "") {
score -= Integer.parseInt(numFourNines) * fourNineValue
}
val tenKingValue = Math.abs(Integer.parseInt(shared?.getString("tenKing", "10")))
val numTenKings = editTexts[tabNum]?.get(7)?.text.toString()
if (numTenKings != "") {
score -= Integer.parseInt(numTenKings) * tenKingValue
}
val aceTwoValue = Math.abs(Integer.parseInt(shared?.getString("aceTwo", "20")))
val numAceTwos = editTexts[tabNum]?.get(8)?.text.toString()
if (numAceTwos != "") {
score -= Integer.parseInt(numAceTwos) * aceTwoValue
}
val jokerValue = Math.abs(Integer.parseInt(shared?.getString("joker", "50")))
val numJokers = editTexts[tabNum]?.get(9)?.text.toString()
if (numJokers != "") {
score -= Integer.parseInt(numJokers) * jokerValue
}
val numExtraPoints = editTexts[tabNum]?.get(10)?.text.toString()
if (numExtraPoints != "") {
score += Integer.parseInt(numExtraPoints)
}
updateFragment(score)
clearEditTexts(tabNum)
return score
}
/**
* Updates the fragment and the tab
*
* @param score the score to add to the fragment and tab
*/
private fun updateFragment(score: Int) {
val temp = adapter?.getItem(tabNum) as ScoreFragment?
temp?.addScore(score)
try {
tabLayout?.getTabAt(tabNum)?.text = temp?.title + '\n' + temp?.score
} catch (e: NullPointerException) {
Log.e("Update Fragment error", "Failed to update tab")
}
tabLayout?.getTabAt(tabNum)?.select()
}
private fun scrollToTop(sv: ScrollView?) {
sv?.smoothScrollTo(0, 0)
}
/**
* Clears the EditTexts
* Clears from the given tab number
*
* @param tabNumber the number of the tab to clear its EditTexts
*/
private fun clearEditTexts(tabNumber: Int) {
editTexts[tabNumber]?.forEach {
it?.setText("")
}
editTexts[tabNumber]?.get(0)?.requestFocus()
}
private fun promptClear() {
val builder = AlertDialog.Builder(this)
builder.setTitle(getString(R.string.clear_all_message))
builder.setPositiveButton(getString(R.string.clear_all_positive)) { _, _ ->
clearAll()
}
builder.setNegativeButton(getString(R.string.clear_all_negative), null)
val dialog = builder.create()
dialog.show()
}
/**
* Clears everything from all tabs
* Does not clear tabs that haven't been made yet
*/
private fun clearAll() {
var temp: ScoreFragment?
for (i in 0..3) {
if (editTexts[i] != null) {
clearEditTexts(i)
temp = adapter?.getItem(i) as ScoreFragment?
temp?.score = 0
try {
tabLayout?.getTabAt(i)?.text = temp?.title + '\n' + temp?.score
} catch (e: NullPointerException) {
Log.e("Clear all error", "Failed to update tab")
}
temp?.scrollView?.fullScroll(ScrollView.FOCUS_UP)
editTexts[i]?.get(0)?.requestFocus()
}
}
}
/**
* Custom FragmentPagerAdapter
*/
inner class PagerAdapter
/**
* Constructs the PagerAdapter
*
* @param fm the FragmentManager
* @param numTabs the number of tabs
*/
(fm: FragmentManager, private val numTabs: Int) : FragmentPagerAdapter(fm) {
private val frags: Array<ScoreFragment?> = arrayOfNulls(numTabs)
init {
frags[0] = makeScoreFrag(getString(R.string.team1))
frags[1] = makeScoreFrag(getString(R.string.team2))
frags[2] = makeScoreFrag(getString(R.string.team3))
frags[3] = makeScoreFrag(getString(R.string.team4))
}
/**
* Gets the fragment at the position
*
* @param position the position of the fragment
* @return the fragment if it exists
*/
@Suppress("UsePropertyAccessSyntax")
override fun getItem(position: Int): Fragment? {
if (position < getCount()) {
return frags[position]
}
return null
}
/**
* Gets the number of tabs
*
* @return numTabs the number of tabs
*/
override fun getCount(): Int {
return frags.size
}
/**
* Makes and returns a ScoreFragment
*
* @param title the fragment's title on the tab
* @return the ScoreFragment
*/
private fun makeScoreFrag(title: String): ScoreFragment {
val bundle = Bundle()
bundle.putInt("score", 0)
bundle.putString("title", title)
val frag = ScoreFragment()
frag.arguments = bundle
return frag
}
}
}
| mit | 2d84acff320e88838b9f7d97c6d1e18b | 32.386473 | 154 | 0.596513 | 4.486206 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/test/kotlin/me/proxer/library/api/messenger/SendMessageEndpointTest.kt | 2 | 1884 | package me.proxer.library.api.messenger
import me.proxer.library.ProxerTest
import me.proxer.library.enums.MessageAction
import me.proxer.library.runRequest
import org.amshove.kluent.invoking
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeNull
import org.amshove.kluent.shouldThrow
import org.junit.jupiter.api.Test
/**
* @author Ruben Gees
*/
class SendMessageEndpointTest : ProxerTest() {
@Test
fun testDefault() {
val (result, _) = server.runRequest("empty.json") {
api.messenger
.sendMessage("123", "message")
.build()
.execute()
}
result.shouldBeNull()
}
@Test
fun testPath() {
val (_, request) = server.runRequest("empty.json") {
api.messenger.sendMessage("123", "message")
.build()
.execute()
}
request.path shouldBeEqualTo "/api/v1/messenger/setmessage"
}
@Test
fun testParameters() {
val (_, request) = server.runRequest("empty.json") {
api.messenger.sendMessage("id", "someMessage")
.build()
.execute()
}
request.body.readUtf8() shouldBeEqualTo "conference_id=id&text=someMessage"
}
@Test
fun testActionParameters() {
val (_, request) = server.runRequest("empty.json") {
api.messenger.sendMessage("id", MessageAction.REMOVE_USER, "Testerio")
.build()
.execute()
}
request.body.readUtf8() shouldBeEqualTo "conference_id=id&text=%2FremoveUser%20Testerio"
}
@Test
fun testInvalidAction() {
invoking {
api.messenger.sendMessage("id", MessageAction.NONE, "")
.build()
.execute()
} shouldThrow IllegalArgumentException::class
}
}
| gpl-3.0 | 0e8c08d49bfc45efabaaad0969600986 | 25.914286 | 96 | 0.58758 | 4.464455 | false | true | false | false |
Esri/arcgis-runtime-samples-android | kotlin/perform-valve-isolation-trace/src/main/java/com/esri/arcgisruntime/sample/performvalveisolationtrace/MainActivity.kt | 1 | 27851 | /*
* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.performvalveisolationtrace
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.ArcGISFeature
import com.esri.arcgisruntime.data.QueryParameters
import com.esri.arcgisruntime.data.ServiceGeodatabase
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.Polyline
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.security.UserCredential
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.performvalveisolationtrace.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.performvalveisolationtrace.databinding.SpinnerTextItemBinding
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
import com.esri.arcgisruntime.utilitynetworks.UtilityCategory
import com.esri.arcgisruntime.utilitynetworks.UtilityCategoryComparison
import com.esri.arcgisruntime.utilitynetworks.UtilityCategoryComparisonOperator
import com.esri.arcgisruntime.utilitynetworks.UtilityElement
import com.esri.arcgisruntime.utilitynetworks.UtilityElementTraceResult
import com.esri.arcgisruntime.utilitynetworks.UtilityNetwork
import com.esri.arcgisruntime.utilitynetworks.UtilityNetworkDefinition
import com.esri.arcgisruntime.utilitynetworks.UtilityNetworkSource
import com.esri.arcgisruntime.utilitynetworks.UtilityTerminal
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceConfiguration
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceFilter
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceParameters
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceType
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.util.UUID
import java.util.*
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
private val TAG = MainActivity::class.java.simpleName
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val fab: FloatingActionButton by lazy {
activityMainBinding.fab
}
private val traceControlsTextView: TextView by lazy {
activityMainBinding.traceControlsTextView
}
private val progressBar: ProgressBar by lazy {
activityMainBinding.progressBar
}
private val traceTypeSpinner: Spinner by lazy {
activityMainBinding.traceTypeSpinner
}
private val traceButton: Button by lazy {
activityMainBinding.traceButton
}
private val resetButton: Button by lazy {
activityMainBinding.resetButton
}
private val includeIsolatedSwitch: SwitchCompat by lazy {
activityMainBinding.includeIsolatedSwitch
}
// objects that implement Loadable must be class fields to prevent being garbage collected before loading
private val featureServiceUrl =
"https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleGas/FeatureServer"
private val utilityNetwork by lazy {
UtilityNetwork(featureServiceUrl)
}
// create a graphics overlay for the starting location and add it to the map view
private val startingLocationGraphicsOverlay by lazy {
GraphicsOverlay()
}
private val filterBarriersGraphicsOverlay by lazy {
GraphicsOverlay()
}
private var utilityTraceParameters: UtilityTraceParameters? = null
private val serviceGeodatabase by lazy {
ServiceGeodatabase(featureServiceUrl)
}
// create and apply renderers for the starting point graphics overlay
private val startingPointSymbol: SimpleMarkerSymbol by lazy {
SimpleMarkerSymbol(
SimpleMarkerSymbol.Style.CROSS,
Color.GREEN,
25f
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
loadServiceGeodatabase()
// create a map with the utility network distribution line and device layers
val map = ArcGISMap(BasemapStyle.ARCGIS_STREETS_NIGHT).apply {
// create and load the utility network
addDoneLoadingListener {
utilityNetworks.add(utilityNetwork)
}
}
mapView.apply {
this.map = map
// set the starting location graphic overlay's renderer and add it to the map view
startingLocationGraphicsOverlay.renderer = SimpleRenderer(startingPointSymbol)
graphicsOverlays.add(startingLocationGraphicsOverlay)
// set the viewpoint to a specific location in Naperville, Illinois
setViewpointAsync(Viewpoint(Point(-9812712.321100, 5124260.390000, 0.000100), 5000.0))
// make sure the fab doesn't obscure the attribution bar
addAttributionViewLayoutChangeListener { _, _, _, _, bottom, _, _, _, oldBottom ->
val layoutParams = fab.layoutParams as CoordinatorLayout.LayoutParams
layoutParams.bottomMargin += bottom - oldBottom
}
// close the options sheet when the map is tapped
onTouchListener = object : DefaultMapViewOnTouchListener(this@MainActivity, mapView) {
override fun onTouch(view: View?, event: MotionEvent?): Boolean {
if (fab.isExpanded) {
fab.isExpanded = false
}
return super.onTouch(view, event)
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
// only pass taps to identify nearest utility element once the utility network has loaded
if (utilityNetwork.loadStatus == LoadStatus.LOADED) {
identifyNearestUtilityElement(
android.graphics.Point(e.x.roundToInt(), e.y.roundToInt())
)
traceTypeSpinner.isEnabled = false
return true
}
return false
}
}
}
// show the options sheet when the floating action button is clicked
fab.setOnClickListener {
fab.isExpanded = !fab.isExpanded
}
}
/*** Load the service geodatabase and initialize the layers.
*/
private fun loadServiceGeodatabase() {
// set user credentials to authenticate with the service
// NOTE: a licensed user is required to perform utility network operations
serviceGeodatabase.credential = UserCredential("viewer01", "I68VGU^nMurF")
serviceGeodatabase.addDoneLoadingListener {
if (serviceGeodatabase.loadStatus == LoadStatus.LOADED) {
// The gas device layer ./0 and gas line layer ./3 are created from the service geodatabase.
val gasDeviceLayerTable = serviceGeodatabase.getTable(0)
val gasLineLayerTable = serviceGeodatabase.getTable(3)
// load the utility network data from the feature service and create feature layers
val deviceLayer = FeatureLayer(gasDeviceLayerTable)
val distributionLineLayer = FeatureLayer(gasLineLayerTable)
// add the utility network feature layers to the map for display
mapView.map.operationalLayers.add(deviceLayer)
mapView.map.operationalLayers.add(distributionLineLayer)
loadUtilityNetwork()
} else {
val error =
"Error loading service geodatabase: " + serviceGeodatabase.loadError.cause?.message
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
Log.e(TAG, error)
}
}
serviceGeodatabase.loadAsync()
}
/**
* Create and load a utility network from the string resource url and initialize a starting point
* from it.
*/
private fun loadUtilityNetwork(): UtilityNetwork {
utilityNetwork.loadAsync()
utilityNetwork.addDoneLoadingListener {
if (utilityNetwork.loadStatus == LoadStatus.LOADED) {
// get a trace configuration from a tier
val networkDefinition = utilityNetwork.definition
val domainNetwork = networkDefinition.getDomainNetwork("Pipeline")
val tier = domainNetwork.getTier("Pipe Distribution System")
val traceConfiguration = tier.traceConfiguration
// create a trace filter
traceConfiguration.filter = UtilityTraceFilter()
// get a default starting location
val networkSource = networkDefinition.getNetworkSource("Gas Device")
val assetGroup = networkSource.getAssetGroup("Meter")
val assetType = assetGroup.getAssetType("Customer")
val startingLocation = utilityNetwork.createElement(
assetType,
UUID.fromString("98A06E95-70BE-43E7-91B7-E34C9D3CB9FF")
)
// create new base trace parameters
utilityTraceParameters = UtilityTraceParameters(
UtilityTraceType.ISOLATION,
Collections.singletonList(startingLocation)
)
// get a list of features for the starting location element
val elementFeaturesFuture =
utilityNetwork.fetchFeaturesForElementsAsync(listOf(startingLocation))
elementFeaturesFuture.addDoneListener {
try {
val startingLocationFeatures = elementFeaturesFuture.get()
if (startingLocationFeatures.isNotEmpty()) {
// get the geometry of the first feature for the starting location as a point
(startingLocationFeatures[0].geometry as? Point)?.let { startingLocationGeometryPoint ->
// create a graphic for the starting location and add it to the graphics overlay
val startingLocationGraphic =
Graphic(startingLocationGeometryPoint, startingPointSymbol)
startingLocationGraphicsOverlay.graphics.add(startingLocationGraphic)
// create a graphics overlay for filter barriers and add it to the map view
mapView.graphicsOverlays.add(filterBarriersGraphicsOverlay)
// create and apply a renderer for the filter barriers graphics overlay
val barrierPointSymbol = SimpleMarkerSymbol(
SimpleMarkerSymbol.Style.CROSS, Color.RED, 25f
)
filterBarriersGraphicsOverlay.renderer = SimpleRenderer(
barrierPointSymbol
)
populateCategorySpinner(networkDefinition)
traceButton.setOnClickListener {
fab.isExpanded = false
performTrace(
utilityNetwork,
traceConfiguration
)
}
resetButton.setOnClickListener {
reset(
)
}
}
} else {
val message = "Starting location features not found."
Log.i(TAG, message)
Toast.makeText(
this,
message,
Toast.LENGTH_LONG
).show()
}
} catch (e: Exception) {
val error = "Error loading starting location feature: ${e.message}"
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
}
}
} else {
val error = "Error loading utility network: ${utilityNetwork.loadError}"
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
}
}
return utilityNetwork
}
private fun identifyNearestUtilityElement(screenPoint: android.graphics.Point) {
traceControlsTextView.text = getString(R.string.add_another_filter_barrier)
// ensure the utility network is loaded before processing clicks on the map view
if (utilityNetwork.loadStatus == LoadStatus.LOADED) {
// show the progress indicator
progressBar.visibility = View.VISIBLE
// identify the feature to be used
val identifyLayerResultsFuture = mapView.identifyLayersAsync(screenPoint, 10.0, false)
identifyLayerResultsFuture.addDoneListener {
try {
// get the result of the query
val identifyLayerResults = identifyLayerResultsFuture.get()
// return if no features are identified
if (identifyLayerResults.isNotEmpty()) {
// retrieve the identify result elements as ArcGISFeatures
val elements = identifyLayerResults.map { it.elements[0] as ArcGISFeature }
// create utility elements from the list of ArcGISFeature elements
val utilityElements = elements.map { utilityNetwork.createElement(it) }
// get a reference to the closest junction if there is one
val junction =
utilityElements.firstOrNull { it.networkSource.sourceType == UtilityNetworkSource.Type.JUNCTION }
// get a reference to the closest edge if there is one
val edge =
utilityElements.firstOrNull { it.networkSource.sourceType == UtilityNetworkSource.Type.EDGE }
// preferentially select junctions, otherwise an edge
val utilityElement = junction ?: edge
// retrieve the first result and get its contents
if (junction != null) {
// check if the feature has a terminal configuration and multiple terminals
if (junction.assetType.terminalConfiguration != null) {
val utilityTerminalConfiguration =
junction.assetType.terminalConfiguration
val terminals =
utilityTerminalConfiguration.terminals
if (terminals.size > 1) {
// prompt the user to select a terminal for this feature
promptForTerminalSelection(junction, terminals)
}
}
} else if (edge != null) {
// get the geometry of the identified feature as a polyline, and remove the z component
val polyline =
GeometryEngine.removeZ(elements[0].geometry) as Polyline
// get the clicked map point
val mapPoint = mapView.screenToLocation(screenPoint)
// compute how far the clicked location is along the edge feature
val fractionAlongEdge =
GeometryEngine.fractionAlong(polyline, mapPoint, -1.0)
if (fractionAlongEdge.isNaN()) {
Toast.makeText(
this,
"Cannot add starting location or barrier here.",
Toast.LENGTH_LONG
).show()
return@addDoneListener
}
// set the fraction along edge
edge.fractionAlongEdge = fractionAlongEdge
// update the status label text
Toast.makeText(
this,
"Fraction along edge: " + edge.fractionAlongEdge.roundToInt(),
Toast.LENGTH_LONG
).show()
}
// add the element to the list of filter barriers
utilityTraceParameters?.filterBarriers?.add(utilityElement)
// get the clicked map point
val mapPoint = mapView.screenToLocation(screenPoint)
// find the closest coordinate on the selected element to the clicked point
val proximityResult =
GeometryEngine.nearestCoordinate(elements[0].geometry, mapPoint)
// create a graphic for the new utility element
val utilityElementGraphic = Graphic().apply {
// set the graphic's geometry to the coordinate on the element and add it to the graphics overlay
geometry = proximityResult.coordinate
}
// add utility element graphic to the filter barriers graphics overlay
filterBarriersGraphicsOverlay.graphics.add(utilityElementGraphic)
}
} catch (e: Exception) {
val error = "Error identifying tapped feature: " + e.message
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
} finally {
progressBar.visibility = View.GONE
}
}
}
}
/**
* Prompts the user to select a terminal from a provided list.
*
* @param terminals a list of terminals for the user to choose from
* @return the user's selected terminal
*/
private fun promptForTerminalSelection(
utilityElement: UtilityElement,
terminals: List<UtilityTerminal>
) {
// get a list of terminal names from the terminals
val terminalNames = terminals.map { it.name }
AlertDialog.Builder(this).apply {
setTitle("Select utility terminal:")
setItems(terminalNames.toTypedArray()) { _, which ->
// apply the selected terminal
val terminal = terminals[which]
utilityElement.terminal = terminal
// show the terminals name in the status label
val terminalName = if (terminal.name != null) terminal.name else "default"
Toast.makeText(
this@MainActivity,
"Feature added at terminal: $terminalName",
Toast.LENGTH_LONG
).show()
}.show()
}
}
/**
* Performs a valve isolation trace according to the defined trace configuration and starting* location, and selects the resulting features on the map.
*
* @param utilityNetwork the utility network to perform the trace on
* @param traceConfiguration the trace configuration to apply to the trace
*/
private fun performTrace(
utilityNetwork: UtilityNetwork,
traceConfiguration: UtilityTraceConfiguration
) {
progressBar.visibility = View.VISIBLE
// create a category comparison for the trace
// NOTE: UtilityNetworkAttributeComparison or UtilityCategoryComparisonOperator.DOES_NOT_EXIST
// can also be used. These conditions can be joined with either UtilityTraceOrCondition or UtilityTraceAndCondition.
val utilityCategoryComparison = UtilityCategoryComparison(
traceTypeSpinner.selectedItem as UtilityCategory,
UtilityCategoryComparisonOperator.EXISTS
)
// set the category comparison to the barriers of the configuration's trace filter
traceConfiguration.apply {
filter = UtilityTraceFilter()
filter.barriers = utilityCategoryComparison
// set the configuration to include or leave out isolated features
isIncludeIsolatedFeatures = includeIsolatedSwitch.isChecked
}
// build parameters for the isolation trace
utilityTraceParameters!!.traceConfiguration = traceConfiguration
// run the trace and get the result
val utilityTraceResultsFuture = utilityNetwork.traceAsync(utilityTraceParameters)
utilityTraceResultsFuture.addDoneListener {
try {
// get the first element of the trace result if it is not null
(utilityTraceResultsFuture.get()[0] as? UtilityElementTraceResult)?.let { utilityElementTraceResult ->
if (utilityElementTraceResult.elements.isNotEmpty()) {
// iterate over the map's feature layers
mapView.map.operationalLayers.filterIsInstance<FeatureLayer>()
.forEach { featureLayer ->
// clear any selections from a previous trace
featureLayer.clearSelection()
val queryParameters = QueryParameters()
// for each utility element in the trace, check if its network source is the same as
// the feature table, and if it is, add it to the query parameters to be selected
utilityElementTraceResult.elements.filter { it.networkSource.name == featureLayer.featureTable.tableName }
.forEach { utilityElement ->
queryParameters.objectIds.add(utilityElement.objectId)
}
// select features that match the query
featureLayer.selectFeaturesAsync(
queryParameters,
FeatureLayer.SelectionMode.NEW
)
}
} else {
// iterate over the map's feature layers
mapView.map.operationalLayers.filterIsInstance<FeatureLayer>()
.forEach { featureLayer ->
// clear any selections from a previous trace
featureLayer.clearSelection()
}
// trace result is empty
val message = "Utility Element Trace Result had no elements!"
Log.i(TAG, message)
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
}
// hide the progress bar when the trace is completed or failed
progressBar.visibility = View.GONE
} catch (e: Exception) {
val error = "Error loading utility trace results: ${e.message}"
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
}
}
}
private fun reset() {
traceControlsTextView.text = getString(R.string.choose_category_for_filter_barrier)
traceTypeSpinner.isEnabled = true
mapView.map.operationalLayers.forEach { layer ->
(layer as? FeatureLayer)?.clearSelection()
}
utilityTraceParameters?.filterBarriers?.clear()
filterBarriersGraphicsOverlay.graphics.clear()
}
/**
* Initialize the category selection spinner using a utility network definition.
*
* @param networkDefinition the utility network definition to populate the spinner
*/
private fun populateCategorySpinner(
networkDefinition: UtilityNetworkDefinition
) {
// populate the spinner with utility categories as the data and their names as the text
traceTypeSpinner.adapter =
object : ArrayAdapter<UtilityCategory>(
this,
R.layout.spinner_text_item,
networkDefinition.categories
) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val binding = SpinnerTextItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
binding.textView.text = (getItem(position) as UtilityCategory).name
return binding.root
}
override fun getDropDownView(
position: Int,
convertView: View?,
parent: ViewGroup
): View = getView(position, convertView, parent)
}
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | e8c5d184d93fb28aaaae85421ff5d61b | 44.657377 | 155 | 0.590033 | 5.937114 | false | false | false | false |
jayrave/falkon | falkon-dao/src/main/kotlin/com/jayrave/falkon/dao/insert/InsertBuilderImpl.kt | 1 | 2428 | package com.jayrave.falkon.dao.insert
import com.jayrave.falkon.dao.lib.LinkedHashMapBackedDataConsumer
import com.jayrave.falkon.engine.CompiledStatement
import com.jayrave.falkon.engine.bindAll
import com.jayrave.falkon.engine.closeIfOpThrows
import com.jayrave.falkon.engine.safeCloseAfterExecution
import com.jayrave.falkon.iterables.IterableBackedIterable
import com.jayrave.falkon.mapper.Column
import com.jayrave.falkon.mapper.Table
import com.jayrave.falkon.sqlBuilders.InsertSqlBuilder
import java.sql.SQLException
internal class InsertBuilderImpl<T : Any>(
override val table: Table<T, *>, private val insertSqlBuilder: InsertSqlBuilder) :
InsertBuilder<T> {
private val dataConsumer = LinkedHashMapBackedDataConsumer()
/**
* Calling this method again for columns that have been already set will overwrite the
* existing values for those columns
*/
override fun values(setter: InnerSetter<T>.() -> Any?): Ender {
InnerSetterImpl().setter()
return EnderImpl()
}
private inner class EnderImpl : Ender {
override fun build(): Insert {
val map = dataConsumer.map
val sql = insertSqlBuilder.build(table.name, IterableBackedIterable.create(map.keys))
return InsertImpl(table.name, sql, IterableBackedIterable.create(map.values))
}
override fun compile(): CompiledStatement<Int> {
val insert = build()
return table.configuration.engine
.compileInsert(table.name, insert.sql)
.closeIfOpThrows { bindAll(insert.arguments) }
}
override fun insert() {
val numberOfRecordsInserted = compile().safeCloseAfterExecution()
if (numberOfRecordsInserted != 1) {
throw SQLException(
"Number of records inserted: $numberOfRecordsInserted. " +
"It should have been 1"
)
}
}
}
private inner class InnerSetterImpl : InnerSetter<T> {
/**
* Calling this method again for a column that has been already set will overwrite the
* existing value for that column
*/
override fun <C> set(column: Column<T, C>, value: C) {
dataConsumer.setColumnName(column.name)
column.putStorageFormIn(value, dataConsumer)
}
}
} | apache-2.0 | ce90c08018ec4674845f224a54bf360a | 34.720588 | 97 | 0.654448 | 4.660269 | false | false | false | false |
AlmasB/FXGL | fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/level/text/TextLevelLoader.kt | 1 | 1309 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.entity.level.text
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.GameWorld
import com.almasb.fxgl.entity.SpawnData
import com.almasb.fxgl.entity.level.Level
import com.almasb.fxgl.entity.level.LevelLoader
import java.net.URL
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class TextLevelLoader
@JvmOverloads constructor(
val blockWidth: Int,
val blockHeight: Int,
val emptyChar: Char = ' '
) : LevelLoader {
override fun load(url: URL, world: GameWorld): Level {
val lines = url.openStream().bufferedReader().readLines()
val entities = ArrayList<Entity>()
var maxWidth = 0
lines.forEachIndexed { i, line ->
if (line.length > maxWidth)
maxWidth = line.length
line.forEachIndexed { j, c ->
if (c != emptyChar) {
val e = world.create("$c", SpawnData(j.toDouble() * blockWidth, i.toDouble() * blockHeight))
entities.add(e)
}
}
}
return Level(maxWidth * blockWidth, lines.size * blockWidth, entities)
}
} | mit | bdc24014269e91924d32d561199c1677 | 25.2 | 112 | 0.615737 | 4.065217 | false | false | false | false |
AndroidX/constraintlayout | demoProjects/ComposeMail/app/src/main/java/com/example/composemail/ui/home/toptoolbar/SearchBar.kt | 2 | 3013 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.composemail.ui.home.toptoolbar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.composemail.ui.theme.textBackgroundColor
@Composable
fun SearchBar(
modifier: Modifier = Modifier
) {
var placeholder: String by remember { mutableStateOf("Search in mails") }
OutlinedTextField(
modifier = modifier
.clip(RoundedCornerShape(32.dp))
.background(MaterialTheme.colors.textBackgroundColor)
.onFocusChanged {
placeholder = if (it.isFocused) {
"I'm not implemented yet!"
} else {
"Search in mails"
}
},
value = "",
onValueChange = { newText ->
},
placeholder = {
Text(text = placeholder)
},
leadingIcon = {
Icon(imageVector = Icons.Default.Search, contentDescription = null)
},
singleLine = true,
shape = MaterialTheme.shapes.small,
colors = TextFieldDefaults.textFieldColors(
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
)
)
}
@Preview
@Composable
private fun SearchBarPreview() {
Column(
Modifier
.fillMaxWidth()
.height(400.dp)
) {
SearchBar(Modifier.fillMaxWidth())
}
} | apache-2.0 | 7d08596825b481df5206f0d6b25abba8 | 32.488889 | 79 | 0.710587 | 4.635385 | false | false | false | false |
lvtanxi/TanxiNote | app/src/main/java/com/lv/note/helper/BGARefreshDelegate.kt | 1 | 3803 | package com.lv.note.helper
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import cn.bingoogolapple.refreshlayout.BGARefreshLayout
import cn.bingoogolapple.refreshlayout.BGARefreshViewHolder
import cn.bingoogolapple.refreshlayout.BGAStickinessRefreshViewHolder
import com.lv.note.R
/**
* User: 吕勇
* Date: 2016-05-04
* Time: 09:18
* Description:下拉刷新使用
*/
class BGARefreshDelegate : BGARefreshLayout.BGARefreshLayoutDelegate {
private var mRefreshLayout: BGARefreshLayout? = null
var isMore: Boolean = false
private set
private var mRefreshListener: BGARefreshListener? = null
constructor(refreshLayout: BGARefreshLayout, refreshListener: BGARefreshListener, loadMore: Boolean) {
initBga(refreshListener, refreshLayout)
mRefreshLayout!!.setRefreshViewHolder(getRefreshViewHolder(refreshLayout.context, loadMore))
}
@JvmOverloads constructor(refreshLayout: BGARefreshLayout, refreshListener: BGARefreshListener, recyclerView: RecyclerView?, loadMore: Boolean, column: Int = 0) {
initBga(refreshListener, refreshLayout)
if (null != recyclerView)
mRefreshLayout!!.setRefreshViewHolder(getBGARefreshViewHolder(recyclerView, loadMore, column))
else
mRefreshLayout!!.setRefreshViewHolder(getRefreshViewHolder(refreshLayout.context, loadMore))
}
private fun initBga(refreshListener: BGARefreshListener, refreshLayout: BGARefreshLayout) {
try {
mRefreshListener = refreshListener
mRefreshLayout = refreshLayout
if (mRefreshListener == null || mRefreshLayout == null)
throw Exception("BGARefreshListener或者BGARefreshLayout为空")
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onBGARefreshLayoutBeginRefreshing(refreshLayout: BGARefreshLayout) {
isMore = false
mRefreshListener!!.onBGARefresh()
}
override fun onBGARefreshLayoutBeginLoadingMore(refreshLayout: BGARefreshLayout): Boolean {
isMore = true
return mRefreshListener!!.onBGARefresh()
}
fun stopRefresh() {
if (null == mRefreshLayout)
return
if (isMore)
mRefreshLayout!!.endLoadingMore()
else
mRefreshLayout!!.endRefreshing()
}
/**
* 获取RecyclerView的RefreshViewHolder
* @param recyclerView RecyclerView
* *
* @param loadMore 是否加载更多
*/
fun getBGARefreshViewHolder(recyclerView: RecyclerView, loadMore: Boolean, column: Int): BGARefreshViewHolder {
if (column > 0)
recyclerView.layoutManager = StaggeredGridLayoutManager(column, StaggeredGridLayoutManager.VERTICAL)
else
recyclerView.layoutManager = LinearLayoutManager(recyclerView.context, LinearLayoutManager.VERTICAL, false)
return getRefreshViewHolder(recyclerView.context, loadMore)
}
/**
* 获取其他空间的RefreshViewHolder
* @param loadMore 是否加载更多
*/
fun getRefreshViewHolder(context: Context, loadMore: Boolean): BGARefreshViewHolder {
val stickinessRefreshViewHolder = BGAStickinessRefreshViewHolder(context, loadMore)
stickinessRefreshViewHolder.setStickinessColor(R.color.colorPrimary)
stickinessRefreshViewHolder.setRotateImage(R.mipmap.bga_refresh_stickiness)
stickinessRefreshViewHolder.setLoadingMoreText("")
return stickinessRefreshViewHolder
}
interface BGARefreshListener {
fun onBGARefresh(): Boolean
}
fun cleanListener() {
mRefreshListener = null
}
}
| apache-2.0 | 69eb6ca4e1848233d40ee47199a68750 | 34.235849 | 166 | 0.718608 | 4.869622 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-permissions-bukkit/src/test/kotlin/com/rpkit/permissions/bukkit/group/test/RPKGroupImplTests.kt | 1 | 1587 | /*
* Copyright 2021 Ren Binden
* 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.rpkit.permissions.bukkit.group.test
import com.rpkit.permissions.bukkit.group.RPKGroupImpl
import com.rpkit.permissions.bukkit.group.RPKGroupName
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
class RPKGroupImplTests : WordSpec({
val inheritedGroup = RPKGroupImpl(
name = RPKGroupName("test inherited"),
allow = listOf(
"rpkit.permissions.inherited.test"
),
deny = listOf(),
inheritance = listOf()
)
val group = RPKGroupImpl(
name = RPKGroupName("test group"),
allow = listOf(
"rpkit.permissions.test"
),
deny = listOf(
"rpkit.permissions.denied.test"
),
inheritance = listOf(
inheritedGroup
)
)
"RPKGroupImpl.deserialize" should {
"return an equivalent instance to what was serialized" {
RPKGroupImpl.deserialize(group.serialize()) shouldBe group
}
}
})
| apache-2.0 | b74431d2e1e5db9b167bdf7b97190328 | 31.387755 | 75 | 0.669187 | 4.35989 | false | true | false | false |
Doist/TodoistModels | src/main/java/com/todoist/pojo/Note.kt | 1 | 529 | package com.todoist.pojo
open class Note<F : FileAttachment> @JvmOverloads constructor(
id: Long,
open var content: String?,
open var posted: Long = System.currentTimeMillis(),
open var postedUid: Long,
open var uidsToNotify: Set<Long> = emptySet(),
open var fileAttachment: F? = null,
open var reactions: Map<String, LongArray> = emptyMap(),
open var projectId: Long?,
open var itemId: Long?,
open var isArchived: Boolean = false,
isDeleted: Boolean = false
) : Model(id, isDeleted)
| mit | 0f2490fd054782df72a9e7536138d608 | 34.266667 | 62 | 0.6862 | 4.069231 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/user/TagSelectActivity.kt | 1 | 4593 | package com.fuyoul.sanwenseller.ui.user
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.CheckBox
import com.csl.refresh.SmartRefreshLayout
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.base.BaseAdapter
import com.fuyoul.sanwenseller.base.BaseViewHolder
import com.fuyoul.sanwenseller.bean.AdapterMultiItem
import com.fuyoul.sanwenseller.bean.MultBaseBean
import com.fuyoul.sanwenseller.bean.reqhttp.ReqRegistMasterInfo
import com.fuyoul.sanwenseller.bean.reshttp.ResTagBean
import com.fuyoul.sanwenseller.configs.Code
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.structure.model.TagSelectM
import com.fuyoul.sanwenseller.structure.presenter.TagSelectP
import com.fuyoul.sanwenseller.structure.view.TagSelectV
import com.fuyoul.sanwenseller.utils.NormalFunUtils
import kotlinx.android.synthetic.main.tagselectlayout.*
/**
* @author: chen
* @CreatDate: 2017\10\31 0031
* @Desc:
*/
class TagSelectActivity : BaseActivity<TagSelectM, TagSelectV, TagSelectP>() {
private val selectTags = ArrayList<ResTagBean>()
private var adapter: BaseAdapter? = null
private var reqRegistMasterInfo: ReqRegistMasterInfo? = null
companion object {
fun start(context: Context, reqRegistMasterInfo: ReqRegistMasterInfo) {
val intent = Intent(context, TagSelectActivity::class.java)
val bund = Bundle()
bund.putSerializable("data", reqRegistMasterInfo)
intent.putExtras(bund)
context.startActivity(intent)
}
}
override fun setLayoutRes(): Int = R.layout.tagselectlayout
override fun initData(savedInstanceState: Bundle?) {
reqRegistMasterInfo = intent.extras.getSerializable("data") as ReqRegistMasterInfo
getPresenter().getTagList(this)
}
override fun setListener() {
tagSelectBtn.setOnClickListener {
if (selectTags.isNotEmpty() && selectTags.size > 3) {
reqRegistMasterInfo?.labelList = selectTags
RegistMasterInfoActivity.start(this, reqRegistMasterInfo!!)
} else {
NormalFunUtils.showToast(this, "请选择4~6个合适的标签")
}
}
}
override fun getPresenter(): TagSelectP = TagSelectP(initViewImpl())
override fun initViewImpl(): TagSelectV = object : TagSelectV() {
override fun getAdapter(): BaseAdapter {
if (adapter == null) {
adapter = object : BaseAdapter(this@TagSelectActivity) {
override fun convert(holder: BaseViewHolder, position: Int, allDatas: List<MultBaseBean>) {
val item = allDatas[position] as ResTagBean
val tagTitle = holder.itemView.findViewById<CheckBox>(R.id.tagTitle)
tagTitle.text = item.label
tagTitle.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
selectTags.add(item)
} else {
selectTags.remove(item)
}
}
}
override fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) {
multiItems.add(AdapterMultiItem(Code.VIEWTYPE_TAG, R.layout.alltagitem))
}
override fun onItemClicked(view: View, position: Int) {
}
override fun onEmpryLayou(view: View, layoutResId: Int) {
}
override fun getSmartRefreshLayout(): SmartRefreshLayout = SmartRefreshLayout(this@TagSelectActivity)
override fun getRecyclerView(): RecyclerView = tagDataList
}
}
return adapter!!
}
override fun setTag(datas: List<ResTagBean>) {
val manager = GridLayoutManager(this@TagSelectActivity, 3)
tagDataList.layoutManager = manager
tagDataList.adapter = getAdapter()
getAdapter().setData(true, datas)
}
}
override fun initTopBar(): TopBarOption {
val op = TopBarOption()
op.isShowBar = true
op.mainTitle = "选择您的个人标签"
return op
}
} | apache-2.0 | 4c5edb33a3265694912146e922456128 | 32.284672 | 121 | 0.638956 | 4.85 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/connectivityQuietHours/receivers/DeleteNotificationIntent.kt | 1 | 1913 | package com.itachi1706.cheesecakeutilities.modules.connectivityQuietHours.receivers
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import com.itachi1706.cheesecakeutilities.BaseBroadcastReceiver
import com.itachi1706.helperlib.helpers.LogHelper
/**
* Created by Kenneth on 1/1/2019.
* for com.itachi1706.cheesecakeutilities.modules.ConnectivityQuietHours.Receivers in CheesecakeUtilities
*/
class DeleteNotificationIntent : BaseBroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
val action = intent.action ?: return
LogHelper.i(TAG, "Received Notification Removal Intent ($action)")
when (action) {
NotificationHelper.NOTIFICATION_SUM_CANCEL -> {
LogHelper.i(TAG, "Removing all notifications")
if (NotificationHelper.lines == null) return
NotificationHelper.lines!!.clear()
NotificationHelper.lines = null
NotificationHelper.summaryId = -9999
}
NotificationHelper.NOTIFICATION_CANCEL -> {
if (NotificationHelper.lines == null || NotificationHelper.lines!!.size <= 0) return
val data = intent.getStringExtra("data")
LogHelper.i(TAG, "Size: " + NotificationHelper.lines!!.size + " | Removing " + data)
NotificationHelper.lines!!.remove(intent.getStringExtra("data"))
LogHelper.i(TAG, "Removed and updating notification. New Size: " + NotificationHelper.lines!!.size)
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
NotificationHelper.createSummaryNotification(context, manager)
}
}
}
companion object {
private val TAG = "QuietHour-Notif"
}
}
| mit | 6fd002f747e4537a750a92d1dc49eae9 | 43.488372 | 115 | 0.674334 | 5.19837 | false | false | false | false |
appnexus/mobile-sdk-android | examples/kotlin/LazyLoadDemo/app/src/main/java/com/xandr/lazyloaddemo/MARSettingsActivity.kt | 1 | 3462 | package com.xandr.lazyloaddemo
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Spinner
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import appnexus.com.appnexussdktestapp.adapter.AdRecyclerAdapter
import com.xandr.lazyloaddemo.listener.RecyclerItemClickListener
import kotlinx.android.synthetic.main.activity_marsettings.*
class MARSettingsActivity : AppCompatActivity(), RecyclerItemClickListener {
var selectedAdType = ""
var arrayListAdType = ArrayList<String>()
var arrayListRecycler = ArrayList<String>()
lateinit var spinnerAdType: Spinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_marsettings)
setupSpinners()
setupButtonClick()
var layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerList.layoutManager = layoutManager
recyclerList.adapter = AdRecyclerAdapter(arrayListRecycler, this, this)
}
private fun setupButtonClick() {
var btnAdd = findViewById<Button>(R.id.btnAdd)
btnAdd.setOnClickListener(View.OnClickListener {
if (!TextUtils.isEmpty(selectedAdType)) {
arrayListAdType.add(selectedAdType)
arrayListRecycler.add("$selectedAdType")
spinnerAdType.setSelection(0)
recyclerList.adapter!!.notifyDataSetChanged()
}
})
var btnLoad: Button = findViewById(R.id.btnLoad)
btnLoad.setOnClickListener(View.OnClickListener {
val intent = Intent(this@MARSettingsActivity, MARLoadAndDisplayActivity::class.java)
intent.putExtra(MARLoadAndDisplayActivity.AD_TYPE, arrayListAdType)
startActivity(intent)
})
}
private fun setupSpinners() {
spinnerAdType = findViewById(R.id.spnrAdUnitType)
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter.createFromResource(
this,
R.array.ad_type_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spinnerAdType.adapter = adapter
}
spinnerAdType.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, pos: Int, id: Long) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
selectedAdType = resources.getStringArray(R.array.ad_type_array)[pos]
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// Another interface callback
}
}
}
override fun onItemClick(position: Int) {
arrayListRecycler.removeAt(position)
arrayListAdType.removeAt(position)
recyclerList.adapter!!.notifyDataSetChanged()
}
}
| apache-2.0 | af51136dd4b165bd68a1cbcc9e61afe5 | 38.793103 | 99 | 0.69353 | 5.237519 | false | false | false | false |
shiraji/permissions-dispatcher-plugin | src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/models/GeneratePMCodeModel.kt | 1 | 2434 | package com.github.shiraji.permissionsdispatcherplugin.models
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
class GeneratePMCodeModel(val project: Project) {
private val activityPsiClass: PsiClass? = createPsiClass("android.app.Activity")
private val fragmentPsiClass: PsiClass? = createPsiClass("android.app.Fragment")
private val supportFragmentPsiClass: PsiClass? = createPsiClass("android.support.v4.app.Fragment")
private val specialPermissionNames = listOf("SYSTEM_ALERT_WINDOW", "WRITE_SETTINGS")
var permissions: List<String> = emptyList()
var needsPermissionMethodName: String = ""
var onShowRationaleMethodName: String = ""
var onPermissionDeniedMethodName: String = ""
var onNeverAskAgainMethodName: String = ""
var maxSdkVersion: Int = -1
fun isActivity(aClass: PsiClass): Boolean {
activityPsiClass ?: return false
return aClass.isInheritor(activityPsiClass, true)
}
fun isFragment(aClass: PsiClass): Boolean {
fragmentPsiClass ?: return false
return aClass.isInheritor(fragmentPsiClass, true)
}
fun isSupportFragment(aClass: PsiClass): Boolean {
supportFragmentPsiClass ?: return false
return aClass.isInheritor(supportFragmentPsiClass, true)
}
fun isActivityOrFragment(aClass: PsiClass) = isActivity(aClass) || isFragment(aClass) || isSupportFragment(aClass)
fun createPsiClass(qualifiedName: String): PsiClass? {
val psiFacade = JavaPsiFacade.getInstance(project)
val searchScope = GlobalSearchScope.allScope(project)
return psiFacade.findClass(qualifiedName, searchScope)
}
fun toPermissionParameter(): String {
return when (permissions.size) {
0 -> ""
1 -> "Manifest.permission.${permissions[0]}"
else -> "{${permissions.map { "Manifest.permission.$it" }.joinToString { it }}}"
}
}
fun toListParameter(): String {
return when (permissions.size) {
0 -> ""
1 -> "Manifest.permission.${permissions[0]}"
else -> permissions.map { "Manifest.permission.$it" }.joinToString { it }
}
}
fun isSpecialPermissions(): Boolean {
return permissions.size == 1 && specialPermissionNames.contains(permissions[0])
}
} | apache-2.0 | 42246b9a07b37e19959b818c519a8c7e | 35.343284 | 118 | 0.692276 | 4.781925 | false | false | false | false |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/adapters/BookmarksAdapter.kt | 1 | 10521 | package be.digitalia.fosdem.adapters
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.collection.SimpleArrayMap
import androidx.core.content.ContextCompat
import androidx.core.text.set
import androidx.core.view.isGone
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver
import be.digitalia.fosdem.R
import be.digitalia.fosdem.activities.EventDetailsActivity
import be.digitalia.fosdem.model.Event
import be.digitalia.fosdem.model.RoomStatus
import be.digitalia.fosdem.utils.DateUtils
import be.digitalia.fosdem.utils.atZoneOrNull
import be.digitalia.fosdem.widgets.MultiChoiceHelper
import java.time.ZoneId
import java.time.format.DateTimeFormatter
class BookmarksAdapter(context: Context, private val multiChoiceHelper: MultiChoiceHelper) :
ListAdapter<Event, BookmarksAdapter.ViewHolder>(DIFF_CALLBACK) {
private val timeFormatter = DateUtils.getTimeFormatter(context)
@ColorInt
private val errorColor: Int
private val observers = SimpleArrayMap<AdapterDataObserver, BookmarksDataObserverWrapper>()
var zoneId: ZoneId? = null
set(value) {
if (field != value) {
field = value
notifyItemRangeChanged(0, itemCount, DETAILS_PAYLOAD)
}
}
var roomStatuses: Map<String, RoomStatus> = emptyMap()
set(value) {
if (field != value) {
field = value
notifyItemRangeChanged(0, itemCount, DETAILS_PAYLOAD)
}
}
init {
setHasStableIds(true)
with(context.theme.obtainStyledAttributes(R.styleable.ErrorColors)) {
errorColor = getColor(R.styleable.ErrorColors_colorError, 0)
recycle()
}
}
override fun getItemId(position: Int) = getItem(position).id
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_event, parent, false)
return ViewHolder(view, multiChoiceHelper, timeFormatter, errorColor)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val event = getItem(position)
holder.bind(event)
val previous = if (position > 0) getItem(position - 1) else null
val next = if (position + 1 < itemCount) getItem(position + 1) else null
holder.bindDetails(event, previous, next, zoneId, roomStatuses[event.roomName])
holder.bindSelection()
}
override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: List<Any>) {
if (payloads.isEmpty()) {
onBindViewHolder(holder, position)
} else {
val event = getItem(position)
if (DETAILS_PAYLOAD in payloads) {
val previous = if (position > 0) getItem(position - 1) else null
val next = if (position + 1 < itemCount) getItem(position + 1) else null
holder.bindDetails(event, previous, next, zoneId, roomStatuses[event.roomName])
}
if (MultiChoiceHelper.SELECTION_PAYLOAD in payloads) {
holder.bindSelection()
}
}
}
override fun registerAdapterDataObserver(observer: AdapterDataObserver) {
if (!observers.containsKey(observer)) {
val wrapper = BookmarksDataObserverWrapper(observer, this)
observers.put(observer, wrapper)
super.registerAdapterDataObserver(wrapper)
}
}
override fun unregisterAdapterDataObserver(observer: AdapterDataObserver) {
val wrapper = observers.remove(observer)
if (wrapper != null) {
super.unregisterAdapterDataObserver(wrapper)
}
}
class ViewHolder(itemView: View, helper: MultiChoiceHelper,
private val timeFormatter: DateTimeFormatter, @ColorInt private val errorColor: Int)
: MultiChoiceHelper.ViewHolder(itemView, helper), View.OnClickListener {
private val title: TextView = itemView.findViewById(R.id.title)
private val persons: TextView = itemView.findViewById(R.id.persons)
private val trackName: TextView = itemView.findViewById(R.id.track_name)
private val details: TextView = itemView.findViewById(R.id.details)
private var event: Event? = null
init {
setOnClickListener(this)
}
fun bind(event: Event) {
val context = itemView.context
this.event = event
title.text = event.title
val personsSummary = event.personsSummary
persons.text = personsSummary
persons.isGone = personsSummary.isNullOrEmpty()
val track = event.track
trackName.text = track.name
trackName.setTextColor(ContextCompat.getColorStateList(context, track.type.textColorResId))
trackName.contentDescription = context.getString(R.string.track_content_description, track.name)
}
fun bindDetails(event: Event, previous: Event?, next: Event?, zoneId: ZoneId?, roomStatus: RoomStatus?) {
val context = details.context
val startTimeString = event.startTime?.atZoneOrNull(zoneId)?.format(timeFormatter) ?: "?"
val endTimeString = event.endTime?.atZoneOrNull(zoneId)?.format(timeFormatter) ?: "?"
val roomName = event.roomName.orEmpty()
val detailsText: CharSequence = "${event.day.shortName}, $startTimeString ― $endTimeString | $roomName"
val detailsSpannable = SpannableString(detailsText)
var detailsDescription = detailsText
// Highlight the date and time with error color in case of conflicting schedules
if (isOverlapping(event, previous, next)) {
val endPosition = detailsText.indexOf(" | ")
detailsSpannable[0, endPosition] = ForegroundColorSpan(errorColor)
detailsSpannable[0, endPosition] = StyleSpan(Typeface.BOLD)
detailsDescription = context.getString(R.string.bookmark_conflict_content_description, detailsDescription)
}
if (roomStatus != null) {
val color = ContextCompat.getColor(context, roomStatus.colorResId)
detailsSpannable[detailsText.length - roomName.length, detailsText.length] = ForegroundColorSpan(color)
}
details.text = detailsSpannable
details.contentDescription = context.getString(R.string.details_content_description, detailsDescription)
}
/**
* Checks if the current event is overlapping with the previous or next one.
*/
private fun isOverlapping(event: Event, previous: Event?, next: Event?): Boolean {
val startTime = event.startTime
val previousEndTime = previous?.endTime
if (startTime != null && previousEndTime != null && previousEndTime > startTime) {
// The event overlaps with the previous one
return true
}
val endTime = event.endTime
val nextStartTime = next?.startTime
// The event overlaps with the next one
return endTime != null && nextStartTime != null && nextStartTime < endTime
}
override fun onClick(view: View) {
event?.let {
val context = view.context
val intent = Intent(context, EventDetailsActivity::class.java)
.putExtra(EventDetailsActivity.EXTRA_EVENT, it)
context.startActivity(intent)
}
}
}
/**
* An observer dispatching updates to the source observer while additionally notifying changes
* of the immediately previous and next items in order to properly update their overlapping status display.
*/
private class BookmarksDataObserverWrapper(private val observer: AdapterDataObserver, private val adapter: RecyclerView.Adapter<*>)
: AdapterDataObserver() {
private fun updatePrevious(position: Int) {
if (position >= 0) {
observer.onItemRangeChanged(position, 1, DETAILS_PAYLOAD)
}
}
private fun updateNext(position: Int) {
if (position < adapter.itemCount) {
observer.onItemRangeChanged(position, 1, DETAILS_PAYLOAD)
}
}
override fun onChanged() {
observer.onChanged()
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
observer.onItemRangeChanged(positionStart, itemCount)
updatePrevious(positionStart - 1)
updateNext(positionStart + itemCount)
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
observer.onItemRangeChanged(positionStart, itemCount, payload)
updatePrevious(positionStart - 1)
updateNext(positionStart + itemCount)
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
observer.onItemRangeInserted(positionStart, itemCount)
updatePrevious(positionStart - 1)
updateNext(positionStart + itemCount)
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
observer.onItemRangeRemoved(positionStart, itemCount)
updatePrevious(positionStart - 1)
updateNext(positionStart)
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
updatePrevious(fromPosition - 1)
updateNext(fromPosition + itemCount)
observer.onItemRangeMoved(fromPosition, toPosition, itemCount)
updatePrevious(toPosition - 1)
updateNext(toPosition + itemCount)
}
}
companion object {
private val DIFF_CALLBACK: DiffUtil.ItemCallback<Event> = createSimpleItemCallback { it.id }
private val DETAILS_PAYLOAD = Any()
}
} | apache-2.0 | 33920ee0ea209dfff5244b6c291ddea5 | 41.08 | 135 | 0.659759 | 5.113758 | false | false | false | false |
peterholak/mogul | native/src/mogul/microdom/Events.kt | 2 | 2612 | package mogul.microdom
import mogul.microdom.primitives.MicroDomMarker
import mogul.platform.*
typealias Handler<T> = (event: T) -> Unit
typealias MouseEventHandler = Handler<MouseEvent>
abstract class DomEventType : EventType()
object MouseOver : DomEventType()
object MouseOut : DomEventType()
object Click : DomEventType()
@Suppress("unused")
@MicroDomMarker
class Events {
val map = mutableMapOf<EventType, MutableList<Handler<Event>>>()
override fun equals(other: Any?) = other is Events && other.map == map
override fun hashCode() = map.hashCode()
private fun <T: Event> addHandler(type: DomEventType, handler: Handler<T>) {
@Suppress("UNCHECKED_CAST")
map.getOrPut(type, { mutableListOf() }).add(handler as Handler<Event>)
}
// In the React-like part, just one possible handler per event is enough, not sure about the general "microdom"
// though.
inner class EventDsl<out T: Event>(val type: DomEventType) {
operator fun plusAssign(handler: Handler<T>?) = handler?.let { addHandler(type, it) } ?: Unit
}
fun clearAll() = map.clear()
val click; get() = EventDsl<MouseEvent>(Click)
val mouseOver; get() = EventDsl<MouseEvent>(MouseOver)
val mouseOut; get() = EventDsl<MouseEvent>(MouseOut)
}
fun events(code: Events.() -> Unit): Events {
val e = Events()
code(e)
return e
}
@Suppress("unused")
/**
* Shitty unfinished hack for the problem where each lambda gets re-created on every render(), and then it appears
* as if props have changed (because the lambda instance is different) when in reality they haven't,
* which can cause unnecessary re-renders.
*
* This class simply makes the caller assign a string tag (like a hashCode) and manually use a different one
* whenever the code in the event handler changes. The idea is that it almost never changes, so 99% of the time,
* it won't be necessary to change it and the default value (empty string) will be fine.
*
* The other alternative is to use bound method references instead of lambdas (or to be ok with those
* extra re-renders, or to use something like `shouldComponentUpdate`).
*
* I'm currently experimenting with various approaches to things, so classes like this exist around the codebase.
*/
class UniqueLambdaWrapper<out T>(val tag: String = "", val lambda: T) {
override fun equals(other: Any?) = other is UniqueLambdaWrapper<*> && other.tag == tag
override fun hashCode() = tag.hashCode()
}
@Suppress("unused")
/** See [UniqueLambdaWrapper] */
fun <T> u(tag: String = "", lambda: T) = UniqueLambdaWrapper(tag, lambda) | mit | 59456cdbd7df59edf9d88f6e6f965466 | 36.869565 | 115 | 0.710184 | 4.006135 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/terraform/config/model/version/Constraint.kt | 1 | 5451 | /*
* Copyright 2000-2019 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 org.intellij.plugins.hcl.terraform.config.model.version
import java.util.*
import java.util.function.BiFunction
import java.util.regex.Pattern
class VersionConstraint private constructor(val constraints: List<Constraint>) {
data class Constraint(val operation: ConstraintFunction, val check: Version, val original: String) {
fun check(version: Version): Boolean {
return operation.apply(version, this.check)
}
override fun toString(): String {
return original
}
}
companion object {
val AnyVersion by lazy { return@lazy parse(">=0.0.0") }
@Throws(MalformedConstraintException::class)
fun parse(source: String): VersionConstraint {
return VersionConstraint(source.split(',').map {
parseSingle(it)
})
}
private val ops = mapOf(
"" to ConstraintFunction.Equal,
"=" to ConstraintFunction.Equal,
"!=" to ConstraintFunction.NotEqual,
">" to ConstraintFunction.GreaterThan,
"<" to ConstraintFunction.LessThan,
">=" to ConstraintFunction.GreaterThanEqual,
"<=" to ConstraintFunction.LessThanEqual,
"~>" to ConstraintFunction.Pessimistic
)
private val constraintRegexp = String.format("^\\s*(%s)\\s*(%s)\\s*\$", ops.keys.joinToString("|") { Pattern.quote(it) }, VersionRegexpRaw).toRegex()
private fun parseSingle(s: String): Constraint {
val match = constraintRegexp.matchEntire(s)?.groupValues ?: throw MalformedConstraintException("Malformed constraint: $s")
val version = try {
Version.parse(match[2])
} catch (e: MalformedVersionException) {
throw MalformedConstraintException(e.message!!)
}
val operation = ops[match[1]] ?: throw MalformedConstraintException("Unsupported operation: ${match[1]}")
return Constraint(operation, version, s)
}
}
fun check(version: Version): Boolean {
return constraints.all { it.check(version) }
}
override fun toString(): String {
return constraints.joinToString(",")
}
}
class MalformedConstraintException(message: String) : Exception(message)
fun prereleaseCheck(v: Version, c: Version): Boolean {
val vPre = v.pre.isNotEmpty()
val cPre = c.pre.isNotEmpty()
if (cPre && vPre) {
// A constraint with a pre-release can only match a pre-release version
// with the same base segments.
return Arrays.equals(c.segments, v.segments)
}
if (!cPre && vPre) {
// A constraint without a pre-release can only match a version without a
// pre-release.
return false
}
if (cPre && !vPre) {
// OK, except with the pessimistic operator
}
if (!cPre && !vPre) {
// OK
}
return true
}
sealed class ConstraintFunction(val name: String, private val f: (Version, Version) -> Boolean) : BiFunction<Version, Version, Boolean> {
override fun apply(t: Version, u: Version): Boolean = f(t, u)
object Equal : ConstraintFunction("=", { v, c -> v == c })
object NotEqual : ConstraintFunction("!=", { v, c -> v != c })
object GreaterThan : ConstraintFunction(">", { v, c -> prereleaseCheck(v, c) && v > c })
object LessThan : ConstraintFunction("<", { v, c -> prereleaseCheck(v, c) && v < c })
object GreaterThanEqual : ConstraintFunction(">=", { v, c -> prereleaseCheck(v, c) && v >= c })
object LessThanEqual : ConstraintFunction("<=", { v, c -> prereleaseCheck(v, c) && v <= c })
object Pessimistic : ConstraintFunction("~>", fun(v: Version, c: Version): Boolean {
if (!prereleaseCheck(v, c) || (c.pre.isNotEmpty() && v.pre.isEmpty())) {
// Using a pessimistic constraint with a pre-release, restricts versions to pre-releases
return false
}
// If the version being checked is naturally less than the constraint, then there
// is no way for the version to be valid against the constraint
if (v < c) {
return false
}
// If the version being checked has less specificity than the constraint, then there
// is no way for the version to be valid against the constraint
if (c.segments.size > v.segments.size) {
return false
}
// Check the segments in the constraint against those in the version. If the version
// being checked, at any point, does not have the same values in each index of the
// constraints segments, then it cannot be valid against the constraint.
for (i in 0..(c.si - 2)) {
if (v.segments[i] != c.segments[i]) {
return false
}
}
// Check the last part of the segment in the constraint. If the version segment at
// this index is less than the constraints segment at this index, then it cannot
// be valid against the constraint
if (c.segments[c.si - 1] > v.segments[c.si - 1]) {
return false
}
// If nothing has rejected the version by now, it's valid
return true
})
}
| apache-2.0 | 343e6eb056cc3f86316c36f51dafb928 | 35.099338 | 153 | 0.668868 | 4.058824 | false | false | false | false |
PhilGlass/auto-moshi | processor/src/main/kotlin/glass/phil/auto/moshi/AutoValue.kt | 1 | 680 | package glass.phil.auto.moshi
import com.google.auto.value.extension.AutoValueExtension.Context
import com.squareup.javapoet.TypeVariableName
import javax.annotation.processing.Filer
import javax.annotation.processing.Messager
import javax.lang.model.util.Types
val Context.filer: Filer get() = processingEnvironment().filer
val Context.messager: Messager get() = processingEnvironment().messager
val Context.types: Types get() = processingEnvironment().typeUtils
val Context.generic: Boolean get() = autoValueClass().typeParameters.isNotEmpty()
val Context.typeVariables: List<TypeVariableName> get() = autoValueClass().typeParameters
.map { TypeVariableName.get(it) }
| apache-2.0 | 8f6416343018c9b20c5e006ba116937d | 36.777778 | 89 | 0.810294 | 4.33121 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/item/ItemVoltmeter.kt | 2 | 1973 | package item
import com.cout970.magneticraft.Debug
import com.cout970.magneticraft.api.energy.IElectricNode
import com.cout970.magneticraft.misc.player.sendMessage
import com.cout970.magneticraft.misc.world.isServer
import com.cout970.magneticraft.registry.ELECTRIC_NODE_HANDLER
import com.cout970.magneticraft.registry.fromTile
import com.teamwizardry.librarianlib.common.base.item.ItemMod
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumActionResult
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.util.text.TextComponentString
import net.minecraft.world.World
import org.lwjgl.input.Keyboard
/**
* Created by cout970 on 20/07/2016.
*/
object ItemVoltmeter : ItemMod("voltmeter") {
override fun onItemUse(stack: ItemStack?, playerIn: EntityPlayer, worldIn: World, pos: BlockPos, hand: EnumHand?, facing: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): EnumActionResult {
//DEBUG
if (Debug.DEBUG && Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
val tile = worldIn.getTileEntity(pos)
playerIn.sendMessage("Server: ${worldIn.isServer}, Tile: ${tile?.serializeNBT()}\n")
}
//NO DEBUG
if (worldIn.isServer) {
val tile = worldIn.getTileEntity(pos)
if (tile != null) {
val handler = ELECTRIC_NODE_HANDLER!!.fromTile(tile)
if (handler != null) {
for (i in handler.nodes) {
if (i is IElectricNode) {
playerIn.addChatComponentMessage(TextComponentString("%.2fV %.2fA %.2fW".format(i.voltage, i.amperage, i.voltage * i.amperage)))
}
}
}
}
}
return super.onItemUse(stack, playerIn, worldIn, pos, hand, facing, hitX, hitY, hitZ)
}
} | gpl-2.0 | 0ada05365cf544ca6981b8c6e534ed14 | 37.705882 | 197 | 0.668525 | 4.127615 | false | false | false | false |
EyeSeeTea/QAApp | app/src/main/java/org/eyeseetea/malariacare/factories/MetadataFactory.kt | 1 | 2487 | package org.eyeseetea.malariacare.factories
import android.content.Context
import org.eyeseetea.malariacare.data.database.datasources.OrgUnitLocalDataSource
import org.eyeseetea.malariacare.data.database.datasources.ProgramLocalDataSource
import org.eyeseetea.malariacare.data.repositories.OrgUnitRepository
import org.eyeseetea.malariacare.data.repositories.ProgramRepository
import org.eyeseetea.malariacare.data.repositories.ServerMetadataRepository
import org.eyeseetea.malariacare.data.repositories.UserAccountRepository
import org.eyeseetea.malariacare.domain.boundary.repositories.IOrgUnitRepository
import org.eyeseetea.malariacare.domain.boundary.repositories.IProgramRepository
import org.eyeseetea.malariacare.domain.boundary.repositories.IServerMetadataRepository
import org.eyeseetea.malariacare.domain.boundary.repositories.IUserAccountRepository
import org.eyeseetea.malariacare.domain.usecase.GetOrgUnitByUidUseCase
import org.eyeseetea.malariacare.domain.usecase.GetOrgUnitsUseCase
import org.eyeseetea.malariacare.domain.usecase.GetProgramByUidUseCase
import org.eyeseetea.malariacare.domain.usecase.GetProgramsUseCase
import org.eyeseetea.malariacare.domain.usecase.GetServerMetadataUseCase
object MetadataFactory {
fun provideGetProgramByUidUseCase(): GetProgramByUidUseCase =
GetProgramByUidUseCase(provideProgramRepository())
fun provideGetOrgUnitByUidUseCase(): GetOrgUnitByUidUseCase =
GetOrgUnitByUidUseCase(provideOrgUnitRepository())
fun provideGetProgramsUseCase(): GetProgramsUseCase =
GetProgramsUseCase(provideProgramRepository())
fun provideGetOrgUnitsUseCase(): GetOrgUnitsUseCase =
GetOrgUnitsUseCase(provideOrgUnitRepository())
fun provideServerMetadataUseCase(context: Context): GetServerMetadataUseCase =
GetServerMetadataUseCase(provideServerMetadataRepository(context))
private fun provideServerMetadataRepository(context: Context): IServerMetadataRepository =
ServerMetadataRepository(context)
private fun provideOrgUnitRepository(): IOrgUnitRepository =
OrgUnitRepository(provideOrgUnitLocalDataSource())
private fun provideOrgUnitLocalDataSource(): OrgUnitLocalDataSource =
OrgUnitLocalDataSource()
fun provideUserAccountRepository(context: Context): IUserAccountRepository =
UserAccountRepository(context)
private fun provideProgramRepository(): IProgramRepository =
ProgramRepository(ProgramLocalDataSource())
} | gpl-3.0 | e797c4daeae00da9e42934d8723a5e86 | 47.784314 | 94 | 0.842782 | 5.291489 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-recyclerview/src/main/java/reactivecircus/flowbinding/recyclerview/RecyclerViewScrollEventFlow.kt | 1 | 1610 | @file:Suppress("MatchingDeclarationName")
package reactivecircus.flowbinding.recyclerview
import androidx.annotation.CheckResult
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [Flow] of scroll events on the [RecyclerView] instance.
*
* Note: Created flow keeps a strong reference to the [RecyclerView] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* recyclerView.scrollEvents()
* .onEach { event ->
* // handle recycler view scroll event
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun RecyclerView.scrollEvents(): Flow<RecyclerViewScrollEvent> = callbackFlow {
checkMainThread()
val listener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
trySend(
RecyclerViewScrollEvent(
view = this@scrollEvents,
dx = dx,
dy = dy
)
)
}
}
addOnScrollListener(listener)
awaitClose { removeOnScrollListener(listener) }
}.conflate()
public data class RecyclerViewScrollEvent(
public val view: RecyclerView,
public val dx: Int,
public val dy: Int
)
| apache-2.0 | 2615dc68e731794c78a0ee1d9f517f63 | 29.377358 | 86 | 0.696273 | 4.923547 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/topsites/TopSites.kt | 1 | 5883 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.topsites
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import mozilla.components.feature.top.sites.TopSite
import mozilla.components.support.ktx.kotlin.getRepresentativeCharacter
import org.mozilla.focus.R
import org.mozilla.focus.ui.menu.CustomDropdownMenu
import org.mozilla.focus.ui.menu.MenuItem
import org.mozilla.focus.ui.theme.focusColors
/**
* A list of top sites.
*
* @param topSites List of [TopSite] to display.
* @param onTopSiteClicked Invoked when the user clicked the top site
* @param onRemoveTopSiteClicked Invoked when the user clicked 'Remove' item from drop down menu
* @param onRenameTopSiteClicked Invoked when the user clicked 'Rename' item from drop down menu
*/
@Composable
fun TopSites(
topSites: List<TopSite>,
onTopSiteClicked: (TopSite) -> Unit,
onRemoveTopSiteClicked: (TopSite) -> Unit,
onRenameTopSiteClicked: (TopSite) -> Unit,
) {
Row(
modifier = Modifier
.padding(horizontal = 10.dp)
.size(width = 324.dp, height = 84.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(28.dp),
) {
topSites.forEach { topSite ->
TopSiteItem(
topSite = topSite,
menuItems = listOfNotNull(
MenuItem(
title = stringResource(R.string.rename_top_site_item),
onClick = { onRenameTopSiteClicked(topSite) },
),
MenuItem(
title = stringResource(R.string.remove_top_site),
onClick = { onRemoveTopSiteClicked(topSite) },
),
),
onTopSiteClick = { item -> onTopSiteClicked(item) },
)
}
}
}
/**
* A top site item.
*
* @param topSite The [TopSite] to display.
* @param menuItems List of [MenuItem] to display in a top site dropdown menu.
* @param onTopSiteClick Invoked when the user clicks on a top site.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TopSiteItem(
topSite: TopSite,
menuItems: List<MenuItem>,
onTopSiteClick: (TopSite) -> Unit = {},
) {
var menuExpanded by remember { mutableStateOf(false) }
Box {
Column(
modifier = Modifier
.combinedClickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = { onTopSiteClick(topSite) },
onLongClick = { menuExpanded = true },
)
.size(width = 60.dp, height = 84.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
TopSiteFaviconCard(topSite = topSite)
Text(
text = topSite.title ?: topSite.url,
modifier = Modifier.padding(top = 8.dp),
color = focusColors.topSiteTitle,
fontSize = 12.sp,
overflow = TextOverflow.Ellipsis,
maxLines = 1,
)
CustomDropdownMenu(
menuItems = menuItems,
isExpanded = menuExpanded,
onDismissClicked = { menuExpanded = false },
)
}
}
}
/**
* The top site favicon card.
*
* @param topSite The [TopSite] to display.
*/
@Composable
private fun TopSiteFaviconCard(topSite: TopSite) {
Card(
modifier = Modifier.size(60.dp),
shape = RoundedCornerShape(8.dp),
backgroundColor = focusColors.topSiteBackground,
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Surface(
modifier = Modifier.size(36.dp),
shape = RoundedCornerShape(4.dp),
color = focusColors.surface,
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = if (topSite.title.isNullOrEmpty()) {
topSite.url.getRepresentativeCharacter()
} else {
topSite.title?.get(0).toString()
},
color = focusColors.topSiteFaviconText,
fontSize = 20.sp,
)
}
}
}
}
}
| mpl-2.0 | d4e3bf9b7dc6a121c318d4ac0db5b60f | 34.439759 | 96 | 0.618392 | 4.691388 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2019/Day16.kt | 1 | 1679 | package com.s13g.aoc.aoc2019
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import kotlin.math.abs
/**
* --- Day 16: Flawed Frequency Transmission ---
* https://adventofcode.com/2019/day/16
*/
class Day16 : Solver {
override fun solve(lines: List<String>): Result {
val input = lines[0].map { "$it".toInt() }
val patterns = genPatterns(listOf(0, 1, 0, -1), input.size)
println("Patterns generated")
var state = input
for (n in 1..100) {
state = phaseStep(state, patterns)
}
val resultA = state.subList(0, 8).map { "$it" }.reduce { acc, i -> acc + i }
// Repeat input 10.000 times for PartB
// val inputB = mutableListOf<Int>()
// for (n in 1..10000) {
// inputB.addAll(input)
// }
// var stateB = inputB.toList()
// for (n in 1..100) {
// stateB = phaseStep(stateB, patterns)
// }
return Result(resultA, "n/a")
}
private fun phaseStep(input: List<Int>, patterns: List<List<Int>>): List<Int> {
val output = mutableListOf<Int>()
for (i in input.indices) {
output.add(calcItem(input, patterns[i]))
}
return output
}
private fun calcItem(input: List<Int>, pattern: List<Int>): Int {
var result = 0
for ((i, v) in input.withIndex()) {
result += (v * pattern[(i + 1) % pattern.size])
}
return abs(result % 10)
}
private fun genPatterns(base: List<Int>, num: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
for (n in 0..num) {
val pattern = mutableListOf<Int>()
for (x in base) {
for (i in 0..n) {
pattern.add(x)
}
}
result.add(pattern)
}
return result
}
} | apache-2.0 | b2889229eb0c202f467d62663077f4a9 | 24.846154 | 81 | 0.585468 | 3.222649 | false | false | false | false |
tmarsteel/compiler-fiddle | src/compiler/ast/type/TypeModifier.kt | 1 | 1118 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.ast.type
enum class TypeModifier {
MUTABLE,
READONLY,
IMMUTABLE;
infix fun isAssignableTo(targetModifier: TypeModifier): Boolean =
this == targetModifier
||
when (this) {
MUTABLE, IMMUTABLE -> targetModifier == READONLY
READONLY -> false
}
}
| lgpl-3.0 | 9f18e148e918d945727af1c35b150192 | 32.878788 | 77 | 0.701252 | 4.544715 | false | false | false | false |
youlookwhat/CloudReader | app/src/main/java/com/example/jingbin/cloudreader/bean/BannerItemBean.kt | 1 | 351 | package com.example.jingbin.cloudreader.bean
import java.io.Serializable
/**
* Created by jingbin on 2020/12/5.
*/
class BannerItemBean : Serializable {
companion object {
private const val serialVersionUID = 1L
}
val randpic: String? = null
val code: String? = null
val type = 0
val randpic_desc: String? = null
} | apache-2.0 | 80be3ba075fa89c09cf754d28ab42452 | 19.705882 | 47 | 0.672365 | 3.734043 | false | false | false | false |
Commit451/YouTubeExtractor | youtubeextractor/src/main/java/com/commit451/youtubeextractor/PlayerResponse.kt | 1 | 1329 | package com.commit451.youtubeextractor
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal data class PlayerResponse(
@Json(name = "streamingData")
var streamingData: StreamingData? = null,
@Json(name = "videoDetails")
var videoDetails: VideoDetails? = null
) {
@JsonClass(generateAdapter = true)
data class StreamingData(
@Json(name = "hlsManifestUrl")
var hlsManifestUrl: String? = null,
@Json(name = "formats")
var formats: List<Format>? = null,
@Json(name = "adaptiveFormats")
var adaptiveFormats: List<Format>? = null
)
@JsonClass(generateAdapter = true)
data class Format(
@Json(name = "itag")
var itag: Int? = null,
@Json(name = "approxDurationMs")
var approxDurationMs: String? = null,
@Json(name = "url")
var url: String? = null,
@Json(name = "signatureCipher")
var cipher: String? = null
)
@JsonClass(generateAdapter = true)
data class VideoDetails(
@Json(name = "title")
var title: String? = null,
@Json(name = "author")
var author: String? = null,
@Json(name = "shortDescription")
var description: String? = null
)
}
| apache-2.0 | e12a3ad6b50a61e7b9f20a4cb3812abc | 28.533333 | 49 | 0.602709 | 4.051829 | false | false | false | false |
ybonjour/test-store | backend/src/main/kotlin/ch/yvu/teststore/result/ResultDiffService.kt | 1 | 3538 | package ch.yvu.teststore.result
import ch.yvu.teststore.result.ResultDiffService.DiffCategory.*
import ch.yvu.teststore.result.TestWithResults.TestResult.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*
@Service
open class ResultDiffService @Autowired constructor(
open val resultService: ResultService) {
enum class DiffCategory {
NEW_PASSED, NEW_FAILED, NEW_RETRIED,
FIXED, BROKE,
RETRIED_AFTER_FAILED, RETRIED_AFTER_PASSED,
STILL_FAILING, STILL_PASSING, STILL_RETRIED,
REMOVED
}
fun findDiff(prevRunId: UUID?, runId: UUID): Map<DiffCategory, List<TestWithResults>> {
val prevResults = if (prevRunId == null) emptyList<TestWithResults>() else resultService.getTestsWithResults(prevRunId)
val prevTestNames = prevResults.map { it.testName }
val results = resultService.getTestsWithResults(runId)
val testNames = results.map { it.testName }
val commonTests = results
.map { result -> Pair(result, prevResults.find { it.testName == result.testName }) }
.filter { it.second != null }
.map { ResultDiff(it.first, it.second!!) }
val newTests = results.filter { !prevTestNames.contains(it.testName) }
val removedTests = prevResults.filter { !testNames.contains(it.testName) }
return mapOf(
Pair(NEW_PASSED, newTests.filter { it.getTestResult() == PASSED }),
Pair(NEW_FAILED, newTests.filter { it.getTestResult() == FAILED }),
Pair(NEW_RETRIED, newTests.filter { it.getTestResult() == RETRIED }),
Pair(REMOVED, removedTests),
Pair(FIXED, filterCommonResults(commonTests, { it.isFixed })),
Pair(BROKE, filterCommonResults(commonTests, { it.isBroken })),
Pair(STILL_FAILING, filterCommonResults(commonTests, { it.isStillFailing })),
Pair(STILL_PASSING, filterCommonResults(commonTests, { it.isStillPassing })),
Pair(RETRIED_AFTER_PASSED, filterCommonResults(commonTests, { it.isRetriedAfterPassed })),
Pair(RETRIED_AFTER_FAILED, filterCommonResults(commonTests, { it.isRetriedAfterFailed })),
Pair(STILL_RETRIED, filterCommonResults(commonTests, { it.isStillRetried })))
.filter { !it.value.isEmpty() }
}
private fun filterCommonResults(commonResults: List<ResultDiff>,
predicate: (ResultDiff) -> Boolean): List<TestWithResults> {
return commonResults.filter {
predicate(it)
}.map { it.result }
}
data class ResultDiff(val result: TestWithResults, val prevResult: TestWithResults) {
val isFixed = prevResult.getTestResult() != PASSED && result.getTestResult() == PASSED
val isBroken = prevResult.getTestResult() != FAILED && result.getTestResult() == FAILED
val isStillFailing = prevResult.getTestResult() == FAILED && result.getTestResult() == FAILED
val isStillPassing = prevResult.getTestResult() == PASSED && result.getTestResult() == PASSED
val isRetriedAfterPassed = prevResult.getTestResult() == PASSED && result.getTestResult() == RETRIED
val isRetriedAfterFailed = prevResult.getTestResult() == FAILED && result.getTestResult() == RETRIED
val isStillRetried = prevResult.getTestResult() == RETRIED && result.getTestResult() == RETRIED
}
} | mit | 32293ddc4c3aa1f7397ef24e8327e783 | 48.152778 | 127 | 0.661391 | 4.262651 | false | true | false | false |
googlesamples/glass-enterprise-samples | NotesSample/app/src/main/java/com/example/glass/notessample/viewpager/BaseViewPagerFragment.kt | 1 | 4469 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.glass.notessample.viewpager
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.speech.RecognizerIntent
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.glass.notessample.R
import com.example.glass.notessample.model.Note
import com.example.glass.notessample.model.NoteViewModel
import com.example.glass.notessample.voicecommand.OnVoiceCommandListener
import com.example.glass.ui.GlassGestureDetector
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
/**
* Base class for the view pager fragments
*/
open class BaseViewPagerFragment : Fragment(), GlassGestureDetector.OnGestureListener,
OnVoiceCommandListener {
companion object {
private val TAG = AddNoteFragment::class.java.simpleName
const val ADD_NOTE_REQUEST_CODE = 205
const val EDIT_NOTE_REQUEST_CODE = 210
}
private lateinit var noteViewModel: NoteViewModel
private var noteToEditId: Int? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.notes_fragment_layout, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
noteViewModel = ViewModelProvider(this).get(NoteViewModel::class.java)
}
override fun onGesture(gesture: GlassGestureDetector.Gesture): Boolean =
when (gesture) {
GlassGestureDetector.Gesture.SWIPE_DOWN -> {
requireActivity().finish()
true
}
else -> false
}
override fun onVoiceCommandDetected(menuItem: MenuItem) {
when (menuItem.itemId) {
R.id.addNote -> startVoiceRecognition(ADD_NOTE_REQUEST_CODE)
R.id.edit -> startVoiceRecognition(EDIT_NOTE_REQUEST_CODE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
val results: List<String>? =
data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
if (results != null && results.isNotEmpty() && results[0].isNotEmpty()) {
if (requestCode == ADD_NOTE_REQUEST_CODE) {
noteViewModel.insert(Note(results[0], results[0], getDateTime()))
} else if (requestCode == EDIT_NOTE_REQUEST_CODE) {
if (noteToEditId != null) {
val editedNote = Note(results[0], results[0], getDateTime())
editedNote.id = noteToEditId!!
noteViewModel.update(editedNote)
}
}
} else {
Log.d(TAG, "Voice recognition result is empty")
}
} else {
Log.d(TAG, "Voice recognition activity results with bad request or result code")
}
}
fun startVoiceRecognition(requestCode: Int) {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
)
startActivityForResult(intent, requestCode)
}
fun editNoteWithId(id: Int) {
noteToEditId = id
startVoiceRecognition(EDIT_NOTE_REQUEST_CODE)
}
private fun getDateTime() =
SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date())
} | apache-2.0 | eee9ac4d859e7d17ecd8a307b9223798 | 35.639344 | 95 | 0.672634 | 4.597737 | false | false | false | false |
JimSeker/ui | Advanced/BotNavGuiDemo_kt/app/src/main/java/edu/cs4730/botnavguidemo_kt/Input_Fragment.kt | 1 | 2269 | package edu.cs4730.botnavguidemo_kt
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import android.widget.EditText
import android.text.TextWatcher
import android.text.Editable
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
class Input_Fragment : Fragment(), View.OnClickListener {
var TAG = "Input_fragment"
lateinit var myContext: Context
lateinit var et_single: EditText
lateinit var et_mutli: EditText
lateinit var et_pwd: EditText
lateinit var btn: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "OnCreate")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.input_fragment, container, false)
et_single = view.findViewById(R.id.et_single)
et_pwd = view.findViewById(R.id.et_pwd)
et_pwd.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) {
//doing nothing.
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// do nothing here.
}
override fun afterTextChanged(s: Editable) {
// When the text is changed.
Toast.makeText(myContext, et_pwd.getText(), Toast.LENGTH_SHORT).show()
}
}
)
btn = view.findViewById(R.id.button)
btn.setOnClickListener(this)
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
myContext = context
Log.d(TAG, "onAttach")
}
override fun onClick(v: View) {
Toast.makeText(myContext, et_single!!.text, Toast.LENGTH_LONG).show()
}
} | apache-2.0 | 7234ab62aafb959cf0309a899a8cea17 | 30.09589 | 98 | 0.611283 | 4.659138 | false | false | false | false |
yawkat/javap | server/src/main/kotlin/at/yawk/javap/ExchangeUtil.kt | 1 | 2279 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
@file:Suppress("UnstableApiUsage")
package at.yawk.javap
import at.yawk.javap.model.HttpException
import com.google.common.net.MediaType
import io.undertow.server.HttpHandler
import io.undertow.server.HttpServerExchange
import io.undertow.server.handlers.ExceptionHandler
import io.undertow.util.Headers
import io.undertow.util.StatusCodes
import kotlinx.serialization.json.Json
import java.lang.IllegalArgumentException
val HttpServerExchange.accept: MediaType?
get() = requestHeaders.getLast(Headers.ACCEPT)?.let {
try {
MediaType.parse(it)
} catch (fail: IllegalArgumentException) {
null
}
}
val HttpServerExchange.contentType: MediaType
@Throws(HttpException::class)
get() {
val contentTypeHeader = requestHeaders.getFirst(Headers.CONTENT_TYPE)
?: throw HttpException(StatusCodes.BAD_REQUEST, "Missing Content-Type")
try {
return MediaType.parse(contentTypeHeader)
} catch (e: IllegalArgumentException) {
throw HttpException(StatusCodes.UNSUPPORTED_MEDIA_TYPE, "Bad Content-Type")
}
}
private val json = Json{ jsonConfiguration }
fun handleHttpException(xhg: HttpServerExchange, exception: HttpException) {
xhg.statusCode = exception.code
if (xhg.accept?.withoutParameters() == MediaType.JSON_UTF_8.withoutParameters()) {
val serialized = json.encodeToString(HttpException.serializer(), exception)
xhg.responseHeaders.put(Headers.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
xhg.responseSender.send(serialized)
} else {
xhg.responseHeaders.put(Headers.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString())
xhg.responseSender.send(exception.message)
}
}
inline fun handleExceptions(xhg: HttpServerExchange, f: () -> Unit) {
try {
f()
} catch (e: HttpException) {
handleHttpException(xhg, e)
}
}
fun handleExceptions(handler: HttpHandler): HttpHandler = HttpHandler { xhg ->
handleExceptions(xhg) { handler.handleRequest(xhg) }
} | mpl-2.0 | cd25c0ece39fe1658333d40d9c058224 | 33.545455 | 92 | 0.709083 | 4.181651 | false | false | false | false |
mario222k/manga-rx | app/src/main/java/de/mario222k/mangarx/application/PluginDialogFragment.kt | 1 | 3530 | package de.mario222k.mangarx.application
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import de.mario222k.mangarx.R
import de.mario222k.mangarx.plugin.PluginDetail
import de.mario222k.mangarx.plugin.PluginProvider
import kotlinx.android.synthetic.main.fragment_plugins.view.*
import javax.inject.Inject
open class PluginDialogFragment : DialogFragment() {
@Inject
lateinit var pluginProvider: PluginProvider
private var layout: View? = null
private var selectListener: PluginSelectListener? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = activity!!
(activity.application as? MyApp)?.pluginComponent?.inject(this)
layout = activity.layoutInflater?.inflate(R.layout.fragment_plugins, null)
layout?.list_view?.layoutManager = LinearLayoutManager(activity)
onListenerChanged()
val builder = AlertDialog.Builder(activity)
builder.setCancelable(true)
builder.setView(layout)
return builder.create()
}
fun setPluginSelectListener(listener: PluginSelectListener?) {
selectListener = listener
onListenerChanged()
}
private fun onListenerChanged() {
layout?.list_view?.adapter = PluginAdapter(pluginProvider, selectListener)
onAdapterChanged()
}
private fun onAdapterChanged() {
layout?.list_view?.let {
if (it.adapter?.itemCount ?: 0 == 0) {
it.visibility = View.GONE
layout?.empty_text?.visibility = View.VISIBLE
} else {
it.visibility = View.VISIBLE
layout?.empty_text?.visibility = View.GONE
}
}
}
}
private class PluginAdapter(provider: PluginProvider?, listener: PluginSelectListener? = null) : RecyclerView.Adapter<PluginViewHolder>() {
internal var selectListener = listener
private val pluginProvider = provider
override fun onBindViewHolder(viewHolder: PluginViewHolder, index: Int) {
val plugin = pluginProvider?.plugins?.get(index)
val context = viewHolder.context
viewHolder.icon.setImageDrawable(plugin?.getIcon(context))
viewHolder.name.text = plugin?.getName(context)
viewHolder.version.text = plugin?.getVersion(context)
viewHolder.itemView?.setOnClickListener({ v ->
pluginProvider?.activePlugin = plugin
selectListener?.onPluginSelect(plugin)
})
}
override fun onCreateViewHolder(container: ViewGroup, viewType: Int): PluginViewHolder {
val inflater = LayoutInflater.from(container.context)
return PluginViewHolder(inflater.inflate(R.layout.layout_plugin_item, null))
}
override fun getItemCount() = pluginProvider?.plugins?.size ?: 0
}
interface PluginSelectListener {
fun onPluginSelect(plugin: PluginDetail?)
}
private class PluginViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val context = view.context
val icon = view.findViewById(R.id.plugin_icon) as ImageView
val name = view.findViewById(R.id.plugin_name) as TextView
val version = view.findViewById(R.id.plugin_version) as TextView
}
| apache-2.0 | bda8c6ac7c4406922d65d803aab3e412 | 34.3 | 139 | 0.713598 | 4.537275 | false | false | false | false |
SerCeMan/intellij-community | plugins/settings-repository/src/IcsUrlBuilder.kt | 3 | 783 | package org.jetbrains.settingsRepository
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.util.SystemInfo
val PROJECTS_DIR_NAME: String = "_projects/"
private fun getOsFolderName() = when {
SystemInfo.isMac -> "_mac"
SystemInfo.isWindows -> "_windows"
SystemInfo.isLinux -> "_linux"
SystemInfo.isFreeBSD -> "_freebsd"
SystemInfo.isUnix -> "_unix"
else -> "_unknown"
}
fun buildPath(path: String, roamingType: RoamingType, projectKey: String? = null): String {
fun String.osIfNeed() = if (roamingType == RoamingType.PER_OS) "${getOsFolderName()}/$this" else this
return if (projectKey == null) {
(if (path.charAt(0) == '$') path else "\$ROOT_CONFIG$/$path").osIfNeed()
}
else {
"$PROJECTS_DIR_NAME$projectKey/$path"
}
} | apache-2.0 | 35f28b8a90629097108283c13dac8890 | 29.153846 | 103 | 0.696041 | 3.728571 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/user/repository/UserRepository.kt | 1 | 4270 | package mixit.user.repository
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import mixit.security.model.Cryptographer
import mixit.user.model.Role
import mixit.user.model.User
import mixit.util.encodeToMd5
import org.slf4j.LoggerFactory
import org.springframework.core.io.ClassPathResource
import org.springframework.data.mongodb.core.ReactiveMongoTemplate
import org.springframework.data.mongodb.core.count
import org.springframework.data.mongodb.core.find
import org.springframework.data.mongodb.core.findAll
import org.springframework.data.mongodb.core.findById
import org.springframework.data.mongodb.core.findOne
import org.springframework.data.mongodb.core.query.Criteria.where
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.TextCriteria
import org.springframework.data.mongodb.core.query.TextQuery
import org.springframework.data.mongodb.core.query.inValues
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.data.mongodb.core.remove
import org.springframework.stereotype.Repository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Repository
class UserRepository(
private val template: ReactiveMongoTemplate,
private val objectMapper: ObjectMapper,
private val cryptographer: Cryptographer
) {
private val logger = LoggerFactory.getLogger(this.javaClass)
fun initData() {
if (count().block() == 0L) {
val usersResource = ClassPathResource("data/users.json")
val users: List<User> = objectMapper.readValue(usersResource.inputStream)
users.forEach { save(it).block() }
logger.info("Users data initialization complete")
}
}
fun findFullText(criteria: List<String>): Flux<User> {
val textCriteria = TextCriteria()
criteria.forEach { textCriteria.matching(it) }
val query = TextQuery(textCriteria).sortByScore()
return template.find(query)
}
fun count() = template.count<User>()
fun findByNonEncryptedEmail(email: String) = template.findOne<User>(
Query(
where("role").inValues(Role.STAFF, Role.STAFF_IN_PAUSE, Role.USER, Role.VOLUNTEER)
.orOperator(where("email").isEqualTo(cryptographer.encrypt(email)), where("emailHash").isEqualTo(email.encodeToMd5()))
)
)
suspend fun coFindByNonEncryptedEmail(email: String): User =
findByNonEncryptedEmail(email).awaitSingle()
fun findByRoles(roles: List<Role>) =
template.find<User>(Query(where("role").inValues(roles)))
suspend fun coFindByRoles(roles: List<Role>): List<User> =
findByRoles(roles).collectList().awaitSingle()
fun findOneByRoles(login: String, roles: List<Role>) =
template.findOne<User>(Query(where("role").inValues(roles).and("_id").isEqualTo(login)))
suspend fun coFindOneByRoles(login: String, roles: List<Role>) =
findOneByRoles(login, roles).awaitSingle()
fun findAll() =
template.findAll<User>().doOnComplete { logger.info("Load all users") }
suspend fun coFindAll(): List<User> =
findAll().collectList().awaitSingle()
fun findAllByIds(login: List<String>): Flux<User> {
val criteria = where("login").inValues(login)
return template.find(Query(criteria))
}
fun findOne(login: String) =
template.findById<User>(login)
suspend fun coFindOne(login: String): User? =
findOne(login).awaitSingleOrNull()
fun findMany(logins: List<String>) =
template.find<User>(Query(where("_id").inValues(logins)))
fun findByLegacyId(id: Long) =
template.findOne<User>(Query(where("legacyId").isEqualTo(id)))
suspend fun coFindByLegacyId(id: Long) =
findByLegacyId(id).awaitSingleOrNull()
fun deleteAll() =
template.remove<User>(Query())
fun deleteOne(login: String) =
template.remove<User>(Query(where("_id").isEqualTo(login)))
fun save(user: User) =
template.save(user)
fun save(user: Mono<User>) =
template.save(user)
}
| apache-2.0 | 169d6fe8a687975b3ed7940d417a9450 | 35.495726 | 134 | 0.720375 | 4.133591 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.