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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
allotria/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/ErrorReportConfigurable.kt | 1 | 2195 | // 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.diagnostic
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.SERVICE_NAME_PREFIX
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.components.*
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.XCollection
@State(name = "ErrorReportConfigurable", storages = [Storage(StoragePathMacros.CACHE_FILE)])
internal class ErrorReportConfigurable : PersistentStateComponent<DeveloperList>, SimpleModificationTracker() {
companion object {
@JvmStatic
val SERVICE_NAME = "$SERVICE_NAME_PREFIX — JetBrains Account"
@JvmStatic
fun getInstance() = service<ErrorReportConfigurable>()
@JvmStatic
fun getCredentials() = PasswordSafe.instance.get(CredentialAttributes(SERVICE_NAME))
}
var developerList = DeveloperList()
set(value) {
field = value
incModificationCount()
}
override fun getState() = developerList
override fun loadState(value: DeveloperList) {
developerList = value
}
}
// 24 hours
private const val UPDATE_INTERVAL = 24L * 60 * 60 * 1000
internal class DeveloperList {
constructor() {
developers = mutableListOf()
timestamp = 0
}
constructor(list: MutableList<Developer>) {
developers = list
timestamp = System.currentTimeMillis()
}
@field:XCollection(style = XCollection.Style.v2)
val developers: List<Developer>
@field:Attribute
var timestamp: Long
private set
fun isUpToDateAt() = timestamp != 0L && (System.currentTimeMillis() - timestamp) < UPDATE_INTERVAL
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DeveloperList
return developers == other.developers || timestamp == other.timestamp
}
override fun hashCode(): Int {
var result = developers.hashCode()
result = 31 * result + timestamp.hashCode()
return result
}
} | apache-2.0 | d477da03c8396b498164c55db528084a | 28.648649 | 140 | 0.738714 | 4.559252 | false | false | false | false |
maiktheknife/KittyCat | app/src/main/kotlin/net/kivitro/kittycat/presenter/DetailPresenter.kt | 1 | 2873 | package net.kivitro.kittycat.presenter
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.util.Pair
import android.view.View
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import net.kivitro.kittycat.BuildConfig
import net.kivitro.kittycat.R
import net.kivitro.kittycat.model.Cat
import net.kivitro.kittycat.network.TheCatAPI
import net.kivitro.kittycat.view.DetailView
import net.kivitro.kittycat.view.activity.FullScreenImageActivity
import timber.log.Timber
import java.util.concurrent.TimeUnit
/**
* Created by Max on 10.03.2016.
*/
class DetailPresenter : Presenter<DetailView>() {
private var voteDisposable: Disposable? = null
private var favDisposable: Disposable? = null
private var defavDisposable: Disposable? = null
override fun detachView() {
super.detachView()
voteDisposable?.dispose()
favDisposable?.dispose()
defavDisposable?.dispose()
}
fun onVoted(cat: Cat, rating: Int) {
Timber.d("onVoted %s", cat)
voteDisposable = TheCatAPI.API
.vote(cat.id!!, rating)
.timeout(BuildConfig.REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ _ ->
view?.onVoting(rating)
},
{ t ->
Timber.d(t, "onVoted")
view?.onVotingError(t.message ?: "Unknown Error")
}
)
}
fun onFavourited(cat: Cat) {
Timber.d("onFavourited %s", cat)
favDisposable = TheCatAPI.API
.favourite(cat.id!!, TheCatAPI.ACTION_ADD)
.timeout(BuildConfig.REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ _ ->
view?.onFavourited()
},
{ t ->
Timber.d(t, "onFavourited")
view?.onFavouritedError(t.message ?: "Unknown Error")
})
}
fun onDefavourited(cat: Cat) {
Timber.d("onDefavourited %s", cat)
defavDisposable = TheCatAPI.API
.favourite(cat.id!!, TheCatAPI.ACTION_REMOVE)
.timeout(BuildConfig.REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ _ ->
view?.onDefavourited()
},
{ t ->
Timber.d(t, "onDefavourited")
view?.onFavouritedError(t.message ?: "Unknown Error")
})
}
fun onImageClicked(cat: Cat, mutedColor: Int, vibrateColor: Int, vibrateColorDark: Int, v: View) {
Timber.d("onImageClicked %s", cat)
view?.let {
val ac = it.activity
val aoc = ActivityOptionsCompat.makeSceneTransitionAnimation(ac,
Pair(v, ac.getString(R.string.transition_cat_image))
)
ac.startActivity(FullScreenImageActivity.getStarterIntent(ac, cat, mutedColor, vibrateColor, vibrateColorDark), aoc.toBundle())
}
}
} | mit | 9b7d2c71a7343615b0a9d798dde363af | 28.628866 | 130 | 0.705534 | 3.478208 | false | false | false | false |
google/Kotlin-FirViewer | src/main/kotlin/io/github/tgeng/firviewer/uiUtils.kt | 1 | 11361 | // Copyright 2021 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 io.github.tgeng.firviewer
import com.google.common.base.CaseFormat
import com.google.common.primitives.Primitives
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.ui.components.JBLabel
import com.intellij.ui.scale.JBUIScale
import org.jetbrains.kotlin.KtPsiSourceElement
import org.jetbrains.kotlin.fir.FirPureAbstractElement
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.render
import org.jetbrains.kotlin.fir.resolve.dfa.cfg.CFGNode
import org.jetbrains.kotlin.util.AttributeArrayOwner
import org.jetbrains.kotlin.analysis.api.tokens.HackToForceAllowRunningAnalyzeOnEDT
import org.jetbrains.kotlin.analysis.api.tokens.hackyAllowRunningOnEdt
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import java.awt.Color
import java.awt.FlowLayout
import java.awt.Font
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
import kotlin.reflect.KCallable
import kotlin.reflect.KFunction
import kotlin.reflect.KProperty
import kotlin.reflect.KVisibility
import kotlin.reflect.full.createType
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.javaGetter
import kotlin.reflect.jvm.javaMethod
fun label(
s: String,
bold: Boolean = false,
italic: Boolean = false,
multiline: Boolean = false,
icon: Icon? = null,
tooltipText: String? = null
) = JBLabel(
if (multiline) ("<html>" + s.replace("\n", "<br/>").replace(" ", " ") + "</html>") else s
).apply {
this.icon = icon
this.toolTipText = toolTipText
font = font.deriveFont((if (bold) Font.BOLD else Font.PLAIN) + if (italic) Font.ITALIC else Font.PLAIN)
}
fun render(e: FirElement) = JBLabel(e.render())
fun type(e: TreeNode<*>): JComponent {
val nameAndType = label(
if (e.name == "" || e.name.startsWith('<')) {
""
} else {
e.name + ": "
} + e.t::class.simpleName,
bold = true
)
val address = label("@" + Integer.toHexString(System.identityHashCode(e.t)))
val nameTypeAndAddress = nameAndType + address
return if (e.t is FirDeclaration) {
nameTypeAndAddress + label(e.t.resolvePhase.toString(), italic = true)
} else {
nameTypeAndAddress
}
}
private val twoPoint = JBUIScale.scale(2)
operator fun JComponent.plus(that: JComponent?): JPanel {
return if (this is JPanel) {
add(that)
this
} else {
JPanel(FlowLayout(FlowLayout.LEFT).apply {
vgap = twoPoint
}).apply {
add(this@plus)
if (that != null) add(that)
isOpaque = false
}
}
}
fun highlightInEditor(obj: Any, project: Project) {
val editorManager = FileEditorManager.getInstance(project) ?: return
val editor: Editor = editorManager.selectedTextEditor ?: return
editor.markupModel.removeAllHighlighters()
val (vf, startOffset, endOffset) = when (obj) {
is FirPureAbstractElement -> obj.source?.let {
val source = it as? KtPsiSourceElement ?: return@let null
FileLocation(source.psi.containingFile.virtualFile, it.startOffset, it.endOffset)
}
is PsiElement -> obj.textRange?.let {
FileLocation(
obj.containingFile.virtualFile,
it.startOffset,
it.endOffset
)
}
is CFGNode<*> -> obj.fir.source?.let {
val source = it as? KtPsiSourceElement ?: return@let null
FileLocation(source.psi.containingFile.virtualFile, it.startOffset, it.endOffset)
}
else -> null
} ?: return
if (vf != FileEditorManager.getInstance(project).selectedFiles.firstOrNull()) return
val textAttributes =
TextAttributes(null, null, Color.GRAY, EffectType.BOXED, Font.PLAIN)
editor.markupModel.addRangeHighlighter(
startOffset,
endOffset,
HighlighterLayer.CARET_ROW,
textAttributes,
HighlighterTargetArea.EXACT_RANGE
)
}
private data class FileLocation(val vf: VirtualFile, val startIndex: Int, val endIndex: Int)
val unitType = Unit::class.createType()
val skipMethodNames = setOf(
"copy",
"toString",
"delete",
"clone",
"getUserDataString",
"hashCode",
"getClass",
"component1",
"component2",
"component3",
"component4",
"component5"
)
val psiElementMethods = PsiElement::class.java.methods.map { it.name }.toSet() - setOf(
"getTextRange",
"getTextRangeInParent",
"getTextLength",
"getText",
"getResolveScope",
"getUseScope",
"getReferences",
)
@OptIn(HackToForceAllowRunningAnalyzeOnEDT::class)
fun Any.traverseObjectProperty(
propFilter: (KCallable<*>) -> Boolean = { true }, methodFilter: (Method) -> Boolean = { true },
fn: (name: String, value: Any?, () -> Any?) -> Unit
) {
try {
this::class.members
.filter { propFilter(it) && it.parameters.size == 1 && it.visibility == KVisibility.PUBLIC && it.returnType != unitType && it.name !in skipMethodNames && (this !is PsiElement || it.name !in psiElementMethods) }
.sortedWith { m1, m2 ->
fun KCallable<*>.declaringClass() = when (this) {
is KFunction<*> -> javaMethod?.declaringClass
is KProperty<*> -> javaGetter?.declaringClass
else -> null
}
val m1Class = m1.declaringClass()
val m2Class = m2.declaringClass()
when {
m1Class == m2Class -> 0
m1Class == null -> 1
m2Class == null -> -1
m1Class.isAssignableFrom(m2Class) -> -1
else -> 1
}
}
.forEach { prop ->
val value = try {
prop.isAccessible = true
hackyAllowRunningOnEdt {
prop.call(this)
}
} catch (e: Throwable) {
return@forEach
}
fn(prop.name, value) {
hackyAllowRunningOnEdt {
prop.call(this)
}
}
}
} catch (e: Throwable) {
// fallback to traverse with Java reflection
this::class.java.methods
.filter { methodFilter(it) && it.name !in skipMethodNames && it.parameterCount == 0 && it.modifiers and Modifier.PUBLIC != 0 && it.returnType.simpleName != "void" && (this !is PsiElement || it.name !in psiElementMethods) }
// methods in super class is at the beginning
.sortedWith { m1, m2 ->
when {
m1.declaringClass == m2.declaringClass -> 0
m1.declaringClass.isAssignableFrom(m2.declaringClass) -> -1
else -> 1
}
}
.distinctBy { it.name }
.forEach { method ->
val value = try {
hackyAllowRunningOnEdt {
method.invoke(this)
}
} catch (e: Throwable) {
return@forEach
}
fn(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, method.name.removePrefix("get")), value) {
hackyAllowRunningOnEdt {
method.invoke(this)
}
}
}
}
}
fun Any.getTypeAndId(): String {
return when {
isData() -> this::class.simpleName
?: this::class.toString()
else -> this::class.simpleName + " @" + Integer.toHexString(System.identityHashCode(this))
}
}
fun Any.getForMapKey(): String {
return when {
isData() -> toString()
else -> this::class.simpleName + " @" + Integer.toHexString(System.identityHashCode(this)) + " | " + toString()
}
}
fun Any.isData(): Boolean = try {
this is Iterable<*> || this is Map<*, *> || this is AttributeArrayOwner<*, *> ||
this is Enum<*> || this::class.java.isPrimitive || Primitives.isWrapperType(this::class.java) ||
this::class.java == String::class.java || this::class.java == Name::class.java ||
this::class.isData || this::class.objectInstance != null
} catch (e: Throwable) {
false
}
//private class CfgGraphViewer(state: TreeUiState, index: Int, graph: ControlFlowGraph) :
// ObjectViewer(state, index) {
//
// private val nodeNameMap = mutableMapOf<CFGNode<*>, String>()
// private val nodeClassCounter = mutableMapOf<String, AtomicInteger>()
// val CFGNode<*>.name:String get() = nodeNameMap.computeIfAbsent(this) { node ->
// val nodeClassName = (node::class.simpleName?:node::class.toString()).removeSuffix("Node")
// nodeClassName + nodeClassCounter.computeIfAbsent(nodeClassName) { AtomicInteger() }.getAndIncrement()
// }
//
// private val graph = SingleGraph("foo").apply {
// graph.nodes.forEach { node ->
// addNode(node.name)
// }
// val edgeCounter = AtomicInteger()
// val edgeNameMap = mutableMapOf<String, EdgeData>()
// graph.nodes.forEach { node ->
// node.followingNodes.forEach { to ->
// val edgeId = edgeCounter.getAndIncrement().toString()
// addEdge(edgeId, node.name, to.name)
// }
// }
// }
//
// data class EdgeData(val from:CFGNode<*>, val to: CFGNode<*>, val edge: Edge?)
//
// val viewer = SwingViewer(this.graph, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD).apply {
// enableAutoLayout()
// }
// override val view: JComponent = viewer.addDefaultView(false) as JComponent
//
// override fun selectAndGetObject(name: String): Any? {
// return null
// }
//}
| apache-2.0 | ab3e5f072dcfe31a41ef5f5976d40899 | 36.744186 | 238 | 0.602764 | 4.388181 | false | false | false | false |
EGF2/android-client | egf2-generator/src/main/kotlin/com/eigengraph/egf2/generator/mappers/IntegerMapper.kt | 1 | 1232 | package com.eigengraph.egf2.generator.mappers
import com.eigengraph.egf2.generator.Field
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.MethodSpec
import java.util.*
import javax.lang.model.element.Modifier
class IntegerMapper(targetPackage: String) : Mapper(targetPackage) {
override fun getField(field: Field, custom_schemas: LinkedHashMap<String, LinkedList<Field>>): FieldSpec {
val fs: FieldSpec.Builder
fs = FieldSpec.builder(Int::class.java, field.name, Modifier.PUBLIC)
return fs.build()
}
override fun deserialize(field: Field, supername: String, deserialize: MethodSpec.Builder, custom_schemas: LinkedHashMap<String, LinkedList<Field>>) {
if (field.required) {
deserialize.addStatement("final int \$L = jsonObject.get(\"\$L\").getAsInt()", field.name, field.name)
deserialize.addStatement("\$L.\$L = \$L", supername, field.name, field.name)
} else {
deserialize.beginControlFlow("if(jsonObject.has(\"\$L\"))", field.name)
deserialize.addStatement("final int \$L = jsonObject.get(\"\$L\").getAsInt()", field.name, field.name)
deserialize.addStatement("\$L.\$L = \$L", supername, field.name, field.name)
deserialize.endControlFlow()
}
deserialize.addCode("\n")
}
} | mit | f13ff95808d116e251d117ec12797b7a | 43.035714 | 151 | 0.738636 | 3.6997 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/android/src/test/java/expo/modules/benchmarks/NewArchitectureBenchmark.kt | 2 | 2276 | package expo.modules.benchmarks
import com.facebook.react.bridge.Dynamic
import com.facebook.react.bridge.DynamicFromObject
import com.facebook.react.bridge.JavaOnlyArray
import com.facebook.react.bridge.ReadableArray
import expo.modules.adapters.react.NativeModulesProxy
import expo.modules.kotlin.ModulesProvider
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
class NewArchitectureBenchmark {
private val benchmarkRule = BenchmarkRule(iteration = 1000000)
private lateinit var proxy: NativeModulesProxy
class MyModule : Module() {
private fun retNull(): Any? {
return null
}
override fun definition() = ModuleDefinition {
name("MyModule")
function("m1") { -> retNull() }
function("m2") { _: Int, _: Int -> retNull() }
function("m3") { _: IntArray -> retNull() }
function("m4") { _: String -> retNull() }
}
}
@Before
fun before() {
val legacyModuleRegister = expo.modules.core.ModuleRegistry(
emptyList(),
emptyList(),
emptyList(),
emptyList()
)
proxy = NativeModulesProxy(
null, legacyModuleRegister,
object : ModulesProvider {
override fun getModulesList(): List<Class<out Module>> =
listOf(MyModule::class.java)
}
)
}
@Ignore("It's a benchmark")
@Test
fun `call function with simple arguments`() {
val testCases = listOf<Pair<Dynamic, ReadableArray>>(
DynamicFromObject("m1") to JavaOnlyArray(),
DynamicFromObject("m2") to JavaOnlyArray().apply {
pushInt(1)
pushInt(2)
},
DynamicFromObject("m3") to JavaOnlyArray().apply {
pushArray(
JavaOnlyArray().apply {
pushInt(1)
pushInt(2)
pushInt(3)
}
)
},
DynamicFromObject("m4") to JavaOnlyArray().apply {
pushString("expo is awesome")
}
)
val emptyPromise = EmptyRNPromise()
repeat(3) {
benchmarkRule.run(::`call function with simple arguments`.name) {
testCases.forEach { (method, args) ->
proxy.callMethod("MyModule", method, args, emptyPromise)
}
}
}
}
}
| bsd-3-clause | 9d8cce62aa91beba982976286dc63bab | 26.756098 | 71 | 0.641037 | 4.222635 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoTypeDeclarationHandler2.kt | 1 | 2959 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.navigation.actions
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.navigation.CtrlMouseInfo
import com.intellij.codeInsight.navigation.impl.*
import com.intellij.codeInsight.navigation.impl.NavigationActionResult.MultipleTargets
import com.intellij.codeInsight.navigation.impl.NavigationActionResult.SingleTarget
import com.intellij.openapi.actionSystem.ex.ActionUtil.underModalProgress
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.ui.list.createTargetPopup
internal object GotoTypeDeclarationHandler2 : CodeInsightActionHandler {
override fun startInWriteAction(): Boolean = false
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val dumbService = DumbService.getInstance(project)
val result: NavigationActionResult? = try {
underModalProgress(project, CodeInsightBundle.message("progress.title.resolving.reference")) {
dumbService.computeWithAlternativeResolveEnabled<NavigationActionResult?, Throwable> {
handleLookup(project, editor, offset)
?: gotoTypeDeclaration(file, offset)?.result()
}
}
}
catch (e: IndexNotReadyException) {
dumbService.showDumbModeNotification(CodeInsightBundle.message("message.navigation.is.not.available.here.during.index.update"))
return
}
if (result == null) {
return
}
gotoTypeDeclaration(project, editor, result)
}
private fun gotoTypeDeclaration(project: Project, editor: Editor, actionResult: NavigationActionResult) {
when (actionResult) {
is SingleTarget -> {
navigateRequest(project, actionResult.request)
}
is MultipleTargets -> {
val popup = createTargetPopup(
CodeInsightBundle.message("choose.type.popup.title"),
actionResult.targets, LazyTargetWithPresentation::presentation
) { (requestor, _) ->
navigateRequestLazy(project, requestor)
}
popup.showInBestPositionFor(editor)
}
}
}
private fun handleLookup(project: Project, editor: Editor, offset: Int): NavigationActionResult? {
val fromLookup = TargetElementUtil.getTargetElementFromLookup(project) ?: return null
return result(elementTypeTargets(editor, offset, listOf(fromLookup)))
}
@JvmStatic
fun getCtrlMouseInfo(file: PsiFile, offset: Int): CtrlMouseInfo? {
return gotoTypeDeclaration(file, offset)?.ctrlMouseInfo()
}
}
| apache-2.0 | 4eb94d87b7ffb5cc9068de4682ab15ca | 41.271429 | 158 | 0.761068 | 4.85082 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/util/ApplicationUtils.kt | 1 | 4304 | // 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.util.application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.impl.CancellationCheck
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
fun <T> runReadAction(action: () -> T): T {
return ApplicationManager.getApplication().runReadAction<T>(action)
}
fun <T> runWriteAction(action: () -> T): T {
return ApplicationManager.getApplication().runWriteAction<T>(action)
}
/**
* Run under the write action if the supplied element is physical; run normally otherwise.
*
* @param e context element
* @param action action to execute
* @return result of action execution
*/
fun <T> runWriteActionIfPhysical(e: PsiElement, action: () -> T): T {
if (e.isPhysical) {
return ApplicationManager.getApplication().runWriteAction<T>(action)
}
return action()
}
fun <T> runWriteActionInEdt(action: () -> T): T {
return if (isDispatchThread()) {
runWriteAction(action)
} else {
var result: T? = null
ApplicationManager.getApplication().invokeLater {
result = runWriteAction(action)
}
result!!
}
}
fun Project.executeWriteCommand(@NlsContexts.Command name: String, command: () -> Unit) {
CommandProcessor.getInstance().executeCommand(this, { runWriteAction(command) }, name, null)
}
fun <T> Project.executeWriteCommand(@NlsContexts.Command name: String, groupId: Any? = null, command: () -> T): T {
return executeCommand<T>(name, groupId) { runWriteAction(command) }
}
fun <T> Project.executeCommand(@NlsContexts.Command name: String, groupId: Any? = null, command: () -> T): T {
@Suppress("UNCHECKED_CAST") var result: T = null as T
CommandProcessor.getInstance().executeCommand(this, { result = command() }, name, groupId)
@Suppress("USELESS_CAST")
return result as T
}
fun <T> runWithCancellationCheck(block: () -> T): T = CancellationCheck.runWithCancellationCheck(block)
inline fun executeOnPooledThread(crossinline action: () -> Unit) =
ApplicationManager.getApplication().executeOnPooledThread { action() }
inline fun invokeLater(crossinline action: () -> Unit) =
ApplicationManager.getApplication().invokeLater { action() }
inline fun invokeLater(expired: Condition<*>, crossinline action: () -> Unit) =
ApplicationManager.getApplication().invokeLater({ action() }, expired)
inline fun isUnitTestMode(): Boolean = ApplicationManager.getApplication().isUnitTestMode
inline fun isDispatchThread(): Boolean = ApplicationManager.getApplication().isDispatchThread
inline fun isApplicationInternalMode(): Boolean = ApplicationManager.getApplication().isInternal
inline fun <reified T : Any> ComponentManager.getService(): T? = this.getService(T::class.java)
inline fun <reified T : Any> ComponentManager.getServiceSafe(): T =
this.getService(T::class.java) ?: error("Unable to locate service ${T::class.java.name}")
fun <T> executeInBackgroundWithProgress(project: Project? = null, @NlsContexts.ProgressTitle title: String, block: () -> T): T {
assert(!ApplicationManager.getApplication().isWriteAccessAllowed) {
"Rescheduling computation into the background is impossible under the write lock"
}
return ProgressManager.getInstance().runProcessWithProgressSynchronously(
ThrowableComputable { block() }, title, true, project
)
}
fun KotlinExceptionWithAttachments.withPsiAttachment(name: String, element: PsiElement?): KotlinExceptionWithAttachments {
kotlin.runCatching { element?.getElementTextWithContext() }.getOrNull()?.let { withAttachment(name, it) }
return this
} | apache-2.0 | 936fdcd1231c729767294ae0652f1c27 | 40.796117 | 158 | 0.748374 | 4.618026 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/util/LazyMatrix.kt | 1 | 720 | package de.fabmax.kool.util
import de.fabmax.kool.math.Mat4d
import de.fabmax.kool.math.Mat4f
class LazyMat4d(val update: (Mat4d) -> Unit) {
var isDirty = true
private val mat = Mat4d()
fun clear() {
isDirty = false
mat.setIdentity()
}
fun get(): Mat4d {
if (isDirty) {
update(mat)
isDirty = false
}
return mat
}
}
class LazyMat4f(val update: (Mat4f) -> Unit) {
var isDirty = true
private val mat = Mat4f()
fun clear() {
isDirty = false
mat.setIdentity()
}
fun get(): Mat4f {
if (isDirty) {
update(mat)
isDirty = false
}
return mat
}
} | apache-2.0 | d5874214ba314ac4e7a9a61cea3054a8 | 16.166667 | 46 | 0.518056 | 3.61809 | false | false | false | false |
Pattonville-App-Development-Team/Android-App | app/src/androidTest/java/org/pattonvillecs/pattonvilleapp/service/repository/directory/DirectoryRepositoryTest.kt | 1 | 3445 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* 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 org.pattonvillecs.pattonvilleapp.service.repository.directory
import android.arch.persistence.room.Room
import android.support.test.InstrumentationRegistry
import android.support.test.filters.MediumTest
import android.support.test.runner.AndroidJUnit4
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.contains
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.pattonvillecs.pattonvilleapp.service.model.DataSource
import org.pattonvillecs.pattonvilleapp.service.model.directory.Faculty
import org.pattonvillecs.pattonvilleapp.service.repository.AppDatabase
import org.pattonvillecs.pattonvilleapp.service.repository.awaitValue
/**
* Tests adding and removing faculty from an in-memory database.
*
* @author Mitchell Skaggs
* @since 1.3.0
*/
@Suppress("TestFunctionName")
@RunWith(AndroidJUnit4::class)
@MediumTest
class DirectoryRepositoryTest {
private lateinit var appDatabase: AppDatabase
private lateinit var directoryRepository: DirectoryRepository
@Before
fun createDb() {
val context = InstrumentationRegistry.getTargetContext()
appDatabase = AppDatabase.init(Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)).build()
directoryRepository = DirectoryRepository(appDatabase)
}
@After
fun closeDb() {
appDatabase.close()
}
@Test
fun Given_Faculty_When_UpsertAllCalled_Then_ReturnSameFaculty() {
val faculty = testFaculty()
directoryRepository.upsertAll(listOf(faculty))
val facultyMembers = directoryRepository.getFacultyFromLocations(DataSource.DISTRICT).awaitValue()
assertThat(facultyMembers, contains(faculty))
}
private fun testFaculty(firstName: String = "test_first_name",
lastName: String = "test_last_name",
pcn: String = "test_pcn",
description: String = "test_description",
location: DataSource? = DataSource.DISTRICT,
email: String? = "test_email",
officeNumber1: String? = null,
extension1: String? = null,
officeNumber2: String? = null,
extension2: String? = null,
officeNumber3: String? = null,
extension3: String? = null): Faculty {
return Faculty(firstName, lastName, pcn, description, location, email, officeNumber1, extension1, officeNumber2, extension2, officeNumber3, extension3)
}
} | gpl-3.0 | 04e5d0e8500727f3440c7330a45a14de | 39.069767 | 159 | 0.696952 | 4.719178 | false | true | false | false |
ingokegel/intellij-community | plugins/github/src/org/jetbrains/plugins/github/GHOpenInBrowserActionGroup.kt | 1 | 11429 | // 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.plugins.github
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.URLUtil
import com.intellij.vcs.log.VcsLogDataKeys
import com.intellij.vcsUtil.VcsUtil
import git4idea.GitFileRevision
import git4idea.GitRevisionNumber
import git4idea.GitUtil
import git4idea.history.GitHistoryUtils
import git4idea.repo.GitRepository
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
import org.jetbrains.plugins.github.util.GithubNotificationIdsHolder
import org.jetbrains.plugins.github.util.GithubNotifications
import org.jetbrains.plugins.github.util.GithubUtil
open class GHOpenInBrowserActionGroup
: ActionGroup(GithubBundle.messagePointer("open.on.github.action"),
GithubBundle.messagePointer("open.on.github.action.description"),
AllIcons.Vcs.Vendors.Github), DumbAware {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun update(e: AnActionEvent) {
val data = getData(e.dataContext)
e.presentation.isEnabledAndVisible = !data.isNullOrEmpty()
e.presentation.isPerformGroup = data?.size == 1
e.presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, e.presentation.isPerformGroup);
e.presentation.isPopupGroup = true
e.presentation.isDisableGroupIfEmpty = false
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
e ?: return emptyArray()
val data = getData(e.dataContext) ?: return emptyArray()
if (data.size <= 1) return emptyArray()
return data.map { GithubOpenInBrowserAction(it) }.toTypedArray()
}
override fun actionPerformed(e: AnActionEvent) {
getData(e.dataContext)?.let { GithubOpenInBrowserAction(it.first()) }?.actionPerformed(e)
}
protected open fun getData(dataContext: DataContext): List<Data>? {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return null
return getDataFromPullRequest(project, dataContext)
?: getDataFromHistory(project, dataContext)
?: getDataFromLog(project, dataContext)
?: getDataFromVirtualFile(project, dataContext)
}
private fun getDataFromPullRequest(project: Project, dataContext: DataContext): List<Data>? {
val pullRequest = dataContext.getData(GHPRActionKeys.SELECTED_PULL_REQUEST)
?: dataContext.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)?.detailsData?.loadedDetails
?: return null
return listOf(Data.URL(project, pullRequest.url))
}
private fun getDataFromHistory(project: Project, dataContext: DataContext): List<Data>? {
val fileRevision = dataContext.getData(VcsDataKeys.VCS_FILE_REVISION) ?: return null
if (fileRevision !is GitFileRevision) return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(fileRevision.path)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories.map { Data.Revision(project, it.ghRepositoryCoordinates, fileRevision.revisionNumber.asString()) }
}
private fun getDataFromLog(project: Project, dataContext: DataContext): List<Data>? {
val selection = dataContext.getData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION) ?: return null
val selectedCommits = selection.commits
if (selectedCommits.size != 1) return null
val commit = ContainerUtil.getFirstItem(selectedCommits) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(commit.root)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories.map { Data.Revision(project, it.ghRepositoryCoordinates, commit.hash.asString()) }
}
private fun getDataFromVirtualFile(project: Project, dataContext: DataContext): List<Data>? {
val virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(virtualFile)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
val changeListManager = ChangeListManager.getInstance(project)
if (changeListManager.isUnversioned(virtualFile)) return null
val change = changeListManager.getChange(virtualFile)
return if (change != null && change.type == Change.Type.NEW) null
else accessibleRepositories.map { Data.File(project, it.ghRepositoryCoordinates, repository.root, virtualFile) }
}
protected sealed class Data(val project: Project) {
@Nls
abstract fun getName(): String
class File(project: Project,
val repository: GHRepositoryCoordinates,
val gitRepoRoot: VirtualFile,
val virtualFile: VirtualFile) : Data(project) {
override fun getName(): String {
@NlsSafe
val formatted = repository.toString().replace('_', ' ')
return formatted
}
}
class Revision(project: Project, val repository: GHRepositoryCoordinates, val revisionHash: String) : Data(project) {
override fun getName(): String {
@NlsSafe
val formatted = repository.toString().replace('_', ' ')
return formatted
}
}
class URL(project: Project, @NlsSafe val htmlUrl: String) : Data(project) {
override fun getName() = htmlUrl
}
}
private companion object {
class GithubOpenInBrowserAction(val data: Data)
: DumbAwareAction({ data.getName() }) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
when (data) {
is Data.Revision -> openCommitInBrowser(data.repository, data.revisionHash)
is Data.File -> openFileInBrowser(data.project, data.gitRepoRoot, data.repository, data.virtualFile,
e.getData(CommonDataKeys.EDITOR))
is Data.URL -> BrowserUtil.browse(data.htmlUrl)
}
}
private fun openCommitInBrowser(path: GHRepositoryCoordinates, revisionHash: String) {
BrowserUtil.browse("${path.toUrl()}/commit/$revisionHash")
}
private fun openFileInBrowser(project: Project,
repositoryRoot: VirtualFile,
path: GHRepositoryCoordinates,
virtualFile: VirtualFile,
editor: Editor?) {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repositoryRoot)
if (relativePath == null) {
GithubNotifications.showError(project, GithubNotificationIdsHolder.OPEN_IN_BROWSER_FILE_IS_NOT_UNDER_REPO,
GithubBundle.message("cannot.open.in.browser"),
GithubBundle.message("open.on.github.file.is.not.under.repository"),
"Root: " + repositoryRoot.presentableUrl + ", file: " + virtualFile.presentableUrl)
return
}
val hash = getCurrentFileRevisionHash(project, virtualFile)
if (hash == null) {
GithubNotifications.showError(project,
GithubNotificationIdsHolder.OPEN_IN_BROWSER_CANNOT_GET_LAST_REVISION,
GithubBundle.message("cannot.open.in.browser"),
GithubBundle.message("cannot.get.last.revision"))
return
}
val githubUrl = GHPathUtil.makeUrlToOpen(editor, relativePath, hash, path)
BrowserUtil.browse(githubUrl)
}
private fun getCurrentFileRevisionHash(project: Project, file: VirtualFile): String? {
val ref = Ref<GitRevisionNumber>()
object : Task.Modal(project, GithubBundle.message("open.on.github.getting.last.revision"), true) {
override fun run(indicator: ProgressIndicator) {
ref.set(GitHistoryUtils.getCurrentRevision(project, VcsUtil.getFilePath(file), "HEAD") as GitRevisionNumber?)
}
override fun onThrowable(error: Throwable) {
GithubUtil.LOG.warn(error)
}
}.queue()
return if (ref.isNull) null else ref.get().rev
}
}
}
}
object GHPathUtil {
fun getFileURL(repository: GitRepository,
path: GHRepositoryCoordinates,
virtualFile: VirtualFile,
editor: Editor?): String? {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repository.root)
if (relativePath == null) {
return null
}
val hash = repository.currentRevision
if (hash == null) {
return null
}
return makeUrlToOpen(editor, relativePath, hash, path)
}
fun makeUrlToOpen(editor: Editor?, relativePath: String, branch: String, path: GHRepositoryCoordinates): String {
val builder = StringBuilder()
if (StringUtil.isEmptyOrSpaces(relativePath)) {
builder.append(path.toUrl()).append("/tree/").append(branch)
}
else {
builder.append(path.toUrl()).append("/blob/").append(branch).append('/').append(URLUtil.encodePath(relativePath))
}
if (editor != null && editor.document.lineCount >= 1) {
// lines are counted internally from 0, but from 1 on github
val selectionModel = editor.selectionModel
val begin = editor.document.getLineNumber(selectionModel.selectionStart) + 1
val selectionEnd = selectionModel.selectionEnd
var end = editor.document.getLineNumber(selectionEnd) + 1
if (editor.document.getLineStartOffset(end - 1) == selectionEnd) {
end -= 1
}
builder.append("#L").append(begin)
if (begin != end) {
builder.append("-L").append(end)
}
}
return builder.toString()
}
} | apache-2.0 | b43921ced29a8103085ac38d650207c1 | 41.333333 | 132 | 0.704524 | 4.947619 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/helpers/utils.kt | 1 | 2091 | // 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.completion.contributors.helpers
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.scopes.KtScope
import org.jetbrains.kotlin.analysis.api.scopes.KtScopeNameFilter
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.idea.completion.checkers.CompletionVisibilityChecker
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
internal fun createStarTypeArgumentsList(typeArgumentsCount: Int): String =
if (typeArgumentsCount > 0) {
List(typeArgumentsCount) { "*" }.joinToString(prefix = "<", postfix = ">")
} else {
""
}
internal fun KtAnalysisSession.collectNonExtensions(
scope: KtScope,
visibilityChecker: CompletionVisibilityChecker,
scopeNameFilter: KtScopeNameFilter,
symbolFilter: (KtCallableSymbol) -> Boolean = { true }
): Sequence<KtCallableSymbol> = scope.getCallableSymbols { name ->
listOfNotNull(name, name.toJavaGetterName(), name.toJavaSetterName()).any(scopeNameFilter)
}
.filterNot { it.isExtension }
.filter { symbolFilter(it) }
.filter { visibilityChecker.isVisible(it) }
private fun Name.toJavaGetterName(): Name? = identifierOrNullIfSpecial?.let { Name.identifier(JvmAbi.getterName(it)) }
private fun Name.toJavaSetterName(): Name? = identifierOrNullIfSpecial?.let { Name.identifier(JvmAbi.setterName(it)) }
internal fun KtDeclaration.canDefinitelyNotBeSeenFromOtherFile(): Boolean {
return when {
isPrivate() -> true
hasModifier(KtTokens.INTERNAL_KEYWORD) && containingKtFile.isCompiled -> {
// internal declarations from library are invisible from source modules
true
}
else -> false
}
} | apache-2.0 | 914b1a59cc8d1de19a8516173cb3ca93 | 42.583333 | 158 | 0.757532 | 4.392857 | false | false | false | false |
leafclick/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectNotificationAware.kt | 1 | 2680 | // 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.externalSystem.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.project.Project
import gnu.trove.THashSet
import org.jetbrains.annotations.TestOnly
class ProjectNotificationAware : Disposable {
private var isHidden = false
private val projectsWithNotification = THashSet<ExternalSystemProjectId>()
fun notificationNotify(projectAware: ExternalSystemProjectAware) = runInEdt {
val projectId = projectAware.projectId
LOG.debug("${projectId.readableName}: Notify notification")
projectsWithNotification.add(projectId)
revealNotification()
}
fun notificationExpire(projectId: ExternalSystemProjectId) = runInEdt {
LOG.debug("${projectId.readableName}: Expire notification")
projectsWithNotification.remove(projectId)
revealNotification()
}
fun notificationExpire() = runInEdt {
LOG.debug("Expire notification")
projectsWithNotification.clear()
revealNotification()
}
override fun dispose() {
notificationExpire()
}
private fun setHideStatus(isHidden: Boolean) = runInEdt {
this.isHidden = isHidden
ApplicationManager.getApplication().assertIsDispatchThread()
val toolbarProvider = ProjectRefreshFloatingProvider.getExtension()
toolbarProvider.updateAllToolbarComponents()
}
private fun revealNotification() = setHideStatus(false)
fun hideNotification() = setHideStatus(true)
fun isNotificationVisible(): Boolean {
ApplicationManager.getApplication().assertIsDispatchThread()
return !isHidden && projectsWithNotification.isNotEmpty()
}
fun getSystemIds(): Set<ProjectSystemId> {
ApplicationManager.getApplication().assertIsDispatchThread()
return projectsWithNotification.map { it.systemId }.toSet()
}
@TestOnly
fun getProjectsWithNotification(): Set<ExternalSystemProjectId> {
ApplicationManager.getApplication().assertIsDispatchThread()
return projectsWithNotification.toSet()
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
@JvmStatic
fun getInstance(project: Project): ProjectNotificationAware {
return ServiceManager.getService(project, ProjectNotificationAware::class.java)
}
}
} | apache-2.0 | 7f0decb76a5d4a01d59db8ce22ba6204 | 33.818182 | 140 | 0.784701 | 5.193798 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-decompiler/src/org/jetbrains/kotlin/idea/jvmDecompiler/DecompileKotlinToJavaAction.kt | 1 | 2500 | // 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.jvmDecompiler
import com.intellij.codeInsight.AttachSourcesProvider
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.util.ActionCallback
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.base.util.KotlinPlatformUtils
import org.jetbrains.kotlin.psi.KtFile
class DecompileKotlinToJavaAction : AnAction(KotlinJvmDecompilerBundle.message("action.decompile.java.name")) {
override fun actionPerformed(e: AnActionEvent) {
val binaryFile = getBinaryKotlinFile(e) ?: return
KotlinJvmDecompilerFacadeImpl.showDecompiledCode(binaryFile)
}
override fun update(e: AnActionEvent) {
when {
KotlinPlatformUtils.isCidr -> e.presentation.isEnabledAndVisible = false
else -> e.presentation.isEnabled = getBinaryKotlinFile(e) != null
}
}
private fun getBinaryKotlinFile(e: AnActionEvent): KtFile? {
val file = e.getData(CommonDataKeys.PSI_FILE) as? KtFile ?: return null
if (!file.canBeDecompiledToJava()) return null
return file
}
}
fun KtFile.canBeDecompiledToJava() = isCompiled && virtualFile?.fileType == JavaClassFileType.INSTANCE
// Add action to "Attach sources" notification panel
class DecompileKotlinToJavaActionProvider : AttachSourcesProvider {
override fun getActions(
orderEntries: MutableList<LibraryOrderEntry>,
psiFile: PsiFile
): Collection<AttachSourcesProvider.AttachSourcesAction> {
if (psiFile !is KtFile || !psiFile.canBeDecompiledToJava()) return emptyList()
return listOf(object : AttachSourcesProvider.AttachSourcesAction {
override fun getName() = KotlinJvmDecompilerBundle.message("action.decompile.java.name")
override fun perform(orderEntriesContainingFile: List<LibraryOrderEntry>?): ActionCallback {
KotlinJvmDecompilerFacadeImpl.showDecompiledCode(psiFile)
return ActionCallback.DONE
}
override fun getBusyText() = KotlinJvmDecompilerBundle.message("action.decompile.busy.text")
})
}
}
| apache-2.0 | 3657a800881a9531525c599e7bf3436b | 40.666667 | 158 | 0.7472 | 4.92126 | false | false | false | false |
taigua/exercism | kotlin/luhn/src/main/kotlin/Luhn.kt | 1 | 989 | /**
* Created by Corwin on 2017/1/31.
*/
class Luhn(num: Long) {
companion object {
private fun digits(num: Long) : List<Int> {
var n = num
val digits: MutableList<Int> = mutableListOf()
while (n != 0L) {
digits.add((n % 10).toInt())
n /= 10
}
return digits.toList()
}
private fun addends(num: Long) : List<Int> {
return digits(num).mapIndexed { i, v ->
if (i % 2 != 0) {
val temp = v * 2
if (temp > 9) temp - 9 else temp
} else {
v
}
}
}
}
val addends : List<Int> = Companion.addends(num).reversed()
val checkDigit: Int = addends.last()
val checksum: Int = addends.sum()
val isValid: Boolean = checksum % 10 == 0
val create: Long = num * 10 + (10 - Companion.addends(num * 10).sum() % 10) % 10
} | mit | 7c48583dc1018ded350196100e49cf19 | 25.052632 | 84 | 0.446916 | 4.020325 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinIdeDescriptorRenderer.kt | 2 | 58506 | // 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.parameterInfo
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.builtins.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.idea.ClassifierNamePolicyEx
import org.jetbrains.kotlin.idea.parameterInfo.KotlinIdeDescriptorRendererHighlightingManager.Companion.Attributes
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.renderer.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils.isCompanionObject
import org.jetbrains.kotlin.resolve.constants.AnnotationValue
import org.jetbrains.kotlin.resolve.constants.ArrayValue
import org.jetbrains.kotlin.resolve.constants.ConstantValue
import org.jetbrains.kotlin.resolve.constants.KClassValue
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.descriptorUtil.declaresOrInheritsDefaultValue
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.TypeUtils.CANNOT_INFER_FUNCTION_PARAM_TYPE
import org.jetbrains.kotlin.types.error.*
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.typeUtil.isUnresolvedType
import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly
import java.util.*
open class KotlinIdeDescriptorRenderer(
open val options: KotlinIdeDescriptorOptions
) : DescriptorRenderer(), DescriptorRendererOptions by options /* this gives access to options without qualifier */ {
private var overriddenHighlightingManager: KotlinIdeDescriptorRendererHighlightingManager<Attributes>? = null
get() = field ?: options.highlightingManager
private inline fun <R> withNoHighlighting(action: () -> R): R {
val old = overriddenHighlightingManager
overriddenHighlightingManager = KotlinIdeDescriptorRendererHighlightingManager.NO_HIGHLIGHTING
val result = action()
overriddenHighlightingManager = old
return result
}
fun withIdeOptions(changeOptions: KotlinIdeDescriptorOptions.() -> Unit): KotlinIdeDescriptorRenderer {
val options = this.options.copy()
options.changeOptions()
options.lock()
return KotlinIdeDescriptorRenderer(options)
}
companion object {
fun withOptions(changeOptions: KotlinIdeDescriptorOptions.() -> Unit): KotlinIdeDescriptorRenderer {
val options = KotlinIdeDescriptorOptions()
options.changeOptions()
options.lock()
return KotlinIdeDescriptorRenderer(options)
}
private val STANDARD_JAVA_ALIASES = setOf(
"kotlin.collections.RandomAccess",
"kotlin.collections.ArrayList",
"kotlin.collections.LinkedHashMap",
"kotlin.collections.HashMap",
"kotlin.collections.LinkedHashSet",
"kotlin.collections.HashSet"
)
}
private val functionTypeAnnotationsRenderer: KotlinIdeDescriptorRenderer by lazy {
withIdeOptions {
excludedTypeAnnotationClasses += listOf(StandardNames.FqNames.extensionFunctionType)
}
}
private fun StringBuilder.appendHighlighted(
value: String,
attributesBuilder: KotlinIdeDescriptorRendererHighlightingManager<Attributes>.() -> Attributes
) {
return with(overriddenHighlightingManager!!) { [email protected](value, attributesBuilder()) }
}
private fun highlight(
value: String,
attributesBuilder: KotlinIdeDescriptorRendererHighlightingManager<Attributes>.() -> Attributes
): String {
return with(overriddenHighlightingManager!!) { buildString { appendHighlighted(value, attributesBuilder()) } }
}
private fun highlightByLexer(value: String): String {
return with(overriddenHighlightingManager!!) { buildString { appendCodeSnippetHighlightedByLexer(value) } }
}
/* FORMATTING */
private fun renderKeyword(keyword: String): String {
val highlighted = highlight(keyword) { asKeyword }
return when (textFormat) {
RenderingFormat.PLAIN -> highlighted
RenderingFormat.HTML -> if (options.bold && !boldOnlyForNamesInHtml) "<b>$highlighted</b>" else highlighted
}
}
protected fun renderError(message: String): String {
val highlighted = highlight(message) { asError }
return when (textFormat) {
RenderingFormat.PLAIN -> highlighted
RenderingFormat.HTML -> if (options.bold) "<b>$highlighted</b>" else highlighted
}
}
protected fun escape(string: String) = textFormat.escape(string)
protected fun lt() = highlight(escape("<")) { asOperationSign }
protected fun gt() = highlight(escape(">")) { asOperationSign }
protected fun arrow(): String {
return highlight(escape("->")) { asArrow }
}
override fun renderMessage(message: String): String {
val highlighted = highlight(message) { asInfo }
return when (textFormat) {
RenderingFormat.PLAIN -> highlighted
RenderingFormat.HTML -> "<i>$highlighted</i>"
}
}
/* NAMES RENDERING */
override fun renderName(name: Name, rootRenderedElement: Boolean): String {
val escaped = escape(name.render())
return if (options.bold && boldOnlyForNamesInHtml && textFormat == RenderingFormat.HTML && rootRenderedElement) {
"<b>$escaped</b>"
} else
escaped
}
protected fun StringBuilder.appendName(descriptor: DeclarationDescriptor, rootRenderedElement: Boolean) {
append(renderName(descriptor.name, rootRenderedElement))
}
private fun StringBuilder.appendName(
descriptor: DeclarationDescriptor,
rootRenderedElement: Boolean,
attributesBuilder: KotlinIdeDescriptorRendererHighlightingManager<Attributes>.() -> Attributes
) {
return with(options.highlightingManager) {
[email protected](renderName(descriptor.name, rootRenderedElement), attributesBuilder())
}
}
private fun StringBuilder.appendCompanionObjectName(descriptor: DeclarationDescriptor) {
if (renderCompanionObjectName) {
if (startFromName) {
appendHighlighted("companion object") { asKeyword }
}
appendSpaceIfNeeded()
val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration != null) {
appendHighlighted("of ") { asInfo }
appendHighlighted(renderName(containingDeclaration.name, false)) { asObjectName }
}
}
if (verbose || descriptor.name != SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT) {
if (!startFromName) appendSpaceIfNeeded()
appendHighlighted(renderName(descriptor.name, true)) { asObjectName }
}
}
override fun renderFqName(fqName: FqNameUnsafe) = renderFqName(fqName.pathSegments())
private fun renderFqName(pathSegments: List<Name>): String {
val rendered = buildString {
for (element in pathSegments) {
if (isNotEmpty()) {
appendHighlighted(".") { asDot }
}
appendHighlighted(element.render()) { asClassName }
}
}
return escape(rendered)
}
override fun renderClassifierName(klass: ClassifierDescriptor): String = if (ErrorUtils.isError(klass)) {
klass.typeConstructor.toString()
} else
classifierNamePolicy.renderClassifier(klass, this)
fun renderClassifierNameWithType(klass: ClassifierDescriptor, type: KotlinType): String = if (ErrorUtils.isError(klass)) {
klass.typeConstructor.toString()
} else {
val policy = classifierNamePolicy
if (policy is ClassifierNamePolicyEx) {
policy.renderClassifierWithType(klass, this, type)
} else {
policy.renderClassifier(klass, this)
}
}
/* TYPES RENDERING */
override fun renderType(type: KotlinType): String = buildString {
appendNormalizedType(typeNormalizer(type))
}
private fun StringBuilder.appendNormalizedType(type: KotlinType) {
val abbreviated = type.unwrap() as? AbbreviatedType
if (abbreviated != null) {
if (renderTypeExpansions) {
appendNormalizedTypeAsIs(abbreviated.expandedType)
} else {
// TODO nullability is lost for abbreviated type?
appendNormalizedTypeAsIs(abbreviated.abbreviation)
if (renderUnabbreviatedType) {
appendAbbreviatedTypeExpansion(abbreviated)
}
}
return
}
appendNormalizedTypeAsIs(type)
}
private fun StringBuilder.appendAbbreviatedTypeExpansion(abbreviated: AbbreviatedType) {
if (options.doNotExpandStandardJavaTypeAliases && abbreviated.fqName?.asString() in STANDARD_JAVA_ALIASES) {
return
}
if (textFormat == RenderingFormat.HTML) {
append("<i>")
}
val expandedType = withNoHighlighting { buildString { appendNormalizedTypeAsIs(abbreviated.expandedType) } }
appendHighlighted(" /* = $expandedType */") { asInfo }
if (textFormat == RenderingFormat.HTML) {
append("</i></font>")
}
}
private fun StringBuilder.appendNormalizedTypeAsIs(type: KotlinType) {
if (type is WrappedType && debugMode && !type.isComputed()) {
appendHighlighted("<Not computed yet>") { asInfo }
return
}
when (val unwrappedType = type.unwrap()) {
is FlexibleType -> append(unwrappedType.render(this@KotlinIdeDescriptorRenderer, this@KotlinIdeDescriptorRenderer))
is SimpleType -> appendSimpleType(unwrappedType)
}
}
private fun StringBuilder.appendSimpleType(type: SimpleType) {
if (type == CANNOT_INFER_FUNCTION_PARAM_TYPE || TypeUtils.isDontCarePlaceholder(type)) {
appendHighlighted("???") { asError }
return
}
if (ErrorUtils.isUninferredTypeVariable(type)) {
if (uninferredTypeParameterAsName) {
append(renderError((type.constructor as ErrorTypeConstructor).getParam(0)))
} else {
appendHighlighted("???") { asError }
}
return
}
if (type.isError) {
appendDefaultType(type)
return
}
if (shouldRenderAsPrettyFunctionType(type)) {
appendFunctionType(type)
} else {
appendDefaultType(type)
}
}
protected fun shouldRenderAsPrettyFunctionType(type: KotlinType): Boolean {
return type.isBuiltinFunctionalType && type.arguments.none { it.isStarProjection }
}
override fun renderFlexibleType(lowerRendered: String, upperRendered: String, builtIns: KotlinBuiltIns): String {
val lowerType = escape(StringUtil.removeHtmlTags(lowerRendered))
val upperType = escape(StringUtil.removeHtmlTags(upperRendered))
if (differsOnlyInNullability(lowerType, upperType)) {
if (upperType.startsWith("(")) {
// the case of complex type, e.g. (() -> Unit)?
return buildString {
appendHighlighted("(") { asParentheses }
append(lowerRendered)
appendHighlighted(")") { asParentheses }
appendHighlighted("!") { asOperationSign }
}
}
return buildString {
append(lowerRendered)
appendHighlighted("!") { asOperationSign }
}
}
val kotlinCollectionsPrefix = classifierNamePolicy.renderClassifier(builtIns.collection, this)
.let { escape(StringUtil.removeHtmlTags(it)) }
.substringBefore("Collection")
val mutablePrefix = "Mutable"
// java.util.List<Foo> -> (Mutable)List<Foo!>!
val simpleCollection = replacePrefixes(
lowerType,
kotlinCollectionsPrefix + mutablePrefix,
upperType,
kotlinCollectionsPrefix,
"$kotlinCollectionsPrefix($mutablePrefix)"
)
if (simpleCollection != null) return simpleCollection
// java.util.Map.Entry<Foo, Bar> -> (Mutable)Map.(Mutable)Entry<Foo!, Bar!>!
val mutableEntry = replacePrefixes(
lowerType,
kotlinCollectionsPrefix + "MutableMap.MutableEntry",
upperType,
kotlinCollectionsPrefix + "Map.Entry",
"$kotlinCollectionsPrefix(Mutable)${highlight("Map") { asClassName }}.(Mutable)${highlight("Entry") { asClassName }}"
)
if (mutableEntry != null) return mutableEntry
val kotlinPrefix = classifierNamePolicy.renderClassifier(builtIns.array, this)
.let { escape(StringUtil.removeHtmlTags(it)) }
.substringBefore("Array")
// Foo[] -> Array<(out) Foo!>!
val array = replacePrefixes(
lowerType,
kotlinPrefix + escape("Array<"),
upperType,
kotlinPrefix + escape("Array<out "),
kotlinPrefix + highlight("Array") { asClassName } + escape("<(out) ")
)
if (array != null) return array
return "($lowerRendered..$upperRendered)"
}
override fun renderTypeArguments(typeArguments: List<TypeProjection>): String = if (typeArguments.isEmpty()) ""
else buildString {
append(lt())
appendTypeProjections(typeArguments)
append(gt())
}
private fun StringBuilder.appendDefaultType(type: KotlinType) {
appendAnnotations(type)
if (type.isError) {
if (isUnresolvedType(type) && presentableUnresolvedTypes) {
appendHighlighted(ErrorUtils.unresolvedTypeAsItIs(type)) { asError }
} else {
if (type is ErrorType && !informativeErrorType) {
appendHighlighted(type.debugMessage) { asError }
} else {
appendHighlighted(type.constructor.toString()) { asError } // Debug name of an error type is more informative
}
appendHighlighted(renderTypeArguments(type.arguments)) { asError }
}
} else {
appendTypeConstructorAndArguments(type)
}
if (type.isMarkedNullable) {
appendHighlighted("?") { asNullityMarker }
}
if (classifierNamePolicy !is ClassifierNamePolicyEx) {
if (type.isDefinitelyNotNullType) {
appendHighlighted(" & Any") { asNonNullAssertion }
}
}
}
private fun StringBuilder.appendTypeConstructorAndArguments(
type: KotlinType,
typeConstructor: TypeConstructor = type.constructor
) {
val possiblyInnerType = type.buildPossiblyInnerType()
if (possiblyInnerType == null) {
append(renderTypeConstructorOfType(typeConstructor, type))
append(renderTypeArguments(type.arguments))
return
}
appendPossiblyInnerType(possiblyInnerType)
}
private fun StringBuilder.appendPossiblyInnerType(possiblyInnerType: PossiblyInnerType) {
possiblyInnerType.outerType?.let {
appendPossiblyInnerType(it)
appendHighlighted(".") { asDot }
appendHighlighted(renderName(possiblyInnerType.classifierDescriptor.name, false)) { asClassName }
} ?: append(renderTypeConstructor(possiblyInnerType.classifierDescriptor.typeConstructor))
append(renderTypeArguments(possiblyInnerType.arguments))
}
override fun renderTypeConstructor(typeConstructor: TypeConstructor): String = when (val cd = typeConstructor.declarationDescriptor) {
is TypeParameterDescriptor -> highlight(renderClassifierName(cd)) { asTypeParameterName }
is ClassDescriptor -> highlight(renderClassifierName(cd)) { asClassName }
is TypeAliasDescriptor -> highlight(renderClassifierName(cd)) { asTypeAlias }
null -> highlight(escape(typeConstructor.toString())) { asClassName }
else -> error("Unexpected classifier: " + cd::class.java)
}
private fun renderTypeConstructorOfType(typeConstructor: TypeConstructor, type: KotlinType): String =
when (val cd = typeConstructor.declarationDescriptor) {
is TypeParameterDescriptor -> highlight(renderClassifierNameWithType(cd, type)) { asTypeParameterName }
is ClassDescriptor -> highlight(renderClassifierNameWithType(cd, type)) { asClassName }
is TypeAliasDescriptor -> highlight(renderClassifierNameWithType(cd, type)) { asTypeAlias }
null -> highlight(escape(typeConstructor.toString())) { asClassName }
else -> error("Unexpected classifier: " + cd::class.java)
}
override fun renderTypeProjection(typeProjection: TypeProjection) = buildString {
appendTypeProjections(listOf(typeProjection))
}
private fun StringBuilder.appendTypeProjections(typeProjections: List<TypeProjection>) {
typeProjections.joinTo(this, highlight(", ") { asComma }) {
if (it.isStarProjection) {
highlight("*") { asOperationSign }
} else {
val type = renderType(it.type)
if (it.projectionKind == Variance.INVARIANT) type
else "${highlight(it.projectionKind.toString()) { asKeyword }} $type"
}
}
}
private fun StringBuilder.appendFunctionType(type: KotlinType) {
val lengthBefore = length
// we need special renderer to skip @ExtensionFunctionType
with(functionTypeAnnotationsRenderer) {
appendAnnotations(type)
}
val hasAnnotations = length != lengthBefore
val isSuspend = type.isSuspendFunctionType
val isNullable = type.isMarkedNullable
val receiverType = type.getReceiverTypeFromFunctionType()
val needParenthesis = isNullable || (hasAnnotations && receiverType != null)
if (needParenthesis) {
if (isSuspend) {
insert(lengthBefore, highlight("(") { asParentheses })
} else {
if (hasAnnotations) {
assert(last().isWhitespace())
if (get(lastIndex - 1) != ')') {
// last annotation rendered without parenthesis - need to add them otherwise parsing will be incorrect
insert(lastIndex, highlight("()") { asParentheses })
}
}
appendHighlighted("(") { asParentheses }
}
}
appendModifier(isSuspend, "suspend")
if (receiverType != null) {
val surroundReceiver = shouldRenderAsPrettyFunctionType(receiverType) && !receiverType.isMarkedNullable ||
receiverType.hasModifiersOrAnnotations()
if (surroundReceiver) {
appendHighlighted("(") { asParentheses }
}
appendNormalizedType(receiverType)
if (surroundReceiver) {
appendHighlighted(")") { asParentheses }
}
appendHighlighted(".") { asDot }
}
appendHighlighted("(") { asParentheses }
val parameterTypes = type.getValueParameterTypesFromFunctionType()
for ((index, typeProjection) in parameterTypes.withIndex()) {
if (index > 0) appendHighlighted(", ") { asComma }
val name = if (parameterNamesInFunctionalTypes) typeProjection.type.extractParameterNameFromFunctionTypeArgument() else null
if (name != null) {
appendHighlighted(renderName(name, false)) { asParameter }
appendHighlighted(": ") { asColon }
}
append(renderTypeProjection(typeProjection))
}
appendHighlighted(") ") { asParentheses }
append(arrow())
append(" ")
appendNormalizedType(type.getReturnTypeFromFunctionType())
if (needParenthesis) appendHighlighted(")") { asParentheses }
if (isNullable) appendHighlighted("?") { asNullityMarker }
}
protected fun KotlinType.hasModifiersOrAnnotations() =
isSuspendFunctionType || !annotations.isEmpty()
/* METHODS FOR ALL KINDS OF DESCRIPTORS */
private fun StringBuilder.appendDefinedIn(descriptor: DeclarationDescriptor) {
if (descriptor is PackageFragmentDescriptor || descriptor is PackageViewDescriptor) {
return
}
if (descriptor is ModuleDescriptor) {
append(renderMessage(" is a module"))
return
}
val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration != null && containingDeclaration !is ModuleDescriptor) {
append(renderMessage(" defined in "))
val fqName = DescriptorUtils.getFqName(containingDeclaration)
append(if (fqName.isRoot) "root package" else renderFqName(fqName))
if (withSourceFileForTopLevel &&
containingDeclaration is PackageFragmentDescriptor &&
descriptor is DeclarationDescriptorWithSource
) {
descriptor.source.containingFile.name?.let { sourceFileName ->
append(renderMessage(" in file "))
append(sourceFileName)
}
}
}
}
private fun StringBuilder.appendAnnotations(
annotated: Annotated,
placeEachAnnotationOnNewLine: Boolean = false,
target: AnnotationUseSiteTarget? = null
) {
if (DescriptorRendererModifier.ANNOTATIONS !in modifiers) return
val excluded = if (annotated is KotlinType) excludedTypeAnnotationClasses else excludedAnnotationClasses
val annotationFilter = annotationFilter
for (annotation in annotated.annotations) {
if (annotation.fqName !in excluded
&& !annotation.isParameterName()
&& (annotationFilter == null || annotationFilter(annotation))
) {
append(renderAnnotation(annotation, target))
if (placeEachAnnotationOnNewLine) {
appendLine()
} else {
append(" ")
}
}
}
}
protected fun AnnotationDescriptor.isParameterName(): Boolean {
return fqName == StandardNames.FqNames.parameterName
}
override fun renderAnnotation(annotation: AnnotationDescriptor, target: AnnotationUseSiteTarget?): String {
return buildString {
appendHighlighted("@") { asAnnotationName }
if (target != null) {
appendHighlighted(target.renderName) { asKeyword }
appendHighlighted(":") { asAnnotationName }
}
val annotationType = annotation.type
val renderedAnnotationName = withNoHighlighting { renderType(annotationType) }
appendHighlighted(renderedAnnotationName) { asAnnotationName }
if (includeAnnotationArguments) {
val arguments = renderAndSortAnnotationArguments(annotation)
if (includeEmptyAnnotationArguments || arguments.isNotEmpty()) {
arguments.joinTo(
this, highlight(", ") { asComma }, highlight("(") { asParentheses }, highlight(")") { asParentheses })
}
}
if (verbose && (annotationType.isError || annotationType.constructor.declarationDescriptor is NotFoundClasses.MockClassDescriptor)) {
appendHighlighted(" /* annotation class not found */") { asError }
}
}
}
private fun renderAndSortAnnotationArguments(descriptor: AnnotationDescriptor): List<String> {
val allValueArguments = descriptor.allValueArguments
val classDescriptor = if (renderDefaultAnnotationArguments) descriptor.annotationClass else null
val parameterDescriptorsWithDefaultValue = classDescriptor?.unsubstitutedPrimaryConstructor?.valueParameters
?.filter { it.declaresDefaultValue() }
?.map { it.name }
.orEmpty()
val defaultList = parameterDescriptorsWithDefaultValue
.filter { it !in allValueArguments }
.map {
buildString {
appendHighlighted(it.asString()) { asAnnotationAttributeName }
appendHighlighted(" = ") { asOperationSign }
appendHighlighted("...") { asInfo }
}
}
val argumentList = allValueArguments.entries
.map { (name, value) ->
buildString {
appendHighlighted(name.asString()) { asAnnotationAttributeName }
appendHighlighted(" = ") { asOperationSign }
if (name !in parameterDescriptorsWithDefaultValue) {
append(renderConstant(value))
} else {
appendHighlighted("...") { asInfo }
}
}
}
return (defaultList + argumentList).sorted()
}
private fun renderConstant(value: ConstantValue<*>): String {
return when (value) {
is ArrayValue -> {
buildString {
appendHighlighted("{") { asBraces }
value.value.joinTo(this, highlight(", ") { asComma }) { renderConstant(it) }
appendHighlighted("}") { asBraces }
}
}
is AnnotationValue -> renderAnnotation(value.value).removePrefix("@")
is KClassValue -> when (val classValue = value.value) {
is KClassValue.Value.LocalClass -> buildString {
appendHighlighted(classValue.type.toString()) { asClassName }
appendHighlighted("::") { asDoubleColon }
appendHighlighted("class") { asKeyword }
}
is KClassValue.Value.NormalClass -> {
var type = classValue.classId.asSingleFqName().asString()
repeat(classValue.arrayDimensions) {
type = buildString {
appendHighlighted("kotlin") { asClassName }
appendHighlighted(".") { asDot }
appendHighlighted("Array") { asClassName }
appendHighlighted("<") { asOperationSign }
append(type)
appendHighlighted(">") { asOperationSign }
}
}
buildString {
append(type)
appendHighlighted("::") { asDoubleColon }
appendHighlighted("class") { asKeyword }
}
}
}
else -> highlightByLexer(value.toString())
}
}
private fun StringBuilder.appendVisibility(visibility: DescriptorVisibility): Boolean {
@Suppress("NAME_SHADOWING")
var visibility = visibility
if (DescriptorRendererModifier.VISIBILITY !in modifiers) return false
if (normalizedVisibilities) {
visibility = visibility.normalize()
}
if (!renderDefaultVisibility && visibility == DescriptorVisibilities.DEFAULT_VISIBILITY) return false
append(renderKeyword(visibility.internalDisplayName))
append(" ")
return true
}
private fun StringBuilder.appendModality(modality: Modality, defaultModality: Modality) {
if (!renderDefaultModality && modality == defaultModality) return
appendModifier(DescriptorRendererModifier.MODALITY in modifiers, modality.name.toLowerCaseAsciiOnly())
}
private fun MemberDescriptor.implicitModalityWithoutExtensions(): Modality {
if (this is ClassDescriptor) {
return if (kind == ClassKind.INTERFACE) Modality.ABSTRACT else Modality.FINAL
}
val containingClassDescriptor = containingDeclaration as? ClassDescriptor ?: return Modality.FINAL
if (this !is CallableMemberDescriptor) return Modality.FINAL
if (this.overriddenDescriptors.isNotEmpty()) {
if (containingClassDescriptor.modality != Modality.FINAL) return Modality.OPEN
}
return if (containingClassDescriptor.kind == ClassKind.INTERFACE && this.visibility != DescriptorVisibilities.PRIVATE) {
if (this.modality == Modality.ABSTRACT) Modality.ABSTRACT else Modality.OPEN
} else
Modality.FINAL
}
private fun StringBuilder.appendModalityForCallable(callable: CallableMemberDescriptor) {
if (!DescriptorUtils.isTopLevelDeclaration(callable) || callable.modality != Modality.FINAL) {
if (overrideRenderingPolicy == OverrideRenderingPolicy.RENDER_OVERRIDE && callable.modality == Modality.OPEN &&
overridesSomething(callable)
) {
return
}
appendModality(callable.modality, callable.implicitModalityWithoutExtensions())
}
}
private fun StringBuilder.appendOverride(callableMember: CallableMemberDescriptor) {
if (DescriptorRendererModifier.OVERRIDE !in modifiers) return
if (overridesSomething(callableMember)) {
if (overrideRenderingPolicy != OverrideRenderingPolicy.RENDER_OPEN) {
appendModifier(true, "override")
if (verbose) {
appendHighlighted("/*${callableMember.overriddenDescriptors.size}*/ ") { asInfo }
}
}
}
}
private fun StringBuilder.appendMemberKind(callableMember: CallableMemberDescriptor) {
if (DescriptorRendererModifier.MEMBER_KIND !in modifiers) return
if (verbose && callableMember.kind != CallableMemberDescriptor.Kind.DECLARATION) {
appendHighlighted("/*${callableMember.kind.name.toLowerCaseAsciiOnly()}*/ ") { asInfo }
}
}
private fun StringBuilder.appendModifier(value: Boolean, modifier: String) {
if (value) {
append(renderKeyword(modifier))
append(" ")
}
}
private fun StringBuilder.appendMemberModifiers(descriptor: MemberDescriptor) {
appendModifier(descriptor.isExternal, "external")
appendModifier(DescriptorRendererModifier.EXPECT in modifiers && descriptor.isExpect, "expect")
appendModifier(DescriptorRendererModifier.ACTUAL in modifiers && descriptor.isActual, "actual")
}
private fun StringBuilder.appendAdditionalModifiers(functionDescriptor: FunctionDescriptor) {
val isOperator =
functionDescriptor.isOperator && (functionDescriptor.overriddenDescriptors.none { it.isOperator } || alwaysRenderModifiers)
val isInfix =
functionDescriptor.isInfix && (functionDescriptor.overriddenDescriptors.none { it.isInfix } || alwaysRenderModifiers)
appendModifier(functionDescriptor.isTailrec, "tailrec")
appendSuspendModifier(functionDescriptor)
appendModifier(functionDescriptor.isInline, "inline")
appendModifier(isInfix, "infix")
appendModifier(isOperator, "operator")
}
private fun StringBuilder.appendSuspendModifier(functionDescriptor: FunctionDescriptor) {
appendModifier(functionDescriptor.isSuspend, "suspend")
}
override fun render(declarationDescriptor: DeclarationDescriptor): String {
return buildString {
declarationDescriptor.accept(RenderDeclarationDescriptorVisitor(), this)
if (withDefinedIn) {
appendDefinedIn(declarationDescriptor)
}
}
}
/* TYPE PARAMETERS */
private fun StringBuilder.appendTypeParameter(typeParameter: TypeParameterDescriptor, topLevel: Boolean) {
if (topLevel) {
append(lt())
}
if (verbose) {
appendHighlighted("/*${typeParameter.index}*/ ") { asInfo }
}
appendModifier(typeParameter.isReified, "reified")
val variance = typeParameter.variance.label
appendModifier(variance.isNotEmpty(), variance)
appendAnnotations(typeParameter)
appendName(typeParameter, topLevel) { asTypeParameterName }
val upperBoundsCount = typeParameter.upperBounds.size
if ((upperBoundsCount > 1 && !topLevel) || upperBoundsCount == 1) {
val upperBound = typeParameter.upperBounds.iterator().next()
if (!KotlinBuiltIns.isDefaultBound(upperBound)) {
appendHighlighted(" : ") { asColon }
append(renderType(upperBound))
}
} else if (topLevel) {
var first = true
for (upperBound in typeParameter.upperBounds) {
if (KotlinBuiltIns.isDefaultBound(upperBound)) {
continue
}
if (first) {
appendHighlighted(" : ") { asColon }
} else {
appendHighlighted(" & ") { asOperationSign }
}
append(renderType(upperBound))
first = false
}
} else {
// rendered with "where"
}
if (topLevel) {
append(gt())
}
}
private fun StringBuilder.appendTypeParameters(typeParameters: List<TypeParameterDescriptor>, withSpace: Boolean) {
if (withoutTypeParameters) return
if (typeParameters.isNotEmpty()) {
append(lt())
appendTypeParameterList(typeParameters)
append(gt())
if (withSpace) {
append(" ")
}
}
}
private fun StringBuilder.appendTypeParameterList(typeParameters: List<TypeParameterDescriptor>) {
val iterator = typeParameters.iterator()
while (iterator.hasNext()) {
val typeParameterDescriptor = iterator.next()
appendTypeParameter(typeParameterDescriptor, false)
if (iterator.hasNext()) {
appendHighlighted(", ") { asComma }
}
}
}
/* FUNCTIONS */
private fun StringBuilder.appendFunction(function: FunctionDescriptor) {
if (!startFromName) {
if (!startFromDeclarationKeyword) {
appendAnnotations(function, eachAnnotationOnNewLine)
appendVisibility(function.visibility)
appendModalityForCallable(function)
if (includeAdditionalModifiers) {
appendMemberModifiers(function)
}
appendOverride(function)
if (includeAdditionalModifiers) {
appendAdditionalModifiers(function)
} else {
appendSuspendModifier(function)
}
appendMemberKind(function)
if (verbose) {
if (function.isHiddenToOvercomeSignatureClash) {
appendHighlighted("/*isHiddenToOvercomeSignatureClash*/ ") { asInfo }
}
if (function.isHiddenForResolutionEverywhereBesideSupercalls) {
appendHighlighted("/*isHiddenForResolutionEverywhereBesideSupercalls*/ ") { asInfo }
}
}
}
append(renderKeyword("fun"))
append(" ")
appendTypeParameters(function.typeParameters, true)
appendReceiver(function)
}
appendName(function, true) { asFunDeclaration }
appendValueParameters(function.valueParameters, function.hasSynthesizedParameterNames())
appendReceiverAfterName(function)
val returnType = function.returnType
if (!withoutReturnType && (unitReturnType || (returnType == null || !KotlinBuiltIns.isUnit(returnType)))) {
appendHighlighted(": ") { asColon }
append(if (returnType == null) highlight("[NULL]") { asError } else renderType(returnType))
}
appendWhereSuffix(function.typeParameters)
}
private fun StringBuilder.appendReceiverAfterName(callableDescriptor: CallableDescriptor) {
if (!receiverAfterName) return
val receiver = callableDescriptor.extensionReceiverParameter
if (receiver != null) {
appendHighlighted(" on ") { asInfo }
append(renderType(receiver.type))
}
}
private fun StringBuilder.appendReceiver(callableDescriptor: CallableDescriptor) {
val receiver = callableDescriptor.extensionReceiverParameter
if (receiver != null) {
appendAnnotations(receiver, target = AnnotationUseSiteTarget.RECEIVER)
val type = receiver.type
var result = renderType(type)
if (shouldRenderAsPrettyFunctionType(type) && !TypeUtils.isNullableType(type)) {
result = "${highlight("(") { asParentheses }}$result${highlight(")") { asParentheses }}"
}
append(result)
appendHighlighted(".") { asDot }
}
}
private fun StringBuilder.appendConstructor(constructor: ConstructorDescriptor) {
appendAnnotations(constructor)
val visibilityRendered = (options.renderDefaultVisibility || constructor.constructedClass.modality != Modality.SEALED)
&& appendVisibility(constructor.visibility)
appendMemberKind(constructor)
val constructorKeywordRendered = renderConstructorKeyword || !constructor.isPrimary || visibilityRendered
if (constructorKeywordRendered) {
append(renderKeyword("constructor"))
}
val classDescriptor = constructor.containingDeclaration
if (secondaryConstructorsAsPrimary) {
if (constructorKeywordRendered) {
append(" ")
}
appendName(classDescriptor, true) { asClassName }
appendTypeParameters(constructor.typeParameters, false)
}
appendValueParameters(constructor.valueParameters, constructor.hasSynthesizedParameterNames())
if (renderConstructorDelegation && !constructor.isPrimary && classDescriptor is ClassDescriptor) {
val primaryConstructor = classDescriptor.unsubstitutedPrimaryConstructor
if (primaryConstructor != null) {
val parametersWithoutDefault = primaryConstructor.valueParameters.filter {
!it.declaresDefaultValue() && it.varargElementType == null
}
if (parametersWithoutDefault.isNotEmpty()) {
appendHighlighted(" : ") { asColon }
append(renderKeyword("this"))
append(parametersWithoutDefault.joinToString(
prefix = highlight("(") { asParentheses },
separator = highlight(", ") { asComma },
postfix = highlight(")") { asParentheses }
) { "" }
)
}
}
}
if (secondaryConstructorsAsPrimary) {
appendWhereSuffix(constructor.typeParameters)
}
}
private fun StringBuilder.appendWhereSuffix(typeParameters: List<TypeParameterDescriptor>) {
if (withoutTypeParameters) return
val upperBoundStrings = ArrayList<String>(0)
for (typeParameter in typeParameters) {
typeParameter.upperBounds
.drop(1) // first parameter is rendered by renderTypeParameter
.mapTo(upperBoundStrings) {
buildString {
appendHighlighted(renderName(typeParameter.name, false)) { asTypeParameterName }
appendHighlighted(" : ") { asColon }
append(renderType(it))
}
}
}
if (upperBoundStrings.isNotEmpty()) {
append(" ")
append(renderKeyword("where"))
append(" ")
upperBoundStrings.joinTo(this, highlight(", ") { asComma })
}
}
override fun renderValueParameters(parameters: Collection<ValueParameterDescriptor>, synthesizedParameterNames: Boolean) = buildString {
appendValueParameters(parameters, synthesizedParameterNames)
}
private fun StringBuilder.appendValueParameters(
parameters: Collection<ValueParameterDescriptor>,
synthesizedParameterNames: Boolean
) {
val includeNames = shouldRenderParameterNames(synthesizedParameterNames)
val parameterCount = parameters.size
valueParametersHandler.appendBeforeValueParameters(parameterCount, this)
for ((index, parameter) in parameters.withIndex()) {
valueParametersHandler.appendBeforeValueParameter(parameter, index, parameterCount, this)
appendValueParameter(parameter, includeNames, false)
valueParametersHandler.appendAfterValueParameter(parameter, index, parameterCount, this)
}
valueParametersHandler.appendAfterValueParameters(parameterCount, this)
}
private fun shouldRenderParameterNames(synthesizedParameterNames: Boolean): Boolean = when (parameterNameRenderingPolicy) {
ParameterNameRenderingPolicy.ALL -> true
ParameterNameRenderingPolicy.ONLY_NON_SYNTHESIZED -> !synthesizedParameterNames
ParameterNameRenderingPolicy.NONE -> false
}
/* VARIABLES */
private fun StringBuilder.appendValueParameter(
valueParameter: ValueParameterDescriptor,
includeName: Boolean,
topLevel: Boolean
) {
if (topLevel) {
append(renderKeyword("value-parameter"))
append(" ")
}
if (verbose) {
appendHighlighted("/*${valueParameter.index}*/ ") { asInfo }
}
appendAnnotations(valueParameter)
appendModifier(valueParameter.isCrossinline, "crossinline")
appendModifier(valueParameter.isNoinline, "noinline")
val isPrimaryConstructor = renderPrimaryConstructorParametersAsProperties &&
(valueParameter.containingDeclaration as? ClassConstructorDescriptor)?.isPrimary == true
if (isPrimaryConstructor) {
appendModifier(actualPropertiesInPrimaryConstructor, "actual")
}
appendVariable(valueParameter, includeName, topLevel, isPrimaryConstructor)
val withDefaultValue =
defaultParameterValueRenderer != null &&
(if (debugMode) valueParameter.declaresDefaultValue() else valueParameter.declaresOrInheritsDefaultValue())
if (withDefaultValue) {
appendHighlighted(" = ") { asOperationSign }
append(highlightByLexer(defaultParameterValueRenderer!!(valueParameter)))
}
}
private fun StringBuilder.appendValVarPrefix(variable: VariableDescriptor, isInPrimaryConstructor: Boolean = false) {
if (isInPrimaryConstructor || variable !is ValueParameterDescriptor) {
if (variable.isVar) {
appendHighlighted("var") { asVar }
} else {
appendHighlighted("val") { asVal }
}
append(" ")
}
}
private fun StringBuilder.appendVariable(
variable: VariableDescriptor,
includeName: Boolean,
topLevel: Boolean,
isInPrimaryConstructor: Boolean = false
) {
val realType = variable.type
val varargElementType = (variable as? ValueParameterDescriptor)?.varargElementType
val typeToRender = varargElementType ?: realType
appendModifier(varargElementType != null, "vararg")
if (isInPrimaryConstructor || topLevel && !startFromName) {
appendValVarPrefix(variable, isInPrimaryConstructor)
}
if (includeName) {
appendName(variable, topLevel) { asLocalVarOrVal }
appendHighlighted(": ") { asColon }
}
append(renderType(typeToRender))
appendInitializer(variable)
if (verbose && varargElementType != null) {
val expandedType = withNoHighlighting { renderType(realType) }
appendHighlighted(" /*${expandedType}*/") { asInfo }
}
}
private fun StringBuilder.appendProperty(property: PropertyDescriptor) {
if (!startFromName) {
if (!startFromDeclarationKeyword) {
appendPropertyAnnotations(property)
appendVisibility(property.visibility)
appendModifier(DescriptorRendererModifier.CONST in modifiers && property.isConst, "const")
appendMemberModifiers(property)
appendModalityForCallable(property)
appendOverride(property)
appendModifier(DescriptorRendererModifier.LATEINIT in modifiers && property.isLateInit, "lateinit")
appendMemberKind(property)
}
appendValVarPrefix(property)
appendTypeParameters(property.typeParameters, true)
appendReceiver(property)
}
appendName(property, true) { asInstanceProperty }
appendHighlighted(": ") { asColon }
append(renderType(property.type))
appendReceiverAfterName(property)
appendInitializer(property)
appendWhereSuffix(property.typeParameters)
}
private fun StringBuilder.appendPropertyAnnotations(property: PropertyDescriptor) {
if (DescriptorRendererModifier.ANNOTATIONS !in modifiers) return
appendAnnotations(property, eachAnnotationOnNewLine)
property.backingField?.let { appendAnnotations(it, target = AnnotationUseSiteTarget.FIELD) }
property.delegateField?.let { appendAnnotations(it, target = AnnotationUseSiteTarget.PROPERTY_DELEGATE_FIELD) }
if (propertyAccessorRenderingPolicy == PropertyAccessorRenderingPolicy.NONE) {
property.getter?.let {
appendAnnotations(it, target = AnnotationUseSiteTarget.PROPERTY_GETTER)
}
property.setter?.let { setter ->
setter.let {
appendAnnotations(it, target = AnnotationUseSiteTarget.PROPERTY_SETTER)
}
setter.valueParameters.single().let {
appendAnnotations(it, target = AnnotationUseSiteTarget.SETTER_PARAMETER)
}
}
}
}
private fun StringBuilder.appendInitializer(variable: VariableDescriptor) {
if (includePropertyConstant) {
variable.compileTimeInitializer?.let { constant ->
appendHighlighted(" = ") { asOperationSign }
append(escape(renderConstant(constant)))
}
}
}
private fun StringBuilder.appendTypeAlias(typeAlias: TypeAliasDescriptor) {
appendAnnotations(typeAlias, eachAnnotationOnNewLine)
appendVisibility(typeAlias.visibility)
appendMemberModifiers(typeAlias)
append(renderKeyword("typealias"))
append(" ")
appendName(typeAlias, true) { asTypeAlias }
appendTypeParameters(typeAlias.declaredTypeParameters, false)
appendCapturedTypeParametersIfRequired(typeAlias)
appendHighlighted(" = ") { asOperationSign }
append(renderType(typeAlias.underlyingType))
}
private fun StringBuilder.appendCapturedTypeParametersIfRequired(classifier: ClassifierDescriptorWithTypeParameters) {
val typeParameters = classifier.declaredTypeParameters
val typeConstructorParameters = classifier.typeConstructor.parameters
if (verbose && classifier.isInner && typeConstructorParameters.size > typeParameters.size) {
val capturedTypeParametersInfo = buildString {
append(" /*captured type parameters: ")
withNoHighlighting {
appendTypeParameterList(typeConstructorParameters.subList(typeParameters.size, typeConstructorParameters.size))
}
append("*/")
}
appendHighlighted(capturedTypeParametersInfo) { asInfo }
}
}
/* CLASSES */
private fun StringBuilder.appendClass(klass: ClassDescriptor) {
val isEnumEntry = klass.kind == ClassKind.ENUM_ENTRY
if (!startFromName) {
appendAnnotations(klass, eachAnnotationOnNewLine)
if (!isEnumEntry) {
appendVisibility(klass.visibility)
}
if (!(klass.kind == ClassKind.INTERFACE && klass.modality == Modality.ABSTRACT ||
klass.kind.isSingleton && klass.modality == Modality.FINAL)
) {
appendModality(klass.modality, klass.implicitModalityWithoutExtensions())
}
appendMemberModifiers(klass)
appendModifier(DescriptorRendererModifier.INNER in modifiers && klass.isInner, "inner")
appendModifier(DescriptorRendererModifier.DATA in modifiers && klass.isData, "data")
appendModifier(DescriptorRendererModifier.INLINE in modifiers && klass.isInline, "inline")
appendModifier(DescriptorRendererModifier.VALUE in modifiers && klass.isValue, "value")
appendModifier(DescriptorRendererModifier.FUN in modifiers && klass.isFun, "fun")
appendClassKindPrefix(klass)
}
if (!isCompanionObject(klass)) {
if (!startFromName) appendSpaceIfNeeded()
appendName(klass, true) { asClassName }
} else {
appendCompanionObjectName(klass)
}
if (isEnumEntry) return
val typeParameters = klass.declaredTypeParameters
appendTypeParameters(typeParameters, false)
appendCapturedTypeParametersIfRequired(klass)
val primaryConstructor = klass.unsubstitutedPrimaryConstructor
if (primaryConstructor != null &&
(klass.isData && options.dataClassWithPrimaryConstructor || !klass.kind.isSingleton && classWithPrimaryConstructor)
) {
if (!klass.isData || !primaryConstructor.annotations.isEmpty()) {
append(" ")
appendAnnotations(primaryConstructor)
appendVisibility(primaryConstructor.visibility)
append(renderKeyword("constructor"))
}
appendValueParameters(primaryConstructor.valueParameters, primaryConstructor.hasSynthesizedParameterNames())
appendSuperTypes(klass, indent = " ")
} else {
appendSuperTypes(klass, prefix = "\n ")
}
appendWhereSuffix(typeParameters)
}
private fun StringBuilder.appendSuperTypes(klass: ClassDescriptor, prefix: String = " ", indent: String = " ") {
if (withoutSuperTypes) return
if (KotlinBuiltIns.isNothing(klass.defaultType)) return
val supertypes = klass.typeConstructor.supertypes.toMutableList()
if (klass.kind == ClassKind.ENUM_CLASS) {
supertypes.removeIf { KotlinBuiltIns.isEnum(it) }
}
if (supertypes.isEmpty() || supertypes.size == 1 && KotlinBuiltIns.isAnyOrNullableAny(supertypes.iterator().next())) return
append(prefix)
appendHighlighted(": ") { asColon }
val separator = when {
supertypes.size <= 3 -> ", "
else -> ",\n$indent "
}
supertypes.joinTo(this, highlight(separator) { asComma }) { renderType(it) }
}
private fun StringBuilder.appendClassKindPrefix(klass: ClassDescriptor) {
append(renderKeyword(getClassifierKindPrefix(klass)))
}
/* OTHER */
private fun StringBuilder.appendPackageView(packageView: PackageViewDescriptor) {
appendPackageHeader(packageView.fqName, "package")
if (debugMode) {
appendHighlighted(" in context of ") { asInfo }
appendName(packageView.module, false) { asPackageName }
}
}
private fun StringBuilder.appendPackageFragment(fragment: PackageFragmentDescriptor) {
appendPackageHeader(fragment.fqName, "package-fragment")
if (debugMode) {
appendHighlighted(" in ") { asInfo }
appendName(fragment.containingDeclaration, false) { asPackageName }
}
}
private fun StringBuilder.appendPackageHeader(fqName: FqName, fragmentOrView: String) {
append(renderKeyword(fragmentOrView))
val fqNameString = renderFqName(fqName.toUnsafe())
if (fqNameString.isNotEmpty()) {
append(" ")
append(fqNameString)
}
}
private fun StringBuilder.appendAccessorModifiers(descriptor: PropertyAccessorDescriptor) {
appendMemberModifiers(descriptor)
}
/* STUPID DISPATCH-ONLY VISITOR */
private inner class RenderDeclarationDescriptorVisitor : DeclarationDescriptorVisitor<Unit, StringBuilder> {
override fun visitValueParameterDescriptor(descriptor: ValueParameterDescriptor, builder: StringBuilder) {
builder.appendValueParameter(descriptor, true, true)
}
override fun visitVariableDescriptor(descriptor: VariableDescriptor, builder: StringBuilder) {
builder.appendVariable(descriptor, true, true)
}
override fun visitPropertyDescriptor(descriptor: PropertyDescriptor, builder: StringBuilder) {
builder.appendProperty(descriptor)
}
override fun visitPropertyGetterDescriptor(descriptor: PropertyGetterDescriptor, builder: StringBuilder) {
visitPropertyAccessorDescriptor(descriptor, builder, "getter")
}
override fun visitPropertySetterDescriptor(descriptor: PropertySetterDescriptor, builder: StringBuilder) {
visitPropertyAccessorDescriptor(descriptor, builder, "setter")
}
private fun visitPropertyAccessorDescriptor(descriptor: PropertyAccessorDescriptor, builder: StringBuilder, kind: String) {
when (propertyAccessorRenderingPolicy) {
PropertyAccessorRenderingPolicy.PRETTY -> {
builder.appendAccessorModifiers(descriptor)
builder.appendHighlighted("$kind for ") { asInfo }
builder.appendProperty(descriptor.correspondingProperty)
}
PropertyAccessorRenderingPolicy.DEBUG -> {
visitFunctionDescriptor(descriptor, builder)
}
PropertyAccessorRenderingPolicy.NONE -> {
}
}
}
override fun visitFunctionDescriptor(descriptor: FunctionDescriptor, builder: StringBuilder) {
builder.appendFunction(descriptor)
}
override fun visitReceiverParameterDescriptor(descriptor: ReceiverParameterDescriptor, builder: StringBuilder) {
builder.append(descriptor.name) // renders <this>
}
override fun visitConstructorDescriptor(constructorDescriptor: ConstructorDescriptor, builder: StringBuilder) {
builder.appendConstructor(constructorDescriptor)
}
override fun visitTypeParameterDescriptor(descriptor: TypeParameterDescriptor, builder: StringBuilder) {
builder.appendTypeParameter(descriptor, true)
}
override fun visitPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor, builder: StringBuilder) {
builder.appendPackageFragment(descriptor)
}
override fun visitPackageViewDescriptor(descriptor: PackageViewDescriptor, builder: StringBuilder) {
builder.appendPackageView(descriptor)
}
override fun visitModuleDeclaration(descriptor: ModuleDescriptor, builder: StringBuilder) {
builder.appendName(descriptor, true) { asPackageName }
}
override fun visitScriptDescriptor(scriptDescriptor: ScriptDescriptor, builder: StringBuilder) {
visitClassDescriptor(scriptDescriptor, builder)
}
override fun visitClassDescriptor(descriptor: ClassDescriptor, builder: StringBuilder) {
builder.appendClass(descriptor)
}
override fun visitTypeAliasDescriptor(descriptor: TypeAliasDescriptor, builder: StringBuilder) {
builder.appendTypeAlias(descriptor)
}
}
private fun StringBuilder.appendSpaceIfNeeded() {
if (isEmpty() || this[length - 1] != ' ') {
append(' ')
}
}
private fun replacePrefixes(
lowerRendered: String,
lowerPrefix: String,
upperRendered: String,
upperPrefix: String,
foldedPrefix: String
): String? {
if (lowerRendered.startsWith(lowerPrefix) && upperRendered.startsWith(upperPrefix)) {
val lowerWithoutPrefix = lowerRendered.substring(lowerPrefix.length)
val upperWithoutPrefix = upperRendered.substring(upperPrefix.length)
val flexibleCollectionName = foldedPrefix + lowerWithoutPrefix
return when {
lowerWithoutPrefix == upperWithoutPrefix -> flexibleCollectionName
differsOnlyInNullability(lowerWithoutPrefix, upperWithoutPrefix) -> "$flexibleCollectionName!"
else -> null
}
}
return null
}
private fun differsOnlyInNullability(lower: String, upper: String) =
lower == upper.replace("?", "") || upper.endsWith("?") && ("$lower?") == upper || "($lower)?" == upper
private fun overridesSomething(callable: CallableMemberDescriptor) = !callable.overriddenDescriptors.isEmpty()
}
| apache-2.0 | e3068dfc6f28d4fbb584f9733ee8b26e | 41 | 145 | 0.636482 | 5.716268 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/ChangeTypeFixUtils.kt | 3 | 2928 | // 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.quickfix
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
object ChangeTypeFixUtils {
fun familyName(): String = KotlinBundle.message("fix.change.return.type.family")
fun functionOrConstructorParameterPresentation(element: KtCallableDeclaration, containerName: String?): String? {
val name = element.name
return if (name != null) {
val fullName = if (containerName != null) "'${containerName}.$name'" else "'$name'"
when (element) {
is KtParameter -> KotlinBundle.message("fix.change.return.type.presentation.property", fullName)
is KtProperty -> KotlinBundle.message("fix.change.return.type.presentation.property", fullName)
else -> KotlinBundle.message("fix.change.return.type.presentation.function", fullName)
}
} else null
}
fun baseFunctionOrConstructorParameterPresentation(presentation: String): String =
KotlinBundle.message("fix.change.return.type.presentation.base", presentation)
fun baseFunctionOrConstructorParameterPresentation(element: KtCallableDeclaration, containerName: String?): String? {
val presentation = functionOrConstructorParameterPresentation(element, containerName) ?: return null
return baseFunctionOrConstructorParameterPresentation(presentation)
}
fun getTextForQuickFix(
element: KtCallableDeclaration,
presentation: String?,
isUnitType: Boolean,
typePresentation: String
): String {
if (isUnitType && element is KtFunction && element.hasBlockBody()) {
return if (presentation == null)
KotlinBundle.message("fix.change.return.type.remove.explicit.return.type")
else
KotlinBundle.message("fix.change.return.type.remove.explicit.return.type.of", presentation)
}
return when (element) {
is KtFunction -> {
if (presentation != null)
KotlinBundle.message("fix.change.return.type.return.type.text.of", presentation, typePresentation)
else
KotlinBundle.message("fix.change.return.type.return.type.text", typePresentation)
}
else -> {
if (presentation != null)
KotlinBundle.message("fix.change.return.type.type.text.of", presentation, typePresentation)
else
KotlinBundle.message("fix.change.return.type.type.text", typePresentation)
}
}
}
} | apache-2.0 | 20534dc48d0ad6631f6c2951414d2ab8 | 45.492063 | 158 | 0.671107 | 5.083333 | false | false | false | false |
dkrivoruchko/ScreenStream | mjpeg/src/main/kotlin/info/dvkr/screenstream/mjpeg/state/MjpegStateMachine.kt | 1 | 21301 | package info.dvkr.screenstream.mjpeg.state
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.common.AppError
import info.dvkr.screenstream.common.AppStateMachine
import info.dvkr.screenstream.common.getLog
import info.dvkr.screenstream.common.settings.AppSettings
import info.dvkr.screenstream.mjpeg.*
import info.dvkr.screenstream.mjpeg.httpserver.HttpServer
import info.dvkr.screenstream.mjpeg.image.BitmapCapture
import info.dvkr.screenstream.mjpeg.image.NotificationBitmap
import info.dvkr.screenstream.mjpeg.settings.MjpegSettings
import info.dvkr.screenstream.mjpeg.state.helper.BroadcastHelper
import info.dvkr.screenstream.mjpeg.state.helper.ConnectivityHelper
import info.dvkr.screenstream.mjpeg.state.helper.NetworkHelper
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.util.concurrent.LinkedBlockingDeque
class MjpegStateMachine(
private val serviceContext: Context,
private val appSettings: AppSettings,
private val mjpegSettings: MjpegSettings,
private val effectSharedFlow: MutableSharedFlow<AppStateMachine.Effect>,
private val onSlowConnectionDetected: () -> Unit
) : AppStateMachine {
private val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
XLog.e(getLog("onCoroutineException"), throwable)
onError(CoroutineException)
}
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default + coroutineExceptionHandler)
private val bitmapStateFlow = MutableStateFlow(Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888))
private val projectionManager = serviceContext.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
private val projectionCallback = object : MediaProjection.Callback() {
override fun onStop() {
XLog.i([email protected]("MediaProjection.Callback", "onStop"))
sendEvent(AppStateMachine.Event.StopStream)
}
}
private val broadcastHelper = BroadcastHelper.getInstance(serviceContext)
private val connectivityHelper: ConnectivityHelper = ConnectivityHelper.getInstance(serviceContext)
private val networkHelper = NetworkHelper(serviceContext)
private val notificationBitmap = NotificationBitmap(serviceContext, mjpegSettings)
private val httpServer = HttpServer(serviceContext, coroutineScope, mjpegSettings, bitmapStateFlow.asStateFlow(), notificationBitmap)
private var mediaProjectionIntent: Intent? = null
private val powerManager = serviceContext.getSystemService(Context.POWER_SERVICE) as PowerManager
private var wakeLock: PowerManager.WakeLock? = null
internal sealed class InternalEvent : AppStateMachine.Event() {
object DiscoverAddress : InternalEvent()
object StartServer : InternalEvent()
data class ComponentError(val appError: AppError) : InternalEvent()
object StartStopFromWebPage : InternalEvent()
data class RestartServer(val reason: RestartReason) : InternalEvent()
object ScreenOff : InternalEvent()
object Destroy : InternalEvent()
override fun toString(): String = javaClass.simpleName
}
internal sealed class RestartReason(private val msg: String) {
class ConnectionChanged(msg: String) : RestartReason(msg)
class SettingsChanged(msg: String) : RestartReason(msg)
class NetworkSettingsChanged(msg: String) : RestartReason(msg)
override fun toString(): String = "${javaClass.simpleName}[$msg]"
}
override fun sendEvent(event: AppStateMachine.Event, timeout: Long) {
if (timeout > 0) {
XLog.d(getLog("sendEvent[Timeout: $timeout]", "Event: $event"))
coroutineScope.launch { delay(timeout); sendEvent(event) }
return
}
XLog.d(getLog("sendEvent", "Event: $event"))
runCatching {
eventDeque.addLast(event)
eventSharedFlow.tryEmit(event) || throw IllegalStateException("eventSharedFlow IsFull")
XLog.d(getLog("sendEvent", "Pending events => $eventDeque"))
}.onFailure { cause ->
XLog.e(getLog("sendEvent", "Pending events => $eventDeque"), cause)
coroutineScope.launch(NonCancellable) {
streamState = componentError(streamState, ChannelException, true)
effectSharedFlow.emit(streamState.toPublicState())
}
}
}
private var streamState = StreamState()
private var previousStreamState = StreamState()
private val eventSharedFlow = MutableSharedFlow<AppStateMachine.Event>(replay = 5, extraBufferCapacity = 8)
private val eventDeque = LinkedBlockingDeque<AppStateMachine.Event>()
init {
XLog.d(getLog("init"))
coroutineScope.launch {
if (mjpegSettings.enablePinFlow.first() && mjpegSettings.newPinOnAppStartFlow.first())
mjpegSettings.setPin(randomPin())
}
coroutineScope.launch(CoroutineName("MjpegAppStateMachine.eventSharedFlow")) {
eventSharedFlow.onEach { event ->
XLog.d([email protected]("eventSharedFlow.onEach", "$event"))
if (StateToEventMatrix.skippEvent(streamState.state, event).not()) {
previousStreamState = streamState
streamState = when (event) {
is InternalEvent.DiscoverAddress -> discoverAddress(streamState)
is InternalEvent.StartServer -> startServer(streamState)
is InternalEvent.ComponentError -> componentError(streamState, event.appError, false)
is InternalEvent.StartStopFromWebPage -> startStopFromWebPage(streamState)
is InternalEvent.RestartServer -> restartServer(streamState, event.reason)
is InternalEvent.ScreenOff -> screenOff(streamState)
is InternalEvent.Destroy -> destroy(streamState)
is AppStateMachine.Event.StartStream -> startStream(streamState)
is AppStateMachine.Event.CastPermissionsDenied -> castPermissionsDenied(streamState)
is AppStateMachine.Event.StartProjection -> startProjection(streamState, event.intent)
is AppStateMachine.Event.StopStream -> stopStream(streamState)
is AppStateMachine.Event.RequestPublicState -> requestPublicState(streamState)
is AppStateMachine.Event.RecoverError -> recoverError(streamState)
else -> throw IllegalArgumentException("Unknown AppStateMachine.Event: $event")
}
if (streamState.isPublicStatePublishRequired(previousStreamState)) effectSharedFlow.emit(streamState.toPublicState())
XLog.i([email protected]("eventSharedFlow.onEach", "New state:${streamState.state}"))
}
eventDeque.pollFirst()
XLog.d([email protected]("eventSharedFlow.onEach.done", eventDeque.toString()))
}
.catch { cause ->
XLog.e([email protected]("eventSharedFlow.catch"), cause)
streamState = componentError(streamState, CoroutineException, true)
effectSharedFlow.emit(streamState.toPublicState())
}
.collect()
}
mjpegSettings.htmlEnableButtonsFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.HTML_ENABLE_BUTTONS.name)))
}
mjpegSettings.htmlBackColorFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.HTML_BACK_COLOR.name)))
}
mjpegSettings.enablePinFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.ENABLE_PIN.name)))
}
mjpegSettings.pinFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.PIN.name)))
}
mjpegSettings.blockAddressFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.BLOCK_ADDRESS.name)))
}
mjpegSettings.useWiFiOnlyFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.USE_WIFI_ONLY.name)))
}
mjpegSettings.enableIPv6Flow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.ENABLE_IPV6.name)))
}
mjpegSettings.enableLocalHostFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.ENABLE_LOCAL_HOST.name)))
}
mjpegSettings.localHostOnlyFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.LOCAL_HOST_ONLY.name)))
}
mjpegSettings.serverPortFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.SERVER_PORT.name)))
}
broadcastHelper.startListening(
onScreenOff = { sendEvent(InternalEvent.ScreenOff) },
onConnectionChanged = { sendEvent(InternalEvent.RestartServer(RestartReason.ConnectionChanged("BroadcastHelper"))) }
)
connectivityHelper.startListening(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.ConnectionChanged("ConnectivityHelper")))
}
coroutineScope.launch(CoroutineName("MjpegStateMachine.httpServer.eventSharedFlow")) {
httpServer.eventSharedFlow.onEach { event ->
if (event !is HttpServer.Event.Statistic)
XLog.d([email protected]("httpServer.eventSharedFlow.onEach", "$event"))
when (event) {
is HttpServer.Event.Action ->
when (event) {
is HttpServer.Event.Action.StartStopRequest -> sendEvent(InternalEvent.StartStopFromWebPage)
}
is HttpServer.Event.Statistic ->
when (event) {
is HttpServer.Event.Statistic.Clients -> {
effectSharedFlow.emit(AppStateMachine.Effect.Statistic.Clients(event.clients))
if (appSettings.autoStartStopFlow.first()) checkAutoStartStop(event.clients)
if (mjpegSettings.notifySlowConnectionsFlow.first()) checkForSlowClients(event.clients)
}
is HttpServer.Event.Statistic.Traffic ->
effectSharedFlow.emit(AppStateMachine.Effect.Statistic.Traffic(event.traffic))
}
is HttpServer.Event.Error -> onError(event.error)
}
}
.catch { cause ->
XLog.e([email protected]("httpServer.eventSharedFlow.catch"), cause)
onError(CoroutineException)
}
.collect()
}
}
private var slowClients: List<MjpegClient> = emptyList()
private fun checkForSlowClients(clients: List<MjpegClient>) {
val currentSlowConnections = clients.filter { it.isSlowConnection }.toList()
if (slowClients.containsAll(currentSlowConnections).not()) onSlowConnectionDetected()
slowClients = currentSlowConnections
}
private fun checkAutoStartStop(clients: List<MjpegClient>) {
if (clients.isNotEmpty() && streamState.isStreaming().not()) {
XLog.d(getLog("checkAutoStartStop", "Auto starting"))
sendEvent(AppStateMachine.Event.StartStream)
}
if (clients.isEmpty() && streamState.isStreaming()) {
XLog.d(getLog("checkAutoStartStop", "Auto stopping"))
sendEvent(AppStateMachine.Event.StopStream)
}
}
override fun destroy() {
XLog.d(getLog("destroy"))
wakeLock?.release()
wakeLock = null
sendEvent(InternalEvent.Destroy)
try {
runBlocking(coroutineScope.coroutineContext) { withTimeout(1000) { httpServer.destroy().await() } }
} catch (cause: Throwable) {
XLog.e(getLog("destroy", cause.toString()))
}
broadcastHelper.stopListening()
connectivityHelper.stopListening()
coroutineScope.cancel()
mediaProjectionIntent = null
}
private fun onError(appError: AppError) {
XLog.e(getLog("onError", "AppError: $appError"))
wakeLock?.release()
wakeLock = null
sendEvent(InternalEvent.ComponentError(appError))
}
private fun stopProjection(streamState: StreamState): StreamState {
XLog.d(getLog("stopProjection"))
if (streamState.isStreaming()) {
streamState.bitmapCapture?.destroy()
streamState.mediaProjection?.unregisterCallback(projectionCallback)
streamState.mediaProjection?.stop()
}
wakeLock?.release()
wakeLock = null
return streamState.copy(mediaProjection = null, bitmapCapture = null)
}
private suspend fun discoverAddress(streamState: StreamState): StreamState {
XLog.d(getLog("discoverAddress"))
val netInterfaces = networkHelper.getNetInterfaces(
mjpegSettings.useWiFiOnlyFlow.first(), mjpegSettings.enableIPv6Flow.first(),
mjpegSettings.enableLocalHostFlow.first(), mjpegSettings.localHostOnlyFlow.first()
)
if (netInterfaces.isEmpty())
return if (streamState.httpServerAddressAttempt < 3) {
sendEvent(InternalEvent.DiscoverAddress, 1000)
streamState.copy(httpServerAddressAttempt = streamState.httpServerAddressAttempt + 1)
} else {
XLog.w(getLog("discoverAddress", "No address found"))
streamState.copy(
state = StreamState.State.ERROR,
netInterfaces = emptyList(),
httpServerAddressAttempt = 0,
appError = AddressNotFoundException
)
}
sendEvent(InternalEvent.StartServer)
return streamState.copy(
state = StreamState.State.ADDRESS_DISCOVERED,
netInterfaces = netInterfaces,
httpServerAddressAttempt = 0
)
}
private suspend fun startServer(streamState: StreamState): StreamState {
XLog.d(getLog("startServer"))
require(streamState.netInterfaces.isNotEmpty())
withTimeoutOrNull(300) { httpServer.stop().await() }
httpServer.start(streamState.netInterfaces)
bitmapStateFlow.tryEmit(notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.START))
return streamState.copy(state = StreamState.State.SERVER_STARTED)
}
private fun startStream(streamState: StreamState): StreamState {
XLog.d(getLog("startStream"))
return if (mediaProjectionIntent != null) {
sendEvent(AppStateMachine.Event.StartProjection(mediaProjectionIntent!!))
streamState
} else {
streamState.copy(state = StreamState.State.PERMISSION_PENDING)
}
}
private fun castPermissionsDenied(streamState: StreamState): StreamState {
XLog.d(getLog("castPermissionsDenied"))
return streamState.copy(state = StreamState.State.SERVER_STARTED)
}
private suspend fun startProjection(streamState: StreamState, intent: Intent): StreamState {
XLog.d(getLog("startProjection", "Intent: $intent"))
try {
val mediaProjection = withContext(Dispatchers.Main) {
delay(500)
projectionManager.getMediaProjection(Activity.RESULT_OK, intent).apply {
registerCallback(projectionCallback, Handler(Looper.getMainLooper()))
}
}
mediaProjectionIntent = intent
val bitmapCapture = BitmapCapture(serviceContext, mjpegSettings, mediaProjection, bitmapStateFlow, ::onError)
bitmapCapture.start()
if (appSettings.keepAwakeFlow.first()) {
@Suppress("DEPRECATION")
@SuppressLint("WakelockTimeout")
wakeLock = powerManager.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "ScreenStream::StreamingTag"
).apply { acquire() }
}
return streamState.copy(
state = StreamState.State.STREAMING,
mediaProjection = mediaProjection,
bitmapCapture = bitmapCapture
)
} catch (cause: Throwable) {
XLog.e(getLog("startProjection"), cause)
}
mediaProjectionIntent = null
return streamState.copy(state = StreamState.State.ERROR, appError = CastSecurityException)
}
private suspend fun stopStream(streamState: StreamState): StreamState {
XLog.d(getLog("stopStream"))
val state = stopProjection(streamState)
if (mjpegSettings.enablePinFlow.first() && mjpegSettings.autoChangePinFlow.first()) {
mjpegSettings.setPin(randomPin())
} else {
bitmapStateFlow.tryEmit(notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.START))
}
return state.copy(state = StreamState.State.SERVER_STARTED)
}
private suspend fun screenOff(streamState: StreamState): StreamState {
XLog.d(getLog("screenOff"))
return if (appSettings.stopOnSleepFlow.first() && streamState.isStreaming()) stopStream(streamState)
else streamState
}
private fun destroy(streamState: StreamState): StreamState {
XLog.d(getLog("destroy"))
return stopProjection(streamState).copy(state = StreamState.State.DESTROYED)
}
private suspend fun startStopFromWebPage(streamState: StreamState): StreamState {
XLog.d(getLog("startStopFromWebPage"))
if (streamState.isStreaming()) return stopStream(streamState)
if (streamState.state == StreamState.State.SERVER_STARTED)
return streamState.copy(state = StreamState.State.PERMISSION_PENDING)
return streamState
}
private suspend fun restartServer(streamState: StreamState, reason: RestartReason): StreamState {
XLog.d(getLog("restartServer"))
val state = stopProjection(streamState)
when (reason) {
is RestartReason.ConnectionChanged ->
effectSharedFlow.emit(AppStateMachine.Effect.ConnectionChanged)
is RestartReason.SettingsChanged ->
bitmapStateFlow.emit(notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.RELOAD_PAGE))
is RestartReason.NetworkSettingsChanged ->
bitmapStateFlow.emit(notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.NEW_ADDRESS))
}
withTimeoutOrNull(300) { httpServer.stop().await() }
if (state.state == StreamState.State.ERROR)
sendEvent(AppStateMachine.Event.RecoverError)
else
sendEvent(InternalEvent.DiscoverAddress, 1000)
return state.copy(
state = StreamState.State.RESTART_PENDING,
netInterfaces = emptyList(),
httpServerAddressAttempt = 0
)
}
private fun componentError(streamState: StreamState, appError: AppError, report: Boolean): StreamState {
XLog.d(getLog("componentError"))
if (report) XLog.e(getLog("componentError"), appError)
return stopProjection(streamState).copy(state = StreamState.State.ERROR, appError = appError)
}
private fun recoverError(streamState: StreamState): StreamState {
XLog.d(getLog("recoverError"))
sendEvent(InternalEvent.DiscoverAddress)
return streamState.copy(state = StreamState.State.RESTART_PENDING, appError = null)
}
private suspend fun requestPublicState(streamState: StreamState): StreamState {
XLog.d(getLog("requestPublicState"))
effectSharedFlow.emit(streamState.toPublicState())
return streamState
}
private fun <T> Flow<T>.listenForChange(scope: CoroutineScope, action: suspend (T) -> Unit) =
distinctUntilChanged().drop(1).onEach { action(it) }.launchIn(scope)
} | mit | 1ef12dc595da3c2091d401153020740c | 44.227176 | 137 | 0.67072 | 5.197901 | false | false | false | false |
jwren/intellij-community | python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.kt | 1 | 9333 | // 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.jetbrains.python.console
import com.intellij.application.options.RegistryManager
import com.intellij.codeInsight.hint.HintManager
import com.intellij.execution.console.LanguageConsoleImpl
import com.intellij.execution.console.LanguageConsoleView
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.console.actions.CommandQueueForPythonConsoleService
import com.jetbrains.python.console.pydev.ConsoleCommunication
import com.jetbrains.python.console.pydev.ConsoleCommunicationListener
import com.jetbrains.python.psi.PyElementGenerator
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyStatementList
import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher
import java.awt.Font
open class PydevConsoleExecuteActionHandler(private val myConsoleView: LanguageConsoleView,
processHandler: ProcessHandler,
final override val consoleCommunication: ConsoleCommunication) : PythonConsoleExecuteActionHandler(processHandler, false), ConsoleCommunicationListener {
private val project = myConsoleView.project
private val myEnterHandler = PyConsoleEnterHandler()
private var myIpythonInputPromptCount = 2
fun decreaseInputPromptCount(value : Int) {
myIpythonInputPromptCount -= value
}
override var isEnabled: Boolean = false
set(value) {
field = value
updateConsoleState()
}
init {
this.consoleCommunication.addCommunicationListener(this)
}
override fun processLine(line: String) {
executeMultiLine(line)
}
private fun executeMultiLine(text: String) {
val commandText = if (!text.endsWith("\n")) {
text + "\n"
}
else {
text
}
sendLineToConsole(ConsoleCommunication.ConsoleCodeFragment(commandText, checkSingleLine(text)))
}
override fun checkSingleLine(text: String): Boolean {
val languageLevel = PythonLanguageLevelPusher.getLanguageLevelForVirtualFile(project, myConsoleView.virtualFile)
val pyFile = PyElementGenerator.getInstance(project).createDummyFile(languageLevel, text) as PyFile
return PsiTreeUtil.findChildOfAnyType(pyFile, PyStatementList::class.java) == null && pyFile.statements.size < 2
}
private fun sendLineToConsole(code: ConsoleCommunication.ConsoleCodeFragment) {
val consoleComm = consoleCommunication
if (!consoleComm.isWaitingForInput) {
executingPrompt()
}
if (ipythonEnabled && !consoleComm.isWaitingForInput && !code.getText().isBlank()) {
++myIpythonInputPromptCount
}
if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) {
// add new command to CommandQueue service
service<CommandQueueForPythonConsoleService>().addNewCommand(this, code)
} else {
consoleComm.execInterpreter(code) {}
}
}
override fun updateConsoleState() {
if (!isEnabled) {
executingPrompt()
}
else if (consoleCommunication.isWaitingForInput) {
waitingForInputPrompt()
}
else if (canExecuteNow()) {
if (consoleCommunication.needsMore()) {
more()
}
else {
inPrompt()
}
}
else {
if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) {
inPrompt()
} else {
executingPrompt()
}
}
}
private fun inPrompt() {
if (ipythonEnabled) {
ipythonInPrompt()
}
else {
ordinaryPrompt()
}
}
private fun ordinaryPrompt() {
if (PyConsoleUtil.ORDINARY_PROMPT != myConsoleView.prompt) {
myConsoleView.prompt = PyConsoleUtil.ORDINARY_PROMPT
myConsoleView.indentPrompt = PyConsoleUtil.INDENT_PROMPT
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
private val ipythonEnabled: Boolean
get() = PyConsoleUtil.getOrCreateIPythonData(myConsoleView.virtualFile).isIPythonEnabled
private fun ipythonInPrompt() {
myConsoleView.setPromptAttributes(object : ConsoleViewContentType("", TextAttributes()) {
override fun getAttributes(): TextAttributes {
val attrs = EditorColorsManager.getInstance().globalScheme.getAttributes(USER_INPUT_KEY);
attrs.fontType = Font.PLAIN
return attrs
}
})
val prompt = "In [$myIpythonInputPromptCount]:"
val indentPrompt = PyConsoleUtil.IPYTHON_INDENT_PROMPT.padStart(prompt.length)
myConsoleView.prompt = prompt
myConsoleView.indentPrompt = indentPrompt
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
private fun executingPrompt() {
myConsoleView.prompt = PyConsoleUtil.EXECUTING_PROMPT
myConsoleView.indentPrompt = PyConsoleUtil.EXECUTING_PROMPT
}
private fun waitingForInputPrompt() {
if (PyConsoleUtil.INPUT_PROMPT != myConsoleView.prompt && PyConsoleUtil.HELP_PROMPT != myConsoleView.prompt) {
myConsoleView.prompt = PyConsoleUtil.INPUT_PROMPT
myConsoleView.indentPrompt = PyConsoleUtil.INPUT_PROMPT
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
private fun more() {
val prompt = if (ipythonEnabled) {
PyConsoleUtil.IPYTHON_INDENT_PROMPT
}
else {
PyConsoleUtil.INDENT_PROMPT
}
if (prompt != myConsoleView.prompt) {
myConsoleView.prompt = prompt
myConsoleView.indentPrompt = prompt
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
override fun commandExecuted(more: Boolean): Unit = updateConsoleState()
override fun inputRequested() {
isEnabled = true
}
override val cantExecuteMessage: String
get() {
if (!isEnabled) {
return consoleIsNotEnabledMessage
}
else if (!canExecuteNow()) {
return prevCommandRunningMessage
}
else {
return "Can't execute the command"
}
}
override fun runExecuteAction(console: LanguageConsoleView) {
if (isEnabled) {
if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) {
doRunExecuteAction(console)
} else {
if (!canExecuteNow()) {
HintManager.getInstance().showErrorHint(console.consoleEditor, prevCommandRunningMessage)
}
else {
doRunExecuteAction(console)
}
}
}
else {
HintManager.getInstance().showErrorHint(console.consoleEditor, consoleIsNotEnabledMessage)
}
}
private fun doRunExecuteAction(console: LanguageConsoleView) {
val doc = myConsoleView.editorDocument
val endMarker = doc.createRangeMarker(doc.textLength, doc.textLength)
endMarker.isGreedyToLeft = false
endMarker.isGreedyToRight = true
val isComplete = myEnterHandler.handleEnterPressed(console.consoleEditor)
if (isComplete || consoleCommunication.isWaitingForInput) {
deleteString(doc, endMarker)
if (shouldCopyToHistory(console)) {
(console as? PythonConsoleView)?.let { pythonConsole ->
pythonConsole.flushDeferredText()
pythonConsole.storeExecutionCounterLineNumber(myIpythonInputPromptCount,
pythonConsole.historyViewer.document.lineCount +
console.consoleEditor.document.lineCount)
}
copyToHistoryAndExecute(console)
}
else {
processLine(myConsoleView.consoleEditor.document.text)
}
}
}
private fun copyToHistoryAndExecute(console: LanguageConsoleView) = super.runExecuteAction(console)
override fun canExecuteNow(): Boolean = !consoleCommunication.isExecuting || consoleCommunication.isWaitingForInput
protected open val consoleIsNotEnabledMessage: String
get() = notEnabledMessage
companion object {
val prevCommandRunningMessage: String
get() = "Previous command is still running. Please wait or press Ctrl+C in console to interrupt."
val notEnabledMessage: String
get() = "Console is not enabled."
private fun shouldCopyToHistory(console: LanguageConsoleView): Boolean {
return !PyConsoleUtil.isPagingPrompt(console.prompt)
}
fun deleteString(document: Document, endMarker : RangeMarker) {
if (endMarker.endOffset - endMarker.startOffset > 0) {
ApplicationManager.getApplication().runWriteAction {
CommandProcessor.getInstance().runUndoTransparentAction {
document.deleteString(endMarker.startOffset, endMarker.endOffset)
}
}
}
}
}
}
private var LanguageConsoleView.indentPrompt: String
get() {
return (this as? LanguageConsoleImpl)?.consolePromptDecorator?.indentPrompt ?: ""
}
set(value) {
(this as? LanguageConsoleImpl)?.consolePromptDecorator?.indentPrompt = value
}
| apache-2.0 | 840943173d2547c57835c973e6f57713 | 33.439114 | 197 | 0.716276 | 5.025848 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/SpecifyExplicitTypeFixFactories.kt | 1 | 2661 | /*
* Copyright 2010-2021 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.quickfix.fixes
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.KotlinApplicableQuickFix
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactory
import org.jetbrains.kotlin.idea.codeinsights.impl.base.CallableReturnTypeUpdaterUtils.TypeInfo
import org.jetbrains.kotlin.idea.codeinsights.impl.base.CallableReturnTypeUpdaterUtils.getTypeInfo
import org.jetbrains.kotlin.idea.codeinsights.impl.base.CallableReturnTypeUpdaterUtils.updateType
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
object SpecifyExplicitTypeFixFactories {
val ambiguousAnonymousTypeInferred =
diagnosticFixFactory(KtFirDiagnostic.AmbiguousAnonymousTypeInferred::class) { createQuickFix(it.psi) }
val noExplicitReturnTypeInApiMode =
diagnosticFixFactory(KtFirDiagnostic.NoExplicitReturnTypeInApiMode::class) { createQuickFix(it.psi) }
val noExplicitReturnTypeInApiModeWarning =
diagnosticFixFactory(KtFirDiagnostic.NoExplicitReturnTypeInApiModeWarning::class) { createQuickFix(it.psi) }
context(KtAnalysisSession)
private fun createQuickFix(declaration: KtDeclaration) =
if (declaration is KtCallableDeclaration) listOf(SpecifyExplicitTypeQuickFix(declaration, getTypeInfo(declaration)))
else emptyList()
private class SpecifyExplicitTypeQuickFix(
target: KtCallableDeclaration,
private val typeInfo: TypeInfo,
) : KotlinApplicableQuickFix<KtCallableDeclaration>(target) {
override fun getFamilyName(): String = KotlinBundle.message("specify.type.explicitly")
override fun getActionName(element: KtCallableDeclaration): String = when (element) {
is KtFunction -> KotlinBundle.message("specify.return.type.explicitly")
else -> KotlinBundle.message("specify.type.explicitly")
}
override fun apply(element: KtCallableDeclaration, project: Project, editor: Editor?, file: KtFile) =
updateType(element, typeInfo, project, editor)
}
} | apache-2.0 | 44818dc6313377dec44b0d076538fb02 | 51.196078 | 124 | 0.796693 | 4.927778 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/collections/KotlinCollectionChainBuilder.kt | 6 | 3383 | // 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.collections
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.impl.KotlinChainBuilderBase
import org.jetbrains.kotlin.idea.debugger.sequence.psi.previousCall
import org.jetbrains.kotlin.idea.core.receiverType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
class KotlinCollectionChainBuilder
: KotlinChainBuilderBase(CollectionChainTransformer()) {
private companion object {
// TODO: Avoid enumeration of all available types
val SUPPORTED_RECEIVERS = setOf(
"kotlin.collections.Iterable", "kotlin.CharSequence", "kotlin.Array",
"kotlin.BooleanArray", "kotlin.ByteArray", "kotlin.ShortArray", "kotlin.CharArray", "kotlin.IntArray",
"kotlin.LongArray", "kotlin.DoubleArray", "kotlin.FloatArray"
)
}
private fun isCollectionTransformationCall(expression: KtCallExpression): Boolean {
val receiverType = expression.receiverType() ?: return false
if (isTypeSuitable(receiverType)) return true
return receiverType.supertypes().any { isTypeSuitable(it) }
}
override val existenceChecker: ExistenceChecker = object : ExistenceChecker() {
override fun visitCallExpression(expression: KtCallExpression) {
if (isFound()) return
if (isCollectionTransformationCall(expression)) {
fireElementFound()
} else {
super.visitCallExpression(expression)
}
}
}
override fun createChainsBuilder(): ChainBuilder = object : ChainBuilder() {
private val previousCalls: MutableMap<KtCallExpression, KtCallExpression> = mutableMapOf()
private val visitedCalls: MutableSet<KtCallExpression> = mutableSetOf()
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
if (isCollectionTransformationCall(expression)) {
visitedCalls.add(expression)
val previous = expression.previousCall()
if (previous != null && isCollectionTransformationCall(previous)) {
previousCalls[expression] = previous
}
}
}
override fun chains(): List<List<KtCallExpression>> {
val notLastCalls: Set<KtCallExpression> = previousCalls.values.toSet()
return visitedCalls.filter { it !in notLastCalls }.map { buildPsiChain(it) }
}
private fun buildPsiChain(expression: KtCallExpression): List<KtCallExpression> {
val result = mutableListOf<KtCallExpression>()
var current: KtCallExpression? = expression
while (current != null) {
result.add(current)
current = previousCalls[current]
}
result.reverse()
return result
}
}
private fun isTypeSuitable(type: KotlinType): Boolean =
SUPPORTED_RECEIVERS.contains(KotlinPsiUtil.getTypeWithoutTypeParameters(type))
} | apache-2.0 | 246ea451afe10e985d52fd9c97d587b3 | 43.526316 | 158 | 0.680757 | 5.172783 | false | false | false | false |
smmribeiro/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/testUtils.kt | 2 | 6681 | // 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.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: WorkspaceEntityStorage, virtualFileManager: VirtualFileUrlManager): ByteArray {
storage as WorkspaceEntityStorageImpl
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 WorkspaceEntityStorageBuilderImpl).toStorage()
deserialized.assertConsistency()
assertStorageEquals(storage, deserialized)
storage.assertConsistency()
return byteArray
}
private fun assertStorageEquals(expected: WorkspaceEntityStorageImpl, actual: WorkspaceEntityStorageImpl) {
// 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 | 0ca3617e59551bd2cc0a03b813799dbf | 41.826923 | 155 | 0.721449 | 4.598073 | false | false | false | false |
jrg94/PopLibrary | mobile/app/src/main/java/com/therenegadecoder/poplibrary/frontend/BookActivity.kt | 1 | 1403 | package com.therenegadecoder.poplibrary.frontend
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.therenegadecoder.poplibrary.R
class BookActivity : AppCompatActivity() {
private lateinit var titleView: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.book_add_form)
titleView = findViewById(R.id.book_title_input_form)
val submitButton = findViewById<Button>(R.id.book_submit_button)
submitButton.setOnClickListener {
val replyIntent = Intent()
if (TextUtils.isEmpty(titleView.text)) {
setResult(Activity.RESULT_CANCELED, replyIntent)
} else {
val title = titleView.text.toString()
replyIntent.putExtra(EXTRA_REPLY, title)
setResult(Activity.RESULT_OK, replyIntent)
}
finish()
}
}
fun loadMainActivity(view: View) {
val intent: Intent = Intent(this, MainActivity::class.java)
this.startActivity(intent)
}
companion object {
const val EXTRA_REPLY = "com.example.android.wordlistsql.REPLY"
}
} | gpl-3.0 | 6005d6514a95fc7760986c8a800412e6 | 30.909091 | 72 | 0.681397 | 4.482428 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/db/PreRoomMigration.kt | 1 | 28001 | package com.orgzly.android.db
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.text.TextUtils
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQueryBuilder
import com.orgzly.android.App
import com.orgzly.android.db.mappers.OrgTimestampMapper
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.util.MiscUtils
import com.orgzly.org.datetime.OrgDateTime
import com.orgzly.org.parser.OrgNestedSetParser
import java.util.*
import java.util.regex.Pattern
object PreRoomMigration {
val MIGRATION_130_131 = object : Migration(130, 131) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE books ADD COLUMN title") // TITLE
}
}
val MIGRATION_131_132 = object : Migration(131, 132) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE books ADD COLUMN is_indented INTEGER DEFAULT 0") // IS_INDENTED
db.execSQL("ALTER TABLE books ADD COLUMN used_encoding TEXT") // USED_ENCODING
db.execSQL("ALTER TABLE books ADD COLUMN detected_encoding TEXT") // DETECTED_ENCODING
db.execSQL("ALTER TABLE books ADD COLUMN selected_encoding TEXT") // SELECTED_ENCODING
}
}
val MIGRATION_132_133 = object : Migration(132, 133) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_133_134 = object : Migration(133, 134) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE notes ADD COLUMN parent_id") // PARENT_ID
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_is_visible ON notes(is_visible)") // LFT
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_parent_position ON notes(parent_position)") // RGT
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_is_collapsed ON notes(is_collapsed)") // IS_FOLDED
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_is_under_collapsed ON notes(is_under_collapsed)") // FOLDED_UNDER_ID
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_parent_id ON notes(parent_id)") // PARENT_ID
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_has_children ON notes(has_children)") // DESCENDANTS_COUNT
convertNotebooksFromPositionToNestedSet(db)
}
}
private fun convertNotebooksFromPositionToNestedSet(db: SupportSQLiteDatabase) {
val query = SupportSQLiteQueryBuilder
.builder("books")
.columns(arrayOf("_id"))
.create()
eachForQuery(db, query) { cursor ->
val bookId = cursor.getLong(0)
convertNotebookFromPositionToNestedSet(db, bookId)
updateParentIds(db, bookId)
}
}
private fun convertNotebookFromPositionToNestedSet(db: SupportSQLiteDatabase, bookId: Long) {
/* Insert root note. */
val rootNoteValues = ContentValues()
rootNoteValues.put("level", 0)
rootNoteValues.put("book_id", bookId)
rootNoteValues.put("position", 0)
db.insert("notes", SQLiteDatabase.CONFLICT_ROLLBACK, rootNoteValues)
updateNotesPositionsFromLevel(db, bookId)
}
private fun updateNotesPositionsFromLevel(db: SupportSQLiteDatabase, bookId: Long) {
val stack = Stack<NotePosition>()
var prevLevel = -1
var sequence = OrgNestedSetParser.STARTING_VALUE - 1
val query = SupportSQLiteQueryBuilder
.builder("notes")
.selection("book_id = $bookId", null)
.orderBy("position")
.create()
eachForQuery(db, query) { cursor ->
val note = noteFromCursor(cursor)
if (prevLevel < note.level) {
/*
* This is a descendant of previous thisNode.
*/
/* Put the current thisNode on the stack. */
sequence += 1
note.lft = sequence
stack.push(note)
} else if (prevLevel == note.level) {
/*
* This is a sibling, which means that the last thisNode visited can be completed.
* Take it off the stack, update its rgt value and announce it.
*/
val nodeFromStack = stack.pop()
sequence += 1
nodeFromStack.rgt = sequence
calculateAndSetDescendantsCount(nodeFromStack)
updateNotePositionValues(db, nodeFromStack)
/* Put the current thisNode on the stack. */
sequence += 1
note.lft = sequence
stack.push(note)
} else {
/*
* Note has lower level then the previous one - we're out of the set.
* Start popping the stack, up to and including the thisNode with the same level.
*/
while (!stack.empty()) {
val nodeFromStack = stack.peek()
if (nodeFromStack.level >= note.level) {
stack.pop()
sequence += 1
nodeFromStack.rgt = sequence
calculateAndSetDescendantsCount(nodeFromStack)
updateNotePositionValues(db, nodeFromStack)
} else {
break
}
}
/* Put the current thisNode on the stack. */
sequence += 1
note.lft = sequence
stack.push(note)
}
prevLevel = note.level
}
/* Pop remaining nodes. */
while (!stack.empty()) {
val nodeFromStack = stack.pop()
sequence += 1
nodeFromStack.rgt = sequence
calculateAndSetDescendantsCount(nodeFromStack)
updateNotePositionValues(db, nodeFromStack)
}
}
private fun updateNotePositionValues(db: SupportSQLiteDatabase, note: NotePosition): Int {
val values = contentValuesFromNote(note)
return db.update("notes", SQLiteDatabase.CONFLICT_ROLLBACK, values, "_id = ${note.id}", null)
}
private fun calculateAndSetDescendantsCount(node: NotePosition) {
node.descendantsCount = (node.rgt - node.lft - 1).toInt() / (2 * 1)
}
private fun updateParentIds(db: SupportSQLiteDatabase, bookId: Long) {
val parentId = "(SELECT _id FROM notes AS n WHERE " +
"book_id = " + bookId + " AND " +
"n.is_visible < notes.is_visible AND " +
"notes.parent_position < n.parent_position ORDER BY n.is_visible DESC LIMIT 1)"
db.execSQL("UPDATE notes SET parent_id = " + parentId +
" WHERE book_id = " + bookId + " AND is_cut = 0 AND level > 0")
}
private fun noteFromCursor(cursor: Cursor): NotePosition {
val position = NotePosition()
position.id = cursor.getLong(cursor.getColumnIndex("_id"))
position.bookId = cursor.getLong(cursor.getColumnIndex("book_id"))
position.level = cursor.getInt(cursor.getColumnIndex("level"))
position.lft = cursor.getLong(cursor.getColumnIndex("is_visible"))
position.rgt = cursor.getLong(cursor.getColumnIndex("parent_position"))
position.descendantsCount = cursor.getInt(cursor.getColumnIndex("has_children"))
position.foldedUnderId = cursor.getLong(cursor.getColumnIndex("is_under_collapsed"))
position.parentId = cursor.getLong(cursor.getColumnIndex("parent_id"))
position.isFolded = cursor.getInt(cursor.getColumnIndex("is_collapsed")) != 0
return position
}
private fun contentValuesFromNote(position: NotePosition): ContentValues {
val values = ContentValues()
// values.put("_id", position.id)
values.put("book_id", position.bookId)
values.put("level", position.level)
values.put("is_visible", position.lft)
values.put("parent_position", position.rgt)
values.put("has_children", position.descendantsCount)
values.put("is_under_collapsed", position.foldedUnderId)
values.put("parent_id", position.parentId)
values.put("is_collapsed", if (position.isFolded) 1 else 0)
values.put("position", 0)
return values
}
private class NotePosition {
var id: Long = 0
var bookId: Long = 0
var lft: Long = 0
var rgt: Long = 0
var level: Int = 0
var descendantsCount: Int = 0
var foldedUnderId: Long = 0
var parentId: Long = 0
var isFolded: Boolean = false
}
val MIGRATION_134_135 = object : Migration(134, 135) {
override fun migrate(db: SupportSQLiteDatabase) {
fixOrgRanges(db)
}
}
/**
* 1.4-beta.1 misused insertWithOnConflict due to
* https://code.google.com/p/android/issues/detail?id=13045.
*
* org_ranges ended up with duplicates having -1 for
* start_timestamp_id and end_timestamp_id.
*
* Delete those, update notes tables and add a unique constraint to the org_ranges.
*/
private fun fixOrgRanges(db: SupportSQLiteDatabase) {
val notesFields = arrayOf("scheduled_range_id", "deadline_range_id", "closed_range_id", "clock_range_id")
val query = SupportSQLiteQueryBuilder
.builder("org_ranges")
.columns(arrayOf("_id", "string"))
.selection("start_timestamp_id = -1 OR end_timestamp_id = -1", null)
.create()
eachForQuery(db, query) { cursor ->
val id = cursor.getLong(0)
val string = cursor.getString(1)
val validTimestampId = "(start_timestamp_id IS NULL OR start_timestamp_id != -1) AND (end_timestamp_id IS NULL OR end_timestamp_id != -1)"
val validEntry = "(SELECT _id FROM org_ranges WHERE string = " + android.database.DatabaseUtils.sqlEscapeString(string) + " and " + validTimestampId + ")"
for (field in notesFields) {
db.execSQL("UPDATE notes SET $field = $validEntry WHERE $field = $id")
}
}
db.execSQL("DELETE FROM org_ranges WHERE start_timestamp_id = -1 OR end_timestamp_id = -1")
db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS i_org_ranges_string ON org_ranges(string)")
}
/* Properties moved from content. */
val MIGRATION_135_136 = object : Migration(135, 136) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE IF NOT EXISTS note_properties (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"note_id INTEGER," +
"position INTEGER," +
"property_id INTEGER," +
"UNIQUE(note_id, position, property_id))")
db.execSQL("CREATE TABLE IF NOT EXISTS property_names (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT UNIQUE)")
db.execSQL("CREATE TABLE IF NOT EXISTS property_values (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"value TEXT UNIQUE)")
db.execSQL("CREATE TABLE IF NOT EXISTS properties (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name_id INTEGER," +
"value_id INTEGER," +
"UNIQUE(name_id, value_id))")
movePropertiesFromBody(db)
}
}
private fun movePropertiesFromBody(db: SupportSQLiteDatabase) {
val query = SupportSQLiteQueryBuilder
.builder("notes")
.columns(arrayOf("_id", "content"))
.create()
val contentUpdates = hashMapOf<Long, ContentValues>()
eachForQuery(db, query) { cursor ->
val noteId = cursor.getLong(0)
val content = cursor.getString(1)
if (!TextUtils.isEmpty(content)) {
val newContent = StringBuilder()
val properties = getPropertiesFromContent(content, newContent)
if (properties.isNotEmpty()) {
var pos = 1
for (property in properties) {
val nameId = getOrInsert(
db, "property_names", arrayOf("name"), arrayOf(property[0]))
val valueId = getOrInsert(
db, "property_values", arrayOf("value"), arrayOf(property[1]))
val propertyId = getOrInsert(
db,
"properties",
arrayOf("name_id", "value_id"),
arrayOf(nameId.toString(), valueId.toString()))
getOrInsert(
db,
"note_properties",
arrayOf("note_id", "position", "property_id"),
arrayOf(noteId.toString(), pos++.toString(), propertyId.toString()))
}
// New content and its line count
contentUpdates[noteId] = ContentValues().apply {
put("content", newContent.toString())
put("content_line_count", MiscUtils.lineCount(newContent.toString()))
}
}
}
}
// This was causing issues (skipped notes) when done inside eachForQuery loop
for ((id, values) in contentUpdates) {
db.update("notes", SQLiteDatabase.CONFLICT_ROLLBACK, values, "_id = $id", null)
}
}
private fun getOrInsert(
db: SupportSQLiteDatabase,
table: String,
fieldNames: Array<String>,
fieldValues: Array<String>): Long {
val selection = fieldNames.joinToString(" AND ") { "$it = ?" }
val query = SupportSQLiteQueryBuilder
.builder(table)
.columns(arrayOf("_id"))
.selection(selection, fieldValues)
.create()
val id = db.query(query).use { cursor ->
if (cursor != null && cursor.moveToFirst()) {
cursor.getLong(0)
} else {
0
}
}
return if (id > 0) {
id
} else {
val values = ContentValues()
fieldNames.forEachIndexed { index, field ->
values.put(field, fieldValues[index])
}
db.insert(table, SQLiteDatabase.CONFLICT_ROLLBACK, values)
}
}
private fun getPropertiesFromContent(content: String, newContent: StringBuilder): List<Array<String>> {
val properties = ArrayList<Array<String>>()
val propertiesPattern = Pattern.compile("^\\s*:PROPERTIES:(.*?):END: *\n*(.*)", Pattern.DOTALL)
val propertyPattern = Pattern.compile("^:([^:\\s]+):\\s+(.*)\\s*$")
val m = propertiesPattern.matcher(content)
if (m.find()) {
val propertyLines = m.group(1)?.split("\n") ?: emptyList()
for (propertyLine in propertyLines) {
val pm = propertyPattern.matcher(propertyLine.trim())
if (pm.find()) {
val name = pm.group(1)
val value = pm.group(2)
// Add name-value pair
if (name != null && value != null) {
properties.add(arrayOf(name, value))
}
}
}
newContent.append(m.group(2))
}
return properties
}
val MIGRATION_136_137 = object : Migration(136, 137) {
override fun migrate(db: SupportSQLiteDatabase) {
encodeRookUris(db)
}
}
/**
* file:/dir/file name.org
* file:/dir/file%20name.org
*/
private fun encodeRookUris(db: SupportSQLiteDatabase) {
val query = SupportSQLiteQueryBuilder
.builder("rook_urls")
.columns(arrayOf("_id", "rook_url"))
.create()
eachForQuery(db, query) { cursor ->
val id = cursor.getLong(0)
val uri = cursor.getString(1)
val encodedUri = MiscUtils.encodeUri(uri)
if (uri != encodedUri) {
encodeRookUri(db, id, encodedUri)
}
}
}
/* Update unless same URL already exists. */
private fun encodeRookUri(db: SupportSQLiteDatabase, id: Long, encodedUri: String?) {
val query = SupportSQLiteQueryBuilder
.builder("rook_urls")
.columns(arrayOf("_id"))
.selection("rook_url = ?", arrayOf(encodedUri))
.create()
if (!db.query(query).moveToFirst()) {
val values = ContentValues()
values.put("rook_url", encodedUri)
db.update("rook_urls", SQLiteDatabase.CONFLICT_ROLLBACK, values, "_id = $id", null)
}
}
val MIGRATION_137_138 = object : Migration(137, 138) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("""
CREATE TABLE IF NOT EXISTS note_ancestors (
book_id INTEGER,
note_id INTEGER,
ancestor_note_id INTEGER)""".trimIndent())
db.execSQL("CREATE INDEX IF NOT EXISTS i_note_ancestors_" + "book_id" + " ON note_ancestors(" + "book_id" + ")")
db.execSQL("CREATE INDEX IF NOT EXISTS i_note_ancestors_" + "note_id" + " ON note_ancestors(" + "note_id" + ")")
db.execSQL("CREATE INDEX IF NOT EXISTS i_note_ancestors_" + "ancestor_note_id" + " ON note_ancestors(" + "ancestor_note_id" + ")")
db.execSQL("INSERT INTO note_ancestors (book_id, note_id, ancestor_note_id) " +
"SELECT n.book_id, n._id, a._id FROM notes n " +
"JOIN notes a on (n.book_id = a.book_id AND a.is_visible < n.is_visible AND n.parent_position < a.parent_position) " +
"WHERE a.level > 0")
}
}
val MIGRATION_138_139 = object : Migration(138, 139) {
override fun migrate(db: SupportSQLiteDatabase) {
migrateOrgTimestamps(db)
}
}
private fun migrateOrgTimestamps(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE org_timestamps RENAME TO org_timestamps_prev")
db.execSQL("""
CREATE TABLE IF NOT EXISTS org_timestamps (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
string TEXT NOT NULL UNIQUE,
is_active INTEGER NOT NULL,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
day INTEGER NOT NULL,
hour INTEGER,
minute INTEGER,
second INTEGER,
end_hour INTEGER,
end_minute INTEGER,
end_second INTEGER,
repeater_type INTEGER,
repeater_value INTEGER,
repeater_unit INTEGER,
habit_deadline_value INTEGER,
habit_deadline_unit INTEGER,
delay_type INTEGER,
delay_value INTEGER,
delay_unit INTEGER,
timestamp INTEGER,
end_timestamp INTEGER)""".trimIndent())
db.execSQL("CREATE INDEX IF NOT EXISTS i_org_timestamps_string ON org_timestamps(string)")
db.execSQL("CREATE INDEX IF NOT EXISTS i_org_timestamps_timestamp ON org_timestamps(timestamp)")
db.execSQL("CREATE INDEX IF NOT EXISTS i_org_timestamps_end_timestamp ON org_timestamps(end_timestamp)")
val query = SupportSQLiteQueryBuilder
.builder("org_timestamps_prev")
.columns(arrayOf("_id", "string"))
.create()
eachForQuery(db, query) { cursor ->
val id = cursor.getLong(0)
val string = cursor.getString(1)
val orgDateTime = OrgDateTime.parse(string)
val values = ContentValues()
values.put("_id", id)
toContentValues(values, orgDateTime)
db.insert("org_timestamps", SQLiteDatabase.CONFLICT_ROLLBACK, values)
}
db.execSQL("DROP TABLE org_timestamps_prev")
}
private fun toContentValues(values: ContentValues, orgDateTime: OrgDateTime) {
values.put("string", orgDateTime.toString())
values.put("is_active", if (orgDateTime.isActive) 1 else 0)
values.put("year", orgDateTime.calendar.get(Calendar.YEAR))
values.put("month", orgDateTime.calendar.get(Calendar.MONTH) + 1)
values.put("day", orgDateTime.calendar.get(Calendar.DAY_OF_MONTH))
if (orgDateTime.hasTime()) {
values.put("hour", orgDateTime.calendar.get(Calendar.HOUR_OF_DAY))
values.put("minute", orgDateTime.calendar.get(Calendar.MINUTE))
values.put("second", orgDateTime.calendar.get(Calendar.SECOND))
} else {
values.putNull("hour")
values.putNull("minute")
values.putNull("second")
}
values.put("timestamp", orgDateTime.calendar.timeInMillis)
if (orgDateTime.hasEndTime()) {
values.put("end_hour", orgDateTime.endCalendar.get(Calendar.HOUR_OF_DAY))
values.put("end_minute", orgDateTime.endCalendar.get(Calendar.MINUTE))
values.put("end_second", orgDateTime.endCalendar.get(Calendar.SECOND))
values.put("end_timestamp", orgDateTime.endCalendar.timeInMillis)
} else {
values.putNull("end_hour")
values.putNull("end_minute")
values.putNull("end_second")
values.putNull("end_timestamp")
}
if (orgDateTime.hasRepeater()) {
values.put("repeater_type", OrgTimestampMapper.repeaterType(orgDateTime.repeater.type))
values.put("repeater_value", orgDateTime.repeater.value)
values.put("repeater_unit", OrgTimestampMapper.timeUnit(orgDateTime.repeater.unit))
if (orgDateTime.repeater.hasHabitDeadline()) {
values.put("habit_deadline_value", orgDateTime.repeater.habitDeadline.value)
values.put("habit_deadline_unit", OrgTimestampMapper.timeUnit(orgDateTime.repeater.habitDeadline.unit))
} else {
values.putNull("habit_deadline_value")
values.putNull("habit_deadline_unit")
}
} else {
values.putNull("repeater_type")
values.putNull("repeater_value")
values.putNull("repeater_unit")
values.putNull("habit_deadline_value")
values.putNull("habit_deadline_unit")
}
if (orgDateTime.hasDelay()) {
values.put("delay_type", OrgTimestampMapper.delayType(orgDateTime.delay.type))
values.put("delay_value", orgDateTime.delay.value)
values.put("delay_unit", OrgTimestampMapper.timeUnit(orgDateTime.delay.unit))
} else {
values.putNull("delay_type")
values.putNull("delay_value")
values.putNull("delay_unit")
}
}
val MIGRATION_139_140 = object : Migration(139, 140) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_140_141 = object : Migration(140, 141) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_141_142 = object : Migration(141, 142) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_142_143 = object : Migration(142, 143) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_143_144 = object : Migration(143, 144) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_144_145 = object : Migration(144, 145) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_145_146 = object : Migration(145, 146) {
override fun migrate(db: SupportSQLiteDatabase) {
insertAgendaSavedSearch(db)
}
}
val MIGRATION_146_147 = object : Migration(146, 147) {
override fun migrate(db: SupportSQLiteDatabase) {
addAndSetCreatedAt(db, App.getAppContext())
}
}
val MIGRATION_147_148 = object : Migration(147, 148) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_148_149 = object : Migration(148, 149) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE book_links ADD COLUMN repo_id INTEGER")
db.execSQL("UPDATE book_links SET repo_id = (SELECT repo_id FROM rooks WHERE rooks._id = rook_id)")
}
}
private fun addAndSetCreatedAt(db: SupportSQLiteDatabase, context: Context) {
db.execSQL("ALTER TABLE notes ADD COLUMN created_at INTEGER DEFAULT 0")
if (!AppPreferences.createdAt(context)) {
return
}
val createdAtPropName = AppPreferences.createdAtProperty(context)
val query = SupportSQLiteQueryBuilder
.builder("note_properties"
+ " JOIN notes ON (notes._id = note_properties.note_id)"
+ " JOIN properties ON (properties._id = note_properties.property_id)"
+ " JOIN property_names ON (property_names._id = properties.name_id)"
+ " JOIN property_values ON (property_values._id = properties.value_id)")
.columns(arrayOf("notes._id AS note_id", "property_values.value AS value"))
.selection("note_id IS NOT NULL AND name IS NOT NULL AND value IS NOT NULL AND name = ?", arrayOf(createdAtPropName))
.distinct()
.create()
eachForQuery(db, query) { cursor ->
val noteId = cursor.getLong(0)
val propValue = cursor.getString(1)
val dateTime = OrgDateTime.doParse(propValue)
if (dateTime != null) {
val millis = dateTime.calendar.timeInMillis
val values = ContentValues()
values.put("created_at", millis)
db.update("notes", SQLiteDatabase.CONFLICT_ROLLBACK, values, "_id = $noteId", null)
}
}
}
private fun insertAgendaSavedSearch(db: SupportSQLiteDatabase) {
val values = ContentValues()
values.put("name", "Agenda")
values.put("search", ".it.done ad.7")
values.put("position", -2) // Display first
db.insert("searches", SQLiteDatabase.CONFLICT_ROLLBACK, values)
values.put("name", "Next 3 days")
values.put("search", ".it.done s.ge.today ad.3")
values.put("position", -1) // Display second
db.insert("searches", SQLiteDatabase.CONFLICT_ROLLBACK, values)
}
private fun eachForQuery(db: SupportSQLiteDatabase, query: SupportSQLiteQuery, action: (Cursor) -> Unit) {
db.query(query).use { cursor ->
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
action(cursor)
cursor.moveToNext()
}
}
}
}
} | gpl-3.0 | 0cb9d5b1b114f1a78570815f9475b171 | 37.411523 | 166 | 0.569801 | 4.622916 | false | false | false | false |
kvnxiao/meirei | meirei-jda/src/main/kotlin/com/github/kvnxiao/discord/meirei/jda/MeireiJDA.kt | 1 | 9851 | /*
* Copyright (C) 2017-2018 Ze Hao Xiao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.kvnxiao.discord.meirei.jda
import com.github.kvnxiao.discord.meirei.Meirei
import com.github.kvnxiao.discord.meirei.command.CommandContext
import com.github.kvnxiao.discord.meirei.command.database.CommandRegistry
import com.github.kvnxiao.discord.meirei.command.database.CommandRegistryImpl
import com.github.kvnxiao.discord.meirei.jda.command.CommandJDA
import com.github.kvnxiao.discord.meirei.jda.command.CommandParserJDA
import com.github.kvnxiao.discord.meirei.jda.command.DefaultErrorHandler
import com.github.kvnxiao.discord.meirei.jda.command.ErrorHandler
import com.github.kvnxiao.discord.meirei.jda.permission.PermissionPropertiesJDA
import com.github.kvnxiao.discord.meirei.utility.SplitString.Companion.splitString
import net.dv8tion.jda.core.JDABuilder
import net.dv8tion.jda.core.entities.ChannelType
import net.dv8tion.jda.core.entities.Message
import net.dv8tion.jda.core.events.ReadyEvent
import net.dv8tion.jda.core.events.message.MessageReceivedEvent
import net.dv8tion.jda.core.hooks.EventListener
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Scheduler
import reactor.core.scheduler.Schedulers
import java.util.EnumSet
class MeireiJDA(jdaBuilder: JDABuilder, registry: CommandRegistry) : Meirei(commandParser = CommandParserJDA(), registry = registry) {
private var botOwnerId: Long = 0
private val errorHandler: ErrorHandler = DefaultErrorHandler()
private val scheduler: Scheduler = Schedulers.newParallel("MeireiExec-pool")
constructor(jdaBuilder: JDABuilder) : this(jdaBuilder, CommandRegistryImpl())
init {
// Register message-received event listener
Flux.create<MessageReceivedEvent> {
jdaBuilder.addEventListener(EventListener { event -> if (event is MessageReceivedEvent) it.next(event) })
}.publishOn(scheduler)
.doOnNext { Meirei.LOGGER.debug { "Received message ${it.message.contentRaw} from ${it.author.id} ${if (it.isFromType(ChannelType.PRIVATE)) "in direct message." else "in guild ${it.guild.id}"}" } }
.doOnError { Meirei.LOGGER.error(it) { "An error occurred in processing a MessageReceivedEvent!" } }
.subscribe(this::consumeMessage)
// Register ready-event listener
Mono.create<ReadyEvent> {
jdaBuilder.addEventListener(EventListener { event -> if (event is ReadyEvent) it.success(event) })
}.publishOn(scheduler)
.doOnSuccess(this::setBotOwner)
.doOnError { Meirei.LOGGER.error(it) { "An error occurred in processing the ReadyEvent!" } }
.subscribe()
}
private fun setBotOwner(event: ReadyEvent) {
event.jda.asBot().applicationInfo.queue {
botOwnerId = it.owner.idLong
Meirei.LOGGER.debug { "Bot owner ID found: ${java.lang.Long.toUnsignedString(botOwnerId)}" }
}
}
override fun registerEventListeners(client: Any) {
val dispatcher = (client as JDABuilder)
commandParser.commandEventListeners.values.forEach {
dispatcher.addEventListener(it)
}
}
private fun consumeMessage(event: MessageReceivedEvent) {
val message = event.message
val rawContent = message.contentRaw
val isPrivate = event.isFromType(ChannelType.PRIVATE)
// Split to check for bot mention
val (firstStr, secondStr) = splitString(rawContent)
firstStr.let {
// Check for bot mention
val hasBotMention = hasBotMention(it, message)
// Process for command alias and arguments
val content = if (hasBotMention) secondStr else rawContent
content?.let { process(it, event, isPrivate, hasBotMention) }
}
}
private fun process(input: String, event: MessageReceivedEvent, isDirectMsg: Boolean, hasBotMention: Boolean) {
val (alias, args) = splitString(input)
alias.let {
val command = registry.getCommandByAlias(it) as CommandJDA?
command?.let {
val properties = registry.getPropertiesById(it.id)
val permissions = registry.getPermissionsById(it.id)
if (properties != null && permissions != null) {
// Execute command
val context = CommandContext(alias, args, properties, permissions,
isDirectMsg, hasBotMention, if (it.registryAware) registry else null)
Meirei.LOGGER.debug { "Evaluating input for potential commands: $input" }
execute(it, context, event)
}
}
}
}
private fun execute(command: CommandJDA, context: CommandContext, event: MessageReceivedEvent): Boolean {
if (!context.properties.isDisabled) {
// Check sub-commands
val args = context.args
if (args != null && registry.hasSubCommands(command.id)) {
// Try getting a sub-command from the args
val (subAlias, subArgs) = splitString(args)
val subCommand = registry.getSubCommandByAlias(subAlias, command.id) as CommandJDA?
if (subCommand != null) {
val subProperties = registry.getPropertiesById(subCommand.id)
val subPermissions = registry.getPermissionsById(subCommand.id)
if (subProperties != null && subPermissions != null) {
// Execute sub-command
val subContext = CommandContext(subAlias, subArgs, subProperties, subPermissions,
context.isDirectMessage, context.hasBotMention, if (subCommand.registryAware) registry else null)
// Execute parent-command if the boolean value is true
if (context.properties.execWithSubCommands) command.execute(context, event)
return execute(subCommand, subContext, event)
}
}
}
return executeCommand(command, context, event)
}
return false
}
private fun executeCommand(command: CommandJDA, context: CommandContext, event: MessageReceivedEvent): Boolean {
// Validate mention-only command
if (!validateMentionOnly(context)) return false
// Validate permissions
if (!validatePermissions(context, event)) return false
// Validate rate-limits
if (!validateRateLimits(command, context, event)) return false
// Remove call msg if set to true
if (context.permissions.data.removeCallMsg) {
event.message.delete().reason("Command $command requires its message to be removed upon a successful call.").queue()
}
try {
Meirei.LOGGER.debug { "Executing command $command" }
command.execute(context, event)
} catch (e: Exception) {
Meirei.LOGGER.error(e) { "An error occurred in executing the command $command" }
}
return true
}
private fun hasBotMention(content: String, message: Message): Boolean {
val botMention = message.jda.selfUser.asMention
return content == botMention
}
// Validation
private fun validateRateLimits(command: CommandJDA, context: CommandContext, event: MessageReceivedEvent): Boolean {
val isNotRateLimited = if (event.isFromType(ChannelType.PRIVATE)) {
command.isNotUserLimited(event.author.idLong, context.permissions.data)
} else {
command.isNotRateLimited(event.guild.idLong, event.author.idLong, context.permissions.data)
}
if (!isNotRateLimited) {
errorHandler.onRateLimit(context, event)
return false
}
return true
}
private fun validateMentionOnly(context: CommandContext): Boolean {
return context.permissions.data.requireMention == context.hasBotMention
}
private fun validatePermissions(context: CommandContext, event: MessageReceivedEvent): Boolean {
val permissions = context.permissions as PermissionPropertiesJDA
if (context.isDirectMessage) {
if (!permissions.data.allowDmFromSender)
errorHandler.onDirectMessageInvalid(context, event)
else return permissions.data.allowDmFromSender
}
// Check if command requires to be guild owner
val isGuildOwner = event.guild.owner.user.idLong == event.author.idLong
// Check if command requires to be bot owner
val isBotOwner = botOwnerId == event.author.idLong
// Check for required user permissions in current channel
val requiredPerms = EnumSet.copyOf(permissions.level)
val userPerms = event.member.getPermissions(event.textChannel)
requiredPerms.removeAll(userPerms)
val hasUserPerms = requiredPerms.isEmpty() && (!permissions.data.reqGuildOwner || isGuildOwner) && (!permissions.data.reqBotOwner || isBotOwner)
return if (hasUserPerms) {
true
} else {
errorHandler.onMissingPermissions(context, event, requiredPerms)
false
}
}
}
| apache-2.0 | 3620f447f2f8852e41e167473c469172 | 44.818605 | 209 | 0.668562 | 4.646698 | false | false | false | false |
wiryls/HomeworkCollectionOfMYLS | 2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/data/UserList.kt | 1 | 4680 | package com.myls.odes.data
import android.os.Parcel
import android.os.Parcelable
import com.myls.odes.utility.Storage
import java.util.*
/**
* Created by myls on 12/8/17.
*
* UserList
*/
data class UserList(val list: MutableList<User> = mutableListOf())
: Parcelable
, Storage.Storable
{
// Parcel
constructor(parcel: Parcel) : this(
mutableListOf<User>().apply {
parcel.readList(this, User::class.java.classLoader)
})
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeList(list)
// [Kotlin parcelable and arrayList of parcelables]
// (https://stackoverflow.com/a/45459675)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<UserList> {
override fun createFromParcel(parcel: Parcel) = UserList(parcel)
override fun newArray(size: Int) = arrayOfNulls<UserList>(size)
}
// data class
data class User(
val info: Info,
var freq: Int = 1,
var date: Long = Calendar.getInstance().timeInMillis,
val dorm: Dorm = Dorm()): Parcelable
{
// Parcel
constructor(parcel: Parcel) : this(
parcel.readParcelable(User::class.java.classLoader),
parcel.readInt(),
parcel.readLong(),
parcel.readParcelable(Dorm::class.java.classLoader))
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeParcelable(info, flags)
parcel.writeInt(freq)
parcel.writeLong(date)
parcel.writeParcelable(dorm, flags)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<User> {
override fun createFromParcel(parcel: Parcel) = User(parcel)
override fun newArray(size: Int) = arrayOfNulls<User>(size)
}
}
data class Dorm(
var pick: String = "",
val fris: MutableList<Friend> = mutableListOf()) : Parcelable
{
// Parcel
constructor(parcel: Parcel) : this(
parcel.readString(),
mutableListOf<Friend>().apply {
parcel.readList(this, Friend::class.java.classLoader)
})
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(pick)
parcel.writeList(fris)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<Dorm> {
override fun createFromParcel(parcel: Parcel) = Dorm(parcel)
override fun newArray(size: Int) = arrayOfNulls<Dorm>(size)
}
// data class
data class Friend(
var stid: String,
var code: String) : Parcelable
{
// Parcel
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString())
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(stid)
parcel.writeString(code)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<Friend> {
override fun createFromParcel(parcel: Parcel) = Friend(parcel)
override fun newArray(size: Int) = arrayOfNulls<Friend>(size)
}
}
}
data class Info(
val stid: String,
var name: String = "",
var gender: String = "",
var grade: String = "",
var code: String = "",
var room: String = "",
var building: String = "",
var location: String = ""): Parcelable
{
// Parcel
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString())
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(stid)
parcel.writeString(name)
parcel.writeString(gender)
parcel.writeString(grade)
parcel.writeString(code)
parcel.writeString(room)
parcel.writeString(building)
parcel.writeString(location)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<Info> {
override fun createFromParcel(parcel: Parcel) = Info(parcel)
override fun newArray(size: Int) = arrayOfNulls<Info>(size)
}
}
}
| mit | 40ec5dc7f18f0850f138caeda511d5cc | 31.275862 | 78 | 0.577778 | 4.849741 | false | true | false | false |
firebase/quickstart-android | analytics/app/src/main/java/com/google/firebase/quickstart/analytics/kotlin/ImageFragment.kt | 2 | 1500 | package com.google.firebase.quickstart.analytics.kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.google.firebase.quickstart.analytics.R
/**
* This fragment displays a featured, specified image.
*/
class ImageFragment : Fragment() {
private var resId: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
resId = it.getInt(ARG_PATTERN)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_main, null)
val imageView = view.findViewById<ImageView>(R.id.imageView)
imageView.setImageResource(resId)
return view
}
companion object {
private const val ARG_PATTERN = "pattern"
/**
* Create a [ImageFragment] displaying the given image.
*
* @param resId to display as the featured image
* @return a new instance of [ImageFragment]
*/
fun newInstance(resId: Int): ImageFragment {
val fragment = ImageFragment()
val args = Bundle()
args.putInt(ARG_PATTERN, resId)
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | 8b6563bca9bd02d5007d3caab7faf11a | 26.777778 | 68 | 0.644 | 4.792332 | false | false | false | false |
facebook/fresco | vito/provider/src/main/java/com/facebook/fresco/vito/provider/impl/kotlin/KFrescoVitoProvider.kt | 2 | 2871 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.provider.impl.kotlin
import com.facebook.callercontext.CallerContextVerifier
import com.facebook.fresco.vito.core.FrescoController2
import com.facebook.fresco.vito.core.FrescoVitoConfig
import com.facebook.fresco.vito.core.FrescoVitoPrefetcher
import com.facebook.fresco.vito.core.ImagePipelineUtils
import com.facebook.fresco.vito.core.VitoImagePipeline
import com.facebook.fresco.vito.core.impl.DebugOverlayHandler
import com.facebook.fresco.vito.core.impl.FrescoVitoPrefetcherImpl
import com.facebook.fresco.vito.core.impl.KFrescoController
import com.facebook.fresco.vito.core.impl.VitoImagePipelineImpl
import com.facebook.fresco.vito.draweesupport.DrawableFactoryWrapper
import com.facebook.fresco.vito.options.ImageOptionsDrawableFactory
import com.facebook.fresco.vito.provider.FrescoVitoProvider
import com.facebook.fresco.vito.provider.impl.NoOpCallerContextVerifier
import com.facebook.imagepipeline.core.ImagePipeline
import com.facebook.imagepipeline.core.ImagePipelineFactory
import java.util.concurrent.Executor
class KFrescoVitoProvider(
private val vitoConfig: FrescoVitoConfig,
private val frescoImagePipeline: ImagePipeline,
private val imagePipelineUtils: ImagePipelineUtils,
private val uiThreadExecutor: Executor,
private val lightweightBackgroundExecutor: Executor,
private val callerContextVerifier: CallerContextVerifier = NoOpCallerContextVerifier,
private val debugOverlayHandler: DebugOverlayHandler? = null
) : FrescoVitoProvider.Implementation {
private val _imagePipeline: VitoImagePipeline by lazy {
VitoImagePipelineImpl(frescoImagePipeline, imagePipelineUtils)
}
private val _controller: FrescoController2 by lazy {
KFrescoController(
config = vitoConfig,
vitoImagePipeline = _imagePipeline,
uiThreadExecutor = uiThreadExecutor,
lightweightBackgroundThreadExecutor = lightweightBackgroundExecutor,
drawableFactory = getFactory())
.also { it.debugOverlayHandler = debugOverlayHandler }
}
private val _prefetcher: FrescoVitoPrefetcher by lazy {
FrescoVitoPrefetcherImpl(frescoImagePipeline, imagePipelineUtils, callerContextVerifier)
}
override fun getController(): FrescoController2 = _controller
override fun getPrefetcher(): FrescoVitoPrefetcher = _prefetcher
override fun getImagePipeline(): VitoImagePipeline = _imagePipeline
override fun getConfig(): FrescoVitoConfig = vitoConfig
private fun getFactory(): ImageOptionsDrawableFactory? {
return ImagePipelineFactory.getInstance().getAnimatedDrawableFactory(null)?.let {
DrawableFactoryWrapper(it)
}
}
}
| mit | 5b2ca7d6016d1e9bbb58ddc742d85a3f | 40.608696 | 92 | 0.805294 | 4.451163 | false | true | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/search/discover/AddIndicator.kt | 1 | 1964 | package com.battlelancer.seriesguide.shows.search.discover
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.battlelancer.seriesguide.databinding.LayoutAddIndicatorBinding
/**
* A three state visual indicator with states add, adding and added from [SearchResult].
*/
class AddIndicator(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {
private val binding: LayoutAddIndicatorBinding
init {
binding = LayoutAddIndicatorBinding.inflate(LayoutInflater.from(context), this)
}
override fun onFinishInflate() {
super.onFinishInflate()
binding.imageViewAddIndicatorAdded.visibility = GONE
binding.progressBarAddIndicator.visibility = GONE
}
fun setContentDescriptionAdded(contentDescription: CharSequence?) {
binding.imageViewAddIndicatorAdded.contentDescription = contentDescription
}
fun setOnAddClickListener(onClickListener: OnClickListener?) {
binding.imageViewAddIndicator.setOnClickListener(onClickListener)
}
fun setState(state: Int) {
when (state) {
SearchResult.STATE_ADD -> {
binding.imageViewAddIndicator.visibility = VISIBLE
binding.progressBarAddIndicator.visibility = GONE
binding.imageViewAddIndicatorAdded.visibility = GONE
}
SearchResult.STATE_ADDING -> {
binding.imageViewAddIndicator.visibility = GONE
binding.progressBarAddIndicator.visibility = VISIBLE
binding.imageViewAddIndicatorAdded.visibility = GONE
}
SearchResult.STATE_ADDED -> {
binding.imageViewAddIndicator.visibility = GONE
binding.progressBarAddIndicator.visibility = GONE
binding.imageViewAddIndicatorAdded.visibility = VISIBLE
}
}
}
} | apache-2.0 | e978f2e5d1161c0a6fe69f1f3498c292 | 36.075472 | 90 | 0.698574 | 5.486034 | false | false | false | false |
andretietz/retroauth | android-accountmanager/src/main/java/com/andretietz/retroauth/AndroidAccountManagerCredentialStorage.kt | 1 | 3569 | /*
* Copyright (c) 2016 Andre Tietz
*
* 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.andretietz.retroauth
import android.accounts.Account
import android.accounts.AccountManager
import android.app.Application
import android.os.Looper
import android.util.Base64
import android.util.Base64.DEFAULT
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
* This is the implementation of a [CredentialStorage] in Android using the Android [AccountManager]
*/
class AndroidAccountManagerCredentialStorage constructor(
private val application: Application
) : CredentialStorage<Account> {
private val accountManager by lazy { AccountManager.get(application) }
private val executor = Executors.newSingleThreadExecutor()
companion object {
private fun createDataKey(type: String, key: String) = "${type}_$key"
}
override fun getCredentials(
owner: Account,
credentialType: String
): Credentials? {
val future = accountManager.getAuthToken(
owner,
credentialType,
null,
ActivityManager[application].activity,
null,
null
)
var token: String? = if (Looper.myLooper() == Looper.getMainLooper()) {
executor.submit(Callable<String?> {
future.result.getString(AccountManager.KEY_AUTHTOKEN)
}).get(100, TimeUnit.MILLISECONDS)
} else future.result.getString(AccountManager.KEY_AUTHTOKEN)
if (token == null) token = accountManager.peekAuthToken(owner, credentialType)
if (token == null) {
return null
}
val dataKeys = accountManager.getUserData(owner, "keys_${owner.type}_$credentialType")
?.let { Base64.decode(it, DEFAULT).toString() }
?.split(",")
return Credentials(
token,
dataKeys
?.associate {
it to accountManager.getUserData(owner, createDataKey(credentialType, it))
}
)
}
override fun removeCredentials(owner: Account, credentialType: String) {
getCredentials(owner, credentialType)?.let { credential ->
accountManager.invalidateAuthToken(owner.type, credential.token)
val dataKeys = accountManager.getUserData(owner, "keys_${owner.type}_$credentialType")
?.let { Base64.decode(it, DEFAULT).toString() }
?.split(",")
dataKeys?.forEach {
accountManager.setUserData(
owner,
createDataKey(credentialType, it),
null
)
}
}
}
override fun storeCredentials(owner: Account, credentialType: String, credentials: Credentials) {
accountManager.setAuthToken(owner, credentialType, credentials.token)
val data = credentials.data
if (data != null) {
val dataKeys = data.keys
.map { Base64.encodeToString(it.toByteArray(), DEFAULT) }
.joinToString { it }
accountManager.setUserData(owner, "keys_${owner.type}_$credentialType", dataKeys)
data.forEach { (key, value) ->
accountManager.setUserData(owner, createDataKey(credentialType, key), value)
}
}
}
}
| apache-2.0 | 052c6ec3bf44efeea2f89de24c172993 | 32.35514 | 100 | 0.699636 | 4.51201 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut08/cameraRelative.kt | 2 | 7077 | package glNext.tut08
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL3
import glNext.*
import glm.*
import glm.mat.Mat4
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.component.Mesh
import uno.glm.MatrixStack
import uno.glsl.programOf
import glm.quat.Quat
/**
* Created by GBarbieri on 10.03.2017.
*/
fun main(args: Array<String>) {
CameraRelative_Next().setup("Tutorial 08 - Camera Relative")
}
class CameraRelative_Next : Framework() {
object OffsetRelative {
val MODEL = 0
val WORLD = 1
val CAMERA = 2
val MAX = 3
}
var theProgram = 0
var modelToCameraMatrixUnif = 0
var cameraToClipMatrixUnif = 0
var baseColorUnif = 0
lateinit var ship: Mesh
lateinit var plane: Mesh
val frustumScale = calcFrustumScale(20.0f)
fun calcFrustumScale(fovDeg: Float) = 1.0f / glm.tan(fovDeg.rad / 2.0f)
val cameraToClipMatrix = Mat4(0.0f)
val camTarget = Vec3(0.0f, 10.0f, 0.0f)
var orientation = Quat(1.0f, 0.0f, 0.0f, 0.0f)
//In spherical coordinates.
val sphereCamRelPos = Vec3(90.0f, 0.0f, 66.0f)
var offset = OffsetRelative.MODEL
public override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
ship = Mesh(gl, javaClass, "tut08/Ship.xml")
plane = Mesh(gl, javaClass, "tut08/UnitPlane.xml")
cullFace {
enable()
cullFace = back
frontFace = cw
}
depth {
test = true
mask = true
func = lEqual
range = 0.0 .. 1.0
}
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut08", "pos-color-local-transform.vert", "color-mult-uniform.frag")
withProgram(theProgram) {
modelToCameraMatrixUnif = "modelToCameraMatrix".location
cameraToClipMatrixUnif = "cameraToClipMatrix".location
baseColorUnif = "baseColor".location
val zNear = 1.0f
val zFar = 600.0f
cameraToClipMatrix[0].x = frustumScale
cameraToClipMatrix[1].y = frustumScale
cameraToClipMatrix[2].z = (zFar + zNear) / (zNear - zFar)
cameraToClipMatrix[2].w = -1.0f
cameraToClipMatrix[3].z = 2f * zFar * zNear / (zNear - zFar)
use { cameraToClipMatrixUnif.mat4 = cameraToClipMatrix }
}
}
public override fun display(gl: GL3) = with(gl) {
clear {
color(0)
depth()
}
val currMatrix = MatrixStack()
val camPos = resolveCamPosition()
currMatrix setMatrix calcLookAtMatrix(camPos, camTarget, Vec3(0.0f, 1.0f, 0.0f))
usingProgram(theProgram) {
currMatrix.apply {
scale(100.0f, 1.0f, 100.0f)
glUniform4f(baseColorUnif, 0.2f, 0.5f, 0.2f, 1.0f)
modelToCameraMatrixUnif.mat4 = top()
plane.render(gl)
} run {
translate(camTarget)
applyMatrix(orientation.toMat4())
rotateX(-90.0f)
glUniform4f(baseColorUnif, 1.0f)
modelToCameraMatrixUnif.mat4 = top()
ship.render(gl, "tint")
}
}
}
fun resolveCamPosition(): Vec3 {
val phi = sphereCamRelPos.x.rad
val theta = (sphereCamRelPos.y + 90.0f).rad
val dirToCamera = Vec3(theta.sin * phi.cos, theta.cos, theta.sin * phi.sin)
return dirToCamera * sphereCamRelPos.z + camTarget
}
fun calcLookAtMatrix(cameraPt: Vec3, lookPt: Vec3, upPt: Vec3): Mat4 {
val lookDir = (lookPt - cameraPt).normalize()
val upDir = upPt.normalize()
val rightDir = (lookDir cross upDir).normalize()
val perpUpDir = rightDir cross lookDir
val rotationMat = Mat4(1.0f)
rotationMat[0] = Vec4(rightDir, 0.0f)
rotationMat[1] = Vec4(perpUpDir, 0.0f)
rotationMat[2] = Vec4(-lookDir, 0.0f)
rotationMat.transpose_()
val translMat = Mat4(1.0f)
translMat[3] = Vec4(-cameraPt, 1.0f)
return rotationMat * translMat
}
public override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
cameraToClipMatrix[0].x = frustumScale * (h / w.f)
cameraToClipMatrix[1].y = frustumScale
usingProgram(theProgram) {cameraToClipMatrixUnif.mat4 = cameraToClipMatrix}
glViewport(w, h)
}
public override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
plane.dispose(gl)
ship.dispose(gl)
}
override fun keyPressed(e: KeyEvent) {
val smallAngleIncrement = 9.0f
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_W -> offsetOrientation(Vec3(1.0f, 0.0f, 0.0f), +smallAngleIncrement)
KeyEvent.VK_S -> offsetOrientation(Vec3(1.0f, 0.0f, 0.0f), -smallAngleIncrement)
KeyEvent.VK_A -> offsetOrientation(Vec3(0.0f, 0.0f, 1.0f), +smallAngleIncrement)
KeyEvent.VK_D -> offsetOrientation(Vec3(0.0f, 0.0f, 1.0f), -smallAngleIncrement)
KeyEvent.VK_Q -> offsetOrientation(Vec3(0.0f, 1.0f, 0.0f), +smallAngleIncrement)
KeyEvent.VK_E -> offsetOrientation(Vec3(0.0f, 1.0f, 0.0f), -smallAngleIncrement)
KeyEvent.VK_SPACE -> {
offset = (++offset) % OffsetRelative.MAX
when (offset) {
OffsetRelative.MODEL -> println("MODEL_RELATIVE")
OffsetRelative.WORLD -> println("WORLD_RELATIVE")
OffsetRelative.CAMERA -> println("CAMERA_RELATIVE")
}
}
KeyEvent.VK_I -> sphereCamRelPos.y -= if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_K -> sphereCamRelPos.y += if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_J -> sphereCamRelPos.x -= if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_L -> sphereCamRelPos.x += if (e.isShiftDown) 1.125f else 11.25f
}
sphereCamRelPos.y = glm.clamp(sphereCamRelPos.y, -78.75f, 10.0f)
}
fun offsetOrientation(axis: Vec3, angDeg: Float) {
axis.normalize()
axis times_ glm.sin(angDeg.rad / 2.0f)
val scalar = glm.cos(angDeg.rad / 2.0f)
val offsetQuat = Quat(scalar, axis)
when (offset) {
OffsetRelative.MODEL -> orientation times_ offsetQuat
OffsetRelative.WORLD -> orientation = offsetQuat * orientation
OffsetRelative.CAMERA -> {
val camPos = resolveCamPosition()
val camMat = calcLookAtMatrix(camPos, camTarget, Vec3(0.0f, 1.0f, 0.0f))
val viewQuat = camMat.toQuat()
val invViewQuat = viewQuat.conjugate()
val worldQuat = invViewQuat * offsetQuat * viewQuat
orientation = worldQuat * orientation
}
}
orientation.normalize_()
}
} | mit | 47844e4d19cf3a6122e540c33cf0953c | 26.328185 | 115 | 0.585135 | 3.790573 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/listener/PlayerEditBookListener.kt | 1 | 2101 | /*
* Copyright 2022 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.characters.bukkit.listener
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.ChatColor
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerEditBookEvent
class PlayerEditBookListener(private val plugin: RPKCharactersBukkit) : Listener {
@EventHandler
fun onPlayerEditBook(event: PlayerEditBookEvent) {
if (!event.isSigning) return
if (!plugin.config.getBoolean("books.change-author-on-sign")) return
val meta = event.newBookMeta
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player) ?: return
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return
var newAuthor = plugin.config.getString("books.author-format") ?: "\${player}"
newAuthor = ChatColor.translateAlternateColorCodes('&', newAuthor)
newAuthor = newAuthor.replace("\${player}", minecraftProfile.name)
newAuthor = newAuthor.replace("\${character}", character.name)
meta.author = newAuthor
event.newBookMeta = meta
}
} | apache-2.0 | 4bd16d00c649ae8846d8feacbfd92cd4 | 43.723404 | 107 | 0.754879 | 4.637969 | false | false | false | false |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/project/tree/ProjectTree.kt | 2 | 3186 | /*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.project.tree
import com.efficios.jabberwocky.context.ViewGroupContext
import com.efficios.jabberwocky.project.TraceProject
import javafx.scene.control.ContextMenu
import javafx.scene.control.TreeCell
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import org.lttng.scope.application.actions.editProject
import org.lttng.scope.common.jfx.JfxUtils
import org.lttng.scope.common.jfx.ScopeMenuItem
import org.lttng.scope.views.context.ViewGroupContextManager
class ProjectTree : TreeView<String>() {
companion object {
private const val NO_PROJECT = "(no project opened)"
private const val PROJECT_SETUP_ACTION = "Project Setup"
}
private val emptyProjectRootItem = TreeItem(NO_PROJECT)
private val projectRootItem = RootTreeItem()
init {
setCellFactory { ProjectTreeCell() }
/* Setup listeners */
ViewGroupContextManager.getCurrent().registerProjectChangeListener(object : ViewGroupContext.ProjectChangeListener(this) {
override fun newProjectCb(newProject: TraceProject<*, *>?) {
JfxUtils.runLaterAndWait(Runnable {
root = if (newProject == null) {
emptyProjectRootItem
} else {
projectRootItem
}
})
}
})
root = emptyProjectRootItem
}
private inner class RootTreeItem : ProjectTreeItem(NO_PROJECT) {
override val contextMenu: ContextMenu
override fun initForProject(project: TraceProject<*, *>) {
value = project.name
}
override fun clear() {
/* Do not call super.clear() (which clears the children, which we don't want here!) */
}
init {
val projectSetupMenuItem = ScopeMenuItem(PROJECT_SETUP_ACTION) {
getCurrentProject()?.let { editProject(this@ProjectTree, it) }
}
contextMenu = ContextMenu(projectSetupMenuItem)
/* Setup tree skeleton */
children.addAll(TracesTreeItem(),
// BookmarksTreeItem(),
FiltersTreeItem(this@ProjectTree))
}
}
}
private class ProjectTreeCell : TreeCell<String>() {
override fun updateItem(item: String?, empty: Boolean) {
super.updateItem(item, empty)
val treeItem = treeItem
if (empty) {
text = null
graphic = null
contextMenu = null
tooltip = null
} else {
text = getItem()?.toString() ?: ""
graphic = treeItem.graphic
if (treeItem is ProjectTreeItem) {
contextMenu = treeItem.contextMenu
tooltip = treeItem.tooltip
}
}
}
}
| epl-1.0 | c3a96f3ad4d112d287a74cc1893ae729 | 29.932039 | 130 | 0.624608 | 4.947205 | false | false | false | false |
zingmars/Cbox-bot | src/BasePlugin.kt | 1 | 2387 | /**
* Base plugin class to be inherited from
* Created by zingmars on 04.10.2015.
*/
package BotPlugins
import Containers.PluginBufferItem
import Settings
import Logger
import Plugins
import ThreadController
open public class BasePlugin() {
public var settings :Settings? = null
public var logger :Logger? = null
public var handler :Plugins? = null
public var pluginName :String? = null
public var controller :ThreadController? = null
init {
// This is the base class for all CBot plugins
// To make a plugin just extend this class and put it in src/BotPlugins/ (or whatever is defined in your settings file) directory
// Note - your filename must match your class name and it must be inside the BotPlugins package
// To initiate just override pubInit() (you can override this initializer too, but you won't have access to any variables at that point), and to do your logic just override connector.
// Note that your connector override will need to have the PluginBufferItem input for it to receive any messages.
// To send data back just add an element to any of the buffers available in ThreadController, (i.e. BoxBuffer will output anything send to it)
// Note that pubInit and connector both return a boolean value that indicates whether or not the plugin was successful
}
//non-overridable classes
final public fun initiate(settings :Settings, logger: Logger, pluginsHandler :Plugins, controller :ThreadController,pluginName :String) :Boolean
{
this.settings = settings
this.logger = logger
this.handler = pluginsHandler
this.pluginName = pluginName
this.controller = controller
if(this.pubInit()) this.logger?.LogPlugin(pluginName, "Started!")
else {
this.stop()
this.logger?.LogPlugin(pluginName, "failed to load!")
return false
}
return true
}
//overridable classes
open public fun pubInit() :Boolean { return true } //Initializer
open public fun connector(buffer :PluginBufferItem) :Boolean { return true } //Receives data from Plugin controller
open public fun stop() {} //This is run when the plugin is unloaded
open public fun executeCommand(command :String) :String { return "Plugin not configured" } //Execute a command
} | bsd-2-clause | 0f90e8f93e24d1f1b2480390dce0e9dd | 47.734694 | 191 | 0.698785 | 4.764471 | false | false | false | false |
danirod/rectball | app/src/main/java/es/danirod/rectball/screens/StatisticsScreen.kt | 1 | 4515 | /*
* This file is part of Rectball
* Copyright (C) 2015-2017 Dani Rodríguez
*
* 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 es.danirod.rectball.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.glutils.FrameBuffer
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.viewport.FitViewport
import es.danirod.rectball.Pixmapper.captureScreenshot
import es.danirod.rectball.RectballGame
import es.danirod.rectball.SoundPlayer
import es.danirod.rectball.android.PixmapSharer
import es.danirod.rectball.android.R
import es.danirod.rectball.scene2d.listeners.ScreenPopper
import es.danirod.rectball.scene2d.ui.StatsTable
/**
* Statistics screen.
*/
class StatisticsScreen(game: RectballGame) : AbstractScreen(game) {
private lateinit var statsTable: StatsTable
private lateinit var pane: ScrollPane
private lateinit var backButton: TextButton
private lateinit var shareButton: ImageButton
private fun statsTable(): StatsTable {
val bold = game.skin.get("bold", LabelStyle::class.java)
val normal = game.skin.get("small", LabelStyle::class.java)
return StatsTable(game, bold, normal)
}
public override fun setUpInterface(table: Table) {
statsTable = statsTable()
pane = ScrollPane(statsTable, game.skin).apply {
fadeScrollBars = false
}
backButton = TextButton(game.context.getString(R.string.core_back), game.skin).apply {
addListener(ScreenPopper(game))
}
shareButton = ImageButton(game.skin, "share").apply {
addListener(object : ChangeListener() {
override fun changed(event: ChangeEvent, actor: Actor) {
game.player.playSound(SoundPlayer.SoundCode.SELECT)
val pmap = buildOffscreenTable()
PixmapSharer(game).share(game.context.getString(R.string.sharing_intent_title), "", pmap)
event.cancel()
}
})
}
table.apply {
add(pane).colspan(2).align(Align.topLeft).expand().fill().row()
add(backButton).fillX().expandX().expandY().height(80f).padTop(20f).align(Align.bottom)
add(shareButton).height(80f).padTop(20f).padLeft(10f).align(Align.bottomRight).row()
}
}
override fun getID(): Int = Screens.STATISTICS
private fun buildOffscreenTable(): Pixmap {
/* Build an FBO object where the offscreen table will be rendered. */
val aspectRatio = statsTable.width / statsTable.height
val width = 480
val height = (480 / aspectRatio).toInt()
val fbo = FrameBuffer(Pixmap.Format.RGBA8888, width, height, false)
/* Build a stage and add the virtual new table. */
val stage = Stage(FitViewport(480f, (480f / aspectRatio)))
val table = statsTable()
table.setFillParent(true)
table.pad(10f)
stage.addActor(table)
/* Then virtually render the stage. */
fbo.begin()
Gdx.gl.glClearColor(0.3f, 0.4f, 0.4f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
stage.act()
stage.draw()
val pmap = captureScreenshot(0, 0, width, height)
fbo.end()
fbo.dispose()
return pmap
}
} | gpl-3.0 | 5a63eb7cf4486cd07d81b2eab870e473 | 37.614035 | 109 | 0.671467 | 3.878007 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/loritta/PostRaffleStatusRoute.kt | 1 | 3462 | package net.perfectdreams.loritta.morenitta.website.routes.api.v1.loritta
import com.github.salomonbrys.kotson.int
import com.github.salomonbrys.kotson.jsonObject
import com.github.salomonbrys.kotson.long
import com.github.salomonbrys.kotson.obj
import com.github.salomonbrys.kotson.string
import com.google.gson.JsonParser
import net.perfectdreams.loritta.morenitta.commands.vanilla.economy.LoraffleCommand
import net.perfectdreams.loritta.morenitta.threads.RaffleThread
import io.ktor.server.application.*
import io.ktor.server.request.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.SonhosPaymentReason
import net.perfectdreams.loritta.morenitta.website.routes.api.v1.RequiresAPIAuthenticationRoute
import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson
class PostRaffleStatusRoute(loritta: LorittaBot) : RequiresAPIAuthenticationRoute(loritta, "/api/v1/loritta/raffle") {
companion object {
val logger = KotlinLogging.logger {}
}
override suspend fun onAuthenticatedRequest(call: ApplicationCall) {
val json = withContext(Dispatchers.IO) { JsonParser.parseString(call.receiveText()).obj }
val userId = json["userId"].long
val quantity = json["quantity"].int
val localeId = json["localeId"].string
val currentUniqueId = RaffleThread.raffleRandomUniqueId
RaffleThread.buyingOrGivingRewardsMutex.withLock {
if (currentUniqueId != RaffleThread.raffleRandomUniqueId || !RaffleThread.isReady) {
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.STALE_RAFFLE_DATA.toString()
)
)
return@withLock
}
val currentUserTicketQuantity = RaffleThread.userIds.count { it == userId }
if (currentUserTicketQuantity + quantity > LoraffleCommand.MAX_TICKETS_BY_USER_PER_ROUND) {
if (currentUserTicketQuantity == LoraffleCommand.MAX_TICKETS_BY_USER_PER_ROUND) {
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.THRESHOLD_EXCEEDED.toString()
)
)
} else {
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.TOO_MANY_TICKETS.toString(),
"ticketCount" to currentUserTicketQuantity
)
)
}
return
}
val requiredCount = quantity.toLong() * 250
logger.info("$userId irá comprar $quantity tickets por ${requiredCount}!")
val lorittaProfile = loritta.getOrCreateLorittaProfile(userId)
if (lorittaProfile.money >= requiredCount) {
loritta.newSuspendedTransaction {
lorittaProfile.takeSonhosAndAddToTransactionLogNested(
requiredCount,
SonhosPaymentReason.RAFFLE
)
}
for (i in 0 until quantity) {
RaffleThread.userIds.add(userId)
}
RaffleThread.logger.info("${userId} comprou $quantity tickets por ${requiredCount}! (Antes ele possuia ${lorittaProfile.money + requiredCount}) sonhos!")
loritta.raffleThread.save()
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.SUCCESS.toString()
)
)
} else {
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.NOT_ENOUGH_MONEY.toString(),
"canOnlyPay" to requiredCount - lorittaProfile.money
)
)
}
}
}
} | agpl-3.0 | 2c81191ecc96905f66b56134ab4a956a | 33.277228 | 157 | 0.756718 | 3.799122 | false | false | false | false |
darakeon/dfm | android/Lib/src/test/kotlin/com/darakeon/dfm/lib/api/ResponseHandlerTest.kt | 1 | 5150 | package com.darakeon.dfm.lib.api
import com.darakeon.dfm.lib.BuildConfig
import com.darakeon.dfm.lib.R
import com.darakeon.dfm.lib.api.entities.Body
import com.darakeon.dfm.lib.api.entities.Environment
import com.darakeon.dfm.lib.api.entities.Theme
import com.darakeon.dfm.lib.auth.getValue
import com.darakeon.dfm.lib.auth.setValue
import com.darakeon.dfm.lib.utils.ActivityMock
import com.darakeon.dfm.lib.utils.ApiActivity
import com.darakeon.dfm.lib.utils.CallMock
import com.darakeon.dfm.testutils.BaseTest
import com.darakeon.dfm.testutils.TestException
import com.darakeon.dfm.testutils.api.internetError
import com.darakeon.dfm.testutils.api.internetSlow
import com.darakeon.dfm.testutils.api.noBody
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog
import retrofit2.Response
import java.net.ConnectException
import java.net.SocketTimeoutException
@RunWith(RobolectricTestRunner::class)
internal class ResponseHandlerTest: BaseTest() {
private lateinit var activity: ApiActivity
private lateinit var handler: ResponseHandler<ApiActivity, String>
private var result: String? = null
private val waitEnded
get() = activity.waitEnded
@Before
fun setup() {
activity = ActivityMock(ApiActivity::class).create()
handler = ResponseHandler(activity) {
result = it
}
}
@Test
fun onResponse_BodyNull() {
val body: Body<String>? = null
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(
activity.errorText,
`is`(noBody)
)
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onResponse_BodyChildrenNull() {
val body = Body<String>(null, null, null, null)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(
activity.errorText,
`is`("Not identified site error. Contact us.")
)
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onResponse_BodySuccessAndFailed() {
val body = Body("success", null, "confusing result", 0)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(
activity.errorText,
`is`("confusing result")
)
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onResponse_ResponseBodyEnvironment() {
val env = Environment(Theme.LightNature, "pt-BR")
val body = Body("result", env, null, null)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(activity.getValue("Theme").toInt(), `is`(R.style.LightNature))
assertThat(activity.getValue("Language"), `is`("pt_BR"))
assertTrue(waitEnded)
assertThat(result, `is`("result"))
}
@Test
fun onResponse_BodySuccess() {
val body = Body("result", null, null, null)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertTrue(waitEnded)
assertThat(result, `is`("result"))
}
@Test
fun onResponse_ErrorOfTfa() {
val errorCode = activity.resources.getInteger(R.integer.TFA)
val body = Body<String>(null, null, "TFA", errorCode)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
val alert = getLatestAlertDialog()
assertNull(alert)
assertTrue(waitEnded)
assertNull(result)
assertTrue(activity.checkedTFA)
}
@Test
fun onResponse_ErrorOfUninvited() {
val errorCode = activity.resources.getInteger(R.integer.uninvited)
val body = Body<String>(null, null, "TFA", errorCode)
val response = Response.success(body)
activity.setValue("Ticket", "fake")
handler.onResponse(CallMock(), response)
val alert = getLatestAlertDialog()
assertNull(alert)
assertTrue(waitEnded)
assertNull(result)
assertTrue(activity.loggedOut)
}
@Test
fun onResponse_ErrorOfAnotherType() {
val body = Body<String>(null, null, "generic", 273)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(activity.errorText, `is`("generic"))
assertTrue(waitEnded)
assertNull(result)
}
@Test(expected = TestException::class)
fun onFailure_ErrorCommonDebug() {
if (!BuildConfig.DEBUG) throw TestException()
handler.onFailure(CallMock(), TestException())
}
@Test
fun onFailure_ErrorCommonRelease() {
if (BuildConfig.DEBUG) return
val error = TestException()
handler.onFailure(CallMock(), error)
assertThat(activity.errorText, `is`(internetError))
assertThat(activity.error, `is`(error))
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onFailure_ErrorOfSocketTimeout() {
handler.onFailure(CallMock(), SocketTimeoutException())
assertThat(
activity.errorText,
`is`(internetSlow)
)
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onFailure_ErrorOfConnect() {
handler.onFailure(CallMock(), ConnectException())
assertThat(
activity.errorText,
`is`(internetSlow)
)
assertTrue(waitEnded)
assertNull(result)
}
}
| gpl-3.0 | 8e0ab02a4fe7572b0ca0d8a63877fea6 | 22.515982 | 75 | 0.749126 | 3.522572 | false | true | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/tcm/patho/OrganSyndrome.kt | 1 | 48090 | package at.cpickl.gadsu.tcm.patho
import at.cpickl.gadsu.tcm.model.Substances
import at.cpickl.gadsu.tcm.model.YinYang
// TODO unbedingt die zunge+puls in eigenen datacontainer, damit diese nicht included werden koennen!
/*
TODOs:
- manche symtpoms haben Qi/Blut/Yin/Yang bezug, manche starke Zang, manche typisch fuer element
- CLI app schreiben, die auswertung printed; zb welche symptoms nur ein zang betreffen, ...
- 9er gruppe finden (auch zukuenftige beruecksichtigen)
- symptoms mit dynTreats matchen (zunge, puls)
- TCM props implementieren
*/
enum class OrganSyndrome(
// MINOR label LONG vs SHORT
val label: String,
val sqlCode: String,
val description: String = "",
val organ: ZangOrgan,
val part: SyndromePart? = null,
val tendency: MangelUeberfluss,
val externalFactors: List<ExternalPathos> = emptyList(),
val symptoms: List<Symptom>
) {
// LEBER
// =================================================================================================================
// verdauung, emo, mens
// sehnen, naegel, augen
// genitalregion, rippenbogen, kopf, augen (meridianverlauf)
LeBlutXu(
label = "Leber Blut Mangel",
sqlCode = "LeBlutXu",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.BlutXu.symptoms + listOf(
// augen
Symptom.UnscharfesSehen,
Symptom.VerschwommenesSehen,
Symptom.Nachtblindheit,
Symptom.MouchesVolantes,
Symptom.TrockeneAugen,
// sehnen
Symptom.SteifeSehnen,
Symptom.Zittern,
// mens
Symptom.AussetzerMenstruation,
Symptom.VerlaengerterZyklus,
// zunge
Symptom.BlasseZunge,
// puls
Symptom.DuennerPuls // fadenfoermig
)
),
LeYinXu(// wie Blutmangel, aber plus Mangel-Hitze
label = "Leber Yin Mangel",
sqlCode = "LeYinXu",
description = "Symptome ähnlich von Leber Feuer, da das Yin das Yang nicht halten kann und aufsteigt, aber da es ein Mangel ist schwächer ausgeprägt.",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.YinXu.symptoms + listOf(
// augen
Symptom.TrockeneAugen,
Symptom.Nachtblindheit,
// ohren
Symptom.Tinnitus,
// Le yang steigt auf
Symptom.Kopfschmerzen,
Symptom.Gereiztheit,
Symptom.Zornesanfaelle,
Symptom.Laehmung,
Symptom.HalbseitigeLaehmung,
Symptom.Schlaganfall,
// zunge
Symptom.RoteZunge, // TODO should not contain BlasseZunge from LeBlutXu! maybe outsource tongue+pulse symptoms in own variable...
Symptom.WenigBelag,
// puls
Symptom.BeschleunigterPuls,
Symptom.DuennerPuls,
Symptom.SchwacherPuls
)
),
LeBlutStau(
label = "Leber Blut Stau",
sqlCode = "LeBlutStau",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
// misc
Symptom.Knoten,
Symptom.Tumore,
Symptom.LeberVergroesserung,
Symptom.MilzVergroesserung,
Symptom.DunkleGesichtsfarbe,
Symptom.StumpfeGesichtsfarbe,
// schmerz
Symptom.StechenderSchmerz,
Symptom.FixierterSchmerz,
Symptom.SchmerzNachtsSchlimmer,
// mens
Symptom.DunklesMenstruationsblut,
Symptom.ZaehesMenstruationsblut,
Symptom.KlumpenInBlut,
// zunge
Symptom.VioletteZunge,
Symptom.DunkleZunge,
Symptom.BlauVioletteZungenpunkte,
Symptom.GestauteVenen, // MINOR gestaute == unterzungenvenen??
Symptom.GestauteUnterzungenvenen,
// puls
Symptom.RauherPuls
)
),
LeQiStau(
label = "Leber Qi Stau",
description = "Greift MP an.",
sqlCode = "LeQiStau",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
// verdauung
Symptom.VielAppettit,
Symptom.WenigAppetit,
Symptom.VoelleGefuehl,
Symptom.Blaehungen,
Symptom.Aufstossen,
Symptom.Sodbrennen,
Symptom.Brechreiz,
Symptom.Erbrechen,
Symptom.Magenschmerzen,
Symptom.Uebelkeit,
Symptom.MorgendlicheUebelkeit,
Symptom.UnregelmaessigerStuhl,
Symptom.WechselhafteVerdauung,
// meridian
Symptom.SpannungZwerchfell,
Symptom.SchmerzZwerchfell,
Symptom.Seufzen,
Symptom.ThorakalesEngegefuehl,
Symptom.DruckgefuehlBrustbein,
Symptom.BrustspannungPMS,
Symptom.Schulterschmerzen,
Symptom.Nackenschmerzen,
Symptom.Kopfschmerzen,
Symptom.FroschImHals,
// mens
Symptom.Zyklusunregelmaessigkeiten,
Symptom.PMS,
Symptom.Regelkraempfe,
Symptom.UnterbauchziehenPMS,
Symptom.EmotionaleSchwankungenMens,
// emotionen
Symptom.Reizbarkeit,
Symptom.Aufbrausen,
Symptom.Zornesausbrueche,
Symptom.Launisch,
Symptom.Frustration,
Symptom.Depression,
Symptom.UnterdrueckteGefuehle,
// zunge
Symptom.NormaleZunge,
Symptom.RoteZungenspitze,
Symptom.RoterZungenrand,
// puls
Symptom.SaitenfoermigerPuls
)
),
LeFeuer(
label = "Leber Feuer (lodert nach oben)",
sqlCode = "LeFeuer",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.HeftigeKopfschmerzen,
Symptom.KopfschmerzenScheitel,
Symptom.Tinnitus,
Symptom.Hoersturz,
Symptom.Schwindel,
Symptom.RoteBindehaut,
Symptom.RoteSkleren,
Symptom.TrockenerMund,
Symptom.BittererMundgeschmack,
Symptom.Nasenbluten,
Symptom.BlutHusten,
Symptom.BlutErbrechen,
// psycho
Symptom.Zornesausbrueche,
Symptom.Gereiztheit,
Symptom.Gewalttaetig,
// verdauung
Symptom.Magenschmerzen,
Symptom.Sodbrennen,
Symptom.Brechreiz,
Symptom.Erbrechen,
Symptom.Verstopfung,
Symptom.BrennenderDurchfall,
// allg. zeichen ueberfluss-hitze (He-Feuer, holz das feuer uebernaehrt); aehnlich dem LeBlutXu
Symptom.Unruhe,
Symptom.Schlaflosigkeit,
Symptom.Durst,
Symptom.Durchfall,
Symptom.WenigUrin,
Symptom.DunklerUrin,
Symptom.RotesGesicht,
Symptom.RoteAugen,
Symptom.Palpitationen,
// zunge
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.RoterZungenrand,
Symptom.GelberBelag,
// puls
Symptom.SaitenfoermigerPuls,
Symptom.BeschleunigterPuls,
Symptom.KraeftigerPuls
)
),
LeWindHitze(
label = "Leber Wind (Extreme Hitze)",
sqlCode = "LeWindHitze",
description = "Von sehr hohem Fieber. Fieberkrämpfe, Verkrampfungen, Augen nach oben rollen.",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LeWind + listOf(// MINOR + ueberfluss-hitze
Symptom.Kraempfe,
Symptom.Koma,
Symptom.Delirium,
// zunge
Symptom.RoteZunge,
Symptom.ScharlachRoteZunge,
Symptom.TrockenerBelag,
Symptom.GelberBelag,
Symptom.SteifeZunge,
// puls
Symptom.SchnellerPuls,
Symptom.VollerPuls,
Symptom.SaitenfoermigerPuls
)
),
LeWindYangAuf(
label = "Leber Wind (Aufsteigendes Leber Yang)",
description = "Ursache ist Le/Ni Yin-Mangel",
sqlCode = "LeWindLeYang",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.Schwindel,
Symptom.Schwanken,
Symptom.KopfUnwillkuerlichBewegt,
Symptom.Laehmung,
Symptom.HalbseitigeLaehmung,
// psycho
Symptom.Desorientiertheit,
Symptom.Bewusstseinsverlust,
Symptom.Sprachstoerungen,
// zunge
Symptom.RoteZunge,
Symptom.WenigBelag,
Symptom.FehlenderBelag,
// puls
Symptom.BeschleunigterPuls
)
),
LeWindBlutXu(
label = "Leber Wind (Blut Mangel)",
description = "Ursache ist Le/allgemeiner Blut-Mangel",
sqlCode = "LeWindBlutXu",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = LeBlutXu.symptoms + listOf(
Symptom.Tics,
Symptom.Augenzucken,
Symptom.KopfUnwillkuerlichBewegt,
Symptom.Sehstoerungen,
Symptom.Schwindel,
Symptom.Benommenheit,
Symptom.DuennerBelag,
Symptom.WeisserBelag
)
),
LeFeuchteHitze(
label = "Feuchtigkeit und Hitze in Le und Gb",
description = "Ursache ist Le-Qi-Stau.",
sqlCode = "LeFeuchteHitze",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.SchmerzBrustkorb,
Symptom.SchmerzZwerchfell,
Symptom.Durst,
Symptom.Unruhe,
Symptom.Gereiztheit,
Symptom.KonzentrierterUrin,
Symptom.DunklerUrin,
Symptom.Fieber, // niedrig, anhaltend
Symptom.Gelbsucht,
// milz
Symptom.WenigAppetit,
Symptom.Brechreiz,
Symptom.Erbrechen,
Symptom.DurckgefuehlBauch,
Symptom.Blaehungen,
Symptom.BittererMundgeschmack,
// frauen
Symptom.GelberAusfluss,
Symptom.RiechenderAusfluss,
Symptom.JuckreizScheide,
Symptom.Entzuendungsherde, // bereich Le-/Gb-meridian
Symptom.Hautpilz,
Symptom.Herpes,
// maenner
Symptom.Hodenschmerzen,
Symptom.Hodenschwellungen,
Symptom.Ausfluss,
Symptom.Prostatitis,
Symptom.Hautausschlag, // bereich Le-/Gb-meridian
// zunge
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.RoterZungenrand,
Symptom.DickerBelag,
Symptom.GelberBelag,
Symptom.SchmierigerBelag,
// puls
Symptom.BeschleunigterPuls,
Symptom.SaitenfoermigerPuls,
Symptom.SchluepfrigerPuls
)
),
LeKaelteJingLuo(
label = "Kälte im Lebermeridian",
sqlCode = "LeKaltMerid",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.Unterbauchschmerzen,
Symptom.Kraempfe,
Symptom.Kontraktionen,
Symptom.WaermeErleichtert,
Symptom.Unfruchtbarkeit,
// frau
Symptom.Menstruationskraempfe,
Symptom.Ausfluss,
// mann
Symptom.Impotenz,
Symptom.UntenZiehendeHoden,
// zunge
Symptom.BlasseZunge,
Symptom.WeisserBelag,
Symptom.FeuchterBelag,
// puls
Symptom.VerlangsamterPuls,
Symptom.TieferPuls,
Symptom.SaitenfoermigerPuls
)
),
// HERZ
// =================================================================================================================
HeBlutXu(
label = "He-Blut-Mangel",
sqlCode = "HeBlutXu",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.BlutXu.symptoms + SpecificSymptoms.HeBlutXu
),
HeYinXu(
label = "He-Yin-Mangel",
sqlCode = "HeYinXu",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = SpecificSymptoms.HeBlutXu + GeneralSymptoms.YinXu.symptoms + listOf(
Symptom.MehrDurstSpaeter,
Symptom.Gereiztheit,
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.DuennerBelag,
Symptom.FehlenderBelag,
Symptom.BeschleunigterPuls
)
),
HeQiXu(
label = "He-Qi-Mangel",
sqlCode = "HeQiXu",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.QiXu.symptoms + SpecificSymptoms.HeQiXu
),
HeYangXu(
label = "He-Yang-Mangel",
sqlCode = "HeYangXu",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = SpecificSymptoms.HeQiXu + GeneralSymptoms.YangXu.symptoms + listOf(
Symptom.ThorakalesEngegefuehl,
// zunge
Symptom.FeuchteZunge,
// puls
Symptom.LangsamerPuls
)
),
// MINOR 3 yang xu subtypes got symptoms of HeYangXu as well??
HeYangXuBlutBewegen(
label = "He-Yang-Mangel (Yang kann das Blut nicht ausreichend bewegen)",
sqlCode = "HeYangXuBlutBewegen",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.HeYangXuPulsTongue + listOf(
Symptom.Zyanose,
Symptom.ThorakalesEngegefuehl,
Symptom.MaessigeSchmerzen,
Symptom.Atemnot // belastungs- / ruhedyspnoe
)
),
HeYangXuUndNiYangErschopeft(
label = "He-Yang-Mangel (He/Ni Yang erschöpft)",
sqlCode = "HeYangXuUndNiYangErschopeft",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.HeYangXuPulsTongue + listOf(
Symptom.UrinierenSchwierigkeiten,
Symptom.Oedeme, // oft oben
Symptom.Husten,
Symptom.Wasserretention // ansammlung (in der lunge)
)
),
HeYangXuKollaps(
label = "He-Yang-Mangel (Kollaps, Yang bricht zusammen)",
sqlCode = "HeYangXuKollaps",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.HeYangXuPulsTongue + listOf(
Symptom.KaelteGefuehl, // extremes
Symptom.Zittern,
Symptom.Zyanose,
Symptom.SchweissAusbruch,
Symptom.Bewusstseinsverlust
)
),
HeBlutStau(
label = "Herz Blut Stauung",
sqlCode = "HeBlutStau",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.StechenderSchmerz,
Symptom.FixierterSchmerz,
Symptom.ArmAusstrahlendeSchmerzen,
Symptom.Magenschmerzen,
Symptom.ThorakalesEngegefuehl,
Symptom.Druckgefuehl,
Symptom.KalteExtremitaeten,
Symptom.Kurzatmigkeit,
Symptom.Palpitationen,
Symptom.BlaufaerbungGesicht,
Symptom.BlaufaerbungNaegeln,
Symptom.VioletteZunge,
Symptom.VioletteZungenflecken,
Symptom.DuennerBelag,
Symptom.RauherPuls,
Symptom.HaengenderPuls,
Symptom.SchwacherPuls,
Symptom.UnregelmaessigerPuls,
Symptom.SaitenfoermigerPuls
)
),
HeFeuer(
label = "Loderndes Herz Feuer",
sqlCode = "HeFeuer",
description = "Stärkere variante von He-Yin-Mangel",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.RotesGesicht,
Symptom.Erosionen,
Symptom.Ulzerationen,
Symptom.BittererMundgeschmack,
Symptom.UrinierenBrennen,
Symptom.BlutInUrin,
Symptom.Gewalttaetig,
Symptom.StarkeSchlafstoerungen,
Symptom.MehrDurst,
Symptom.Unruhe,
Symptom.Gereiztheit,
Symptom.Palpitationen,
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.DuennerBelag,
Symptom.GelberBelag,
Symptom.Zungenspalt,
Symptom.BeschleunigterPuls,
Symptom.KraeftigerPuls,
Symptom.UeberflutenderPuls,
Symptom.JagenderPuls
)
),
HeSchleimFeuerVerstoert(
label = "Schleim-Feuer verstört das Herz",
description = "Psychisches Bild, extrovertiert",
sqlCode = "HeSchleimFeuer",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.Extrovertiertheit,
Symptom.Unruhe,
Symptom.Gereiztheit,
Symptom.Verwirrung,
Symptom.VerwirrtesSprechen,
Symptom.GrundlosesLachen,
Symptom.Weinen,
Symptom.Schreien,
Symptom.Gewalttaetig,
Symptom.Schlafstoerungen,
Symptom.ThorakalesEngegefuehl,
Symptom.BittererMundgeschmack,
Symptom.Palpitationen,
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.GelberBelag,
Symptom.SchmierigerBelag,
Symptom.Dornen,
Symptom.BeschleunigterPuls,
Symptom.SchluepfrigerPuls,
Symptom.SaitenfoermigerPuls // Le einfluss
)
),
HeSchleimKaelteVerstopft(
label = "Kalter Schleim verstopft die Herzöffnungen",
description = "Psychisches Bild, extrovertiert",
sqlCode = "HeSchleimKaelte",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.Introvertiertheit,
Symptom.Verwirrung,
Symptom.GetruebteBewusstsein,
Symptom.Lethargie,
Symptom.Depression,
Symptom.Selbstgespraeche,
Symptom.DahinStarren,
Symptom.NichtReden,
Symptom.Bewusstseinsverlust,
Symptom.RasselndeKehle, // beim einatmen
Symptom.BlasseZunge,
Symptom.DickerBelag,
Symptom.WeisserBelag,
Symptom.SchmierigerBelag,
Symptom.VerlangsamterPuls,
Symptom.SchluepfrigerPuls
)
),
// MILZ
// =================================================================================================================
MPQiXu(
label = "Milz Qi Mangel",
sqlCode = "MPQiXu",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.QiXu.symptoms + SpecificSymptoms.MPQiXu
),
MPYangXu(
label = "Milz Yang Mangel",
sqlCode = "MPYangXu",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Mangel,
symptoms = SpecificSymptoms.MPQiXu + GeneralSymptoms.YangXu.symptoms + listOf(
Symptom.KalterBauch,
Symptom.Unterbauchschmerzen,
Symptom.Kraempfe, // durch waerme gelindert
Symptom.Oedeme,
// verdauung
Symptom.WeicherStuhl,
Symptom.WaessrigerStuhl,
Symptom.UnverdauteNahrungInStuhl,
Symptom.HahnenschreiDiarrhoe,
// zunge
Symptom.LeichtBlaeulicheZunge,
Symptom.NasseZunge,
// puls
Symptom.TieferPuls,
Symptom.LangsamerPuls
)
),
MPYangXuAbsinkenQi(
label = "Absinkendes Milz-Qi",
sqlCode = "MPQiAbsinken",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Mangel,
symptoms = MPYangXu.symptoms + listOf(
Symptom.UntenZiehendeBauchorgane,
Symptom.Prolaps, // "Organsenkung" // von bauch- und unterleibsorgane: magen, darm, nieren, blase, uterus, scheide
Symptom.Schweregefuehl,
Symptom.Hernien,
Symptom.Krampfadern,
Symptom.Haemorrhoiden
)
),
MPYangXuBlutUnkontrolle(
label = "Milz kann das Blut nicht kontrollieren",
sqlCode = "MPBlutUnkontrolle",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Mangel,
symptoms = MPYangXu.symptoms + listOf(
Symptom.Petechien,
Symptom.Purpura,
Symptom.BlaueFlecken,
Symptom.Blutsturz,
Symptom.Hypermenorrhoe,
Symptom.Schmierblutung,
Symptom.BlutInUrin,
Symptom.BlutImStuhl
)
),
MPFeuchtKalt(
label = "Kälte und Feuchtigkeit in Milz",
sqlCode = "MPFeuchtKalt",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
// schwere
Symptom.Muedigkeit,
Symptom.Schlappheit,
Symptom.SchwererKopf,
Symptom.SchwereGliedmassen,
// trinken, essen
Symptom.KeinDurst,
Symptom.WenigDurst,
Symptom.KeinAppetit,
Symptom.VerminderterGeschmackssinn,
Symptom.FaderMundgeschmack,
Symptom.BlanderMundgeschmack,
// verdauung
Symptom.VoelleGefuehl,
Symptom.DurckgefuehlBauch,
Symptom.Uebelkeit,
Symptom.Brechreiz,
Symptom.Erbrechen,
Symptom.WeicherStuhl,
Symptom.KlebrigerStuhl,
Symptom.TrueberUrin,
// misc
Symptom.ThorakalesEngegefuehl,
Symptom.Bauchschmerzen, // besser waerme
Symptom.KaelteGefuehl,
Symptom.Ausfluss,
Symptom.Gelbsucht,
// zunge
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.DickerBelag,
Symptom.WeisserBelag,
// puls
Symptom.SchluepfrigerPuls,
Symptom.VerlangsamterPuls
)
),
MPFeuchtHitze(
label = "Hitze und Feuchtigkeit in Milz",
sqlCode = "MPFeuchtHitze",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.ThorakalesEngegefuehl,
Symptom.DurckgefuehlBauch,
Symptom.Brechreiz,
Symptom.Uebelkeit,
Symptom.Erbrechen,
Symptom.Schlappheit,
Symptom.Schweregefuehl,
Symptom.WenigUrin,
Symptom.KonzentrierterUrin,
Symptom.TrueberUrin,
Symptom.Durst,
Symptom.Bauchschmerzen,
Symptom.AversionWaerme,
Symptom.WeicherStuhl,
Symptom.StinkenderStuhl,
Symptom.Durchfall,
Symptom.AnalesBrennen,
Symptom.Fieber,
Symptom.Gelbsucht,
Symptom.RoteZunge,
Symptom.GelberBelag,
Symptom.DickerBelag,
Symptom.SchmierigerBelag,
Symptom.BeschleunigterPuls,
Symptom.SchluepfrigerPuls
)
),
// LUNGE
// =================================================================================================================
LuQiXu(
label = "Lu-Qi-Mangel",
sqlCode = "LuQiXu",
description = "Hat etwas von einer Art Depression aber ohne der Trauer.",
organ = ZangOrgan.Lung,
part = SyndromePart.Qi,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.QiXu.symptoms + listOf(
Symptom.Kurzatmigkeit,
Symptom.Husten,
Symptom.DuennerSchleim,
Symptom.VielSchleim,
Symptom.Asthma,
Symptom.FlacheAtmung,
Symptom.WenigLeiseSprechen,
Symptom.EnergieMangel,
Symptom.TrauererloseDepression,
Symptom.LeichtesSchwitzen,
Symptom.Erkaeltungen,
Symptom.AversionKaelte, // MINOR really? eigentlich erst bei YangXu...
Symptom.NormaleZunge,
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.SchwacherPuls,
Symptom.WeicherPuls,
Symptom.LeererPuls
)),
LuYinXu(
label = "Lu-Yin-Mangel",
sqlCode = "LuYinXu",
organ = ZangOrgan.Lung,
part = SyndromePart.Yin,
tendency = MangelUeberfluss.Mangel,
// TODO allg-YinMangel-symptoms + allg-QiMangel-symptoms
symptoms = LuQiXu.symptoms + listOf(
Symptom.Heiserkeit,
Symptom.TrockenerHals,
Symptom.TrockenerHusten,
Symptom.HitzeGefuehlAbends,
Symptom.KeinSchleim,
Symptom.WenigSchleim,
Symptom.KlebrigerSchleim,
Symptom.BlutInSchleim,
Symptom.RoteZunge,
Symptom.TrockeneZunge,
Symptom.WenigBelag,
Symptom.BeschleunigterPuls,
Symptom.DuennerPuls
)),
LuWindKaelteWind(
label = "Wind-Kälte attackiert Lu (Invasion äußerer Wind)",
sqlCode = "LuWind",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LuWindKaelte + listOf(
Symptom.AversionWind,
Symptom.FroestelnStarkerAlsFieber,
Symptom.KratzenderHals,
Symptom.Kopfschmerzen,
Symptom.Schwitzen
)
),
LuWindKaelteKaelte(
label = "Wind-Kälte attackiert Lu (Invasion äußere Kälte)",
sqlCode = "LuKalt",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LuWindKaelte + listOf(
Symptom.AversionKaelte,
Symptom.FroestelnStarkerAlsFieber,
Symptom.KeinSchwitzen,
Symptom.WenigDurst,
Symptom.KeinDurst,
Symptom.Husten,
Symptom.Schnupfen,
Symptom.KlarerSchleim,
Symptom.WaessrigerSchleim,
Symptom.VerstopfteNase,
Symptom.Muskelschmerzen,
Symptom.Kopfschmerzen
)
),
LuWindHitze(
label = "Wind-Hitze attackiert Lu",
sqlCode = "LuHitze",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
// TODO plus symptoms of ExoWind; evtl plus HitzeSymptoms
symptoms = listOf(
Symptom.FieberStaerkerAlsFroesteln,
Symptom.Schwitzen,
Symptom.Husten,
Symptom.GelberSchleim,
Symptom.VerstopfteNase,
Symptom.Schnupfen,
Symptom.Halsschmerzen,
Symptom.RoterHals,
Symptom.RoterRachen,
Symptom.MehrDurst,
Symptom.MoechteKaltesTrinken,
Symptom.RoteZungenspitze,
Symptom.DuennerBelag,
Symptom.GelberBelag,
Symptom.OberflaechlicherPuls,
Symptom.BeschleunigterPuls
)
),
LuTrocken(
label = "Trockenheit attackiert Lu",
sqlCode = "LuTrocken",
description = "Keine wirklichen Hitze Symptome.",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.TrockenerMund,
Symptom.TrockeneNase,
Symptom.TrockenerRachen,
Symptom.TrockenerHals,
Symptom.TrockenerHusten,
Symptom.Nasenbluten,
Symptom.Heiserkeit,
Symptom.LeichteKopfschmerzen,
// schleim
Symptom.WenigSchleim,
Symptom.KeinSchleim,
Symptom.ZaeherSchleim,
Symptom.BlutInSchleim,
Symptom.RoteZungenspitze,
Symptom.GelberBelag,
Symptom.DuennerBelag,
Symptom.TrockenerBelag,
Symptom.OberflaechlicherPuls,
Symptom.BeschleunigterPuls
)
),
// @LuSchleim generell:
// - MP produziert schleim, Lu lagert ihn
// - ursachen: MP-Qi/Yang-Mangel, Lu-Qi-Mangel
LuSchleimKalt(
label = "Kalte Schleimretention in Lu",
sqlCode = "LuSchleimKalt",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LuSchleim + listOf(
Symptom.WeisserSchleim,
Symptom.TrueberSchleim,
Symptom.Blaesse,
Symptom.Muedigkeit,
Symptom.KaelteGefuehl,
Symptom.WeisserBelag,
Symptom.LangsamerPuls
)
),
LuSchleimHeiss(
label = "Heisse Schleimretention in Lu",
sqlCode = "LuSchleimHeiss",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LuSchleim + listOf(
Symptom.GelberSchleim,
Symptom.Fieber,
Symptom.HitzeZeichen,
Symptom.GelberBelag,
Symptom.BraunerBelag,
Symptom.BeschleunigterPuls
)
),
// NIERE
// =================================================================================================================
NiYinXu(
label = "Nieren Yin Mangel",
sqlCode = "NiYinXu",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.YinXu.symptoms + listOf(
// schmerzen unten
Symptom.SchmerzenLumbalregion,
Symptom.KnieSchmerzen,
Symptom.FersenSchmerzen,
// sex
Symptom.VermehrteLibido,
Symptom.SexuelleTraeme,
Symptom.VerfruehteEjakulation,
Symptom.NaechtlicheEjakulation,
Symptom.MenstruationBeeinflusst,
// ohren
Symptom.Tinnitus,
Symptom.Hoerverlust,
//misc
Symptom.GedaechtnisStoerungen,
Symptom.Schwindel,
// zunge
Symptom.RoterBelag,
Symptom.DuennerBelag,
Symptom.FehlenderBelag,
// puls
Symptom.DuennerPuls,
Symptom.BeschleunigterPuls
)
),
NiYangXu(
label = "Nieren Yang Mangel",
sqlCode = "NiYangXu",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.YangXu.symptoms + listOf(
Symptom.GedaechtnisStoerungen,
Symptom.Zahnausfall,
Symptom.Oedeme,
// schmerzen unten
Symptom.SchmerzenLumbalregion,
Symptom.KnieSchmerzen,
Symptom.FersenSchmerzen,
// sex
Symptom.VerminderteLibido,
Symptom.Unfruchtbarkeit,
Symptom.Impotenz,
Symptom.Spermatorrhoe,
Symptom.Ausfluss,
// ohren
Symptom.HoervermoegenVermindert,
Symptom.Tinnitus,
// urin
Symptom.KlarerUrin,
Symptom.HellerUrin,
Symptom.ReichlichUrin,
Symptom.WenigUrin,
// MP auch beeinflusst
Symptom.VerdauungAllgemein,
Symptom.BreiigerStuhl,
Symptom.HahnenschreiDiarrhoe,
// zunge
Symptom.BlasseZunge,
Symptom.VergroesserteZunge,
Symptom.DuennerBelag,
Symptom.WeisserBelag,
// puls
Symptom.TieferPuls,
Symptom.SchwacherPuls,
Symptom.VerlangsamterPuls
)
),
NiYangXuUeberfliessenWasser(
label = "Nieren Yang Mangel mit Überfließen des Wassers",
sqlCode = "NiYangXuUeber",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = NiYangXu.symptoms + listOf(
Symptom.Palpitationen, // MINOR hat fix palpitationen! obwohl das eher bei blut-xu vorkommt, vesteh ich nicht
// Lu beeinflusst
Symptom.Husten,
Symptom.Atemnot,
// wasser
Symptom.StarkeOedemeBeine,
Symptom.LungenOedem,
Symptom.Wasserbauch,
// zunge
Symptom.GeschwolleneZunge,
Symptom.DickerBelag,
// puls
Symptom.HaftenderPuls
)
),
NiYangXuFestigkeitXu(
label = "Mangelnde Festigkeit des Nieren Qi",
sqlCode = "NiYangXuFest",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = listOf(// MINOR why not include NiYang symptoms?
// sex
Symptom.Spermatorrhoe,
Symptom.NaechtlicheEjakulation,
Symptom.SexuelleTraeume,
Symptom.VerfruehteEjakulation,
Symptom.Ausfluss,
Symptom.Unfruchtbarkeit,
// urin
Symptom.HaeufigesUrinieren,
Symptom.ReichlichUrin,
Symptom.KlarerUrin,
Symptom.Nachttroepfeln,
Symptom.Harninkontinenz,
// zunge
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
// puls
Symptom.TieferPuls,
Symptom.SchwacherPuls
)
),
NiYangXuQiEinfangen(
label = "Unfähigkeit der Nieren das Qi einzufangen",
sqlCode = "NiYangXuFangen",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = listOf(// MINOR why not include NiYang symptoms?
// Lu
Symptom.Atemnot,
Symptom.Kurzatmigkeit,
Symptom.Asthma,
Symptom.Husten,
Symptom.LeiseSprechen,
Symptom.SchwacheStimme,
Symptom.Infektanfaelligkeit,
// misc
Symptom.KreuzSchmerzen,
Symptom.ReichlichUrin,
Symptom.HellerUrin,
// zunge
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.DuennerBelag,
Symptom.WeisserBelag,
// puls
Symptom.TieferPuls,
Symptom.DuennerPuls,
Symptom.SchwacherPuls,
Symptom.OberflaechlicherPuls,
Symptom.LeererPuls
)
),
NiJingPraenatalXu(
label = "Nieren Jing Mangel (Pränatal)",
sqlCode = "NiJingXuPre",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = listOf(
Symptom.VerzoegerteGeistigeEntwicklung,
Symptom.VerzoegerteKoerperlicheEntwicklung,
Symptom.VerzoegerteKnochenEntwicklung,
Symptom.VeroegertesWachstum,
Symptom.VerzoegerteReifung,
Symptom.GestoerteZahnentwicklung,
Symptom.Hoerstoerung
)
),
NiJingPostnatalXu(
label = "Nieren Jing Mangel (Postnatal)",
sqlCode = "NiJingXuPost",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = listOf(
Symptom.VerfruehtesSenium,
// MINOR rename Probleme to Allgemein
Symptom.ProblemeUntererRuecken,
Symptom.ProblemeKnie,
Symptom.ProblemeFussknoechel,
Symptom.ProblemeKnochen,
Symptom.ProblemeZaehne,
Symptom.ProblemeGedaechtnis,
Symptom.ProblemeGehirn,
Symptom.ProblemeOhren,
Symptom.ProblemeHaare
)
)
}
data class GeneralSymptom(
val yy: YinYang,
val substance: Substances? = null,
val symptoms: List<Symptom>
// val mangel = MangelUeberfluss.Mangel
)
object GeneralSymptoms {
val BlutXu = GeneralSymptom(
yy = YinYang.Yin,
substance = Substances.Xue,
symptoms = listOf(
Symptom.FahleBlaesse,
Symptom.Palpitationen,
Symptom.TaubheitsgefuehlExtremitaeten,
// psycho
Symptom.Konzentrationsstoerungen,
Symptom.Schreckhaftigkeit,
Symptom.Schlafstoerungen
)
)
val YinXu = GeneralSymptom(// hat HITZE
yy = YinYang.Yin,
symptoms = BlutXu.symptoms + listOf(
// psycho
Symptom.Unruhe,
Symptom.Nervoesitaet,
// hitze
Symptom.RoteWangenflecken,
Symptom.FuenfZentrenHitze,
Symptom.Nachtschweiss,
Symptom.HitzeGefuehlAbends,
Symptom.TrockenerMund,
Symptom.TrockenerHals,
Symptom.Halsschmerzen, // haeufig, leichte
Symptom.Durst, // mehr? MehrDurstSpaeter?
// verdauung
Symptom.DunklerUrin,
Symptom.KonzentrierterUrin,
Symptom.Verstopfung,
Symptom.Durchfall
))
val QiXu = GeneralSymptom(
yy = YinYang.Yin,
substance = Substances.Qi,
symptoms = listOf(
Symptom.LeuchtendeBlaesse,
Symptom.Muedigkeit,
Symptom.Schwaeche,
Symptom.AnstrengungSchnellErschoepft
))
val YangXu = GeneralSymptom(
// looks cold, feels cold
yy = YinYang.Yin,
symptoms = QiXu.symptoms + listOf(
Symptom.KalteHaende,
Symptom.KalteFuesse,
Symptom.KaelteGefuehl,
Symptom.AversionKaelte,
// MINOR engegefuehl (auch bei NiYangXu?)
// MINOR schmerzen
Symptom.Kontraktionen,
Symptom.Lethargie,
Symptom.Antriebslosigkeit
))
val LeWind = listOf(
Symptom.PloetzlicheBewegungen,
Symptom.UnkoordinierteBewegungen,
Symptom.Zuckungen,
Symptom.Tics,
Symptom.Augenzucken,
Symptom.AllgemeineUnregelmaessigkeiten,
Symptom.OberkoerperStaerkerBetroffen,
Symptom.KopfStaerkerBetroffen,
Symptom.YangLokalisationenStaerkerBetroffen
)
val LuSchleim = listOf(
Symptom.ThorakalesEngegefuehl,
Symptom.VoelleGefuehl,
Symptom.Atemnot,
Symptom.Asthma,
Symptom.Husten,
Symptom.VielSchleim,
Symptom.RasselndeKehle,
Symptom.WenigAppetit,
Symptom.Breichreiz,
Symptom.DickerBelag,
Symptom.FeuchterBelag,
Symptom.SchmierigerBelag,
Symptom.SchluepfrigerPuls,
Symptom.OberflaechlicherPuls
)
val LuWindKaelte = listOf(
Symptom.NormaleZunge,
Symptom.WeisserBelag,
Symptom.VermehrterBelag,
Symptom.DuennerBelag,
Symptom.OberflaechlicherPuls,
Symptom.GespannterPuls,
Symptom.VerlangsamterPuls
)
val HeYangXuPulsTongue = listOf(
Symptom.VersteckterPuls,
Symptom.SchwacherPuls,
Symptom.UnregelmaessigerPuls,
Symptom.RauherPuls,
Symptom.BlaeulicheZunge,
Symptom.GeschwolleneZunge,
Symptom.GestauteUnterzungenvenen // stark geschwollen
)
}
object SpecificSymptoms {
val HeBlutXu = listOf(
Symptom.Schwindel,
Symptom.Aengstlichkeit,
Symptom.VieleTraeume,
Symptom.SchlechteMerkfaehigkeit,
Symptom.BlasseZunge,
Symptom.DuennerPuls
)
val HeQiXu = listOf(
Symptom.Palpitationen,
Symptom.Kurzatmigkeit,
Symptom.StarkesSchwitzen, // va am tag
Symptom.MentaleMuedigkeit,
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.LaengsrissInZunge,
Symptom.SchwacherPuls,
Symptom.LeererPuls,
Symptom.UnregelmaessigerPuls
)
val MPQiXu = listOf(
Symptom.WenigAppetit,
Symptom.VoelleGefuehl,
Symptom.Blaehungen,
Symptom.Aufstossen,
Symptom.LeichteSchmerzenOberbauch,
Symptom.BreiigerStuhl,
Symptom.EnergieMangel,
Symptom.Ausgezehrt,
Symptom.KraftloseMuskeln,
Symptom.OedemeBauch,
Symptom.Zwischenblutung,
Symptom.KurzeMensZyklen,
Symptom.HelleBlutung,
Symptom.ReichlichBlutung,
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.Zahneindruecke,
Symptom.DuennerBelag,
Symptom.WeisserBelag,
Symptom.SchwacherPuls,
Symptom.WeicherPuls,
Symptom.LeererPuls
)
}
| apache-2.0 | 135bd0ecd8355b360be49eae3b389e56 | 36.553906 | 163 | 0.489317 | 3.634432 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/quests/QuestDetailViewModel.kt | 1 | 2135 | package com.ghstudios.android.features.quests
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import android.util.Log
import com.ghstudios.android.data.classes.*
import com.ghstudios.android.data.DataManager
import com.ghstudios.android.util.loggedThread
import com.ghstudios.android.util.toList
/**
* A ViewModel for the entirety of quest detail data.
* This should be attached to the activity or fragment owning the viewpager.
*/
class QuestDetailViewModel(app : Application) : AndroidViewModel(app) {
private val dataManager = DataManager.get()
val rewards = MutableLiveData<List<QuestReward>>()
val monsters = MutableLiveData<List<MonsterToQuest>>()
val quest = MutableLiveData<Quest>()
val gatherings = MutableLiveData<List<Gathering>>()
val huntingRewards = MutableLiveData<List<HuntingReward>>()
fun setQuest(questId: Long): Quest? {
if (questId == quest.value?.id) {
return quest.value!!
}
val quest = dataManager.getQuest(questId)
this.quest.value = quest
if (quest == null) {
Log.e(this.javaClass.simpleName, "Quest id is unexpectedly null")
return null
}
loggedThread("Quest Load") {
monsters.postValue(dataManager.queryMonsterToQuestQuest(questId).toList { it.monsterToQuest })
rewards.postValue(dataManager.queryQuestRewardQuest(questId).toList { it.questReward })
if (quest.hasGatheringItem) {
val locationId = quest.location?.id ?: -1
val gatherData = dataManager.queryGatheringForQuest(quest.id, locationId, quest.rank ?: "").toList {
it.gathering
}
gatherings.postValue(gatherData)
}else if(quest.hasHuntingRewardItem){
val rewardData = dataManager.queryHuntingRewardForQuest(quest.id,quest.rank?:"").toList {
it.huntingReward
}
huntingRewards.postValue(rewardData)
}
}
return quest
}
} | mit | 4899763234aca9a84c2d19d41dd5eef7 | 35.827586 | 116 | 0.66089 | 4.631236 | false | false | false | false |
eugeis/ee | ee-lang/src/main/kotlin/ee/lang/gen/ts/TsCommon.kt | 1 | 14546 | package ee.lang.gen.ts
import ee.common.ext.*
import ee.design.EntityI
import ee.lang.*
import ee.lang.gen.java.j
import javax.swing.text.html.parser.Entity
fun <T : TypeI<*>> T.toTypeScriptDefault(c: GenerationContext, derived: String, attr: AttributeI<*>): String {
val baseType = findDerivedOrThis()
return when (baseType) {
n.String, n.Text -> "''"
n.Boolean -> "false"
n.Int -> "0"
n.Long -> "0L"
n.Float -> "0f"
n.Date -> "${c.n(j.util.Date)}()"
n.Path -> "${c.n(j.nio.file.Paths)}.get('')"
n.Blob -> "new ByteArray(0)"
n.Void -> ""
n.Error -> "new Throwable()"
n.Exception -> "new Exception()"
n.Url -> "${c.n(j.net.URL)}('')"
n.Map -> (attr.isNotEMPTY() && attr.isMutable().setAndTrue()).ifElse("new Map()", "new Map()")
n.List -> (attr.isNotEMPTY() && attr.isMutable().setAndTrue()).ifElse("new Array()", "new Array()")
else -> {
if (baseType is LiteralI<*>) {
"${(baseType.findParent(EnumTypeI::class.java) as EnumTypeI<*>).toTypeScript(c, derived,
attr)}.${baseType.toTypeScript()}"
} else if (baseType is EnumTypeI<*>) {
"${c.n(this, derived)}.${baseType.literals().first().toTypeScript()}"
} else if (baseType is CompilationUnitI<*>) {
"new ${c.n(this, derived)}()"
} else {
(this.parent() == n).ifElse("''", { "${c.n(this, derived)}.EMPTY" })
}
}
}
}
fun <T : AttributeI<*>> T.toTypeScriptDefault(c: GenerationContext, derived: String): String =
type().toTypeScriptDefault(c, derived, this)
fun <T : ItemI<*>> T.toTypeScriptEMPTY(c: GenerationContext, derived: String): String =
(this.parent() == n).ifElse("''", { "${c.n(this, derived)}.EMPTY" })
fun <T : AttributeI<*>> T.toTypeScriptEMPTY(c: GenerationContext, derived: String): String =
type().toTypeScriptEMPTY(c, derived)
fun <T : AttributeI<*>> T.toTypeScriptTypeSingle(c: GenerationContext, api: String): String =
type().toTypeScript(c, api, this)
fun <T : AttributeI<*>> T.toTypeScriptTypeDef(c: GenerationContext, api: String): String =
"""${type().toTypeScript(c, api, this)}${isNullable().then("?")}"""
fun <T : AttributeI<*>> T.toTypeScriptCompanionObjectName(c: GenerationContext): String =
""" val ${name().toUnderscoredUpperCase()} = "_${name()}""""
fun <T : CompilationUnitI<*>> T.toTypeScriptExtends(c: GenerationContext, derived: String, api: String): String {
if (superUnit().isNotEMPTY() && derived != api) {
return " extends ${c.n(superUnit(), derived)}, ${c.n(this, api)}"
} else if (superUnit().isNotEMPTY()) {
return " extends ${c.n(superUnit(), derived)}"
} else if (derived != api) {
return " extends ${c.n(this, api)}"
} else {
return ""
}
}
fun <T : TypeI<*>> T.toTypeScriptIfNative(c: GenerationContext, derived: String, attr: AttributeI<*>): String? {
val baseType = findDerivedOrThis()
return when (baseType) {
n.Any -> "any"
n.String -> "string"
n.Boolean -> "boolean"
n.Int -> "number"
n.Long -> "number"
n.Float -> "number"
n.Date -> "Date"
n.TimeUnit -> "string"
n.Path -> "string"
n.Text -> "string"
n.Blob -> "Blob"
n.Exception -> "Error"
n.Error -> "Error"
n.Void -> "void"
n.Url -> "string"
n.UUID -> "string"
n.List -> "Array${toTypeScriptGenericTypes(c, derived, attr)}"
n.Map -> "Map${toTypeScriptGenericTypes(c, derived, attr)}"
else -> {
if (this is LambdaI<*>) operation().toTypeScriptLambda(c, derived) else null
}
}
}
fun TypeI<*>.toTypeScriptGenericTypes(c: GenerationContext, derived: String, attr: AttributeI<*>): String =
generics().joinWrappedToString(", ", "", "<", ">") { it.type().toTypeScript(c, derived, attr) }
fun GenericI<*>.toTypeScript(c: GenerationContext, derived: String): String = c.n(type(), derived)
fun TypeI<*>.toTypeScriptGenerics(c: GenerationContext, derived: String, attr: AttributeI<*>): String =
generics().joinWrappedToString(", ", "", "<", ">") { it.toTypeScript(c, derived, attr) }
fun TypeI<*>.toTypeScriptGenericsClassDef(c: GenerationContext, derived: String, attr: AttributeI<*>): String =
generics().joinWrappedToString(", ", "", "<", ">") {
"${it.name()} : ${it.type().toTypeScript(c, derived, attr)}"
}
fun TypeI<*>.toTypeScriptGenericsMethodDef(c: GenerationContext, derived: String, attr: AttributeI<*>): String =
generics().joinWrappedToString(", ", "", "<", "> ") {
"${it.name()} : ${it.type().toTypeScript(c, derived, attr)}"
}
fun TypeI<*>.toTypeScriptGenericsStar(context: GenerationContext, derived: String): String =
generics().joinWrappedToString(", ", "", "<", "> ") { "*" }
fun OperationI<*>.toTypeScriptGenerics(c: GenerationContext, derived: String): String =
generics().joinWrappedToString(", ", "", "<", "> ") {
"${it.name()} : ${it.type().toTypeScript(c, derived)}"
}
fun <T : TypeI<*>> T.toTypeScript(c: GenerationContext, derived: String,
attr: AttributeI<*> = Attribute.EMPTY): String =
toTypeScriptIfNative(c, derived, attr) ?: "${c.n(this, derived)}${this.toTypeScriptGenericTypes(c, derived, attr)}"
fun <T : AttributeI<*>> T.toTypeScriptValue(c: GenerationContext, derived: String): String {
if (value() != null) {
return when (type()) {
n.String, n.Text -> "\"${value()}\""
n.Boolean, n.Int, n.Long, n.Float, n.Date, n.Path, n.Blob, n.Void -> "${value()}"
else -> {
if (value() is LiteralI<*>) {
val lit = value() as LiteralI<*>
"${(lit.parent() as EnumTypeI<*>).toTypeScript(c, derived, this)}.${lit.toTypeScript()}"
} else {
"${value()}"
}
}
}
} else {
return toTypeScriptDefault(c, derived)
}
}
fun <T : AttributeI<*>> T.toTypeScriptInit(c: GenerationContext, derived: String): String {
if (value() != null) {
return " = ${toTypeScriptValue(c, derived)}"
} else if (isNullable()) {
return " = null"
} else if (isInitByDefaultTypeValue()) {
return " = ${toTypeScriptValue(c, derived)}"
} else {
return ""
}
}
fun <T : AttributeI<*>> T.toTypeScriptInitMember(c: GenerationContext, derived: String): String =
"this.${name()}${toTypeScriptInit(c, derived)}"
fun <T : AttributeI<*>> T.toTypeScriptSignature(c: GenerationContext, derived: String, api: String,
init: Boolean = true): String =
"${name()}: ${toTypeScriptTypeDef(c, api)}${init.then { toTypeScriptInit(c, derived) }}"
fun <T : AttributeI<*>> T.toTypeScriptConstructorMember(c: GenerationContext, derived: String, api: String,
init: Boolean = true): String =
//"${isReplaceable().setAndTrue().ifElse("", "readonly ")}${toTypeScriptSignature(c, derived, api, init)}"
"${toTypeScriptSignature(c, derived, api, init)}"
fun <T : AttributeI<*>> T.toTypeScriptMember(c: GenerationContext, derived: String, api: String,
init: Boolean = true, indent: String): String =
//" ${isReplaceable().setAndTrue().ifElse("", "readonly ")}${toTypeScriptSignature(c, derived, api, init)}"
"${indent}${toTypeScriptSignature(c, derived, api, init)}"
fun List<AttributeI<*>>.toTypeScriptSignature(c: GenerationContext, derived: String, api: String): String =
joinWrappedToString(", ") { it.toTypeScriptSignature(c, derived, api) }
fun List<AttributeI<*>>.toTypeScriptMember(c: GenerationContext, derived: String, api: String): String =
joinWrappedToString(", ") { it.toTypeScriptSignature(c, derived, api) }
fun <T : ConstructorI<*>> T.toTypeScriptPrimary(c: GenerationContext, derived: String, api: String): String {
return if (isNotEMPTY()) """(${params().joinWrappedToString(", ", " ") {
it.toTypeScriptConstructorMember(c, derived, api)
}})${superUnit().toTypeScriptCall(c)}""" else ""
}
fun <T : ConstructorI<*>> T.toTypeScript(c: GenerationContext, derived: String, api: String): String {
return if (isNotEMPTY()) """
constructor(${params().joinWrappedToString(", ", " ") {
it.toTypeScriptSignature(c, derived, api)
}}) {${superUnit().isNotEMPTY().then {
(superUnit() as ConstructorI<*>).toTypeScriptCall(c, (parent() != superUnit().parent()).ifElse("super", "this"))
}} ${paramsWithOut(superUnit()).joinSurroundIfNotEmptyToString("${nL} ", prefix = "{${nL} ") {
it.toTypeScriptAssign(c)
}}${(parent() as CompilationUnitI<*>).props().filter { it.isMeta() }.joinSurroundIfNotEmptyToString("${nL} ",
prefix = "${nL} ") {
it.toTypeScriptInitMember(c, derived)
}}
}""" else ""
}
fun <T : ConstructorI<*>> T.toTypeScriptCall(c: GenerationContext, name: String = "this"): String =
isNotEMPTY().then { " : $name(${params().joinWrappedToString(", ") { it.name() }})" }
fun <T : AttributeI<*>> T.toTypeScriptAssign(c: GenerationContext): String = "this.${name()} = ${name()}"
fun <T : LogicUnitI<*>> T.toTypeScriptCall(c: GenerationContext): String =
isNotEMPTY().then { "(${params().joinWrappedToString(", ") { it.name() }})" }
fun <T : LogicUnitI<*>> T.toTypeScriptCallValue(c: GenerationContext, derived: String): String =
isNotEMPTY().then { "(${params().joinWrappedToString(", ") { it.toTypeScriptValue(c, derived) }})" }
fun <T : LiteralI<*>> T.toTypeScriptCallValue(c: GenerationContext, derived: String): String =
params().isNotEmpty().then { "(${params().joinWrappedToString(", ") { it.toTypeScriptValue(c, derived) }})" }
fun <T : AttributeI<*>> T.toTypeScriptType(c: GenerationContext, derived: String): String =
type().toTypeScript(c, derived, this)
fun List<AttributeI<*>>.toTypeScriptTypes(c: GenerationContext, derived: String): String =
joinWrappedToString(", ") { it.toTypeScriptType(c, derived) }
fun <T : OperationI<*>> T.toTypeScriptLambda(c: GenerationContext, derived: String): String =
"""(${params().toTypeScriptTypes(c, derived)}) -> ${retFirst().toTypeScriptType(c, derived)}"""
fun <T : OperationI<*>> T.toTypeScriptImpl(c: GenerationContext, derived: String, api: String): String {
return """
${toTypeScriptGenerics(c, derived)}${name()}(${params().toTypeScriptSignature(c, derived,
api)}): ${retFirst().toTypeScriptTypeDef(c, api)} {
throw new ReferenceError('Not implemented yet.');
}"""
}
fun <T : ItemI<*>> T.toAngularBasicGenerateComponentPart(c: GenerationContext): String =
"""@${c.n("Component")}({
selector: 'app-${this.name().toLowerCase()}',
templateUrl: './${this.name().toLowerCase()}-basic.component.html',
styleUrls: ['./${this.name().toLowerCase()}-basic.component.scss'],
})
"""
fun <T : ItemI<*>> T.toAngularListOnInit(indent: String): String {
return """${indent}ngOnInit(): void {
this.tableHeader = this.generateTableHeader();
this.${this.name().toLowerCase()}DataService.checkSearchRoute();
if (this.${this.name().toLowerCase()}DataService.isSearch) {
this.${this.name().toLowerCase()}DataService.loadSearchData()
} else {
this.${this.name().toLowerCase()}DataService.dataSources =
new MatTableDataSource(this.${this.name().toLowerCase()}DataService.changeMapToArray(
this.${this.name().toLowerCase()}DataService.retrieveItemsFromCache()));
}
}"""
}
/*when (this.type().props().size) {
0 -> """'${this.name().toCamelCase()}'"""
else -> {
this.type().props().filter { !it.isMeta() }.joinSurroundIfNotEmptyToString(", ") {
it.toTypeScriptTypeProperty(c, this)
}
}
}*/
fun <T : AttributeI<*>> T.toAngularGenerateTableHeader(c: GenerationContext): String {
return when (this.type()) {
is EntityI<*>, is ValuesI<*> -> """'${this.name().toLowerCase()}-entity'"""
else -> {
when (this.type().toTypeScriptIfNative(c, "", this)) {
"boolean", "string", "number", "Date" -> """'${this.name().toCamelCase()}'"""
else -> {
when (this.type().props().size) {
0 -> """'${this.name().toCamelCase()}'"""
else -> {
this.type().props().filter { !it.isMeta() }.joinSurroundIfNotEmptyToString(", ") {
it.toTypeScriptTypeProperty(c, this)
}
}
}
}
}
}
}
}
fun <T : AttributeI<*>> T.toTypeScriptTypeProperty(c: GenerationContext, elementParent: AttributeI<*>): String {
return when (this.type()) {
is EntityI<*>, is ValuesI<*> -> """'${this.name().toLowerCase()}-entity'"""
else -> {
when (this.type().props().size) {
0 -> """'${this.name().toCamelCase()}'"""
else -> {
this.type().props().filter { !it.isMeta() }.joinSurroundIfNotEmptyToString(", ") {
it.toTypeScriptTypeProperty(c, elementParent)
}
}
}
}
}
}
fun <T : AttributeI<*>> T.toTypeScriptInitEmptyProps(c: GenerationContext): String {
return when (this.type().toTypeScriptIfNative(c, "", this)) {
"boolean", "string", "number", "Date" -> ""
else -> {
when (this.type().props().size) {
0 -> ""
else -> {
"""
if (this.${this.parent().name().toLowerCase()}.${this.name().toCamelCase()} === undefined) {
this.${this.parent().name().toLowerCase()}.${this.name().toCamelCase()} = new ${c.n(this.type()).capitalize()}();
}"""
}
}
}
}
}
| apache-2.0 | 53c89e8d2bcdee49482b4f7119d61d6d | 44.598746 | 125 | 0.560635 | 4.096311 | false | false | false | false |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/renderer/JsonAdapterFactoryRenderer.kt | 1 | 9094 | package se.ansman.kotshi.renderer
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.moshi.JsonAdapter
import se.ansman.kotshi.*
import se.ansman.kotshi.model.GeneratedAnnotation
import se.ansman.kotshi.model.JsonAdapterFactory
import se.ansman.kotshi.model.render
internal class JsonAdapterFactoryRenderer(
private val factory: JsonAdapterFactory,
private val createAnnotationsUsingConstructor: Boolean
) {
private val nameAllocator = NameAllocator()
fun render(generatedAnnotation: GeneratedAnnotation?, typeSpecModifier: TypeSpec.Builder.() -> Unit): FileSpec {
val annotations = mutableSetOf<AnnotationSpec>()
val properties = mutableSetOf<PropertySpec>()
val createFunction = makeCreateFunction(
typeParam = ParameterSpec(nameAllocator.newName("type"), Types.Java.type),
annotationsParam = ParameterSpec(
nameAllocator.newName("annotations"),
Types.Kotlin.set.parameterizedBy(Types.Kotlin.annotation)
),
moshiParam = ParameterSpec(nameAllocator.newName("moshi"), Types.Moshi.moshi),
annotations = annotations,
properties = properties,
)
return FileSpec.builder(factory.factoryClassName.packageName, factory.factoryClassName.simpleName)
.addFileComment("Code generated by Kotshi. Do not edit.")
.addAnnotation(
AnnotationSpec.builder(Types.Kotlin.suppress)
.addMember("%S", "EXPERIMENTAL_IS_NOT_ENABLED")
.addMember("%S", "REDUNDANT_PROJECTION")
.build()
)
.addType(
TypeSpec.objectBuilder(factory.factoryClassName)
.addModifiers(KModifier.INTERNAL)
.apply { generatedAnnotation?.toAnnotationSpec()?.let(::addAnnotation) }
.apply {
when (factory.usageType) {
JsonAdapterFactory.UsageType.Standalone -> addSuperinterface(Types.Moshi.jsonAdapterFactory)
is JsonAdapterFactory.UsageType.Subclass -> {
if (factory.usageType.parentIsInterface) {
addSuperinterface(factory.usageType.parent)
} else {
superclass(factory.usageType.parent)
}
}
}
}
.addAnnotations(annotations)
.addProperties(properties)
.addFunction(createFunction)
.apply(typeSpecModifier)
.addAnnotation(
AnnotationSpec.builder(Types.Kotlin.optIn)
.addMember("%T::class", Types.Kotshi.internalKotshiApi)
.build()
)
.build()
)
.build()
}
private fun makeCreateFunction(
typeParam: ParameterSpec,
annotationsParam: ParameterSpec,
moshiParam: ParameterSpec,
annotations: MutableSet<AnnotationSpec>,
properties: MutableSet<PropertySpec>,
): FunSpec {
val createSpec = FunSpec.builder("create")
.addModifiers(KModifier.OVERRIDE)
.returns(JsonAdapter::class.asClassName().parameterizedBy(STAR).nullable())
.addParameter(typeParam)
.addParameter(annotationsParam)
.addParameter(moshiParam)
if (factory.isEmpty) {
return createSpec
.addStatement("return null")
.build()
}
val rawType = PropertySpec.builder(nameAllocator.newName("rawType"), Types.Java.clazz.parameterizedBy(STAR))
.initializer("%M(%N)", Functions.Moshi.getRawType, typeParam)
.build()
return createSpec
.addCode("%L", rawType)
.applyIf(factory.manuallyRegisteredAdapters.isNotEmpty()) {
addRegisteredAdapters(typeParam, annotationsParam, moshiParam, rawType, annotations, properties)
}
.addGeneratedAdapters(typeParam, annotationsParam, moshiParam, rawType)
.build()
}
private fun FunSpec.Builder.addRegisteredAdapters(
typeParam: ParameterSpec,
annotationsParam: ParameterSpec,
moshiParam: ParameterSpec,
rawType: PropertySpec,
annotations: MutableSet<AnnotationSpec>,
properties: MutableSet<PropertySpec>,
): FunSpec.Builder = addControlFlow("when") {
for (adapter in factory.manuallyRegisteredAdapters.sorted()) {
addCode("%N·==·%T::class.java", rawType, adapter.targetType.rawType())
if (adapter.qualifiers.isNotEmpty()) {
val qualifiers = PropertySpec
.builder(
nameAllocator.newName(adapter.adapterClassName.simpleName.replaceFirstChar(Char::lowercaseChar) + "Qualifiers"),
Set::class.parameterizedBy(Annotation::class)
)
.addModifiers(KModifier.PRIVATE)
.initializer(CodeBlock.Builder()
.add("%M(⇥", Functions.Kotlin.setOf)
.applyEachIndexed(adapter.qualifiers) { i, qualifier ->
if (i > 0) add(",")
add("\n")
add(qualifier.render(createAnnotationsUsingConstructor))
}
.add("⇤\n)")
.build())
.build()
.also(properties::add)
addCode("·&&·\n⇥%N == %N⇤", annotationsParam, qualifiers)
}
if (adapter.requiresDeepTypeCheck) {
addCode(
"·&&·\n⇥%M(%M<%T>().%M, %N)⇤",
Functions.Kotshi.matches,
Functions.Kotlin.typeOf,
adapter.targetType.unwrapTypeVariables(),
Functions.Kotlin.javaType,
typeParam
)
annotations.add(AnnotationSpec.builder(Types.Kotlin.experimentalStdlibApi).build())
}
addCode("·->« return·")
val constructor = adapter.constructor
if (constructor == null) {
addCode("%T", adapter.adapterTypeName)
} else {
addAdapterConstructorCall(
adapterTypeName = adapter.adapterTypeName,
constructor = adapter.constructor,
moshiParam = moshiParam,
typeParam = typeParam,
)
}
addCode("»\n")
}
}
private fun FunSpec.Builder.addGeneratedAdapters(
typeParam: ParameterSpec,
annotationsParam: ParameterSpec,
moshiParam: ParameterSpec,
rawType: PropertySpec,
): FunSpec.Builder =
if (factory.generatedAdapters.isEmpty()) {
addCode("return·null")
} else {
addStatement("if·(%N.isNotEmpty()) return·null", annotationsParam)
.addCode("\n")
.addControlFlow("return·when·(%N)", rawType) {
for (adapter in factory.generatedAdapters.sorted()) {
addCode("%T::class.java·->«\n", adapter.adapter.targetType.rawType())
addAdapterConstructorCall(
adapterTypeName = adapter.adapter.adapterTypeName,
constructor = adapter.constructor,
moshiParam = moshiParam,
typeParam = typeParam,
)
addCode("»\n")
}
addStatement("else -> null")
}
}
private fun FunSpec.Builder.addAdapterConstructorCall(
adapterTypeName: TypeName,
constructor: KotshiConstructor,
moshiParam: ParameterSpec,
typeParam: ParameterSpec,
): FunSpec.Builder = apply {
addCode("%T(", adapterTypeName.mapTypeArguments { NOTHING })
if (constructor.hasParameters) {
addCode("⇥")
}
if (constructor.moshiParameterName != null) {
addCode("\n%N = %N", constructor.moshiParameterName, moshiParam)
}
if (constructor.typesParameterName != null) {
if (constructor.moshiParameterName != null) {
addCode(",")
}
addCode(
"\n%N = %N.%M",
constructor.typesParameterName,
typeParam,
Functions.Kotshi.typeArgumentsOrFail
)
}
if (constructor.hasParameters) {
addCode("⇤\n")
}
addCode(")")
}
} | apache-2.0 | d7432fe70dc8acf083ade38c6fa66c19 | 41.144186 | 136 | 0.54106 | 5.655431 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/data/feed/FeedRepository.kt | 1 | 2591 | package mil.nga.giat.mage.data.feed
import android.content.Context
import androidx.annotation.WorkerThread
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import mil.nga.giat.mage.network.Resource
import mil.nga.giat.mage.network.api.FeedService
import mil.nga.giat.mage.network.gson.asLongOrNull
import mil.nga.giat.mage.network.gson.asStringOrNull
import mil.nga.giat.mage.sdk.datastore.user.EventHelper
import mil.nga.giat.mage.sdk.utils.ISO8601DateFormatFactory
import java.text.ParseException
import java.util.*
import javax.inject.Inject
class FeedRepository @Inject constructor(
@ApplicationContext private val context: Context,
private val feedLocalDao: FeedLocalDao,
private val feedItemDao: FeedItemDao,
private val feedService: FeedService
) {
suspend fun syncFeed(feed: Feed) = withContext(Dispatchers.IO) {
val resource = try {
val event = EventHelper.getInstance(context).currentEvent
val response = feedService.getFeedItems(event.remoteId, feed.id)
if (response.isSuccessful) {
val content = response.body()!!
saveFeed(feed, content)
Resource.success(content)
} else {
Resource.error(response.message(), null)
}
} catch (e: Exception) {
Resource.error(e.localizedMessage ?: e.toString(), null)
}
val local = FeedLocal(feed.id)
local.lastSync = Date().time
feedLocalDao.upsert(local)
resource
}
@WorkerThread
private fun saveFeed(feed: Feed, content: FeedContent) {
if (!feed.itemsHaveIdentity) {
feedItemDao.removeFeedItems(feed.id)
}
for (item in content.items) {
item.feedId = feed.id
item.timestamp = null
if (feed.itemTemporalProperty != null) {
val temporalElement = item.properties?.asJsonObject?.get(feed.itemTemporalProperty)
item.timestamp = temporalElement?.asLongOrNull() ?: run {
temporalElement?.asStringOrNull()?.let { date ->
try {
ISO8601DateFormatFactory.ISO8601().parse(date)?.time
} catch (ignore: ParseException) { null }
}
}
}
feedItemDao.upsert(item)
}
val itemIds = content.items.map { it.id }
feedItemDao.preserveFeedItems(feed.id, itemIds)
}
} | apache-2.0 | 021db747cb14abd6be4c81a5f29d4468 | 34.027027 | 99 | 0.635662 | 4.545614 | false | false | false | false |
abdoyassen/OnlyU | NoteApp/StartUp/app/src/main/java/com/example/onlyu/startup/AddNotes.kt | 1 | 1731 | package com.example.onlyu.startup
import android.content.ContentValues
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.example.onlyu.R
import kotlinx.android.synthetic.main.activity_add_notes.*
class AddNotes : AppCompatActivity() {
val dbTable="Notes"
var id=0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_notes)
try{
var bundle:Bundle=intent.extras
id=bundle.getInt("ID",0)
if(id!=0) {
etTitle.setText(bundle.getString("name") )
etDes.setText(bundle.getString("des") )
}
}catch (ex:Exception){}
}
fun buAdd(view:View){
var dbManager=DbManager(this)
var values= ContentValues()
values.put("Title",etTitle.text.toString())
values.put("Description",etDes.text.toString())
if(id==0) {
val ID = dbManager.Insert(values)
if (ID > 0) {
Toast.makeText(this, " note is added", Toast.LENGTH_LONG).show()
finish()
} else {
Toast.makeText(this, " cannot add note ", Toast.LENGTH_LONG).show()
}
}else{
var selectionArs= arrayOf(id.toString())
val ID = dbManager.Update(values,"ID=?",selectionArs)
if (ID > 0) {
Toast.makeText(this, " note is added", Toast.LENGTH_LONG).show()
finish()
} else {
Toast.makeText(this, " cannot add note ", Toast.LENGTH_LONG).show()
}
}
}
}
| mit | 8ce80c7f818f55d7ab51916774efd1b1 | 26.046875 | 83 | 0.57539 | 4.121429 | false | false | false | false |
f-droid/fdroidclient | libs/sharedTest/src/main/kotlin/org/fdroid/test/DiffUtils.kt | 1 | 2940 | package org.fdroid.test
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import org.fdroid.index.v2.MetadataV2
import org.fdroid.index.v2.PackageVersionV2
import org.fdroid.index.v2.RepoV2
import kotlin.random.Random
object DiffUtils {
/**
* Create a map diff by adding or removing keys. Note that this does not change keys.
*/
fun <T> Map<String, T?>.randomDiff(factory: () -> T): Map<String, T?> = buildMap {
if ([email protected]()) {
// remove random keys
while (Random.nextBoolean()) put([email protected](), null)
// Note: we don't replace random keys, because we can't easily diff inside T
}
// add random keys
while (Random.nextBoolean()) put(TestUtils.getRandomString(), factory())
}
/**
* Removes keys from a JSON object representing a [RepoV2] which need special handling.
*/
fun JsonObject.cleanRepo(): JsonObject {
val keysToFilter = listOf("mirrors", "antiFeatures", "categories", "releaseChannels")
val newMap = filterKeys { it !in keysToFilter }
return JsonObject(newMap)
}
fun RepoV2.clean() = copy(
mirrors = emptyList(),
antiFeatures = emptyMap(),
categories = emptyMap(),
releaseChannels = emptyMap(),
)
/**
* Removes keys from a JSON object representing a [MetadataV2] which need special handling.
*/
fun JsonObject.cleanMetadata(): JsonObject {
val keysToFilter = listOf("icon", "featureGraphic", "promoGraphic", "tvBanner",
"screenshots")
val newMap = filterKeys { it !in keysToFilter }
return JsonObject(newMap)
}
fun MetadataV2.clean() = copy(
icon = null,
featureGraphic = null,
promoGraphic = null,
tvBanner = null,
screenshots = null,
)
/**
* Removes keys from a JSON object representing a [PackageVersionV2] which need special handling.
*/
fun JsonObject.cleanVersion(): JsonObject {
if (!containsKey("manifest")) return this
val keysToFilter = listOf("features", "usesPermission", "usesPermissionSdk23")
val newMap = toMutableMap()
val filteredManifest = newMap["manifest"]!!.jsonObject.filterKeys { it !in keysToFilter }
newMap["manifest"] = JsonObject(filteredManifest)
return JsonObject(newMap)
}
fun PackageVersionV2.clean() = copy(
manifest = manifest.copy(
features = emptyList(),
usesPermission = emptyList(),
usesPermissionSdk23 = emptyList(),
),
)
fun <T> Map<String, T>.applyDiff(diff: Map<String, T?>): Map<String, T> =
toMutableMap().apply {
diff.entries.forEach { (key, value) ->
if (value == null) remove(key)
else set(key, value)
}
}
}
| gpl-3.0 | 37c638f9d23e702b30606cb4f4920490 | 32.793103 | 101 | 0.618367 | 4.447806 | false | false | false | false |
wireapp/wire-android | app/src/main/kotlin/com/waz/zclient/feature/backup/folders/FoldersBackupDataSource.kt | 1 | 1185 | package com.waz.zclient.feature.backup.folders
import com.waz.zclient.core.extension.empty
import com.waz.zclient.feature.backup.BackUpDataMapper
import com.waz.zclient.feature.backup.BackUpDataSource
import com.waz.zclient.feature.backup.BackUpIOHandler
import com.waz.zclient.storage.db.folders.FoldersEntity
import kotlinx.serialization.Serializable
import java.io.File
@Serializable
data class FoldersBackUpModel(
val id: String,
val name: String = String.empty(),
val type: Int = 0
)
class FoldersBackupMapper : BackUpDataMapper<FoldersBackUpModel, FoldersEntity> {
override fun fromEntity(entity: FoldersEntity) =
FoldersBackUpModel(id = entity.id, name = entity.name, type = entity.type)
override fun toEntity(model: FoldersBackUpModel) =
FoldersEntity(id = model.id, name = model.name, type = model.type)
}
class FoldersBackupDataSource(
override val databaseLocalDataSource: BackUpIOHandler<FoldersEntity, Unit>,
override val backUpLocalDataSource: BackUpIOHandler<FoldersBackUpModel, File>,
override val mapper: BackUpDataMapper<FoldersBackUpModel, FoldersEntity>
) : BackUpDataSource<FoldersBackUpModel, FoldersEntity>()
| gpl-3.0 | 14d912dd57762e9aac2cadac2979d7ea | 38.5 | 82 | 0.791561 | 4.217082 | false | false | false | false |
UKandAndroid/AndroidHelper | app/src/main/java/com/helper/lib/Flow.kt | 1 | 27057 |
package com.helper.lib;
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
typealias SingleCallback = (action: Flow.Action) -> Unit
// Version 3.0.5
// Concurrent execution bug fixed
// ## EXAMPLES ##
// var flow = Flow<String>( flowCode )
// METHOD: registerAction(events = listOf(event1, event2, event3)){} code will be executed when all three events are fired, and then when combined state changes
// METHOD: registerEvents(events = listOf(event1, event2, event3)){} code will be executed every time when an event is fired
// METHOD: waitForEvents(events = listOf(event1, event2, event3)){} code will be executed only once when all three events are fired
// Example 1: flow.registerAction(1, listOf("email_entered", "password_entered", "verify_code_entered") ) action 1 gets called when all those events occur
// : flow.event("email_entered", true, extra(opt), object(opt)) is trigger for the registered event "email_entered",
// : when all three events are triggered with flow.event(...., true), action 1 is executed with bSuccess = true
// : after 3 event true(s), if one event(...., false) sends false, action 1 will be executed with bSuccess = false
// : now action 1 will only trigger again when all onEvents(...., true) are true, i.e the events which sent false, send true again
// var flowCode = object: Flow.ExecuteCode(){
// @override fun onAction(int iAction, boolean bSuccess, int iExtra, Object data){
// when(iAction) {
// 1 -> // this code will run in first example when all events are triggered as true
// 3 -> // this will run when ever run(3) is called
// 4 -> // this will run on ui thread whenever runOnUi(4) is called
// 5 -> // this will run on delayed by 4 secs
// 6(NOT CALLED) -> this wont be called as local callback is provided
// } }
// Example : flow.runOnUi(){} runs code on ui thread
// Example : flow.runRepeat(500){} repeats code until cancelled
// Example : flow.runDelayed(2000){} run code after delay period
// Example : flow.getAction(1) returns action object
// Example : action.getEvents() returns all events associated with the action
// Example : action.getEvent(event) returns selected event
// Example : action.getFiredEvent() returns most recently fired event or null
// Example : action.getWaitingEvent() returns first event that is stopping the action being fired, either its not fired or fired with false
open class Flow<EventType> @JvmOverloads constructor(val tag: String = "", codeBlock: ExecuteCode? = null) : LifecycleObserver {
enum class EventStatus {
WAITING, SUCCESS, FAILURE
}
private var LOG_LEVEL = 4
private var autoIndex = -1
private var bRunning = true
private var hThread: HThread
private val LOG_TAG = "Flow:$tag"
private var listActions = ArrayList<_Action>() // List of registered actions
private var globalCallback: ExecuteCode? = null // Call back for onAction to be executed
// INTERFACE for code execution
interface ExecuteCode {
fun onAction(iAction: Int, bSuccess: Boolean, iExtra: Int, data: Any?)
}
init {
globalCallback = codeBlock
hThread = HThread()
}
fun setLogLevel(level: Int) {
LOG_LEVEL = level
}
fun execute(codeCallback: ExecuteCode) {
globalCallback = codeCallback
}
// STATE METHODS pause, resume, stop the action, should be called to release resources
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
open fun pause() {
loge(1, "Paused !!!: " )
hThread.mHandler.removeCallbacksAndMessages(null)
hThread.mUiHandler.removeCallbacksAndMessages(null)
bRunning = false
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
open fun resume() {
bRunning = true
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
open fun stop() {
loge(1, "Stopped !!! " )
globalCallback = null
try {
for (action in listActions) { action.recycle() }
hThread.mHandler.removeCallbacksAndMessages(null)
hThread.mUiHandler.removeCallbacksAndMessages(null)
hThread.stop()
listActions.clear()
_Event.releasePool()
bRunning = false
} catch (e: Exception) {
}
}
// METHOD sets the type of action callback
// RESULT_CHANGE = When result changes from false to true or true to false
// RESULT_UPDATE = when result updates means all events are fired a
// EVENT_UPDATE = whenever an event associated with action is updated
fun actionRunType(iAction:Int, type: RunType) {
_getAction(iAction)?.runType = type
}
fun getAction(iAction: Int) = _getAction(iAction) as Flow.Action
fun getActionEvents(iAction: Int) = _getAction(iAction)?.getEvents()
fun getActionWaitingEvent(iAction: Int) = _getAction(iAction)?.getWaitingEvent() // Returns first found event that is stopping the action from triggering
fun resetAction(iAction: Int) { _getAction(iAction)?.reset() } // Resets action by resetting all events to initial Waiting state
private fun _getAction(iAction: Int) = listActions.firstOrNull { it.iAction == iAction } // throws NoSuchElementException if action not found
@JvmOverloads
fun runAction(iAction: Int , runOnUi: Boolean = false, bSuccess: Boolean = true, iExtra: Int = 0, obj: Any? = null): Flow<EventType> {
if (runOnUi) hThread.runOnUI(iAction, bSuccess, iExtra, obj) else hThread.run(iAction, bSuccess, iExtra, obj)
return this
}
@JvmOverloads
fun runRepeat(iAction: Int = autoIndex--, runOnUi: Boolean = false, iDelay: Long, callback: SingleCallback? = null): Flow<EventType> {
val delayEvent = "repeat_event_$iAction"
_registerAction(iAction, runOnUi, false, false, true, listOf(delayEvent), callback)
hThread.mHandler.postDelayed((Runnable { this.event(delayEvent, true, 0, iDelay) }), iDelay)
return this
}
fun runOnUi(callback: SingleCallback){
hThread.runOnUI(0, true, 0, _Action(0, events = listOf<String>(), singleCallback = callback))
}
@JvmOverloads
fun runDelayed(iAction: Int = autoIndex--, runOnUi: Boolean = false, iDelay: Long, bSuccess: Boolean = true, iExtra: Int = 0, any: Any? = null, callback: SingleCallback? = null): Flow<EventType> {
val delayEvent = "delay_event_$iAction"
val action = _registerAction(iAction, runOnUi, true, false, false, listOf(delayEvent), callback)
hThread.mHandler.postDelayed((Runnable { action.onEvent(delayEvent, bSuccess, iExtra, any) }), iDelay)
return this
}
@JvmOverloads
fun registerAction(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: List<EventType>, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, false, false, events, singleCallback)
return this
}
@JvmOverloads
fun registerEvents(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: List<EventType>, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, false, false, events, singleCallback)
actionRunType(iAction, RunType.EVENT_UPDATE)
return this
}
@JvmOverloads
fun registerEvents(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: EventType, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, false, false, listOf(events), singleCallback)
actionRunType(iAction, RunType.EVENT_UPDATE)
return this
}
@JvmOverloads
fun registerAction(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: EventType, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, false, false, listOf(events), singleCallback)
return this
}
@JvmOverloads
fun waitForEvents(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: List<EventType>, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, true, false, false, events, singleCallback)
return this
}
@JvmOverloads
fun waitForEvents(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: EventType, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, true, false, false, listOf(events), singleCallback)
return this
}
fun registerActionSequence(iAction: Int, runOnUi: Boolean, events: List<EventType>, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, true, false, events, singleCallback)
return this
}
fun deleteAction(iAction: Int){ cancelAction(iAction) }
fun removeAction(iAction: Int){ cancelAction(iAction) }
fun cancelAction(action: Action){ cancelAction(action.getId()) }
fun cancelAction(iAction: Int) {
val copyList = ArrayList(listActions) // to avoid deleting of event issues while going through list
copyList.firstOrNull { it.iAction == iAction }?.run {
_cancelAction(this)
loge(1,"CANCEL: Action($iAction), removed ")
}
}
private fun _cancelAction(action: _Action){
hThread.mHandler.removeMessages(action.iAction)
hThread.mUiHandler.removeMessages(action.iAction)
action.recycle()
listActions.remove(action)
}
private fun _registerAction(iAction: Int, bUiThread: Boolean, bRunOnce: Boolean, bSequence: Boolean, bRepeat: Boolean, events: List<*>, actionCallback: SingleCallback? = null): _Action{
cancelAction(iAction) // to stop duplication, remove if the action already exists
val actionFlags = setActionFlags(runOnUI = bUiThread, runOnce = bRunOnce, eventSequence = bSequence, repeatAction = bRepeat)
val aAction = _Action(iAction, actionFlags, events, actionCallback)
listActions.add(aAction)
val buf = StringBuffer(400)
for (event in events) {
buf.append(event.toString() + ", ")
}
log(1,"ACTION: $iAction registered EVENTS = { ${buf.removeSuffix(", ")} }")
return aAction
}
// METHODS to send event
@Synchronized
@JvmOverloads
fun event(sEvent: Any, bSuccess: Boolean = true, iExtra: Int = 0, obj: Any? = null) : Boolean {
if (!bRunning)
return false
var eventFired = false
log(2,"EVENT: $sEvent $bSuccess")
val copyList = ArrayList(listActions) // to avoid deleting of event issues while going through list
try {
for (action in copyList) {
if(action.onEvent(sEvent, bSuccess, iExtra, obj).first){
eventFired = true
}
}
} catch (e: IndexOutOfBoundsException) {
loge(e.toString())
} catch (e: NullPointerException){
logw(2,"event() - null pointer exception")
}
return eventFired
}
// METHOD cancel a runDelay or RunRepeated
fun cancelRun(iAction: Int) {
if (!bRunning) return
hThread.mHandler.removeMessages(iAction)
hThread.mUiHandler.removeMessages(iAction)
}
// CLASS for events for action, when all events occur action is triggered
open class Action( internal val iAction: Int) {
protected var listEvents: MutableList<Event<*>> = ArrayList() // List to store Flow.Events needed for this action
protected var iLastStatus = EventStatus.WAITING // Event set status as a whole, waiting, success, non success
protected var lastFiredEvent : Event<*>? = null // last fired event for this action, null if none
fun getId() = iAction
// returns first event that has not been fired or fired with false
fun getFiredEvent() = lastFiredEvent
fun getFiredEventObj() = lastFiredEvent?.obj
fun getEvents() = listEvents as List<Event<*>>
fun isWaitingFor(event: Any) = getWaitingEvent() == event
fun getEvent(event: Any) = getEvents().firstOrNull{ it.event == event }
fun getWaitingEvent() = listEvents.first { !it.isSuccess() }.event // Throws exception if event not found
fun reset() {
iLastStatus = EventStatus.WAITING
for (event in listEvents) {
(event as _Event).resetEvent()
}
}
}
// CLASS for event Pool
open class Event<ActionEvents> { // CONSTRUCTOR - Private
var obj: Any? = null
var extra = 0
var event: ActionEvents? = null
protected var _status :EventStatus = EventStatus.WAITING // WAITING - waiting not fired yet, SUCCESS - fired with success, FAILURE - fired with failure
// Variable for pool
fun isSuccess() = _status == EventStatus.SUCCESS
}
private inner class _Action(
iAction: Int,
private var actionFlags: Int = 0,
events: List<*>,
private var singleCallback: SingleCallback? = null
) : Action(iAction) {
internal var runType: RunType = RunType.RESULT_CHANGE
internal var iEventCount: Int = events.size // How many event are for this action code to be triggered
init {
for (i in 0 until iEventCount) {
listEvents.add(_Event.obtain(events[i])) // get events from events pool
}
}
internal fun getFlag(flag: Int) = Companion.getFlag(actionFlags, flag)
internal fun setFlag(flag: Int) {
Companion.setFlag(actionFlags, flag, true)
}
internal fun clearFlag(flag: Int) {
Companion.setFlag(actionFlags, flag, false)
}
internal fun execute(): Boolean {
if (singleCallback != null) {
singleCallback?.invoke(this as Action)
return true
}
return false
}
internal fun getEventData(events: EventType): Any? {
return listEvents.find { it.event == events }?.obj
}
// METHOD recycles events and clears actions
internal fun recycle() {
singleCallback = null
iEventCount = 0
/*for (event in listEvents) { don't recycle events as sometimes one event can fire multiple actions
(event as _Event).recycle() // and recycling event deletes event when access by 2nd action
}*/
listEvents = ArrayList()
}
// METHOD searches all actions, if any associated with this event
fun onEvent(sEvent: Any, bResult: Boolean, iExtra: Int, obj: Any?): Pair<Boolean, Boolean> {
var iSuccess = 0 // How many successful events has been fired
var iFiredCount = 0 // How many events for this action have been fired
var bEventFound = false
var bActionExecuted = false
for (i in 0 until iEventCount) {
val event = listEvents[i] as _Event
if (sEvent == event.event) { // If event is found in this event list
bEventFound = true
lastFiredEvent = event
event.setData(bResult, iExtra, obj )
} else if (getFlag(FLAG_SEQUENCE) && event.statusIs(EventStatus.WAITING)) { // if its a Sequence action, no event should be empty before current event
if (i != 0) {
(listEvents[i - 1] as _Event).setStatus( EventStatus.WAITING ) // reset last one, so they are always in sequence
}
break
}
when (event.status()) {
EventStatus.FAILURE -> iFiredCount++
EventStatus.SUCCESS -> {
iSuccess++
iFiredCount++ // Add to fired event regard less of success or failure
}
}
if (bEventFound && getFlag(FLAG_SEQUENCE)) break
}
if (bEventFound) { // if event was found in this Action
logw(2,"ACTION: $iAction FIRED on: $sEvent { Total $iEventCount Fired: $iFiredCount Success: $iSuccess }")
if (runType == RunType.EVENT_UPDATE) { // if this action is launched on every event update
bActionExecuted = true
executeAction(bResult, iExtra)
} else if (iFiredCount == iEventCount) { // if all events for action has been fired
val bSuccess = iSuccess == iEventCount // all events registered success
val iCurStatus = if (bSuccess) EventStatus.SUCCESS else EventStatus.FAILURE
when (runType) {
RunType.RESULT_CHANGE -> if (iCurStatus != iLastStatus) { // If there is a change in action status only then run code
bActionExecuted = true
iLastStatus = iCurStatus
executeAction(bSuccess, iSuccess)
}
RunType.RESULT_UPDATE -> if (bSuccess) {
bActionExecuted = true
executeAction(bSuccess, iSuccess)
}
}
}
}
return Pair(bActionExecuted, getFlag(FLAG_RUNONCE))
}
// METHOD executes action code on appropriate thread
private fun executeAction(bSuccess: Boolean, iExtra: Int) {
logw(1,"ACTION: $iAction Executed with $bSuccess ")
if (getFlag(FLAG_RUNonUI)) {
hThread.runOnUI(iAction, bSuccess, iExtra, this as Flow.Action)
} else {
hThread.run(iAction, bSuccess, iExtra, this)
}
}
}
private class _Event<ExternalEvents> private constructor() : Event<ExternalEvents>(){
companion object {
// EVENTS for self use
private var next: _Event<Any>? = null // Reference to next object
private var sPool: _Event<Any>? = null
private var sPoolSize = 0
private const val MAX_POOL_SIZE = 50
private val sPoolSync = Any() // The lock used for synchronization
// METHOD get pool object only through this method, so no direct allocation are made
fun <ExternalEvents> obtain(sId: ExternalEvents?): _Event<*> {
synchronized(sPoolSync) {
if (sPool != null) {
val e = sPool as _Event<ExternalEvents>
e.event = sId
e.setData(EventStatus.WAITING, 0, null)
sPool = next
next = null
sPoolSize --
return e
}
val eve = _Event<ExternalEvents>()
eve.event = sId
return eve
}
}
// METHOD release pool, ready for garbage collection
fun releasePool() {
sPoolSize = 0
sPool = null
}
}
fun status() = _status
fun setStatus(value: EventStatus) { _status = value }
fun statusIs(value: EventStatus) = _status == value
fun resetEvent() {
obj = null
extra = 0
_status = EventStatus.WAITING
}
fun setData(status : EventStatus, ext : Int, data: Any? ) {
_status = status
obj = data
extra = ext
}
fun setData(status : Boolean, ext : Int, data: Any? ) {
_status = if (status) EventStatus.SUCCESS else EventStatus.FAILURE
obj = data
extra = ext
}
// METHOD object added to the pool, to be reused
internal fun recycle() {
synchronized(sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool as _Event<Any>?
sPool = this as _Event<Any>
sPoolSize++
}
}
}
}
// CLASS for thread handler
private inner class HThread internal constructor() : Handler.Callback {
val mHandler: Handler
val mUiHandler: Handler
var ACTION_FAIL = 0
var ACTION_SUCCESS = 1
@JvmOverloads
fun run(iStep: Int, bRunUI: Boolean = false) {
if (bRunUI) {
runOnUI(iStep, true, 0, null)
} else {
run(iStep, true, 0, null)
}
}
fun run(iAction: Int, bSuccess: Boolean, iExtra: Int, obj: Any?) {
if (bRunning) {
val msg = Message.obtain()
msg.what = iAction
msg.arg1 = iExtra
msg.arg2 = if (bSuccess) ACTION_SUCCESS else ACTION_FAIL
msg.obj = obj
mHandler.sendMessage(msg)
}
}
fun runOnUI(iAction: Int, bSuccess: Boolean, iExtra: Int, obj: Any?) {
if (bRunning) {
val msg = Message.obtain()
msg.what = iAction
msg.arg1 = iExtra
msg.arg2 = if (bSuccess) ACTION_SUCCESS else ACTION_FAIL
msg.obj = obj
mUiHandler.sendMessage(msg)
}
}
// METHOD MESSAGE HANDLER
override fun handleMessage(msg: Message): Boolean {
if (msg.obj !is Flow<*>._Action) { // called directly with runAction() action probably does not exist
globalCallback?.onAction(msg.what, msg.arg2 == ACTION_SUCCESS, msg.arg1, msg.obj)
} else { // is Flow Action with events
val action = msg.obj as Flow<EventType>._Action
if (action.getFlag(FLAG_REPEAT)) { // If its a repeat action, we have to post it again
val event = action.getEvents()[0] // get delay event for data
hThread.mHandler.postDelayed((Runnable { action.onEvent(event.event!!, !event.isSuccess(), ++event.extra, event.obj) }), event.obj as Long)
// posting action.onEvent() not Flow.event(), to keep event local to its own action
}
if (!action.execute()) { // if there is no specific callback for action, call generic call back
globalCallback?.onAction(msg.what, msg.arg2 == ACTION_SUCCESS, msg.arg1, msg.obj as Flow.Action)
}
if (action.getFlag(FLAG_RUNONCE)) {
loge(2,"REMOVING: Action(${action.iAction}, runOnce) as its executed")
_cancelAction(action) // Recycle if its flagged for it
}
}
return true
}
fun stop() {
mHandler.removeCallbacksAndMessages(null)
mUiHandler.removeCallbacksAndMessages(null)
mHandler.looper.quit()
}
init {
val ht = HandlerThread("BGThread_ ${++iThreadCount}")
ht.start()
mHandler = Handler(ht.looper, this)
mUiHandler = Handler(Looper.getMainLooper(), this)
}
}
// METHOD for logging
private fun log(sLog: String) {
log(3, sLog)
}
private fun loge(sLog: String?) {
loge(3, sLog)
}
private fun logw(sLog: String?) {
logw(3, sLog)
}
private fun log(iLevel: Int, sLog: String) {
if (iLevel <= LOG_LEVEL) {
Log.d(LOG_TAG, sLog)
}
}
private fun loge(iLevel: Int, sLog: String?) {
if (iLevel <= LOG_LEVEL) {
Log.e(LOG_TAG, sLog)
}
}
private fun logw(iLevel: Int, sLog: String?) {
if (iLevel <= LOG_LEVEL) {
Log.w(LOG_TAG, sLog)
}
}
enum class RunType {
EVENT_UPDATE, // action will be invoked for each event update
RESULT_CHANGE, // action will be invoked when combined result for events changes e.g true to false or false to true
RESULT_UPDATE // action will be invoked once combined result is achieved, then every time after an event changes
}
companion object {
private var iThreadCount = 0
private const val FLAG_SUCCESS = 0x00000001
private const val FLAG_RUNonUI = 0x00000002
private const val FLAG_REPEAT = 0x00000004
private const val FLAG_RUNONCE = 0x00000008
private const val FLAG_SEQUENCE = 0x00000010
// METHODS for packing data for repeat event
private fun addExtraInt(iValue: Int, iData: Int): Int {
return iValue or (iData shl 8)
}
private fun getExtraInt(iValue: Int): Int {
return iValue shr 8
}
private fun getFlag(iValue: Int, iFlag: Int): Boolean {
return iValue and iFlag == iFlag
}
private fun setFlag(iValue: Int, iFlag: Int, bSet: Boolean = true): Int {
return if (bSet) {
iValue or iFlag
} else {
iValue and iFlag.inv()
}
}
private fun setActionFlags(runOnUI: Boolean = false, runOnce: Boolean = false, eventSequence: Boolean = false, repeatAction: Boolean = false): Int {
var intFlags: Int = 0
intFlags = setFlag(intFlags, FLAG_RUNonUI, runOnUI)
intFlags = setFlag(intFlags, FLAG_RUNONCE, runOnce)
intFlags = setFlag(intFlags, FLAG_SEQUENCE, eventSequence)
intFlags = setFlag(intFlags, FLAG_REPEAT, repeatAction)
return intFlags
}
}
}
| gpl-2.0 | 65e477218282f11688a1196b8aa74ac3 | 40.276563 | 200 | 0.575932 | 4.554284 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/list/InternalPagedListDataSourceTest.kt | 1 | 4089 | package org.wordpress.android.fluxc.list
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId
import org.wordpress.android.fluxc.model.list.datasource.InternalPagedListDataSource
import org.wordpress.android.fluxc.model.list.datasource.ListItemDataSourceInterface
import kotlin.test.assertEquals
private const val NUMBER_OF_ITEMS = 71
private const val IS_LIST_FULLY_FETCHED = false
private val testListDescriptor = TestListDescriptor()
private val testStartAndEndPosition = Pair(5, 10)
internal class InternalPagedListDataSourceTest {
private val remoteItemIds = mock<List<RemoteId>>()
private val mockIdentifiers = mock<List<TestListIdentifier>>()
private val mockItemDataSource = mock<ListItemDataSourceInterface<TestListDescriptor, TestListIdentifier, String>>()
@Before
fun setup() {
whenever(remoteItemIds.size).thenReturn(NUMBER_OF_ITEMS)
whenever(mockIdentifiers.size).thenReturn(NUMBER_OF_ITEMS)
val mockSublist = mock<List<TestListIdentifier>>()
whenever(mockIdentifiers.subList(any(), any())).thenReturn(mockSublist)
whenever(
mockItemDataSource.getItemIdentifiers(
listDescriptor = testListDescriptor,
remoteItemIds = remoteItemIds,
isListFullyFetched = IS_LIST_FULLY_FETCHED
)
).thenReturn(mockIdentifiers)
}
/**
* Tests that item identifiers are cached when a new instance of [InternalPagedListDataSource] is created.
*
* Caching the item identifiers is how we ensure that this component will provide consistent data to
* `PositionalDataSource` so it's very important that we have this test. Since we don't have access to
* `InternalPagedListDataSource.itemIdentifiers` private property, we have to test the internal implementation
* which is more likely to break. However, in this specific case, we DO want the test to break if the internal
* implementation changes.
*/
@Test
fun `init calls getItemIdentifiers`() {
createInternalPagedListDataSource(mockItemDataSource)
verify(mockItemDataSource).getItemIdentifiers(eq(testListDescriptor), any(), any())
}
@Test
fun `total size uses getItemIdentifiers' size`() {
val internalDataSource = createInternalPagedListDataSource(mockItemDataSource)
assertEquals(
NUMBER_OF_ITEMS, internalDataSource.totalSize, "InternalPagedListDataSource should not change the" +
"number of items in a list and should propagate that to its ListItemDataSourceInterface"
)
}
@Test
fun `getItemsInRange creates the correct sublist of the identifiers`() {
val internalDataSource = createInternalPagedListDataSource(mockItemDataSource)
val (startPosition, endPosition) = testStartAndEndPosition
internalDataSource.getItemsInRange(startPosition, endPosition)
verify(mockIdentifiers).subList(startPosition, endPosition)
}
@Test
fun `getItemsInRange propagates the call to getItemsAndFetchIfNecessary correctly`() {
val internalDataSource = createInternalPagedListDataSource(dataSource = mockItemDataSource)
val (startPosition, endPosition) = testStartAndEndPosition
internalDataSource.getItemsInRange(startPosition, endPosition)
verify(mockItemDataSource).getItemsAndFetchIfNecessary(eq(testListDescriptor), any())
}
private fun createInternalPagedListDataSource(
dataSource: TestListItemDataSource
): TestInternalPagedListDataSource {
return InternalPagedListDataSource(
listDescriptor = testListDescriptor,
remoteItemIds = remoteItemIds,
isListFullyFetched = IS_LIST_FULLY_FETCHED,
itemDataSource = dataSource
)
}
}
| gpl-2.0 | 25be47791d5c095b7a811cefd058a255 | 41.59375 | 120 | 0.728785 | 5.495968 | false | true | false | false |
actions-on-google/actions-on-google-java | src/test/kotlin/com/google/actions/api/AogResponseTest.kt | 1 | 26856 | /*
* Copyright 2018 Google Inc. 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.google.actions.api
import com.google.actions.api.impl.AogResponse
import com.google.actions.api.response.ResponseBuilder
import com.google.actions.api.response.helperintent.*
import com.google.api.services.actions_fulfillment.v2.model.*
import com.google.gson.Gson
import com.google.gson.JsonObject
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertNotNull
import org.junit.jupiter.api.assertThrows
import org.testng.annotations.Test
class AogResponseTest {
@Test
fun testBasicResponse() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add("this is a test");
val response = responseBuilder.buildAogResponse()
assertNotNull(response)
val asJson = response.toJson()
assertNotNull(Gson().fromJson(asJson, JsonObject::class.java))
assertEquals("actions.intent.TEXT", response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0)
?.intent)
}
@Test
fun testAskConfirmation() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val confirmation = Confirmation().setConfirmationText("Are you sure?")
val jsonOutput = responseBuilder
.add(confirmation)
.build()
.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val dialogSpec = inputValueData.get("dialogSpec").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.ConfirmationValueSpec",
inputValueData.get("@type").asString)
assertEquals("Are you sure?",
dialogSpec.get("requestConfirmationText").asString)
}
@Test
fun testAskDateTime() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val dateTimePrompt = DateTimePrompt()
.setDatePrompt("What date?")
.setDateTimePrompt("What date and time?")
.setTimePrompt("What time?")
val jsonOutput = responseBuilder
.add(dateTimePrompt)
.build()
.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val dialogSpec = inputValueData.get("dialogSpec").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.DateTimeValueSpec",
inputValueData.get("@type").asString)
assertEquals("What date?",
dialogSpec.get("requestDateText").asString)
assertEquals("What time?",
dialogSpec.get("requestTimeText").asString)
assertEquals("What date and time?",
dialogSpec.get("requestDatetimeText").asString)
}
@Test
fun testAskPermission() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder
.add(Permission()
.setPermissions(arrayOf(PERMISSION_NAME,
PERMISSION_DEVICE_PRECISE_LOCATION))
.setContext("To get your name"))
val response = responseBuilder.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.PermissionValueSpec",
inputValueData.get("@type").asString)
assertEquals("To get your name",
inputValueData.get("optContext").asString)
assertEquals("NAME",
inputValueData.get("permissions").asJsonArray
.get(0).asString)
}
@Test
fun testAskPlace() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val requestPrompt = "Where do you want to have lunch?"
val permissionPrompt = "To find lunch locations"
responseBuilder
.add(Place()
.setRequestPrompt(requestPrompt)
.setPermissionContext(permissionPrompt))
val response = responseBuilder.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val dialogSpec = inputValueData.get("dialog_spec").asJsonObject
val extension = dialogSpec.get("extension").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.PlaceValueSpec",
inputValueData.get("@type").asString)
assertEquals(requestPrompt,
extension.get("requestPrompt").asString)
assertEquals(permissionPrompt,
extension.get("permissionContext").asString)
}
@Test
fun testAskSignIn() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(SignIn())
val response = responseBuilder
.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertNotNull(inputValueData)
}
@Test
fun testAskSignInWithContext() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(SignIn()
.setContext("For testing purposes"))
val response = responseBuilder
.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertNotNull(inputValueData)
assertEquals("For testing purposes",
inputValueData.get("optContext").asString)
}
@Test
fun testListSelect() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val items = ArrayList<ListSelectListItem>()
items.add(ListSelectListItem().setTitle("Android"))
items.add(ListSelectListItem().setTitle("Actions on Google"))
items.add(ListSelectListItem().setTitle("Flutter"))
val response = responseBuilder
.add("placeholder")
.add(SelectionList().setTitle("Topics").setItems(items))
.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val listSelect = inputValueData.get("listSelect").asJsonObject
assertNotNull(listSelect)
assertEquals("Android", listSelect.get("items")
.asJsonArray.get(0)
.asJsonObject
.get("title").asString)
}
@Test
fun testListSelectWithoutSimpleResponse() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val items = ArrayList<ListSelectListItem>()
items.add(ListSelectListItem().setTitle("Android"))
items.add(ListSelectListItem().setTitle("Actions on Google"))
items.add(ListSelectListItem().setTitle("Flutter"))
val response = responseBuilder
.add(SelectionList().setTitle("Topics").setItems(items))
.build()
assertThrows<Exception> {
response.toJson()
}
}
@Test
fun testCarouselSelect() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val items = ArrayList<CarouselSelectCarouselItem>()
items.add(CarouselSelectCarouselItem().setTitle("Android"))
items.add(CarouselSelectCarouselItem().setTitle("Actions on Google"))
items.add(CarouselSelectCarouselItem().setTitle("Flutter"))
val response = responseBuilder
.add("placeholder")
.add(SelectionCarousel().setItems(items))
.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val carouselSelect = inputValueData.get("carouselSelect")
.asJsonObject
assertNotNull(carouselSelect)
assertEquals("Android", carouselSelect.get("items")
.asJsonArray.get(0)
.asJsonObject
.get("title").asString)
}
@Test
fun testCarouselSelectWithoutSimpleResponse() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val items = ArrayList<CarouselSelectCarouselItem>()
items.add(CarouselSelectCarouselItem().setTitle("Android"))
items.add(CarouselSelectCarouselItem().setTitle("Actions on Google"))
items.add(CarouselSelectCarouselItem().setTitle("Flutter"))
val response = responseBuilder
.add(SelectionCarousel().setItems(items))
.build()
assertThrows<Exception> {
response.toJson()
}
}
@Test
fun testConversationDataIsSet() {
val data = HashMap<String, Any>()
data["favorite_color"] = "white"
val responseBuilder = ResponseBuilder(usesDialogflow = false,
conversationData = data)
responseBuilder
.add("this is a test")
val aogResponse = responseBuilder.build() as AogResponse
val jsonOutput = aogResponse.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val serializedValue = jsonObject.get("conversationToken").asString
assertEquals("white",
gson.fromJson(serializedValue, JsonObject::class.java)
.get("data").asJsonObject
.get("favorite_color").asString)
}
@Test
fun testUserStorageIsSet() {
val map = HashMap<String, Any>()
map["favorite_color"] = "white"
val responseBuilder = ResponseBuilder(usesDialogflow = false,
userStorage = map)
responseBuilder
.add("this is a test")
val aogResponse = responseBuilder.build()
val jsonOutput = aogResponse.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val serializedValue = jsonObject.get("userStorage").asString
assertEquals("white",
gson.fromJson(serializedValue, JsonObject::class.java)
.get("data").asJsonObject
.get("favorite_color").asString)
}
@Test
fun testNewSurfaceHelperIntent() {
val capability = Capability.SCREEN_OUTPUT.value
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(NewSurface()
.setCapability(capability)
.setContext("context")
.setNotificationTitle("notification title"))
val response = responseBuilder.buildAogResponse()
val intent = response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0) as ExpectedIntent
assertEquals("actions.intent.NEW_SURFACE", intent.intent)
val capabilitiesArray =
intent.inputValueData["capabilities"] as Array<String>
assertEquals(capability, capabilitiesArray[0])
}
@Test
fun testRegisterDailyUpdate() {
val updateIntent = "intent.foo"
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(RegisterUpdate().setIntent(updateIntent))
val response = responseBuilder.buildAogResponse()
val intent = response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0) as ExpectedIntent
assertEquals("actions.intent.REGISTER_UPDATE", intent.intent)
assertEquals(updateIntent, intent.inputValueData["intent"])
}
@Test
fun testAddSuggestions() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder
.add("this is a test")
.addSuggestions(arrayOf("one", "two", "three"))
val response = responseBuilder.buildAogResponse()
assertEquals("one", response.appResponse
?.expectedInputs?.get(0)
?.inputPrompt
?.richInitialPrompt
?.suggestions?.get(0)
?.title)
assertEquals("actions.intent.TEXT", response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0)
?.intent)
}
@Test
fun testCompletePurchase() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder
.add("placeholder")
.add(CompletePurchase().setSkuId(SkuId()
.setId("PRODUCT_SKU_ID")
.setSkuType("INAPP")
.setPackageName("play.store.package.name"))
.setDeveloperPayload("OPTIONAL_DEVELOPER_PAYLOAD"))
val response = responseBuilder.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.transactions.v3.CompletePurchaseValueSpec",
inputValueData.get("@type").asString)
val skuId = inputValueData.get("skuId").asJsonObject
assertEquals("PRODUCT_SKU_ID", skuId.get("id").asString)
assertEquals("INAPP", skuId.get("skuType").asString)
assertEquals("play.store.package.name", skuId.get("packageName").asString)
assertEquals("OPTIONAL_DEVELOPER_PAYLOAD",
inputValueData.get("developerPayload").asString)
}
@Test
fun testDigitalPurchaseCheck() {
println("testDigitalPurchaseCheck")
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(DigitalPurchaseCheck())
val response = responseBuilder.build()
val jsonOutput = response.toJson()
val intent = response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0) as ExpectedIntent
assertEquals("actions.intent.DIGITAL_PURCHASE_CHECK", intent.intent)
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.transactions.v3.DigitalPurchaseCheckSpec",
inputValueData.get("@type").asString)
}
@Test
fun testTransactionRequirementsCheck() {
val orderOptions = OrderOptions().setRequestDeliveryAddress(false)
val actionProvidedPaymentOptions = ActionProvidedPaymentOptions().setDisplayName("VISA-1234")
.setPaymentType("PAYMENT_CARD")
val paymentOptions = PaymentOptions()
.setActionProvidedOptions(actionProvidedPaymentOptions)
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(TransactionRequirements()
.setOrderOptions(orderOptions)
.setPaymentOptions(paymentOptions))
val response = responseBuilder.buildAogResponse()
val jsonOutput = response.toJson()
val intent = response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0) as ExpectedIntent
assertEquals("actions.intent.TRANSACTION_REQUIREMENTS_CHECK", intent.intent)
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertNotNull(inputValueData)
}
@Test
fun testDeliveryAddress() {
val reason = "Reason"
val options = DeliveryAddressValueSpecAddressOptions()
.setReason(reason)
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(DeliveryAddress()
.setAddressOptions(options))
val response = responseBuilder.buildAogResponse()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.DeliveryAddressValueSpec",
inputValueData.get("@type").asString)
val addressOptions = inputValueData.get("addressOptions").asJsonObject
assertEquals(reason, addressOptions.get("reason").asString)
}
@Test
fun testTransactionDecision() {
val orderOptions = OrderOptions().setRequestDeliveryAddress(true)
val paymentType = "PAYMENT_CARD"
val paymentDisplayName = "VISA-1234"
val actionProvidedPaymentOptions = ActionProvidedPaymentOptions()
.setPaymentType(paymentType)
.setDisplayName(paymentDisplayName)
val paymentOptions = PaymentOptions()
.setActionProvidedOptions(actionProvidedPaymentOptions)
val merchantId = "merchant_id"
val merchantName = "merchant_name"
val merchant = Merchant().setId(merchantId).setName(merchantName)
val amount = Money()
.setCurrencyCode("USD")
.setUnits(1L)
.setNanos(990000000)
val price = Price().setAmount(amount).setType("ACTUAL")
val lineItemName = "item_name"
val lineItemId = "item_id"
val lineItemType = "REGULAR"
val lineItem = LineItem().setName(lineItemName)
.setId(lineItemId)
.setPrice(price).setQuantity(1).setType(lineItemType)
val cart = Cart()
.setMerchant(merchant)
.setLineItems(listOf(lineItem))
val totalAmount = Money().setCurrencyCode("USD").setNanos(1)
.setUnits(99L)
val totalPrice = Price().setAmount(totalAmount).setType("ESTIMATE")
val orderId = "order_id"
val proposedOrder = ProposedOrder().setId(orderId)
.setCart(cart).setTotalPrice(totalPrice)
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(TransactionDecision()
.setOrderOptions(orderOptions)
.setPaymentOptions(paymentOptions)
.setProposedOrder(proposedOrder))
val response = responseBuilder.buildAogResponse()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.TransactionDecisionValueSpec",
inputValueData.get("@type").asString)
val orderOptionsJson = inputValueData.get("orderOptions").asJsonObject
assertEquals(true, orderOptionsJson.get("requestDeliveryAddress").asBoolean)
val actionProvidedOptionsJson = inputValueData
.get("paymentOptions").asJsonObject
.get("actionProvidedOptions").asJsonObject
assertEquals(paymentDisplayName, actionProvidedOptionsJson.get("displayName").asString)
assertEquals(paymentType, actionProvidedOptionsJson.get("paymentType").asString)
val proposedOrderJson = inputValueData.get("proposedOrder").asJsonObject
assertNotNull(proposedOrderJson)
assertEquals(orderId, proposedOrderJson.get("id").asString)
val cartJson = proposedOrderJson.get("cart").asJsonObject
assertNotNull(cartJson)
val lineItemsJson = cartJson.get("lineItems").asJsonArray
assertNotNull(lineItemsJson)
assert(lineItemsJson.size() == 1)
val lineItemJson = lineItemsJson.get(0).asJsonObject
assertEquals(lineItemId, lineItemJson.get("id").asString)
assertEquals(lineItemName, lineItemJson.get("name").asString)
assertEquals(lineItemType, lineItemJson.get("type").asString)
}
@Test
fun testOrderUpdate() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val orderId = "order_id"
val actionOrderId = "action_order_id"
val actionUrl = "http://example.com/customer-service"
val actionTitle = "Customer Service"
val actionType = "CUSTOMER_SERVICE"
val notificationText = "Notification text."
val notificationTitle = "Notification Title"
val orderState = "CREATED"
val orderLabel = "Order created"
val orderUpdate = OrderUpdate().setActionOrderId(actionOrderId)
.setOrderState(
OrderState().setLabel(orderLabel).setState(orderState))
.setReceipt(Receipt().setConfirmedActionOrderId(orderId))
.setOrderManagementActions(
listOf(OrderUpdateAction()
.setButton(Button().setOpenUrlAction(OpenUrlAction()
.setUrl(actionUrl))
.setTitle(actionTitle))
.setType(actionType)))
.setUserNotification(OrderUpdateUserNotification()
.setText(notificationText).setTitle(notificationTitle))
responseBuilder.add(StructuredResponse().setOrderUpdate(orderUpdate))
val response = responseBuilder
.add("placeholder text")
.buildAogResponse()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertNotNull(inputValueData)
val richInitialPrompt = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("inputPrompt").asJsonObject.get("richInitialPrompt").asJsonObject
val items = richInitialPrompt.get("items").asJsonArray
assertNotNull(items)
assert(items.size() == 2)
val structuredResponse = items.get(0).asJsonObject.get("structuredResponse").asJsonObject
assertNotNull(structuredResponse)
val orderUpdateJson = structuredResponse.get("orderUpdate").asJsonObject
assertNotNull(orderUpdateJson)
val orderStateJson = orderUpdateJson.get("orderState").asJsonObject
assertEquals(orderState, orderStateJson.get("state").asString)
assertEquals(orderLabel, orderStateJson.get("label").asString)
val orderManagementUpdateActions = orderUpdateJson.get("orderManagementActions").asJsonArray
assertNotNull(orderManagementUpdateActions)
assert(orderManagementUpdateActions.size() == 1)
val updateAction = orderManagementUpdateActions.get(0).asJsonObject
assertEquals(actionType, updateAction.get("type").asString)
val button = updateAction.get("button").asJsonObject
assertEquals(actionTitle, button.get("title").asString)
assertEquals(actionUrl, button.get("openUrlAction").asJsonObject.get("url").asString)
}
}
| apache-2.0 | 419883914c0e8ca25c406a2f61703f36 | 42.176849 | 101 | 0.635091 | 5.13499 | false | true | false | false |
android/privacy-sandbox-samples | Fledge/FledgeKotlin/app/src/main/java/com/example/adservices/samples/fledge/sampleapp/AdSelectionWrapper.kt | 1 | 9589 | /*
* 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.adservices.samples.fledge.sampleapp
import android.adservices.adselection.AdSelectionConfig
import android.adservices.adselection.AdSelectionOutcome
import android.adservices.adselection.AddAdSelectionOverrideRequest
import android.adservices.adselection.ReportImpressionRequest
import android.adservices.common.AdSelectionSignals
import android.adservices.common.AdTechIdentifier
import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.annotation.RequiresApi
import com.example.adservices.samples.fledge.clients.AdSelectionClient
import com.example.adservices.samples.fledge.clients.TestAdSelectionClient
import com.google.common.util.concurrent.FutureCallback
import com.google.common.util.concurrent.Futures
import java.util.concurrent.Executor
import java.util.function.Consumer
import java.util.stream.Collectors
/**
* Wrapper for the FLEDGE Ad Selection API. This wrapper is opinionated and makes several
* choices such as running impression reporting immediately after every successful ad auction or leaving
* the ad signals empty to limit the complexity that is exposed the user.
*
* @param buyers A list of buyers for the auction.
* @param seller The name of the seller for the auction
* @param decisionUri The URI to retrieve the seller scoring and reporting logic from
* @param trustedScoringUri The URI to retrieve the trusted scoring signals
* @param context The application context.
* @param executor An executor to use with the FLEDGE API calls.
*/
@RequiresApi(api = 34)
class AdSelectionWrapper(
buyers: List<AdTechIdentifier>, seller: AdTechIdentifier, decisionUri: Uri, trustedScoringUri: Uri, context: Context,
executor: Executor
) {
private var adSelectionConfig: AdSelectionConfig
private val adClient: AdSelectionClient
private val executor: Executor
private val overrideClient: TestAdSelectionClient
/**
* Runs ad selection and passes a string describing its status to the input receivers. If ad
* selection succeeds, also report impressions.
* @param statusReceiver A consumer function that is run after ad selection and impression reporting
* with a string describing how the auction and reporting went.
* @param renderUriReceiver A consumer function that is run after ad selection with a message describing the render URI
* or lack thereof.
*/
fun runAdSelection(statusReceiver: Consumer<String>, renderUriReceiver: Consumer<String>) {
try {
Futures.addCallback(adClient.selectAds(adSelectionConfig),
object : FutureCallback<AdSelectionOutcome?> {
override fun onSuccess(adSelectionOutcome: AdSelectionOutcome?) {
statusReceiver.accept("Ran ad selection! ID: " + adSelectionOutcome!!.adSelectionId)
renderUriReceiver.accept("Would display ad from " + adSelectionOutcome.renderUri)
reportImpression(adSelectionOutcome.adSelectionId,
statusReceiver)
}
override fun onFailure(e: Throwable) {
statusReceiver.accept("Error when running ad selection: " + e.message)
renderUriReceiver.accept("Ad selection failed -- no ad to display")
Log.e(TAG, "Exception during ad selection", e)
}
}, executor)
} catch (e: Exception) {
statusReceiver.accept("Got the following exception when trying to run ad selection: $e")
renderUriReceiver.accept("Ad selection failed -- no ad to display")
Log.e(TAG, "Exception calling runAdSelection", e)
}
}
/**
* Helper function of [.runAdSelection]. Runs impression reporting.
*
* @param adSelectionId The auction to report impression on.
* @param statusReceiver A consumer function that is run after impression reporting
* with a string describing how the auction and reporting went.
*/
fun reportImpression(
adSelectionId: Long,
statusReceiver: Consumer<String>
) {
val request = ReportImpressionRequest(adSelectionId, adSelectionConfig)
Futures.addCallback(adClient.reportImpression(request),
object : FutureCallback<Void?> {
override fun onSuccess(unused: Void?) {
statusReceiver.accept("Reported impressions from ad selection")
}
override fun onFailure(e: Throwable) {
statusReceiver.accept("Error when reporting impressions: " + e.message)
Log.e(TAG, e.toString(), e)
}
}, executor)
}
/**
* Overrides remote info for an ad selection config.
*
* @param decisionLogicJS The overriding decision logic javascript
* @param statusReceiver A consumer function that is run after the API call and returns a
* string indicating the outcome of the call.
*/
fun overrideAdSelection(statusReceiver: Consumer<String?>, decisionLogicJS: String?, trustedScoringSignals: AdSelectionSignals?) {
val request = AddAdSelectionOverrideRequest(adSelectionConfig, decisionLogicJS!!, trustedScoringSignals!!);
Futures.addCallback(overrideClient.overrideAdSelectionConfigRemoteInfo(request),
object : FutureCallback<Void?> {
override fun onSuccess(unused: Void?) {
statusReceiver.accept("Added override for ad selection")
}
override fun onFailure(e: Throwable) {
statusReceiver.accept("Error when adding override for ad selection " + e.message)
Log.e(TAG, e.toString(), e)
}
}, executor)
}
/**
* Resets all ad selection overrides.
*
* @param statusReceiver A consumer function that is run after the API call and returns a
* string indicating the outcome of the call.
*/
fun resetAdSelectionOverrides(statusReceiver: Consumer<String?>) {
Futures.addCallback(overrideClient.resetAllAdSelectionConfigRemoteOverrides(),
object : FutureCallback<Void?> {
override fun onSuccess(unused: Void?) {
statusReceiver.accept("Reset ad selection overrides")
}
override fun onFailure(e: Throwable) {
statusReceiver.accept("Error when resetting all ad selection overrides " + e.message)
Log.e(TAG, e.toString(), e)
}
}, executor)
}
/**
* Resets the {code adSelectionConfig} with the new decisionUri associated with this `AdSelectionWrapper`.
* To be used when switching back and forth between dev overrides/mock server states.
*
* @param buyers the list of buyers to be used
* @param seller the seller to be users
* @param decisionUri the new {@code Uri} to be used
* @param trustedScoringUri the scoring signal uri to be used.
*/
fun resetAdSelectionConfig(
buyers: List<AdTechIdentifier>,
seller: AdTechIdentifier,
decisionUri: Uri,
trustedScoringUri: Uri) {
adSelectionConfig = AdSelectionConfig.Builder()
.setSeller(seller)
.setDecisionLogicUri(decisionUri)
.setCustomAudienceBuyers(buyers)
.setAdSelectionSignals(AdSelectionSignals.EMPTY)
.setSellerSignals(AdSelectionSignals.EMPTY)
.setPerBuyerSignals(buyers.stream()
.collect(Collectors.toMap(
{ buyer: AdTechIdentifier -> buyer },
{ AdSelectionSignals.EMPTY })))
.setTrustedScoringSignalsUri(trustedScoringUri)
.build()
}
/**
* Initializes the ad selection wrapper with a specific seller, list of buyers, and decision
* endpoint.
*/
init {
adSelectionConfig = AdSelectionConfig.Builder()
.setSeller(seller)
.setDecisionLogicUri(decisionUri)
.setCustomAudienceBuyers(buyers)
.setAdSelectionSignals(AdSelectionSignals.EMPTY)
.setSellerSignals(AdSelectionSignals.EMPTY)
.setPerBuyerSignals(buyers.stream()
.collect(Collectors.toMap(
{ buyer: AdTechIdentifier -> buyer },
{ AdSelectionSignals.EMPTY })))
.setTrustedScoringSignalsUri(trustedScoringUri)
.build()
adClient = AdSelectionClient.Builder().setContext(context).setExecutor(executor).build()
overrideClient = TestAdSelectionClient.Builder()
.setContext(context)
.setExecutor(executor)
.build()
this.executor = executor
}
} | apache-2.0 | 4dd7c527f21538d609ed395311944199 | 44.885167 | 132 | 0.662113 | 4.823441 | false | true | false | false |
Jire/Strukt | src/main/kotlin/org/jire/strukt/Strukts.kt | 1 | 6450 | /*
* Copyright 2020 Thomas Nappo (Jire)
*
* 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.jire.strukt
import org.jire.strukt.internal.*
import java.io.File
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSubclassOf
interface Strukts {
val type: KClass<*>
var size: Long
var nextIndex: Long
val fields: List<Field>
fun addField(field: Field)
fun free(): Boolean
fun allocate(): Long
fun free(address: Long): Boolean
fun free(strukt: Strukt) = free(strukt.address)
operator fun invoke() = allocate()
fun byteField(default: Byte, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): ByteField =
InternalByteField(type, this, threadSafeType, default)
fun shortField(default: Short, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): ShortField =
InternalShortField(type, this, threadSafeType, default)
fun intField(default: Int, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): IntField =
InternalIntField(type, this, threadSafeType, default)
fun longField(default: Long, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): LongField =
InternalLongField(type, this, threadSafeType, default)
fun floatField(default: Float, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): FloatField =
InternalFloatField(type, this, threadSafeType, default)
fun doubleField(default: Double, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): DoubleField =
InternalDoubleField(type, this, threadSafeType, default)
fun charField(default: Char, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): CharField =
InternalCharField(type, this, threadSafeType, default)
fun booleanField(default: Boolean, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): BooleanField =
InternalBooleanField(type, this, threadSafeType, default)
fun <E : Enum<E>> enumField(
default: E,
threadSafeType: ThreadSafeType = ThreadSafeType.NONE,
values: Array<E> = default.javaClass.enumConstants
): EnumField<E> =
InternalEnumField(type, this, threadSafeType, default, values)
operator fun invoke(default: Byte) = byteField(default)
operator fun invoke(default: Short) = shortField(default)
operator fun invoke(default: Int) = intField(default)
operator fun invoke(default: Long) = longField(default)
operator fun invoke(default: Float) = floatField(default)
operator fun invoke(default: Double) = doubleField(default)
operator fun invoke(default: Char) = charField(default)
operator fun invoke(default: Boolean) = booleanField(default)
operator fun <E : Enum<E>> invoke(default: E, values: Array<E> = default.javaClass.enumConstants) =
enumField(default, values = values)
operator fun Byte.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(byteField(this, prop.threadSafeType))
operator fun Short.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(shortField(this, prop.threadSafeType))
operator fun Int.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(intField(this, prop.threadSafeType))
operator fun Long.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(longField(this, prop.threadSafeType))
operator fun Float.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(floatField(this, prop.threadSafeType))
operator fun Double.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(doubleField(this, prop.threadSafeType))
operator fun Char.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(charField(this, prop.threadSafeType))
operator fun Boolean.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(booleanField(this, prop.threadSafeType))
operator fun <E : Enum<E>> E.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(enumField(this, prop.threadSafeType))
fun toString(address: Long): String
fun toString(strukt: Strukt) = toString(strukt.address)
companion object {
private val KProperty<*>.threadSafeType
get() = annotations
.firstOrNull { it::class.isSubclassOf(ThreadSafe::class) }
?.let { it as ThreadSafe }?.threadSafeType
?: ThreadSafeType.NONE
class FieldDelegate<F : Field>(val delegatedTo: F) {
operator fun getValue(strukts: Strukts, property: KProperty<*>) = delegatedTo
}
const val DEFAULT_ELASTIC_CAPACITY = 1024L
const val DEFAULT_ELASTIC_GROWTH_FACTOR = 2.0
@JvmStatic
fun fixed(type: KClass<*>, capacity: Long): Strukts = FixedStrukts(type, capacity, null)
@JvmStatic
fun fixed(type: Class<*>, capacity: Long): Strukts = fixed(type.kotlin, capacity)
@JvmStatic
fun fixed(type: KClass<*>, capacity: Long, persistedTo: File): Strukts =
FixedStrukts(type, capacity, persistedTo)
@JvmStatic
fun fixed(type: Class<*>, capacity: Long, persistedTo: File): Strukts =
fixed(type.kotlin, capacity, persistedTo)
@JvmStatic
fun fixed(type: KClass<*>, capacity: Long, persistedToPathname: String): Strukts =
FixedStrukts(type, capacity, File(persistedToPathname))
@JvmStatic
fun fixed(type: Class<*>, capacity: Long, persistedToPathname: String): Strukts =
fixed(type.kotlin, capacity, persistedToPathname)
@JvmStatic
fun pointed(type: KClass<*>): Strukts = PointedStrukts(type)
@JvmStatic
fun pointed(type: Class<*>): Strukts = pointed(type.kotlin)
@JvmStatic
@JvmOverloads
fun elastic(
type: KClass<*>,
initialCapacity: Long = DEFAULT_ELASTIC_CAPACITY,
growthFactor: Double = DEFAULT_ELASTIC_GROWTH_FACTOR
): Strukts = ElasticStrukts(type, initialCapacity, growthFactor)
@JvmStatic
@JvmOverloads
fun elastic(
type: Class<*>,
initialCapacity: Long = DEFAULT_ELASTIC_CAPACITY,
growthFactor: Double = DEFAULT_ELASTIC_GROWTH_FACTOR
): Strukts = elastic(type.kotlin, initialCapacity, growthFactor)
}
} | apache-2.0 | 58836b102ebc52bb22c2ff3b17670d1a | 35.241573 | 105 | 0.744961 | 3.694158 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/hazelcast/serializers/OrganizationExternalDatabaseTableStreamSerializer.kt | 1 | 2078 | package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.hazelcast.StreamSerializerTypeIds
import com.openlattice.organization.OrganizationExternalDatabaseTable
import org.springframework.stereotype.Component
import java.util.*
@Component
class OrganizationExternalDatabaseTableStreamSerializer : SelfRegisteringStreamSerializer<OrganizationExternalDatabaseTable> {
companion object {
fun serialize(output: ObjectDataOutput, obj: OrganizationExternalDatabaseTable) {
UUIDStreamSerializerUtils.serialize(output, obj.id)
output.writeUTF(obj.name)
output.writeUTF(obj.title)
output.writeUTF(obj.description)
UUIDStreamSerializerUtils.serialize(output, obj.organizationId)
output.writeInt(obj.oid)
}
fun deserialize(input: ObjectDataInput): OrganizationExternalDatabaseTable {
val id = UUIDStreamSerializerUtils.deserialize(input)
val name = input.readUTF()
val title = input.readUTF()
val description = input.readUTF()
val orgId = UUIDStreamSerializerUtils.deserialize(input)
val oid = input.readInt();
return OrganizationExternalDatabaseTable(id, name, title, Optional.of(description), orgId, oid)
}
}
override fun write(output: ObjectDataOutput, obj: OrganizationExternalDatabaseTable) {
serialize(output, obj)
}
override fun read(input: ObjectDataInput): OrganizationExternalDatabaseTable {
return deserialize(input)
}
override fun getClazz(): Class<out OrganizationExternalDatabaseTable> {
return OrganizationExternalDatabaseTable::class.java
}
override fun getTypeId(): Int {
return StreamSerializerTypeIds.ORGANIZATION_EXTERNAL_DATABASE_TABLE.ordinal
}
} | gpl-3.0 | 02bf46d8a68b251a4e6ec18f26ea9dba | 38.980769 | 126 | 0.74206 | 5.425587 | false | false | false | false |
msebire/intellij-community | plugins/stats-collector/src/com/intellij/completion/NotificationManager.kt | 3 | 1811 | // 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.completion
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.reporting.isSendAllowed
class NotificationManager : StartupActivity {
companion object {
private const val PLUGIN_NAME = "Completion Stats Collector"
private const val MESSAGE_TEXT =
"Data about your code completion usage will be anonymously reported. " +
"No personal data or code will be sent."
private const val MESSAGE_TEXT_EAP = "$MESSAGE_TEXT This is only enabled in EAP builds."
private const val MESSAGE_SHOWN_KEY = "completion.stats.allow.message.shown"
}
private fun isMessageShown() = PropertiesComponent.getInstance().getBoolean(MESSAGE_SHOWN_KEY, false)
private fun setMessageShown(value: Boolean) = PropertiesComponent.getInstance().setValue(MESSAGE_SHOWN_KEY, value)
override fun runActivity(project: Project) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return
}
// Show message in EAP build or if additional plugin installed
if (!isMessageShown() && isSendAllowed()) {
notify(project)
setMessageShown(true)
}
}
private fun notify(project: Project) {
val messageText = if (ApplicationManager.getApplication().isEAP) MESSAGE_TEXT_EAP else MESSAGE_TEXT
val notification = Notification(PLUGIN_NAME, PLUGIN_NAME, messageText, NotificationType.INFORMATION)
notification.notify(project)
}
} | apache-2.0 | e7fead8bb30f89a6640de1363c25fec6 | 39.266667 | 140 | 0.76698 | 4.655527 | false | false | false | false |
Bodo1981/swapi.co | app/src/main/java/com/christianbahl/swapico/list/delegates/TextDelegate.kt | 1 | 1699 | package com.christianbahl.swapico.list.delegates
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.christianbahl.swapico.R
import com.christianbahl.swapico.base.BaseDelegate
import com.christianbahl.swapico.list.model.ListItem
import com.christianbahl.swapico.list.model.ListItemType
import kotlinx.android.synthetic.main.row_single_text.view.*
import org.jetbrains.anko.onClick
/**
* @author Christian Bahl
*/
class TextDelegate(viewType: Int, context: Context, val callback: (detailsId: Int) -> Unit) : BaseDelegate<List<ListItem>>(viewType,
context) {
override fun onCreateViewHolder(parent: ViewGroup?) =
FilmViewHolder(inflater.inflate(R.layout.row_single_text, parent, false), callback)
override fun isForViewType(items: List<ListItem>?, position: Int) =
items?.get(position)?.type == ListItemType.TEXT
override fun onBindViewHolder(items: List<ListItem>?, position: Int, viewHolder: RecyclerView.ViewHolder?) {
(viewHolder as FilmViewHolder).bindView(items?.get(position))
}
class FilmViewHolder(itemView: View, val callback: (detailsId: Int) -> Unit) : RecyclerView.ViewHolder(itemView) {
public fun bindView(listItem: ListItem?) {
itemView.row_single_text_text.text = listItem?.text
if (listItem != null && listItem.url.isNotBlank()) {
itemView.onClick { callback(pathId(listItem.url)) }
}
}
private fun pathId(url: String): Int {
val fixedUrl = if (url.endsWith("/")) url.substring(0, url.length - 1) else url
val urlSplit = fixedUrl.split("/")
return urlSplit[urlSplit.size - 1].toInt()
}
}
} | apache-2.0 | b92da1a87669813fb30c57794460afd8 | 35.956522 | 132 | 0.733373 | 3.997647 | false | false | false | false |
yamamotoj/workshop-jb | src/syntax/ifWhenExpressions.kt | 55 | 737 | package syntax.ifWhenExpressions
fun ifExpression(a: Int, b: Int) {
val max1 = if (a > b) a else b
val max2 = if (a > b) {
println("Choose a")
a
}
else {
println("Choose b")
b
}
}
fun whenExpression(a: Any?) {
val result = when (a) {
null -> "null"
is String -> "String"
is Any -> "Any"
else -> "Don't know"
}
}
fun whenExpression(x: Int) {
when (x) {
0, 11 -> "0 or 11"
in 1..10 -> "from 1 to 10"
!in 12..14 -> "not from 12 to 14"
else -> "otherwise"
}
}
fun whenWithoutArgument(x: Int) {
when {
x == 42 -> "x is 42"
x % 2 == 1 -> "x is odd"
else -> "otherwise"
}
}
| mit | bc176f4c2ad9a3bdf5ffe88b26053ff2 | 16.97561 | 41 | 0.450475 | 3.176724 | false | false | false | false |
hschroedl/FluentAST | core/src/test/kotlin/at.hschroedl.fluentast/ast/expression/ArrayTest.kt | 1 | 2128 | package at.hschroedl.fluentast.ast.expression
import at.hschroedl.fluentast.arrayInit
import at.hschroedl.fluentast.ast.type.FluentArrayType
import at.hschroedl.fluentast.i
import at.hschroedl.fluentast.newArray
import at.hschroedl.fluentast.test.dummyExpression
import at.hschroedl.fluentast.test.dummyLiteral
import at.hschroedl.fluentast.test.dummyType
import at.hschroedl.fluentast.test.toInlineString
import org.eclipse.jdt.core.dom.ArrayAccess
import org.eclipse.jdt.core.dom.ArrayCreation
import org.eclipse.jdt.core.dom.ArrayInitializer
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class ArrayTest {
@Test
internal fun arrayAccess_withExpressions_returnsArrayAccessWithExpressions() {
val expression = dummyExpression("test").index(dummyLiteral(1)).build() as ArrayAccess
assertEquals("test[1]", expression.toInlineString())
}
@Test
internal fun arrayInitializer_withNumbers_returnsArrayInitializerWithNumbers() {
val expression = arrayInit(dummyLiteral(1),
dummyLiteral(2), dummyLiteral(3)).build() as ArrayInitializer
assertEquals("{1,2,3}", expression.toInlineString())
}
@Test
internal fun arrayInitializer_withNestedInitializers_returnsArrayInitializerWithNumbers() {
val expression = arrayInit(dummyLiteral(1), FluentArrayInitializer(
dummyLiteral(2), dummyLiteral(3))).build() as ArrayInitializer
assertEquals("{1,{2,3}}", expression.toInlineString())
}
@Test
internal fun arrayCreation_withType_returnsArrayCreation() {
val expression = newArray(FluentArrayType(dummyType("Integer"), 3)).build() as ArrayCreation
assertEquals("new Integer[][][]", expression.toInlineString())
}
@Test
internal fun arrayCreation_withInitializer_returnsArrayCreation() {
val expression = newArray(FluentArrayType(dummyType("Integer"), 3), arrayInit(
i(1), i(2))).build() as ArrayCreation
assertEquals("new Integer[][][]{1,2}", expression.toInlineString())
}
} | apache-2.0 | 719a37397a02aea30d3a92daf4de60ae | 35.706897 | 100 | 0.730263 | 4.405797 | false | true | false | false |
joan-domingo/Podcasts-RAC1-Android | app/src/test/java/cat/xojan/random1/testutil/Data.kt | 1 | 2234 | package cat.xojan.random1.testutil
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.session.MediaSessionCompat
import cat.xojan.random1.domain.model.Podcast
import cat.xojan.random1.domain.model.PodcastState
import cat.xojan.random1.domain.model.Program
import cat.xojan.random1.domain.model.Section
import java.util.*
val podcast1 = Podcast("id1", "path1", "filePath1", Date(), 0, "podcastId1",
null, null, PodcastState.DOWNLOADED, "programTitle1", 1)
val podcast2 = Podcast("id2", "path1", null, Date(), 0, "podcastId2", null,
null, PodcastState.LOADED, "programTitle1", 1)
val podcast3 = Podcast("id3", "path1", "filePath3", Date(), 0, "podcastId3",
null, null, PodcastState.DOWNLOADING, "programTitle1", 1)
val podcastList = listOf(podcast1, podcast2, podcast3)
val section1 = Section("sectionId1", "sectionTitle1", "http://image.url", "programId1")
val section2 = Section("sectionId2", "sectionTitle2", "http://image.url", "programId1")
val section3 = Section("sectionId3", "sectionTitle3", "http://image.url", "programId1")
val section4 = Section("sectionId4", "sectionTitle4", "http://image.url", "programId1")
val sectionList = listOf(section1, section2, section3, section4)
val sectionListResult1 = listOf(section1, section4)
// PROGRAMS
val program1 = Program("programId1", "programTitle1", null, null)
val program2 = Program("programId2", "programTitle2", null, null)
val program3 = Program("programId3", "programTitle3", null, null)
val programsMap = linkedMapOf(Pair("programId1", program1), Pair("programId2", program2), Pair("programId3", program3))
// Description item
val description1:MediaDescriptionCompat = MediaDescriptionCompat.Builder()
.build()
val description2:MediaDescriptionCompat = MediaDescriptionCompat.Builder()
.build()
val description3:MediaDescriptionCompat = MediaDescriptionCompat.Builder()
.build()
// Queue item
val queueItem1 = MediaSessionCompat.QueueItem(description1, 1)
val queueItem2 = MediaSessionCompat.QueueItem(description2, 2)
val queueItem3 = MediaSessionCompat.QueueItem(description3, 3)
val queueList1Item = listOf(queueItem1)
val queueItemList = listOf(queueItem1, queueItem2, queueItem3) | mit | 01de61a6ca8427474fb41b518ebd41ed | 48.666667 | 119 | 0.760072 | 3.656301 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/reviewer/Binding.kt | 1 | 10521 | /*
* Copyright (c) 2021 David Allison <[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 com.ichi2.anki.reviewer
import android.content.Context
import android.os.Build
import android.view.KeyEvent
import androidx.annotation.VisibleForTesting
import com.ichi2.anki.cardviewer.Gesture
import com.ichi2.compat.CompatHelper
import com.ichi2.utils.StringUtil
import timber.log.Timber
class Binding private constructor(val modifierKeys: ModifierKeys?, val keycode: Int?, val unicodeCharacter: Char?, val gesture: Gesture?) {
constructor(gesture: Gesture?) : this(null, null, null, gesture)
private fun getKeyCodePrefix(): String {
// KEY_PREFIX is not usable before API 23
val keyPrefix = if (CompatHelper.sdkVersion >= Build.VERSION_CODES.M) KEY_PREFIX.toString() else ""
if (keycode == null) {
return keyPrefix
}
if (KeyEvent.isGamepadButton(keycode)) {
return GAMEPAD_PREFIX
}
return keyPrefix
}
fun toDisplayString(context: Context?): String {
val string = StringBuilder()
when {
keycode != null -> {
string.append(getKeyCodePrefix())
string.append(' ')
string.append(modifierKeys!!.toString())
val keyCodeString = KeyEvent.keyCodeToString(keycode)
// replace "Button" as we use the gamepad icon
string.append(StringUtil.toTitleCase(keyCodeString.replace("KEYCODE_", "").replace("BUTTON_", "").replace('_', ' ')))
}
unicodeCharacter != null -> {
string.append(KEY_PREFIX)
string.append(' ')
string.append(modifierKeys!!.toString())
string.append(unicodeCharacter)
}
gesture != null -> {
string.append(gesture.toDisplayString(context!!))
}
}
return string.toString()
}
override fun toString(): String {
val string = StringBuilder()
when {
keycode != null -> {
string.append(KEY_PREFIX)
string.append(modifierKeys!!.toString())
string.append(keycode)
}
unicodeCharacter != null -> {
string.append(UNICODE_PREFIX)
string.append(modifierKeys!!.toString())
string.append(unicodeCharacter)
}
gesture != null -> {
string.append(GESTURE_PREFIX)
string.append(gesture)
}
}
return string.toString()
}
val isValid: Boolean get() = isKey || gesture != null
val isKeyCode: Boolean get() = keycode != null
val isKey: Boolean
get() = isKeyCode || unicodeCharacter != null
val isGesture: Boolean = gesture != null
fun matchesModifier(event: KeyEvent): Boolean {
return modifierKeys == null || modifierKeys.matches(event)
}
open class ModifierKeys internal constructor(private val shift: Boolean, private val ctrl: Boolean, private val alt: Boolean) {
fun matches(event: KeyEvent): Boolean {
// return false if Ctrl+1 is pressed and 1 is expected
return shiftMatches(event) && ctrlMatches(event) && altMatches(event)
}
private fun shiftMatches(event: KeyEvent): Boolean = shift == event.isShiftPressed
private fun ctrlMatches(event: KeyEvent): Boolean = ctrl == event.isCtrlPressed
private fun altMatches(event: KeyEvent): Boolean = altMatches(event.isAltPressed)
open fun shiftMatches(shiftPressed: Boolean): Boolean = shift == shiftPressed
fun ctrlMatches(ctrlPressed: Boolean): Boolean = ctrl == ctrlPressed
fun altMatches(altPressed: Boolean): Boolean = alt == altPressed
override fun toString(): String {
val string = StringBuilder()
if (ctrl) {
string.append("Ctrl+")
}
if (alt) {
string.append("Alt+")
}
if (shift) {
string.append("Shift+")
}
return string.toString()
}
companion object {
fun none(): ModifierKeys = ModifierKeys(shift = false, ctrl = false, alt = false)
fun ctrl(): ModifierKeys = ModifierKeys(shift = false, ctrl = true, alt = false)
fun shift(): ModifierKeys = ModifierKeys(shift = true, ctrl = false, alt = false)
fun alt(): ModifierKeys = ModifierKeys(shift = false, ctrl = false, alt = true)
/**
* Parses a [ModifierKeys] from a string.
* @param s The string to parse
* @return The [ModifierKeys], and the remainder of the string
*/
fun parse(s: String): Pair<ModifierKeys, String> {
var modifiers = none()
val plus = s.lastIndexOf("+")
if (plus == -1) {
return Pair(modifiers, s)
}
modifiers = fromString(s.substring(0, plus + 1))
return Pair(modifiers, s.substring(plus + 1))
}
fun fromString(from: String): ModifierKeys =
ModifierKeys(from.contains("Shift"), from.contains("Ctrl"), from.contains("Alt"))
}
}
/** Modifier keys which cannot be defined by a binding */
private class AppDefinedModifierKeys private constructor() : ModifierKeys(false, false, false) {
override fun shiftMatches(shiftPressed: Boolean): Boolean = true
companion object {
/**
* Specifies a keycode combination binding from an unknown input device
* Should be due to the "default" key bindings and never from user input
*
* If we do not know what the device is, "*" could be a key on the keyboard or Shift + 8
*
* So we need to ignore shift, rather than match it to a value
*
* If we have bindings in the app, then we know whether we need shift or not (in actual fact, we should
* be fine to use keycodes).
*/
fun allowShift(): ModifierKeys = AppDefinedModifierKeys()
}
}
companion object {
const val FORBIDDEN_UNICODE_CHAR = MappableBinding.PREF_SEPARATOR
/**
* https://www.fileformat.info/info/unicode/char/2328/index.htm (Keyboard)
* This is not usable on API 21 or 22
*/
const val KEY_PREFIX = '\u2328'
/** https://www.fileformat.info/info/unicode/char/235d/index.htm (similar to a finger) */
const val GESTURE_PREFIX = '\u235D'
/** https://www.fileformat.info/info/unicode/char/2705/index.htm - checkmark (often used in URLs for unicode)
* Only used for serialisation. [.KEY_PREFIX] is used for display.
*/
const val UNICODE_PREFIX = '\u2705'
const val GAMEPAD_PREFIX = "🎮"
/** This returns multiple bindings due to the "default" implementation not knowing what the keycode for a button is */
fun key(event: KeyEvent): List<Binding> {
val modifiers = ModifierKeys(event.isShiftPressed, event.isCtrlPressed, event.isAltPressed)
val ret: MutableList<Binding> = ArrayList()
val keyCode = event.keyCode
if (keyCode != 0) {
ret.add(keyCode(modifiers, keyCode))
}
// passing in metaState: 0 means that Ctrl+1 returns '1' instead of '\0'
// NOTE: We do not differentiate on upper/lower case via KeyEvent.META_CAPS_LOCK_ON
val unicodeChar = event.getUnicodeChar(event.metaState and (KeyEvent.META_SHIFT_ON or KeyEvent.META_NUM_LOCK_ON))
if (unicodeChar != 0) {
try {
ret.add(unicode(modifiers, unicodeChar.toChar()))
} catch (e: Exception) {
Timber.w(e)
}
}
return ret
}
/**
* Specifies a unicode binding from an unknown input device
* See [AppDefinedModifierKeys]
*/
fun unicode(unicodeChar: Char): Binding =
unicode(AppDefinedModifierKeys.allowShift(), unicodeChar)
fun unicode(modifierKeys: ModifierKeys?, unicodeChar: Char): Binding {
if (unicodeChar == FORBIDDEN_UNICODE_CHAR) return unknown()
return Binding(modifierKeys, null, unicodeChar, null)
}
fun keyCode(keyCode: Int): Binding = keyCode(ModifierKeys.none(), keyCode)
fun keyCode(modifiers: ModifierKeys?, keyCode: Int): Binding =
Binding(modifiers, keyCode, null, null)
fun gesture(gesture: Gesture?): Binding = Binding(null, null, null, gesture)
@VisibleForTesting
fun unknown(): Binding = Binding(ModifierKeys.none(), null, null, null)
fun fromString(from: String): Binding {
if (from.isEmpty()) return unknown()
try {
return when (from[0]) {
GESTURE_PREFIX -> {
gesture(Gesture.valueOf(from.substring(1)))
}
UNICODE_PREFIX -> {
val parsed = ModifierKeys.parse(from.substring(1))
unicode(parsed.first, parsed.second[0])
}
KEY_PREFIX -> {
val parsed = ModifierKeys.parse(from.substring(1))
val keyCode = parsed.second.toInt()
keyCode(parsed.first, keyCode)
}
else -> unknown()
}
} catch (ex: Exception) {
Timber.w(ex)
}
return unknown()
}
}
}
| gpl-3.0 | 10ca10d71427615172b952cf733a3478 | 37.955556 | 139 | 0.57587 | 4.783083 | false | false | false | false |
Samourai-Wallet/samourai-wallet-android | app/src/main/java/com/samourai/wallet/RecoveryWordsActivity.kt | 1 | 7474 | package com.samourai.wallet
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.google.android.material.transition.MaterialSharedAxis
import com.samourai.wallet.access.AccessFactory
import com.samourai.wallet.util.AppUtil
import com.samourai.wallet.util.TimeOutUtil
import kotlinx.android.synthetic.main.activity_recovery_words.*
import kotlinx.android.synthetic.main.fragment_paper_wallet_instructions.*
import kotlinx.android.synthetic.main.fragment_recovery_passphrase.*
import kotlinx.android.synthetic.main.fragment_recovery_words.*
class RecoveryWordsActivity : AppCompatActivity() {
private var step = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recovery_words)
window.statusBarColor = ContextCompat.getColor(this, R.color.window)
navigate()
nextButton.setOnClickListener {
step += 1
navigate()
}
if(BuildConfig.FLAVOR != "staging"){
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
}
}
private fun navigate() {
val wordList = arrayListOf<String>();
var passphrase = ""
intent.extras?.getString(WORD_LIST)?.let { it ->
val words: Array<String> = it.trim { it <= ' ' }.split(" ").toTypedArray()
wordList.addAll(words)
}
intent.extras?.getString(PASSPHRASE)?.let { it ->
passphrase = it
}
if (step >= 3) {
AccessFactory.getInstance(applicationContext).setIsLoggedIn(true)
TimeOutUtil.getInstance().updatePin()
AppUtil.getInstance(applicationContext).restartApp()
return
}
val fragment = when (step) {
0 -> RecoveryTemplateDownload()
1 -> RecoveryWords.newInstance(ArrayList(wordList))
2 -> PassphraseFragment.newInstance(passphrase)
else -> RecoveryTemplateDownload()
}
supportFragmentManager
.beginTransaction()
.replace(recoveryWordsFrame.id, fragment)
.commit()
}
override fun onBackPressed() {
if (step == 0) {
super.onBackPressed()
} else {
step -= 1
this.navigate()
}
}
class RecoveryTemplateDownload : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_paper_wallet_instructions, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true)
returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
downloadRecoveryTemplate.setOnClickListener {
startActivity(Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse("https://samouraiwallet.com/recovery/worksheet")
})
}
}
}
class PassphraseFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_recovery_passphrase, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true)
returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let { bundle->
bundle.getString(PASSPHRASE)?.let {
passphraseView.text = it
}
}
}
companion object {
fun newInstance(passPhrase: String): Fragment {
return PassphraseFragment().apply {
arguments = Bundle().apply {
putString(PASSPHRASE, passPhrase)
}
}
}
}
}
class RecoveryWords : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_recovery_words, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enterTransition = MaterialSharedAxis(MaterialSharedAxis.X,true)
returnTransition = MaterialSharedAxis(MaterialSharedAxis.X,false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let { bundle ->
bundle.getStringArrayList(WORD_LIST)
?.let {
if (it.size == 12) {
it.map { word -> "(${it.indexOf(word) + 1}) $word" }
.forEachIndexed { index, word ->
run {
when (index) {
0 -> word1.text = word
1 -> word2.text = word
2 -> word3.text = word
3 -> word4.text = word
4 -> word5.text = word
5 -> word6.text = word
6 -> word7.text = word
7 -> word8.text = word
8 -> word9.text = word
9 -> word10.text = word
10 -> word11.text = word
11 -> word12.text = word
}
}
}
}
}
}
}
companion object {
fun newInstance(list: ArrayList<String>): Fragment {
return RecoveryWords().apply {
arguments = Bundle().apply {
putStringArrayList(WORD_LIST, list)
}
}
}
}
}
companion object {
const val WORD_LIST = "BIP39_WORD_LIST"
const val PASSPHRASE = "PASSPHRASE"
}
} | unlicense | 1b198561c976bb28e90e9a6910048b1e | 37.333333 | 120 | 0.537062 | 5.662121 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/protobuf/commonMain/src/kotlinx/serialization/protobuf/internal/ProtobufWriter.kt | 1 | 3078 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:OptIn(ExperimentalSerializationApi::class)
package kotlinx.serialization.protobuf.internal
import kotlinx.serialization.*
import kotlinx.serialization.protobuf.*
internal class ProtobufWriter(private val out: ByteArrayOutput) {
fun writeBytes(bytes: ByteArray, tag: Int) {
out.encode32((tag shl 3) or SIZE_DELIMITED)
writeBytes(bytes)
}
fun writeBytes(bytes: ByteArray) {
out.encode32(bytes.size)
out.write(bytes)
}
fun writeOutput(output: ByteArrayOutput, tag: Int) {
out.encode32((tag shl 3) or SIZE_DELIMITED)
writeOutput(output)
}
fun writeOutput(output: ByteArrayOutput) {
out.encode32(output.size())
out.write(output)
}
fun writeInt(value: Int, tag: Int, format: ProtoIntegerType) {
val wireType = if (format == ProtoIntegerType.FIXED) i32 else VARINT
out.encode32((tag shl 3) or wireType)
out.encode32(value, format)
}
fun writeInt(value: Int) {
out.encode32(value)
}
fun writeLong(value: Long, tag: Int, format: ProtoIntegerType) {
val wireType = if (format == ProtoIntegerType.FIXED) i64 else VARINT
out.encode32((tag shl 3) or wireType)
out.encode64(value, format)
}
fun writeLong(value: Long) {
out.encode64(value)
}
fun writeString(value: String, tag: Int) {
val bytes = value.encodeToByteArray()
writeBytes(bytes, tag)
}
fun writeString(value: String) {
val bytes = value.encodeToByteArray()
writeBytes(bytes)
}
fun writeDouble(value: Double, tag: Int) {
out.encode32((tag shl 3) or i64)
out.writeLong(value.reverseBytes())
}
fun writeDouble(value: Double) {
out.writeLong(value.reverseBytes())
}
fun writeFloat(value: Float, tag: Int) {
out.encode32((tag shl 3) or i32)
out.writeInt(value.reverseBytes())
}
fun writeFloat(value: Float) {
out.writeInt(value.reverseBytes())
}
private fun ByteArrayOutput.encode32(
number: Int,
format: ProtoIntegerType = ProtoIntegerType.DEFAULT
) {
when (format) {
ProtoIntegerType.FIXED -> out.writeInt(number.reverseBytes())
ProtoIntegerType.DEFAULT -> encodeVarint64(number.toLong())
ProtoIntegerType.SIGNED -> encodeVarint32(((number shl 1) xor (number shr 31)))
}
}
private fun ByteArrayOutput.encode64(number: Long, format: ProtoIntegerType = ProtoIntegerType.DEFAULT) {
when (format) {
ProtoIntegerType.FIXED -> out.writeLong(number.reverseBytes())
ProtoIntegerType.DEFAULT -> encodeVarint64(number)
ProtoIntegerType.SIGNED -> encodeVarint64((number shl 1) xor (number shr 63))
}
}
private fun Float.reverseBytes(): Int = toRawBits().reverseBytes()
private fun Double.reverseBytes(): Long = toRawBits().reverseBytes()
}
| apache-2.0 | c7d7693d967694cf9243282303725619 | 29.176471 | 109 | 0.64425 | 4.03937 | false | false | false | false |
jonninja/node.kt | src/main/kotlin/node/express/middleware/Static.kt | 1 | 1940 | package node.express.middleware
import node.express.Request
import node.express.Response
import java.io.File
import java.util.HashMap
import node.express.RouteHandler
import node.mimeType
import node.util._withNotNull
/**
* Middleware for serving a tree of static files
*/
public fun static(basePath: String): RouteHandler.()->Unit {
val files = HashMap<String, File>() // a cache of paths to files to improve performance
return {
if (req.method != "get" && req.method != "head")
next()
else {
var requestPath = req.param("*") as? String ?: ""
var srcFile: File? = files[requestPath] ?: {
var path = requestPath
if (!path.startsWith("/")) {
path = "/" + path
}
if (path.endsWith("/")) {
path += "index.html"
}
var f = File(basePath + path)
if (f.exists()) {
files.put(requestPath, f)
f
} else {
null
}
}()
if (srcFile != null) {
res.sendFile(srcFile)
} else {
next()
}
}
}
}
/**
* Middleware that servers static resources from the code pacakage
*/
public fun staticResources(classBasePath: String): RouteHandler.()->Unit {
return {
if (req.method != "get" && req.method != "head")
next()
else {
var requestPath = req.param("*") as? String ?: ""
if (requestPath.length() > 0 && requestPath.charAt(0) == '/') {
requestPath = requestPath.substring(1)
}
var resource = Thread.currentThread().getContextClassLoader().getResource(classBasePath + requestPath)
if (resource != null) {
_withNotNull(requestPath.mimeType()) { res.contentType(it) }
resource.openStream().use {
res.send(it)
}
} else {
next()
}
}
}
} | mit | c2a1451640299525c8be26581795cc2f | 25.958333 | 114 | 0.536082 | 4.340045 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/shows/collected/CollectedShowsFragment.kt | 1 | 4546 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.ui.shows.collected
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import net.simonvt.cathode.R
import net.simonvt.cathode.provider.ProviderSchematic.Shows
import net.simonvt.cathode.settings.Settings
import net.simonvt.cathode.settings.TraktLinkSettings
import net.simonvt.cathode.sync.scheduler.EpisodeTaskScheduler
import net.simonvt.cathode.sync.scheduler.ShowTaskScheduler
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.LibraryType
import net.simonvt.cathode.ui.lists.ListDialog
import net.simonvt.cathode.ui.shows.ShowsFragment
import javax.inject.Inject
class CollectedShowsFragment @Inject constructor(
showScheduler: ShowTaskScheduler,
episodeScheduler: EpisodeTaskScheduler
) : ShowsFragment(showScheduler, episodeScheduler), ListDialog.Callback {
@Inject
lateinit var viewModelFactory: CathodeViewModelFactory
lateinit var viewModel: CollectedShowsViewModel
private var sortBy: SortBy? = null
enum class SortBy constructor(val key: String, val sortOrder: String) {
TITLE("title", Shows.SORT_TITLE), COLLECTED("collected", Shows.SORT_COLLECTED);
override fun toString(): String {
return key
}
companion object {
fun fromValue(value: String) = values().firstOrNull { it.key == value } ?: TITLE
}
}
override fun onCreate(inState: Bundle?) {
sortBy = SortBy.fromValue(
Settings.get(requireContext())
.getString(Settings.Sort.SHOW_COLLECTED, SortBy.TITLE.key)!!
)
super.onCreate(inState)
setEmptyText(R.string.empty_show_collection)
setTitle(R.string.title_shows_collection)
viewModel =
ViewModelProviders.of(this, viewModelFactory).get(CollectedShowsViewModel::class.java)
viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) })
viewModel.shows.observe(this, observer)
}
override fun onViewCreated(view: View, inState: Bundle?) {
super.onViewCreated(view, inState)
swipeRefreshLayout.isEnabled = TraktLinkSettings.isLinked(requireContext())
}
override fun createMenu(toolbar: Toolbar) {
super.createMenu(toolbar)
toolbar.inflateMenu(R.menu.fragment_shows_collected)
}
override fun onRefresh() {
viewModel.refresh()
}
override fun onMenuItemClick(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_sort) {
val items = arrayListOf<ListDialog.Item>()
items.add(ListDialog.Item(R.id.sort_title, R.string.sort_title))
items.add(ListDialog.Item(R.id.sort_collected, R.string.sort_collected))
ListDialog.newInstance(requireFragmentManager(), R.string.action_sort_by, items, this)
.show(requireFragmentManager(), DIALOG_SORT)
return true
}
return super.onMenuItemClick(item)
}
override fun onItemSelected(id: Int) {
when (id) {
R.id.sort_title -> if (sortBy != SortBy.TITLE) {
sortBy = SortBy.TITLE
Settings.get(requireContext())
.edit()
.putString(Settings.Sort.SHOW_COLLECTED, SortBy.TITLE.key)
.apply()
viewModel.setSortBy(sortBy!!)
scrollToTop = true
}
R.id.sort_collected -> if (sortBy != SortBy.COLLECTED) {
sortBy = SortBy.COLLECTED
Settings.get(requireContext())
.edit()
.putString(Settings.Sort.SHOW_COLLECTED, SortBy.COLLECTED.key)
.apply()
viewModel.setSortBy(sortBy!!)
scrollToTop = true
}
}
}
override fun getLibraryType(): LibraryType {
return LibraryType.COLLECTION
}
companion object {
const val TAG = "net.simonvt.cathode.ui.shows.collected.ShowsCollectionFragment"
private const val DIALOG_SORT =
"net.simonvt.cathode.common.ui.fragment.ShowCollectionFragment.sortDialog"
}
}
| apache-2.0 | c18af22b22affaff37769527fdc81609 | 31.705036 | 92 | 0.725693 | 4.268545 | false | false | false | false |
tomhenne/Jerusalem | src/main/java/de/esymetric/jerusalem/osmDataRepresentation/OSMDataReader.kt | 1 | 7034 | package de.esymetric.jerusalem.osmDataRepresentation
import de.esymetric.jerusalem.utils.Utils
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.util.*
class OSMDataReader(
var inputStream: InputStream,
var listener: OSMDataReaderListener, var jumpOverNodes: Boolean
) {
var entityCount: Long = 0
interface OSMDataReaderListener {
fun foundNode(node: OSMNode)
fun foundWay(way: OSMWay)
}
var buffer = ""
fun read(startTime: Date): Boolean {
val lnr = BufferedReader(
InputStreamReader(
inputStream
), 1_000_000
)
try {
readToTag(lnr, "<osm")
readToTag(lnr, ">")
if (jumpOverNodes) {
while (true) {
buffer = lnr.readLine()
if (!buffer.contains("<way")) {
continue
}
break
}
}
while (true) {
if (readToTag(lnr, "<") == null) break
val xmlNodeName = readToTag(lnr, " ")
val sb = StringBuilder()
sb.append(xmlNodeName)
sb.append(' ')
val tail = readToTag(lnr, ">")
sb.append(tail)
if (tail?.last() != '/') {
sb.append('>')
sb.append(readToTag(lnr, "</$xmlNodeName>"))
sb.append("</")
sb.append(xmlNodeName)
}
val content = sb.toString()
entityCount++
if (entityCount and 0xFFFFF == 0L) {
println(
Utils.formatTimeStopWatch(
Date().time - startTime.time
) + " " + entityCount + " entities read"
)
if (entityCount and 0x700000 == 0L) {
print("free memory: "
+ Runtime.getRuntime().freeMemory() / 1024L / 1024L
+ " MB / "
+ Runtime.getRuntime().totalMemory() / 1024L / 1024L
+ " MB "
)
System.gc()
println(
" >>> "
+ Runtime.getRuntime().freeMemory() / 1024L / 1024L
+ " MB / "
+ Runtime.getRuntime().totalMemory() / 1024L / 1024L
+ " MB "
)
}
}
if ("node" == xmlNodeName) {
makeOSMNode(content)
continue
}
if ("way" == xmlNodeName) {
makeOSMWay(content)
continue
}
}
} catch (e: IOException) {
e.printStackTrace()
}
return true
}
private fun makeOSMWay(content: String) {
try {
val way = OSMWay()
val xmlNodes = splitXmlNodes(content)
val attributes = getAttributes(xmlNodes.first())
way.id = attributes["id"]?.toInt() ?: throw OsmReaderXMLParseException()
val nodes = mutableListOf<Long>()
val tags = mutableMapOf<String, String>()
for (childNode in xmlNodes) {
if (childNode.startsWith("nd")) {
val childAttrib = getAttributes(childNode)
childAttrib["ref"]?.toLong()?.let {
nodes.add(it)
}
} else
if (childNode.startsWith("tag")) {
val childAttrib = getAttributes(childNode)
tags[childAttrib["k"]!!] =
childAttrib["v"]!!
}
}
way.nodes = nodes.toTypedArray()
way.tags = tags
listener.foundWay(way)
} catch (e: OsmReaderXMLParseException) {
println("XML Parse Error on: $content")
e.printStackTrace()
}
}
private fun makeOSMNode(content: String) {
try {
val node = OSMNode()
val xmlNodes = splitXmlNodes(content)
val attributes = getAttributes(xmlNodes.first())
node.id = attributes["id"]?.toLong() ?: throw OsmReaderXMLParseException()
node.lat = attributes["lat"]?.toDouble() ?: throw OsmReaderXMLParseException()
node.lng = attributes["lon"]?.toDouble() ?: throw OsmReaderXMLParseException()
listener.foundNode(node)
} catch (e: OsmReaderXMLParseException) {
println("XML Parse Error on: $content")
e.printStackTrace()
}
}
@Throws(IOException::class)
fun readToTag(lnr: BufferedReader, tag: String): String? {
if (buffer.isNotEmpty()) {
val p = buffer.indexOf(tag)
if (p >= 0) {
val head = buffer.substring(0, p)
val tail = buffer.substring(p + tag.length)
buffer = tail + '\n'
return head
}
}
val buf = StringBuffer()
buf.append(buffer)
while (true) {
val line = lnr.readLine() ?: return null
val p = line.indexOf(tag)
if (p < 0) {
buf.append(line)
buf.append('\n')
} else {
val head = line.substring(0, p)
val tail = line.substring(p + tag.length)
buf.append(head)
buffer = tail + '\n'
return buf.toString()
}
}
}
private fun splitXmlNodes(content: String): List<String> =
content.split('<')
private fun getAttributes(content: String): Map<String, String> {
var tail = content
val attrib = mutableMapOf<String, String>()
while(true) {
val pBlank = tail.indexOf(' ')
if (pBlank < 0 ) break;
val pEquals = tail.indexOf('=')
if (pEquals < 0 ) break;
val name = tail.substring(pBlank + 1, pEquals)
tail = tail.substring(pEquals + 2) // jump over quote
val pQuote = tail.indexOf('"')
if (pQuote < 0 ) break;
val value = tail.substring(0, pQuote)
tail = tail.substring(pQuote + 1)
attrib[name] = value
}
return attrib
}
}
class OsmReaderXMLParseException : RuntimeException()
| apache-2.0 | d30582e3b858d3e141ca031bb0b7c4c3 | 32.995025 | 90 | 0.438726 | 5.141813 | false | false | false | false |
RanKKI/PSNine | app/src/main/java/xyz/rankki/psnine/model/topic/Home.kt | 1 | 2384 | package xyz.rankki.psnine.model.topic
import me.ghui.fruit.Attrs
import me.ghui.fruit.annotations.Pick
import xyz.rankki.psnine.base.BaseTopicModel
import xyz.rankki.psnine.common.config.PSNineTypes
class Home : BaseTopicModel() {
@Pick(value = "div.side > div.box > p:nth-child(1) > a > img", attr = Attrs.SRC)
private var _avatar: String = ""
@Pick(value = "div.side > div.box > p:nth-child(2) > a")
private var _username: String = ""
@Pick(value = "div.main > div:nth-child(1) > div:nth-child(1) > div > span:nth-child(3)")
private var _meta: String = ""
@Pick(value = "div.main > div:nth-child(1) > div:nth-child(1) > h1")
private var _title: String = ""
@Pick(value = "div.main > div:nth-child(1) > div.content.pd10", attr = Attrs.INNER_HTML)
private var _content: String = ""
@Pick(value = "div.main > div.box.mt20 > div.post:has(div.ml64)")
private var _replies: ArrayList<Reply> = ArrayList()
@Pick(value = "div.main > div.box.mt20 > div.post > a.btn")
private var _isMoreReplies: String = ""
@Pick(value = "div.main > div.box > table.list > tbody > tr")
var games: ArrayList<Game> = ArrayList()
@Pick(value = "div.main > div:nth-child(1) > div.content.pd10:has(table)", attr = "itemprop")
private var _hasTable: String = ""
@Pick(value = "div.main > div:nth-child(1) > div.content.pd10:has(div.pd10)", attr = "itemprop")
private var _hasTrophy: String = ""
override fun getType(): Int = PSNineTypes.Home
override fun getUsername(): String = _username
override fun getContent(): String = "<h3>$_title</h3><br>$_content"
override fun getTime(): String = _meta
override fun getAvatar(): String = _avatar
override fun isMoreReplies(): Boolean = _isMoreReplies !== ""
override fun getReplies(): ArrayList<Reply> = _replies
override fun usingWebView(): Boolean = _hasTable !== "" || _hasTrophy !== ""
class Game {
@Pick(value = "td.pdd10 > a > img", attr = Attrs.SRC)
var gameAvatar: String = ""
@Pick(value = "td.pd10 > p > a")
var gameName: String = ""
@Pick(value = "td.pd10 > p > span")
var gameEdition: String = ""
@Pick(value = "td.pd10 > div.meta")
var gameTrophy: String = ""
@Pick(value = "td.pd10 > blockquote")
var gameComment: String = ""
}
}
| apache-2.0 | 986f47c96052fd87d3599f4e1d006569 | 31.657534 | 100 | 0.613674 | 3.265753 | false | false | false | false |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/ui/web/WebActivity.kt | 1 | 2040 | package jp.kentan.studentportalplus.ui.web
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import jp.kentan.studentportalplus.R
import jp.kentan.studentportalplus.databinding.ActivityWebBinding
class WebActivity : AppCompatActivity() {
companion object {
private const val EXTRA_TITLE = "EXTRA_TITLE"
private const val EXTRA_URL = "EXTRA_URL"
fun createIntent(context: Context, title: String, url: String) =
Intent(context, WebActivity::class.java).apply {
putExtra(EXTRA_TITLE, title)
putExtra(EXTRA_URL, url)
}
}
private lateinit var webView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
webView = DataBindingUtil.setContentView<ActivityWebBinding>(this, R.layout.activity_web).webView
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val title = intent.getStringExtra(EXTRA_TITLE)
val url = intent.getStringExtra(EXTRA_URL)
if (title == null || url == null) {
finish()
return
}
setTitle(title)
webView.apply {
settings.cacheMode = WebSettings.LOAD_NO_CACHE
settings.setAppCacheEnabled(false)
loadUrl(url)
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
finish()
return true
}
override fun onPause() {
webView.run {
onPause()
pauseTimers()
}
super.onPause()
}
override fun onResume() {
super.onResume()
webView.run {
resumeTimers()
onResume()
}
}
override fun onDestroy() {
webView.destroy()
super.onDestroy()
}
} | gpl-3.0 | d5c3b80c11045ee577523d8ffbde7ef6 | 25.506494 | 105 | 0.630392 | 4.963504 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/ToolBarToolConnector.kt | 1 | 2860 | /*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.project
import javafx.event.EventHandler
import javafx.geometry.Orientation
import javafx.geometry.Side
import javafx.scene.control.Button
import javafx.scene.control.ContextMenu
import javafx.scene.control.MenuItem
import javafx.scene.control.ToolBar
import uk.co.nickthecoder.paratask.ToolBarTool
/**
* Connects the Tool with its tool bar.
*/
class ToolBarToolConnector(
val projectWindow: ProjectWindow,
val tool: ToolBarTool,
val runToolOnEdit: Boolean,
side: Side = Side.TOP) {
val toolBar = ConnectedToolBar()
var side: Side = side
set(v) {
if (field != v) {
field = v
projectWindow.removeToolBar(toolBar)
projectWindow.addToolBar(toolBar, v)
toolBar.orientation = if (v == Side.TOP || v == Side.BOTTOM) Orientation.HORIZONTAL else Orientation.VERTICAL
}
}
init {
toolBar.contextMenu = ContextMenu()
val editItem = MenuItem("Edit Toolbar")
editItem.onAction = EventHandler { editToolBar() }
toolBar.contextMenu.items.add(editItem)
}
fun remove() {
projectWindow.removeToolBar(toolBar)
}
fun update(buttons: List<Button>) {
if (buttons.isEmpty()) {
projectWindow.removeToolBar(toolBar)
} else {
with(toolBar.items) {
clear()
buttons.forEach { button ->
add(button)
}
}
if (toolBar.parent == null) {
projectWindow.addToolBar(toolBar, side)
}
}
}
fun editToolBar() {
tool.toolPane?.halfTab?.let { halfTab ->
halfTab.projectTab.isSelected = true
if (!runToolOnEdit) {
halfTab.toolPane.parametersTab.isSelected = true
}
return
}
val projectTab = projectWindow.tabs.addTool(tool, run = runToolOnEdit)
projectTab.left.toolPane.parametersTab.isSelected = true
}
inner class ConnectedToolBar : ToolBar() {
val connector = this@ToolBarToolConnector
}
}
| gpl-3.0 | bb83f6142c5c09d1c0d3454fbb06a5c2 | 28.484536 | 125 | 0.639161 | 4.539683 | false | false | false | false |
robertwb/incubator-beam | examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/cookbook/FilterExamples.kt | 9 | 9311 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.beam.examples.kotlin.cookbook
import com.google.api.services.bigquery.model.TableFieldSchema
import com.google.api.services.bigquery.model.TableRow
import com.google.api.services.bigquery.model.TableSchema
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO
import org.apache.beam.sdk.io.gcp.bigquery.WriteResult
import org.apache.beam.sdk.options.*
import org.apache.beam.sdk.transforms.*
import org.apache.beam.sdk.values.PCollection
import java.util.logging.Logger
/**
* This is an example that demonstrates several approaches to filtering, and use of the Mean
* transform. It shows how to dynamically set parameters by defining and using new pipeline options,
* and how to use a value derived by the pipeline.
*
*
* Concepts: The Mean transform; Options configuration; using pipeline-derived data as a side
* input; approaches to filtering, selection, and projection.
*
*
* The example reads public samples of weather data from BigQuery. It performs a projection on
* the data, finds the global mean of the temperature readings, filters on readings for a single
* given month, and then outputs only data (for that month) that has a mean temp smaller than the
* derived global mean.
*
*
* Note: Before running this example, you must create a BigQuery dataset to contain your output
* table.
*
*
* To execute this pipeline locally, specify the BigQuery table for the output:
*
* <pre>`--output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
* [--monthFilter=<month_number>]
`</pre> *
*
* where optional parameter `--monthFilter` is set to a number 1-12.
*
*
* To change the runner, specify:
*
* <pre>`--runner=YOUR_SELECTED_RUNNER
`</pre> *
*
* See examples/kotlin/README.md for instructions about how to configure different runners.
*
*
* The BigQuery input table defaults to `clouddataflow-readonly:samples.weather_stations`
* and can be overridden with `--input`.
*/
object FilterExamples {
// Default to using a 1000 row subset of the public weather station table publicdata:samples.gsod.
private const val WEATHER_SAMPLES_TABLE = "clouddataflow-readonly:samples.weather_stations"
internal val LOG = Logger.getLogger(FilterExamples::class.java.name)
internal const val MONTH_TO_FILTER = 7
/**
* Examines each row in the input table. Outputs only the subset of the cells this example is
* interested in-- the mean_temp and year, month, and day-- as a bigquery table row.
*/
internal class ProjectionFn : DoFn<TableRow, TableRow>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val row = c.element()
// Grab year, month, day, mean_temp from the row
val year = Integer.parseInt(row["year"] as String)
val month = Integer.parseInt(row["month"] as String)
val day = Integer.parseInt(row["day"] as String)
val meanTemp = row["mean_temp"].toString().toDouble()
// Prepares the data for writing to BigQuery by building a TableRow object
val outRow = TableRow()
.set("year", year)
.set("month", month)
.set("day", day)
.set("mean_temp", meanTemp)
c.output(outRow)
}
}
/**
* Implements 'filter' functionality.
*
*
* Examines each row in the input table. Outputs only rows from the month monthFilter, which is
* passed in as a parameter during construction of this DoFn.
*/
internal class FilterSingleMonthDataFn(private var monthFilter: Int?) : DoFn<TableRow, TableRow>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val row = c.element()
val month = row["month"]
if (month == this.monthFilter) {
c.output(row)
}
}
}
/**
* Examines each row (weather reading) in the input table. Output the temperature reading for that
* row ('mean_temp').
*/
internal class ExtractTempFn : DoFn<TableRow, Double>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val row = c.element()
val meanTemp = java.lang.Double.parseDouble(row["mean_temp"].toString())
c.output(meanTemp)
}
}
/**
* Finds the global mean of the mean_temp for each day/record, and outputs only data that has a
* mean temp larger than this global mean.
*/
internal class BelowGlobalMean(private var monthFilter: Int?) : PTransform<PCollection<TableRow>, PCollection<TableRow>>() {
override fun expand(rows: PCollection<TableRow>): PCollection<TableRow> {
// Extract the mean_temp from each row.
val meanTemps = rows.apply(ParDo.of(ExtractTempFn()))
// Find the global mean, of all the mean_temp readings in the weather data,
// and prepare this singleton PCollectionView for use as a side input.
val globalMeanTemp = meanTemps.apply(Mean.globally()).apply(View.asSingleton())
// Rows filtered to remove all but a single month
val monthFilteredRows = rows.apply(ParDo.of(FilterSingleMonthDataFn(monthFilter)))
// Then, use the global mean as a side input, to further filter the weather data.
// By using a side input to pass in the filtering criteria, we can use a value
// that is computed earlier in pipeline execution.
// We'll only output readings with temperatures below this mean.
return monthFilteredRows.apply(
"ParseAndFilter",
ParDo.of(
object : DoFn<TableRow, TableRow>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val meanTemp = java.lang.Double.parseDouble(c.element()["mean_temp"].toString())
val gTemp = c.sideInput(globalMeanTemp)
if (meanTemp < gTemp) {
c.output(c.element())
}
}
})
.withSideInputs(globalMeanTemp))
}
}
/**
* Options supported by [FilterExamples].
*
*
* Inherits standard configuration options.
*/
interface Options : PipelineOptions {
@get:Description("Table to read from, specified as <project_id>:<dataset_id>.<table_id>")
@get:Default.String(WEATHER_SAMPLES_TABLE)
var input: String
@get:Description("Table to write to, specified as <project_id>:<dataset_id>.<table_id>. The dataset_id must already exist")
@get:Validation.Required
var output: String
@get:Description("Numeric value of month to filter on")
@get:Default.Integer(MONTH_TO_FILTER)
var monthFilter: Int?
}
/** Helper method to build the table schema for the output table. */
private fun buildWeatherSchemaProjection(): TableSchema {
val fields = arrayListOf<TableFieldSchema>(
TableFieldSchema().setName("year").setType("INTEGER"),
TableFieldSchema().setName("month").setType("INTEGER"),
TableFieldSchema().setName("day").setType("INTEGER"),
TableFieldSchema().setName("mean_temp").setType("FLOAT")
)
return TableSchema().setFields(fields)
}
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
val options = PipelineOptionsFactory.fromArgs(*args).withValidation() as Options
val p = Pipeline.create(options)
val schema = buildWeatherSchemaProjection()
p.apply(BigQueryIO.readTableRows().from(options.input))
.apply(ParDo.of(ProjectionFn()))
.apply(BelowGlobalMean(options.monthFilter))
.apply<WriteResult>(
BigQueryIO.writeTableRows()
.to(options.output)
.withSchema(schema)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE))
p.run().waitUntilFinish()
}
}
| apache-2.0 | 3e82f5b0e457fb5d69ae05ec10f470d2 | 40.382222 | 131 | 0.633015 | 4.455024 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/AutoPromotionPropertyMutationProvider.kt | 1 | 3199 | package net.nemerosa.ontrack.extension.general
import graphql.Scalars.GraphQLString
import graphql.schema.GraphQLInputObjectField
import graphql.schema.GraphQLList
import graphql.schema.GraphQLNonNull
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.graphql.schema.MutationInput
import net.nemerosa.ontrack.graphql.schema.PropertyMutationProvider
import net.nemerosa.ontrack.graphql.schema.optionalStringInputField
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.PromotionLevel
import net.nemerosa.ontrack.model.structure.PropertyType
import net.nemerosa.ontrack.model.structure.StructureService
import org.springframework.stereotype.Component
import kotlin.reflect.KClass
@Component
class AutoPromotionPropertyMutationProvider(
private val structureService: StructureService,
) : PropertyMutationProvider<AutoPromotionProperty> {
override val propertyType: KClass<out PropertyType<AutoPromotionProperty>> = AutoPromotionPropertyType::class
override val mutationNameFragment: String = "AutoPromotion"
override val inputFields: List<GraphQLInputObjectField> = listOf(
GraphQLInputObjectField.newInputObjectField()
.name(AutoPromotionProperty::validationStamps.name)
.description("List of needed validation stamps")
.type(GraphQLList(GraphQLNonNull(GraphQLString)))
.build(),
optionalStringInputField(AutoPromotionProperty::include.name,
"Regular expression to include validation stamps by name"),
optionalStringInputField(AutoPromotionProperty::exclude.name,
"Regular expression to exclude validation stamps by name"),
GraphQLInputObjectField.newInputObjectField()
.name(AutoPromotionProperty::promotionLevels.name)
.description("List of needed promotion levels")
.type(GraphQLList(GraphQLNonNull(GraphQLString)))
.build(),
)
override fun readInput(entity: ProjectEntity, input: MutationInput): AutoPromotionProperty {
if (entity is PromotionLevel) {
val validationStamps = input.getInput<List<String>>(AutoPromotionProperty::validationStamps.name)
?.mapNotNull {
structureService.findValidationStampByName(entity.project.name, entity.branch.name, it).getOrNull()
}
?: emptyList()
val promotionLevels = input.getInput<List<String>>(AutoPromotionProperty::promotionLevels.name)
?.mapNotNull {
structureService.findPromotionLevelByName(entity.project.name, entity.branch.name, it).getOrNull()
}
?: emptyList()
return AutoPromotionProperty(
validationStamps = validationStamps,
include = input.getInput<String>(AutoPromotionProperty::include.name) ?: "",
exclude = input.getInput<String>(AutoPromotionProperty::exclude.name) ?: "",
promotionLevels = promotionLevels,
)
} else {
throw IllegalStateException("Parent entity must be a promotion level")
}
}
}
| mit | c19b6f3828f05d8c2a747acd3f241361 | 47.469697 | 119 | 0.717724 | 5.287603 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-scm/src/test/java/net/nemerosa/ontrack/extension/scm/catalog/api/CatalogGraphQLIT.kt | 1 | 13591 | package net.nemerosa.ontrack.extension.scm.catalog.api
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.scm.catalog.CatalogFixtures.entry
import net.nemerosa.ontrack.extension.scm.catalog.CatalogFixtures.team
import net.nemerosa.ontrack.extension.scm.catalog.CatalogLinkService
import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalog
import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalogAccessFunction
import net.nemerosa.ontrack.extension.scm.catalog.mock.MockSCMCatalogProvider
import net.nemerosa.ontrack.graphql.AbstractQLKTITJUnit4Support
import net.nemerosa.ontrack.json.asJson
import net.nemerosa.ontrack.json.getTextField
import net.nemerosa.ontrack.model.security.Roles
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class CatalogGraphQLIT : AbstractQLKTITJUnit4Support() {
@Autowired
private lateinit var scmCatalog: SCMCatalog
@Autowired
private lateinit var catalogLinkService: CatalogLinkService
@Autowired
private lateinit var scmCatalogProvider: MockSCMCatalogProvider
@Test
fun `SCM catalog stats per team`() {
scmCatalogProvider.clear()
// Registration of mock entries with their teams
val entries = listOf(
entry(
scm = "mocking", repository = "project/repository-1", config = "my-config", teams = listOf(
team("team-1")
)
),
entry(
scm = "mocking", repository = "project/repository-2", config = "my-config", teams = listOf(
team("team-1")
)
),
entry(
scm = "mocking", repository = "project/repository-3", config = "my-config", teams = listOf(
team("team-1")
)
),
entry(
scm = "mocking", repository = "project/repository-4", config = "my-config", teams = listOf(
team("team-2")
)
),
entry(
scm = "mocking", repository = "project/repository-5", config = "my-config", teams = listOf(
team("team-2")
)
),
entry(
scm = "mocking", repository = "project/repository-6", config = "my-config", teams = listOf(
team("team-3"),
)
),
entry(
scm = "mocking", repository = "project/repository-7", config = "my-config", teams = listOf(
team("team-4"),
team("team-5"),
)
),
)
entries.forEach { entry ->
scmCatalogProvider.storeEntry(entry)
}
// Collection of entries
scmCatalog.collectSCMCatalog { println(it) }
// Gets stats about teams
asAdmin {
run(
"""{
scmCatalogTeams {
id
entryCount
entries {
repository
}
}
}"""
) { data ->
val scmCatalogTeams = data.path("scmCatalogTeams")
assertEquals(5, scmCatalogTeams.size())
assertEquals(
mapOf(
"id" to "team-1",
"entryCount" to 3,
"entries" to listOf(
mapOf("repository" to "project/repository-1"),
mapOf("repository" to "project/repository-2"),
mapOf("repository" to "project/repository-3"),
)
).asJson(),
scmCatalogTeams.find { it.getTextField("id") == "team-1" }
)
assertEquals(
mapOf(
"id" to "team-2",
"entryCount" to 2,
"entries" to listOf(
mapOf("repository" to "project/repository-4"),
mapOf("repository" to "project/repository-5"),
)
).asJson(),
scmCatalogTeams.find { it.getTextField("id") == "team-2" }
)
assertEquals(
mapOf(
"id" to "team-3",
"entryCount" to 1,
"entries" to listOf(
mapOf("repository" to "project/repository-6"),
)
).asJson(),
scmCatalogTeams.find { it.getTextField("id") == "team-3" }
)
assertEquals(
mapOf(
"id" to "team-4",
"entryCount" to 1,
"entries" to listOf(
mapOf("repository" to "project/repository-7"),
)
).asJson(),
scmCatalogTeams.find { it.getTextField("id") == "team-4" }
)
assertEquals(
mapOf(
"id" to "team-5",
"entryCount" to 1,
"entries" to listOf(
mapOf("repository" to "project/repository-7"),
)
).asJson(),
scmCatalogTeams.find { it.getTextField("id") == "team-5" }
)
}
}
// Gets stats about team count
asAdmin {
run(
"""{
scmCatalogTeamStats {
teamCount
entryCount
}
}"""
) { data ->
assertEquals(
mapOf(
"scmCatalogTeamStats" to listOf(
mapOf("teamCount" to 2, "entryCount" to 1),
mapOf("teamCount" to 1, "entryCount" to 6),
)
).asJson(),
data
)
}
}
}
@Test
fun `Collection of entries and linking`() {
scmCatalogProvider.clear()
// Registration of mock entry
val entry = entry(scm = "mocking", repository = "project/repository", config = "my-config")
scmCatalogProvider.storeEntry(entry)
// Collection of entries
scmCatalog.collectSCMCatalog { println(it) }
// Checks entry has been collected
val collectionData = withGrantViewToAll {
asUserWith<SCMCatalogAccessFunction, JsonNode> {
run(
"""{
scmCatalog {
pageItems {
entry {
scm
config
repository
repositoryPage
}
}
}
}"""
)
}
}
val item = collectionData["scmCatalog"]["pageItems"][0]
assertEquals("mocking", item["entry"]["scm"].asText())
assertEquals("my-config", item["entry"]["config"].asText())
assertEquals("project/repository", item["entry"]["repository"].asText())
assertEquals("uri:project/repository", item["entry"]["repositoryPage"].asText())
// Search on orphan entries
val orphanData = withGrantViewToAll {
asUserWith<SCMCatalogAccessFunction, JsonNode> {
run(
"""{
scmCatalog(link: "UNLINKED") {
pageItems {
entry {
repository
}
project {
name
}
}
}
}"""
)
}
}
assertNotNull(orphanData) {
val orphanItem = it["scmCatalog"]["pageItems"][0]
assertEquals("project/repository", orphanItem["entry"]["repository"].asText())
assertTrue(orphanItem["project"].isNull, "Entry is not linked")
}
// Link with one project
val project = project {
// Collection of catalog links
scmCatalogProvider.linkEntry(entry, this)
catalogLinkService.computeCatalogLinks()
// Checks the link has been recorded
val linkedEntry = catalogLinkService.getSCMCatalogEntry(this)
assertNotNull(linkedEntry, "Project is linked to a SCM catalog entry") {
assertEquals("mocking", it.scm)
assertEquals("my-config", it.config)
assertEquals("project/repository", it.repository)
assertEquals("uri:project/repository", it.repositoryPage)
}
// Getting the SCM entry through GraphQL & project root
val data = withGrantViewToAll {
asUserWith<SCMCatalogAccessFunction, JsonNode> {
run(
"""
query ProjectInfo {
projects(id: $id) {
scmCatalogEntry {
scm
config
repository
repositoryPage
}
}
}
"""
)
}
}
// Checking data
assertNotNull(data) {
val projectItem = it["projects"][0]["scmCatalogEntry"]
assertEquals("mocking", projectItem["scm"].asText())
assertEquals("my-config", projectItem["config"].asText())
assertEquals("project/repository", projectItem["repository"].asText())
assertEquals("uri:project/repository", projectItem["repositoryPage"].asText())
}
// Getting the data through GraphQL & catalog entries
val entryCollectionData = withGrantViewToAll {
asUserWith<SCMCatalogAccessFunction, JsonNode> {
run(
"""{
scmCatalog {
pageItems {
project {
name
}
}
}
}"""
)
}
}
assertNotNull(entryCollectionData) {
val project = it["scmCatalog"]["pageItems"][0]["project"]
assertEquals(name, project["name"].asText())
}
}
// Search on linked entries
val data = withGrantViewToAll {
asUserWith<SCMCatalogAccessFunction, JsonNode> {
run(
"""{
scmCatalog(link: "LINKED") {
pageItems {
project {
name
}
}
}
}"""
)
}
}
assertNotNull(data) {
val projectItem = it["scmCatalog"]["pageItems"][0]["project"]
assertEquals(project.name, projectItem["name"].asText())
}
}
@Test
fun `SCM Catalog accessible to administrators in view-to-all mode`() {
scmCatalogTest {
withGrantViewToAll {
asAdmin(it)
}
}
}
@Test
fun `SCM Catalog accessible to administrators in restricted mode`() {
scmCatalogTest {
withNoGrantViewToAll {
asAdmin(it)
}
}
}
@Test
fun `SCM Catalog accessible to global read only`() {
scmCatalogTest {
withNoGrantViewToAll {
asAccountWithGlobalRole(Roles.GLOBAL_READ_ONLY, it)
}
}
}
private fun scmCatalogTest(setup: (code: () -> Unit) -> Unit) {
// Collection of entries
val entry = entry(scm = "mocking")
scmCatalogProvider.clear()
scmCatalogProvider.storeEntry(entry)
scmCatalog.collectSCMCatalog { println(it) }
// Link with one project
val project = project {
scmCatalogProvider.linkEntry(entry, this)
catalogLinkService.computeCatalogLinks()
}
// Checks rights
setup {
val data = run(
"""{
scmCatalog(link: "LINKED") {
pageItems {
project {
name
}
}
}
}"""
)
assertNotNull(data) {
val entryItem = it["scmCatalog"]["pageItems"][0]
assertEquals(project.name, entryItem["project"]["name"].asText())
}
}
}
} | mit | f842b37f95dd4d1996abe4e4034aef2e | 35.934783 | 107 | 0.440806 | 5.780944 | false | true | false | false |
chibatching/Kotpref | kotpref/src/main/kotlin/com/chibatching/kotpref/KotprefModel.kt | 1 | 3936 | package com.chibatching.kotpref
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.os.SystemClock
import androidx.annotation.CallSuper
import com.chibatching.kotpref.pref.PreferenceProperty
import kotlin.reflect.KProperty
public abstract class KotprefModel(
private val contextProvider: ContextProvider = StaticContextProvider,
private val preferencesProvider: PreferencesProvider = defaultPreferenceProvider()
) {
public constructor(
context: Context,
preferencesProvider: PreferencesProvider = defaultPreferenceProvider()
) : this(
ContextProvider { context.applicationContext },
preferencesProvider
)
internal var kotprefInTransaction: Boolean = false
internal var kotprefTransactionStartTime: Long = Long.MAX_VALUE
internal val kotprefProperties: MutableMap<String, PreferenceProperty> = mutableMapOf()
/**
* Application Context
*/
public val context: Context
get() = contextProvider.getApplicationContext()
/**
* Preference file name
*/
public open val kotprefName: String = javaClass.simpleName
/**
* commit() all properties in this pref by default instead of apply()
*/
public open val commitAllPropertiesByDefault: Boolean = false
/**
* Preference read/write mode
*/
public open val kotprefMode: Int = Context.MODE_PRIVATE
/**
* Internal shared preferences.
* This property will be initialized on use.
*/
internal val kotprefPreference: KotprefPreferences by lazy {
KotprefPreferences(preferencesProvider.get(context, kotprefName, kotprefMode))
}
/**
* Internal shared preferences editor.
*/
internal var kotprefEditor: KotprefPreferences.KotprefEditor? = null
/**
* SharedPreferences instance exposed.
* Use carefully when during bulk edit, it may cause inconsistent with internal data of Kotpref.
*/
public val preferences: SharedPreferences
get() = kotprefPreference
/**
* Clear all preferences in this model
*/
@CallSuper
public open fun clear() {
beginBulkEdit()
kotprefEditor!!.clear()
commitBulkEdit()
}
/**
* Begin bulk edit mode. You must commit or cancel after bulk edit finished.
*/
@SuppressLint("CommitPrefEdits")
public fun beginBulkEdit() {
kotprefInTransaction = true
kotprefTransactionStartTime = SystemClock.uptimeMillis()
kotprefEditor = kotprefPreference.KotprefEditor(kotprefPreference.edit())
}
/**
* Commit values set in the bulk edit mode to preferences.
*/
public fun commitBulkEdit() {
kotprefEditor!!.apply()
kotprefInTransaction = false
}
/**
* Commit values set in the bulk edit mode to preferences immediately, in blocking manner.
*/
public fun blockingCommitBulkEdit() {
kotprefEditor!!.commit()
kotprefInTransaction = false
}
/**
* Cancel bulk edit mode. Values set in the bulk mode will be rolled back.
*/
public fun cancelBulkEdit() {
kotprefEditor = null
kotprefInTransaction = false
}
/**
* Get preference key for a property.
* @param property property delegated to Kotpref
* @return preference key
*/
public fun getPrefKey(property: KProperty<*>): String? {
return kotprefProperties[property.name]?.preferenceKey
}
/**
* Remove entry from SharedPreferences
* @param property property to remove
*/
@SuppressLint("ApplySharedPref")
public fun remove(property: KProperty<*>) {
preferences.edit().remove(getPrefKey(property)).apply {
if (commitAllPropertiesByDefault) {
commit()
} else {
apply()
}
}
}
}
| apache-2.0 | b8e5b2f36d60690a1657a3615e396097 | 27.729927 | 100 | 0.666667 | 5.178947 | false | false | false | false |
olonho/carkot | translator/src/test/kotlin/tests/null_comparison_1/null_comparison_1.kt | 1 | 697 | class null_comparison_1_class
fun null_comparison_1_getClass(): null_comparison_1_class? {
return null
}
fun null_comparison_1(): Int {
val a: null_comparison_1_class? = null_comparison_1_getClass()
println(if (a == null) 555 else 9990)
if (a == null) {
return 87
}
return 945
}
fun null_comparison_1_reassigned(): Int {
var a: null_comparison_1_class? = null_comparison_1_class()
a = null_comparison_1_getClass()
if (a == null) {
return 87
}
return 945
}
fun null_comparison_1_declaration(): Int {
val a: null_comparison_1_class?
a = null_comparison_1_getClass()
if (a == null) {
return 87
}
return 945
} | mit | 7c9861fa94fb7fe7d19b2df4bed1e55e | 20.8125 | 66 | 0.609756 | 3.257009 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/forge/inspections/sideonly/MethodSideOnlyInspection.kt | 1 | 5585 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.intellij.psi.PsiAnnotation
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 annotation = infos[3] as PsiAnnotation
return if (annotation.isWritable && error === Error.METHOD_IN_WRONG_CLASS) {
RemoveAnnotationInspectionGadgetsFix(annotation, "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 (methodAnnotation, methodSide) = SideOnlyUtil.checkMethod(method)
if (methodAnnotation == null) {
return
}
val resolve = (method.returnType as? PsiClassType)?.resolve()
val (returnAnnotation, returnSide) =
if (resolve == null) null to Side.NONE else SideOnlyUtil.getSideForClass(resolve)
if (returnAnnotation != null && returnSide !== Side.NONE && returnSide !== Side.INVALID &&
returnSide !== methodSide && methodSide !== Side.NONE && methodSide !== Side.INVALID
) {
registerMethodError(
method,
Error.RETURN_TYPE_ON_WRONG_METHOD,
methodAnnotation.renderSide(methodSide),
returnAnnotation.renderSide(returnSide),
method.getAnnotation(methodAnnotation.annotationName)
)
}
for ((classAnnotation, classSide) in SideOnlyUtil.checkClassHierarchy(psiClass)) {
if (classAnnotation != null && classSide !== Side.NONE && classSide !== Side.INVALID) {
if (
methodSide !== classSide &&
methodSide !== Side.NONE &&
methodSide !== Side.INVALID
) {
registerMethodError(
method,
Error.METHOD_IN_WRONG_CLASS,
methodAnnotation.renderSide(methodSide),
classAnnotation.renderSide(classSide),
method.getAnnotation(methodAnnotation.annotationName)
)
}
if (returnAnnotation != null && returnSide !== Side.NONE && returnSide !== Side.INVALID) {
if (returnSide !== classSide) {
registerMethodError(
method,
Error.RETURN_TYPE_IN_WRONG_CLASS,
classAnnotation.renderSide(classSide),
returnAnnotation.renderSide(returnSide),
method.getAnnotation(methodAnnotation.annotationName)
)
}
}
break
}
}
}
}
}
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 | 26b12225d4b2fdcf6cf5964809027814 | 40.679104 | 114 | 0.53214 | 5.652834 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/errorreporter/ErrorReporter.kt | 1 | 5352 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.errorreporter
import com.demonwav.mcdev.update.PluginUtil
import com.intellij.diagnostic.DiagnosticBundle
import com.intellij.diagnostic.LogMessage
import com.intellij.ide.DataManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.idea.IdeaLogger
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.util.Consumer
import java.awt.Component
class ErrorReporter : ErrorReportSubmitter() {
private val ignoredErrorMessages = listOf(
"Key com.demonwav.mcdev.translations.TranslationFoldingSettings duplicated",
"Inspection #EntityConstructor has no description"
)
private val baseUrl = "https://github.com/minecraft-dev/MinecraftDev/issues"
override fun getReportActionText() = "Report to Minecraft Dev GitHub Issue Tracker"
override fun submit(
events: Array<out IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component,
consumer: Consumer<in SubmittedReportInfo>
): Boolean {
val dataContext = DataManager.getInstance().getDataContext(parentComponent)
val project = CommonDataKeys.PROJECT.getData(dataContext)
val event = events[0]
val errorMessage = event.throwableText
if (errorMessage.isNotBlank() && ignoredErrorMessages.any(errorMessage::contains)) {
val task = object : Task.Backgroundable(project, "Ignored error") {
override fun run(indicator: ProgressIndicator) {
consumer.consume(SubmittedReportInfo(null, null, SubmittedReportInfo.SubmissionStatus.DUPLICATE))
}
}
if (project == null) {
task.run(EmptyProgressIndicator())
} else {
ProgressManager.getInstance().run(task)
}
return true
}
val errorData = ErrorData(event.throwable, IdeaLogger.ourLastActionId)
errorData.description = additionalInfo
errorData.message = event.message
PluginManagerCore.getPlugin(PluginUtil.PLUGIN_ID)?.let { plugin ->
errorData.pluginName = plugin.name
errorData.pluginVersion = plugin.version
}
val data = event.data
if (data is LogMessage) {
errorData.throwable = data.throwable
errorData.attachments = data.includedAttachments
}
val (reportValues, attachments) = errorData.formatErrorData()
val task = AnonymousFeedbackTask(
project,
"Submitting error report",
true,
reportValues,
attachments,
{ htmlUrl, token, isDuplicate ->
val type = if (isDuplicate) {
SubmittedReportInfo.SubmissionStatus.DUPLICATE
} else {
SubmittedReportInfo.SubmissionStatus.NEW_ISSUE
}
val message = if (!isDuplicate) {
"<html>Created Issue #$token successfully. <a href=\"$htmlUrl\">View issue.</a></html>"
} else {
"<html>Commented on existing Issue #$token successfully. " +
"<a href=\"$htmlUrl\">View comment.</a></html>"
}
NotificationGroupManager.getInstance().getNotificationGroup("Error Report").createNotification(
DiagnosticBundle.message("error.report.title"),
message,
NotificationType.INFORMATION
).setListener(NotificationListener.URL_OPENING_LISTENER).setImportant(false).notify(project)
val reportInfo = SubmittedReportInfo(htmlUrl, "Issue #$token", type)
consumer.consume(reportInfo)
},
{ e ->
val message = "<html>Error Submitting Issue: ${e.message}<br>Consider opening an issue on " +
"<a href=\"$baseUrl\">the GitHub issue tracker.</a></html>"
NotificationGroupManager.getInstance().getNotificationGroup("Error Report").createNotification(
DiagnosticBundle.message("error.report.title"),
message,
NotificationType.ERROR,
).setListener(NotificationListener.URL_OPENING_LISTENER).setImportant(false).notify(project)
consumer.consume(SubmittedReportInfo(null, null, SubmittedReportInfo.SubmissionStatus.FAILED))
}
)
if (project == null) {
task.run(EmptyProgressIndicator())
} else {
ProgressManager.getInstance().run(task)
}
return true
}
}
| mit | 7af5b905e27ec4de345412f170ad72bf | 38.644444 | 117 | 0.647982 | 5.395161 | false | false | false | false |
vondear/RxTools | RxKit/src/main/java/com/tamsiree/rxkit/RxRegTool.kt | 1 | 16342 | package com.tamsiree.rxkit
import com.tamsiree.rxkit.RxConstTool.REGEX_CHZ
import com.tamsiree.rxkit.RxConstTool.REGEX_DATE
import com.tamsiree.rxkit.RxConstTool.REGEX_EMAIL
import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD
import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD15
import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD18
import com.tamsiree.rxkit.RxConstTool.REGEX_IP
import com.tamsiree.rxkit.RxConstTool.REGEX_MOBILE_EXACT
import com.tamsiree.rxkit.RxConstTool.REGEX_MOBILE_SIMPLE
import com.tamsiree.rxkit.RxConstTool.REGEX_TEL
import com.tamsiree.rxkit.RxConstTool.REGEX_URL
import com.tamsiree.rxkit.RxConstTool.REGEX_USERNAME
import com.tamsiree.rxkit.RxDataTool.Companion.isNullString
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
/**
* @author Tamsiree
* @date 2017/3/15
*/
object RxRegTool {
//--------------------------------------------正则表达式-----------------------------------------
/**
* 原文链接:http://caibaojian.com/regexp-example.html
* 提取信息中的网络链接:(h|H)(r|R)(e|E)(f|F) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)?
* 提取信息中的邮件地址:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
* 提取信息中的图片链接:(s|S)(r|R)(c|C) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)?
* 提取信息中的IP地址:(\d+)\.(\d+)\.(\d+)\.(\d+)
* 提取信息中的中国电话号码(包括移动和固定电话):(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}
* 提取信息中的中国邮政编码:[1-9]{1}(\d+){5}
* 提取信息中的中国身份证号码:\d{18}|\d{15}
* 提取信息中的整数:\d+
* 提取信息中的浮点数(即小数):(-?\d*)\.?\d+
* 提取信息中的任何数字 :(-?\d*)(\.\d+)?
* 提取信息中的中文字符串:[\u4e00-\u9fa5]*
* 提取信息中的双字节字符串 (汉字):[^\x00-\xff]*
*/
/**
* 判断是否为真实手机号
*
* @param mobiles
* @return
*/
@JvmStatic
fun isMobile(mobiles: String?): Boolean {
val p = Pattern.compile("^(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$")
val m = p.matcher(mobiles)
return m.matches()
}
/**
* 验证银卡卡号
*
* @param cardNo
* @return
*/
@JvmStatic
fun isBankCard(cardNo: String?): Boolean {
val p = Pattern.compile("^\\d{16,19}$|^\\d{6}[- ]\\d{10,13}$|^\\d{4}[- ]\\d{4}[- ]\\d{4}[- ]\\d{4,7}$")
val m = p.matcher(cardNo)
return m.matches()
}
/**
* 15位和18位身份证号码的正则表达式 身份证验证
*
* @param idCard
* @return
*/
@JvmStatic
fun validateIdCard(idCard: String?): Boolean {
// 15位和18位身份证号码的正则表达式
val regIdCard = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$"
val p = Pattern.compile(regIdCard)
return p.matcher(idCard).matches()
}
//=========================================正则表达式=============================================
/**
* 验证手机号(简单)
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isMobileSimple(string: String?): Boolean {
return isMatch(REGEX_MOBILE_SIMPLE, string)
}
/**
* 验证手机号(精确)
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isMobileExact(string: String?): Boolean {
return isMatch(REGEX_MOBILE_EXACT, string)
}
/**
* 验证电话号码
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isTel(string: String?): Boolean {
return isMatch(REGEX_TEL, string)
}
/**
* 验证身份证号码15位
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isIDCard15(string: String?): Boolean {
return isMatch(REGEX_IDCARD15, string)
}
/**
* 验证身份证号码18位
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isIDCard18(string: String?): Boolean {
return isMatch(REGEX_IDCARD18, string)
}
/**
* 验证身份证号码15或18位 包含以x结尾
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isIDCard(string: String?): Boolean {
return isMatch(REGEX_IDCARD, string)
}
/*********************************** 身份证验证开始 */
/**
* 身份证号码验证 1、号码的结构 公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为:六位数字地址码,
* 八位数字出生日期码,三位数字顺序码和一位数字校验码。 2、地址码(前六位数)
* 表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。 3、出生日期码(第七位至十四位)
* 表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。 4、顺序码(第十五位至十七位)
* 表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号, 顺序码的奇数分配给男性,偶数分配给女性。 5、校验码(第十八位数)
* (1)十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和
* Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
* (2)计算模 Y = mod(S, 11) (3)通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9 8 7 6 5 4 3 2
*/
/**
* 功能:身份证的有效验证
*
* @param IDStr 身份证号
* @return 有效:返回"有效" 无效:返回String信息
* @throws ParseException
*/
@JvmStatic
fun IDCardValidate(IDStr: String): String {
var errorInfo = "" // 记录错误信息
val ValCodeArr = arrayOf("1", "0", "x", "9", "8", "7", "6", "5", "4",
"3", "2")
val Wi = arrayOf("7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
"9", "10", "5", "8", "4", "2")
var Ai = ""
// ================ 号码的长度 15位或18位 ================
if (IDStr.length != 15 && IDStr.length != 18) {
errorInfo = "身份证号码长度应该为15位或18位。"
return errorInfo
}
// =======================(end)========================
// ================ 数字 除最后以为都为数字 ================
if (IDStr.length == 18) {
Ai = IDStr.substring(0, 17)
} else if (IDStr.length == 15) {
Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15)
}
if (isNumeric(Ai) == false) {
errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。"
return errorInfo
}
// =======================(end)========================
// ================ 出生年月是否有效 ================
val strYear = Ai.substring(6, 10) // 年份
val strMonth = Ai.substring(10, 12) // 月份
val strDay = Ai.substring(12, 14) // 月份
if (isDate("$strYear-$strMonth-$strDay") == false) {
errorInfo = "身份证生日无效。"
return errorInfo
}
val gc = GregorianCalendar()
val s = SimpleDateFormat("yyyy-MM-dd")
try {
if (gc[Calendar.YEAR] - strYear.toInt() > 150
|| gc.time.time - s.parse(
"$strYear-$strMonth-$strDay").time < 0) {
errorInfo = "身份证生日不在有效范围。"
return errorInfo
}
} catch (e: NumberFormatException) {
e.printStackTrace()
} catch (e: ParseException) {
e.printStackTrace()
}
if (strMonth.toInt() > 12 || strMonth.toInt() == 0) {
errorInfo = "身份证月份无效"
return errorInfo
}
if (strDay.toInt() > 31 || strDay.toInt() == 0) {
errorInfo = "身份证日期无效"
return errorInfo
}
// =====================(end)=====================
// ================ 地区码时候有效 ================
val h = GetAreaCode()
if (h[Ai.substring(0, 2)] == null) {
errorInfo = "身份证地区编码错误。"
return errorInfo
}
// ==============================================
// ================ 判断最后一位的值 ================
var TotalmulAiWi = 0
for (i in 0..16) {
TotalmulAiWi = (TotalmulAiWi
+ Ai[i].toString().toInt() * Wi[i].toInt())
}
val modValue = TotalmulAiWi % 11
val strVerifyCode = ValCodeArr[modValue]
Ai = Ai + strVerifyCode
if (IDStr.length == 18) {
if (Ai == IDStr == false) {
errorInfo = "身份证无效,不是合法的身份证号码"
return errorInfo
}
} else {
return "有效"
}
// =====================(end)=====================
return "有效"
}
/**
* 功能:设置地区编码
*
* @return Hashtable 对象
*/
private fun GetAreaCode(): Hashtable<String, String> {
val hashtable = Hashtable<String, String>()
hashtable["11"] = "北京"
hashtable["12"] = "天津"
hashtable["13"] = "河北"
hashtable["14"] = "山西"
hashtable["15"] = "内蒙古"
hashtable["21"] = "辽宁"
hashtable["22"] = "吉林"
hashtable["23"] = "黑龙江"
hashtable["31"] = "上海"
hashtable["32"] = "江苏"
hashtable["33"] = "浙江"
hashtable["34"] = "安徽"
hashtable["35"] = "福建"
hashtable["36"] = "江西"
hashtable["37"] = "山东"
hashtable["41"] = "河南"
hashtable["42"] = "湖北"
hashtable["43"] = "湖南"
hashtable["44"] = "广东"
hashtable["45"] = "广西"
hashtable["46"] = "海南"
hashtable["50"] = "重庆"
hashtable["51"] = "四川"
hashtable["52"] = "贵州"
hashtable["53"] = "云南"
hashtable["54"] = "西藏"
hashtable["61"] = "陕西"
hashtable["62"] = "甘肃"
hashtable["63"] = "青海"
hashtable["64"] = "宁夏"
hashtable["65"] = "新疆"
hashtable["71"] = "台湾"
hashtable["81"] = "香港"
hashtable["82"] = "澳门"
hashtable["91"] = "国外"
return hashtable
}
/**
* 功能:判断字符串是否为数字
*
* @param str
* @return
*/
private fun isNumeric(str: String): Boolean {
val pattern = Pattern.compile("[0-9]*")
val isNum = pattern.matcher(str)
return isNum.matches()
}
/**
* 验证邮箱
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isEmail(string: String?): Boolean {
return isMatch(REGEX_EMAIL, string)
}
/**
* 验证URL
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isURL(string: String?): Boolean {
return isMatch(REGEX_URL, string)
}
/**
* 验证汉字
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isChz(string: String?): Boolean {
return isMatch(REGEX_CHZ, string)
}
/**
* 验证用户名
*
* 取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isUsername(string: String?): Boolean {
return isMatch(REGEX_USERNAME, string)
}
/**
* 验证yyyy-MM-dd格式的日期校验,已考虑平闰年
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isDate(string: String?): Boolean {
return isMatch(REGEX_DATE, string)
}
/**
* 验证IP地址
*
* @param string 待验证文本
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isIP(string: String?): Boolean {
return isMatch(REGEX_IP, string)
}
/**
* string是否匹配regex正则表达式字符串
*
* @param regex 正则表达式字符串
* @param string 要匹配的字符串
* @return `true`: 匹配<br></br>`false`: 不匹配
*/
@JvmStatic
fun isMatch(regex: String?, string: String?): Boolean {
return !isNullString(string) && Pattern.matches(regex, string)
}
/**
* 验证固定电话号码
*
* @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447
*
* **国家(地区) 代码 :**标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字,
* 数字之后是空格分隔的国家(地区)代码。
*
* **区号(城市代码):**这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号——
* 对不使用地区或城市代码的国家(地区),则省略该组件。
*
* **电话号码:**这包含从 0 到 9 的一个或多个数字
* @return 验证成功返回true,验证失败返回false
*/
@JvmStatic
fun checkPhone(phone: String?): Boolean {
val regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"
return Pattern.matches(regex, phone)
}
/**
* 验证整数(正整数和负整数)
*
* @param digit 一位或多位0-9之间的整数
* @return 验证成功返回true,验证失败返回false
*/
@JvmStatic
fun checkDigit(digit: String?): Boolean {
val regex = "\\-?[1-9]\\d+"
return Pattern.matches(regex, digit)
}
/**
* 验证整数和浮点数(正负整数和正负浮点数)
*
* @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30
* @return 验证成功返回true,验证失败返回false
*/
@JvmStatic
fun checkDecimals(decimals: String?): Boolean {
val regex = "\\-?[1-9]\\d+(\\.\\d+)?"
return Pattern.matches(regex, decimals)
}
/**
* 验证空白字符
*
* @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B
* @return 验证成功返回true,验证失败返回false
*/
@JvmStatic
fun checkBlankSpace(blankSpace: String?): Boolean {
val regex = "\\s+"
return Pattern.matches(regex, blankSpace)
}
/**
* 验证日期(年月日)
*
* @param birthday 日期,格式:1992-09-03,或1992.09.03
* @return 验证成功返回true,验证失败返回false
*/
@JvmStatic
fun checkBirthday(birthday: String?): Boolean {
val regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"
return Pattern.matches(regex, birthday)
}
/**
* 匹配中国邮政编码
*
* @param postcode 邮政编码
* @return 验证成功返回true,验证失败返回false
*/
@JvmStatic
fun checkPostcode(postcode: String?): Boolean {
val regex = "[1-9]\\d{5}"
return Pattern.matches(regex, postcode)
}
} | apache-2.0 | 91eb0aafd63d62314578223eeba72a4a | 27.526652 | 173 | 0.493347 | 2.833722 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/exception/CardException.kt | 1 | 794 | package com.stripe.android.exception
import com.stripe.android.core.StripeError
import com.stripe.android.core.exception.StripeException
import java.net.HttpURLConnection
/**
* An [Exception] indicating that there is a problem with a Card used for a request.
* Card errors are the most common type of error you should expect to handle.
* They result when the user enters a card that can't be charged for some reason.
*/
class CardException(
stripeError: StripeError,
requestId: String? = null
) : StripeException(
stripeError,
requestId,
HttpURLConnection.HTTP_PAYMENT_REQUIRED
) {
val code: String? = stripeError.code
val param: String? = stripeError.param
val declineCode: String? = stripeError.declineCode
val charge: String? = stripeError.charge
}
| mit | e9a8012f006a3e96d731564d0d79ced3 | 32.083333 | 84 | 0.751889 | 4.135417 | false | false | false | false |
stripe/stripe-android | camera-core/src/main/java/com/stripe/android/camera/framework/util/FrameSaver.kt | 1 | 2397 | package com.stripe.android.camera.framework.util
import androidx.annotation.CheckResult
import androidx.annotation.RestrictTo
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.LinkedList
/**
* Save data frames for later retrieval.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
abstract class FrameSaver<Identifier, Frame, MetaData> {
private val saveFrameMutex = Mutex()
private val savedFrames = mutableMapOf<Identifier, LinkedList<Frame>>()
/**
* Determine how frames should be classified using [getSaveFrameIdentifier], and then store them
* in a map of frames based on that identifier.
*
* This method keeps track of the total number of saved frames. If the total number or total
* size exceeds the maximum allowed, the oldest frames will be dropped.
*/
suspend fun saveFrame(frame: Frame, metaData: MetaData) {
val identifier = getSaveFrameIdentifier(frame, metaData) ?: return
return saveFrameMutex.withLock {
val maxSavedFrames = getMaxSavedFrames(identifier)
val frames = savedFrames.getOrPut(identifier) { LinkedList() }
frames.addFirst(frame)
while (frames.size > maxSavedFrames) {
// saved frames is over size limit, reduce until it's not
removeFrame(identifier, frames)
}
}
}
/**
* Retrieve a copy of the list of saved frames.
*/
@CheckResult
fun getSavedFrames(): Map<Identifier, LinkedList<Frame>> = savedFrames.toMap()
/**
* Clear all saved frames
*/
suspend fun reset() = saveFrameMutex.withLock {
savedFrames.clear()
}
protected abstract fun getMaxSavedFrames(savedFrameIdentifier: Identifier): Int
/**
* Determine if a data frame should be saved for future processing.
*
* If this method returns a non-null string, the frame will be saved under that identifier.
*/
protected abstract fun getSaveFrameIdentifier(frame: Frame, metaData: MetaData): Identifier?
/**
* Remove a frame from this list. The most recently added frames will be at the beginning of
* this list, while the least recently added frames will be at the end.
*/
protected open fun removeFrame(identifier: Identifier, frames: LinkedList<Frame>) {
frames.removeLast()
}
}
| mit | 887d2bdf0417e508aab6651033bcad51 | 33.73913 | 100 | 0.68544 | 4.718504 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/AddressElementActivityContract.kt | 1 | 2553 | package com.stripe.android.paymentsheet.addresselement
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContract
import androidx.annotation.ColorInt
import androidx.core.os.bundleOf
import com.stripe.android.core.injection.DUMMY_INJECTOR_KEY
import com.stripe.android.core.injection.InjectorKey
import com.stripe.android.view.ActivityStarter
import kotlinx.parcelize.Parcelize
internal class AddressElementActivityContract :
ActivityResultContract<AddressElementActivityContract.Args, AddressLauncherResult>() {
override fun createIntent(context: Context, input: Args): Intent {
val statusBarColor = (context as? Activity)?.window?.statusBarColor
return Intent(context, AddressElementActivity::class.java)
.putExtra(EXTRA_ARGS, input.copy(statusBarColor = statusBarColor))
}
override fun parseResult(resultCode: Int, intent: Intent?) =
intent?.getParcelableExtra<Result>(EXTRA_RESULT)?.addressOptionsResult
?: AddressLauncherResult.Canceled
/**
* Arguments for launching [AddressElementActivity] to collect an address.
*
* @param publishableKey the Stripe publishable key
* @param config the paymentsheet configuration passed from the merchant
* @param injectorKey Parameter needed to perform dependency injection.
* If default, a new graph is created
*/
@Parcelize
data class Args internal constructor(
internal val publishableKey: String,
internal val config: AddressLauncher.Configuration?,
@InjectorKey internal val injectorKey: String = DUMMY_INJECTOR_KEY,
@ColorInt internal val statusBarColor: Int? = null
) : ActivityStarter.Args {
internal companion object {
internal fun fromIntent(intent: Intent): Args? {
return intent.getParcelableExtra(EXTRA_ARGS)
}
}
}
@Parcelize
data class Result(
val addressOptionsResult: AddressLauncherResult
) : ActivityStarter.Result {
override fun toBundle() = bundleOf(EXTRA_RESULT to this)
}
internal companion object {
const val EXTRA_ARGS =
"com.stripe.android.paymentsheet.addresselement" +
".AddressElementActivityContract.extra_args"
const val EXTRA_RESULT =
"com.stripe.android.paymentsheet.addresselement" +
".AddressElementActivityContract.extra_result"
}
}
| mit | 58d309af0251070cb0daa950ac4994d1 | 38.276923 | 90 | 0.710928 | 5.116232 | false | true | false | false |
spring-cloud-samples/spring-cloud-contract-samples | producer_webflux_security/src/test/kotlin/com/ideabaker/samples/scc/security/securedproducerwebflux/contract/ContactBase.kt | 1 | 2407 | package com.ideabaker.samples.scc.security.securedproducerwebflux.contract
import com.ideabaker.samples.scc.security.securedproducerwebflux.config.GlobalSecurityConfig
import com.ideabaker.samples.scc.security.securedproducerwebflux.config.SpringSecurityWebFluxConfig
import com.ideabaker.samples.scc.security.securedproducerwebflux.model.UserContact
import com.ideabaker.samples.scc.security.securedproducerwebflux.service.ContactServiceProvider
import com.ideabaker.samples.scc.security.securedproducerwebflux.web.ContactHandler
import com.ideabaker.samples.scc.security.securedproducerwebflux.web.Routes
import io.restassured.module.webtestclient.RestAssuredWebTestClient
import org.junit.jupiter.api.BeforeEach
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import reactor.core.publisher.Flux
/**
*
* @author Arthur Kazemi<[email protected]>
* @since 2019-06-23 22:41
*/
@SpringBootTest(classes = [GlobalSecurityConfig::class, SpringSecurityWebFluxConfig::class, ContactBase.Config::class, Routes::class],
webEnvironment = SpringBootTest.WebEnvironment.MOCK)
abstract class ContactBase {
@Autowired
lateinit var context: ApplicationContext
@BeforeEach
fun setup() {
RestAssuredWebTestClient.applicationContextSetup(this.context)
}
@Configuration
@EnableAutoConfiguration
class Config {
@Bean
@Primary
fun contactHandler(contactService: ContactServiceProvider): ContactHandler {
return ContactHandler(contactService = contactService)
}
@Bean
@Primary
fun contactService(): ContactServiceProvider {
return MockContactService()
}
}
internal class MockContactService : ContactServiceProvider {
override fun contactSearch(pattern: String): Flux<UserContact> {
if (pattern == "existing") {
val contact1 = UserContact("1", "name 1", "[email protected]", true)
val contact2 = UserContact("2", "name 2", "[email protected]", false)
return Flux.fromArray(arrayOf(contact1, contact2))
}
return Flux.empty()
}
}
} | apache-2.0 | ddff0a05b82fd1e694c63ec414410aa1 | 37.222222 | 134 | 0.795596 | 4.360507 | false | true | false | false |
pyamsoft/padlock | padlock/src/main/java/com/pyamsoft/padlock/service/job/PadLockJobService.kt | 1 | 2837 | /*
* Copyright 2019 Peter Kenji Yamanaka
*
* 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.pyamsoft.padlock.service.job
import android.app.job.JobParameters
import android.app.job.JobService
import android.os.PersistableBundle
import com.pyamsoft.padlock.Injector
import com.pyamsoft.padlock.PadLock
import com.pyamsoft.padlock.PadLockComponent
import com.pyamsoft.padlock.api.service.JobSchedulerCompat
import com.pyamsoft.padlock.api.service.JobSchedulerCompat.JobType.RECHECK
import com.pyamsoft.padlock.api.service.JobSchedulerCompat.JobType.SERVICE_TEMP_PAUSE
import com.pyamsoft.padlock.model.service.Recheck
import com.pyamsoft.padlock.service.RecheckPresenter
import com.pyamsoft.padlock.api.service.ServiceManager
import timber.log.Timber
import javax.inject.Inject
class PadLockJobService : JobService() {
@field:Inject internal lateinit var presenter: RecheckPresenter
@field:Inject internal lateinit var serviceManager: ServiceManager
override fun onCreate() {
super.onCreate()
Injector.obtain<PadLockComponent>(applicationContext)
.inject(this)
}
override fun onDestroy() {
super.onDestroy()
PadLock.getRefWatcher(this)
.watch(this)
}
override fun onStopJob(params: JobParameters): Boolean {
// Returns false to indicate do NOT reschedule
return false
}
private fun handleServicePauseJob() {
Timber.d("Restarting service")
serviceManager.startService(true)
}
private fun handleRecheckJob(extras: PersistableBundle) {
val packageName = requireNotNull(extras.getString(Recheck.EXTRA_PACKAGE_NAME))
val className = requireNotNull(extras.getString(Recheck.EXTRA_CLASS_NAME))
if (packageName.isNotBlank() && className.isNotBlank()) {
Timber.d("Recheck requested for $packageName $className")
presenter.recheck(packageName, className)
}
}
override fun onStartJob(params: JobParameters): Boolean {
val extras = params.extras
val typeName = extras.getString(JobSchedulerCompat.KEY_JOB_TYPE)
val type = JobSchedulerCompat.JobType.valueOf(requireNotNull(typeName))
when (type) {
SERVICE_TEMP_PAUSE -> handleServicePauseJob()
RECHECK -> handleRecheckJob(extras)
}
// Returns false to indicate this runs on main thread synchronously
return false
}
}
| apache-2.0 | dca9b397ab090e784d18614ebfa700da | 31.988372 | 85 | 0.760663 | 4.324695 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/screencapture/ScreenCaptureModule.kt | 2 | 2088 | package abi42_0_0.expo.modules.screencapture
import android.app.Activity
import android.content.Context
import android.view.WindowManager
import abi42_0_0.org.unimodules.core.ExportedModule
import abi42_0_0.org.unimodules.core.ModuleRegistry
import abi42_0_0.org.unimodules.core.Promise
import abi42_0_0.org.unimodules.core.errors.CurrentActivityNotFoundException
import abi42_0_0.org.unimodules.core.interfaces.ActivityProvider
import abi42_0_0.org.unimodules.core.interfaces.ExpoMethod
class ScreenCaptureModule(context: Context) : ExportedModule(context) {
private lateinit var mActivityProvider: ActivityProvider
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
ScreenshotEventEmitter(context, moduleRegistry)
}
@ExpoMethod
fun preventScreenCapture(promise: Promise) {
val activity = getCurrentActivity()
activity.runOnUiThread {
try {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE)
} catch (exception: Exception) {
promise.reject(ERROR_CODE_PREVENTION, "Failed to prevent screen capture: " + exception)
}
}
promise.resolve(null)
}
@ExpoMethod
fun allowScreenCapture(promise: Promise) {
val activity = getCurrentActivity()
activity.runOnUiThread {
try {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
} catch (exception: Exception) {
promise.reject(ERROR_CODE_PREVENTION, "Failed to reallow screen capture: " + exception)
}
}
promise.resolve(null)
}
@Throws(CurrentActivityNotFoundException::class)
fun getCurrentActivity(): Activity {
val activity = mActivityProvider.currentActivity
if (activity != null) {
return activity
} else {
throw CurrentActivityNotFoundException()
}
}
companion object {
private val NAME = "ExpoScreenCapture"
private const val ERROR_CODE_PREVENTION = "ERR_SCREEN_CAPTURE_PREVENTION"
}
}
| bsd-3-clause | 1aa4ada9135d93cef5e1c3f7916b05b9 | 29.26087 | 95 | 0.7409 | 4.386555 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/hints/parameter/RsInlayParameterHintsProvider.kt | 2 | 3086 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.hints.parameter
import com.intellij.codeInsight.hints.HintInfo
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.codeInsight.hints.InlayParameterHintsProvider
import com.intellij.codeInsight.hints.Option
import com.intellij.psi.PsiElement
import org.rust.lang.RsLanguage
import org.rust.lang.core.psi.RsCallExpr
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsMethodCall
import org.rust.lang.core.psi.RsPathExpr
import org.rust.lang.core.psi.ext.patText
import org.rust.lang.core.psi.ext.qualifiedName
import org.rust.lang.core.psi.ext.selfParameter
import org.rust.lang.core.psi.ext.valueParameters
@Suppress("UnstableApiUsage")
class RsInlayParameterHintsProvider : InlayParameterHintsProvider {
override fun getSupportedOptions(): List<Option> = listOf(RsInlayParameterHints.smartOption)
override fun getDefaultBlackList(): Set<String> = emptySet()
override fun getHintInfo(element: PsiElement): HintInfo? {
return when (element) {
is RsCallExpr -> resolve(element)
is RsMethodCall -> resolve(element)
else -> null
}
}
override fun getParameterHints(element: PsiElement): List<InlayInfo> = RsInlayParameterHints.provideHints(element)
override fun getInlayPresentation(inlayText: String): String = inlayText
override fun getBlacklistExplanationHTML(): String {
return """
To disable hints for a function use the appropriate pattern:<br />
<b>std::*</b> - functions from the standard library<br />
<b>std::fs::*(*, *)</b> - functions from the <i>std::fs</i> module with two parameters<br />
<b>(*_)</b> - single parameter function where the parameter name ends with <i>_</i><br />
<b>(key, value)</b> - functions with parameters <i>key</i> and <i>value</i><br />
<b>*.put(key, value)</b> - <i>put</i> functions with <i>key</i> and <i>value</i> parameters
""".trimIndent()
}
companion object {
private fun resolve(call: RsCallExpr): HintInfo.MethodInfo? {
val fn = (call.expr as? RsPathExpr)?.path?.reference?.resolve() as? RsFunction ?: return null
val parameters = fn.valueParameters.map { it.patText ?: "_" }
return createMethodInfo(fn, parameters)
}
private fun resolve(methodCall: RsMethodCall): HintInfo.MethodInfo? {
val fn = methodCall.reference.resolve() as? RsFunction? ?: return null
val parameters = listOfNotNull(fn.selfParameter?.name) + fn.valueParameters.map {
it.patText ?: "_"
}
return createMethodInfo(fn, parameters)
}
private fun createMethodInfo(function: RsFunction, parameters: List<String>): HintInfo.MethodInfo? {
val path = function.qualifiedName ?: return null
return HintInfo.MethodInfo(path, parameters, RsLanguage)
}
}
}
| mit | 6d8377fded81834a8ab2cc9c42493ff8 | 41.861111 | 118 | 0.678872 | 4.274238 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/pastry/layers/PastryColorPicker.kt | 1 | 8321 | package com.teamwizardry.librarianlib.facade.pastry.layers
import com.teamwizardry.librarianlib.albedo.base.buffer.BaseRenderBuffer
import com.teamwizardry.librarianlib.albedo.buffer.Primitive
import com.teamwizardry.librarianlib.albedo.buffer.VertexBuffer
import com.teamwizardry.librarianlib.albedo.shader.Shader
import com.teamwizardry.librarianlib.albedo.shader.attribute.VertexLayoutElement
import com.teamwizardry.librarianlib.albedo.shader.uniform.FloatUniform
import com.teamwizardry.librarianlib.albedo.shader.uniform.Uniform
import com.teamwizardry.librarianlib.core.util.*
import com.teamwizardry.librarianlib.etcetera.eventbus.Event
import com.teamwizardry.librarianlib.facade.layer.GuiDrawContext
import com.teamwizardry.librarianlib.facade.layer.GuiLayer
import com.teamwizardry.librarianlib.facade.layer.GuiLayerEvents
import com.teamwizardry.librarianlib.facade.layers.RectLayer
import com.teamwizardry.librarianlib.facade.layers.SpriteLayer
import com.teamwizardry.librarianlib.facade.pastry.PastryBackgroundStyle
import com.teamwizardry.librarianlib.math.clamp
import com.teamwizardry.librarianlib.mosaic.Mosaic
import net.minecraft.util.Identifier
import org.lwjgl.glfw.GLFW
import java.awt.Color
import kotlin.math.max
public class PastryColorPicker : GuiLayer(0, 0, 80, 50) {
private val gradient = GradientLayer()
private val hueLayer = HueLayer()
private val colorWell = ColorWellLayer()
private var _hue: Float = 0f
public var hue: Float
get() = _hue
set(value) {
_hue = value
_color = Color(Color.HSBtoRGB(hue, saturation, brightness))
BUS.fire(ColorChangeEvent(color))
}
private var _saturation: Float = 0f
public var saturation: Float
get() = _saturation
set(value) {
_saturation = value
_color = Color(Color.HSBtoRGB(hue, saturation, brightness))
BUS.fire(ColorChangeEvent(color))
}
private var _brightness: Float = 0f
public var brightness: Float
get() = _brightness
set(value) {
_brightness = value
_color = Color(Color.HSBtoRGB(hue, saturation, brightness))
BUS.fire(ColorChangeEvent(color))
}
private var _color: Color = Color.white
public var color: Color
get() = _color
set(value) {
_color = value
val hsb = Color.RGBtoHSB(color.red, color.green, color.blue, null)
_hue = hsb[0]
_saturation = hsb[1]
_brightness = hsb[2]
}
public class ColorChangeEvent(public val color: Color) : Event()
init {
this.add(gradient, hueLayer, colorWell)
}
override fun layoutChildren() {
colorWell.size = vec(16, 16)
colorWell.pos = vec(this.width - colorWell.width, 0)
hueLayer.size = vec(10, this.height)
hueLayer.pos = vec(colorWell.x - hueLayer.width - 2, 0)
gradient.pos = vec(0, 0)
gradient.size = vec(max(4.0, hueLayer.x - 2), this.height)
}
private inner class GradientLayer : GuiLayer(0, 0, 0, 0) {
val background = PastryBackground(PastryBackgroundStyle.LIGHT_INSET, 0, 0, 0, 0)
val square = ColorSquare()
var dragging = false
init {
add(background, square)
square.BUS.hook<GuiLayerEvents.MouseDown> {
if (square.mouseOver && it.button == GLFW.GLFW_MOUSE_BUTTON_LEFT) {
dragging = true
updateSB()
}
}
square.BUS.hook<GuiLayerEvents.MouseUp> {
if(it.button == GLFW.GLFW_MOUSE_BUTTON_LEFT) {
dragging = false
}
}
square.BUS.hook<GuiLayerEvents.MouseMove> {
if (dragging) {
updateSB()
}
}
}
private fun updateSB() {
if (square.width == 0.0 || square.height == 0.0) return
val fraction = square.mousePos / square.size
saturation = fraction.x.clamp(0.0, 1.0).toFloat()
brightness = (1 - fraction.y).clamp(0.0, 1.0).toFloat()
}
override fun layoutChildren() {
background.frame = bounds
square.frame = bounds
square.pos += vec(1, 1)
square.size -= vec(2, 2)
}
inner class ColorSquare : GuiLayer(0, 0, 0, 0) {
override fun draw(context: GuiDrawContext) {
super.draw(context)
val minX = 0.0
val minY = 0.0
val maxX = size.xi.toDouble()
val maxY = size.yi.toDouble()
val buffer = ColorPickerRenderBuffer.SHARED
buffer.hue.set(hue)
// u/v is saturation/brightness
buffer.pos(context.transform, minX, minY, 0).sv(0, 1).endVertex()
buffer.pos(context.transform, minX, maxY, 0).sv(0, 0).endVertex()
buffer.pos(context.transform, maxX, maxY, 0).sv(1, 0).endVertex()
buffer.pos(context.transform, maxX, minY, 0).sv(1, 1).endVertex()
buffer.draw(Primitive.QUADS)
}
}
}
private inner class HueLayer : GuiLayer(0, 0, 0, 0) {
private val background = PastryBackground(PastryBackgroundStyle.LIGHT_INSET, 0, 0, 0, 0)
private val sprite = SpriteLayer(hueSprite)
private var dragging = false
init {
Client.minecraft.textureManager.bindTexture(hueLoc)
Client.minecraft.textureManager.getTexture(hueLoc)?.setFilter(false, false)
add(background, sprite)
sprite.BUS.hook<GuiLayerEvents.MouseDown> {
if(sprite.mouseOver && it.button == GLFW.GLFW_MOUSE_BUTTON_LEFT) {
dragging = true
updateH()
}
}
sprite.BUS.hook<GuiLayerEvents.MouseUp> {
if(it.button == GLFW.GLFW_MOUSE_BUTTON_LEFT) {
dragging = false
}
}
sprite.BUS.hook<GuiLayerEvents.MouseMove> {
if(dragging) {
updateH()
}
}
}
fun updateH() {
if (sprite.height == 0.0) return
val fraction = sprite.mousePos.y / sprite.height
hue = (1 - fraction).clamp(0.0, 1.0).toFloat()
}
override fun layoutChildren() {
background.frame = bounds
sprite.frame = bounds
sprite.pos += vec(1, 1)
sprite.size -= vec(2, 2)
}
}
private inner class ColorWellLayer : GuiLayer(0, 0, 0, 0) {
private val background = PastryBackground(PastryBackgroundStyle.LIGHT_INSET, 0, 0, 0, 0)
val colorRect = RectLayer(Color.white, 0, 0, 0, 0)
init {
add(background, colorRect)
colorRect.color_im.set { color }
}
override fun layoutChildren() {
background.frame = this.bounds
colorRect.frame = this.bounds.shrink(1.0)
}
}
private companion object {
val hueLoc = Identifier("liblib-facade:textures/pastry/colorpicker_hue.png")
val hueSprite = Mosaic(hueLoc, 8, 256).getSprite("")
}
private class ColorPickerRenderBuffer(vbo: VertexBuffer) : BaseRenderBuffer<ColorPickerRenderBuffer>(vbo) {
val hue: FloatUniform = +Uniform.float.create("Hue")
private val texCoordAttribute = +VertexLayoutElement("TexCoord", VertexLayoutElement.FloatFormat.FLOAT, 2, false)
init {
bind(colorPickerShader)
}
fun sv(saturation: Int, value: Int): ColorPickerRenderBuffer {
start(texCoordAttribute)
putFloat(saturation.toFloat())
putFloat(value.toFloat())
return this
}
companion object {
val colorPickerShader = Shader.build("pastry_color_picker")
.vertex(Identifier("liblib-facade:pastry_color_picker.vert"))
.fragment(Identifier("liblib-facade:pastry_color_picker.frag"))
.build()
val SHARED = ColorPickerRenderBuffer(VertexBuffer.SHARED)
}
}
}
| lgpl-3.0 | 7c747f74a93027dbfd5249707b7e285d | 34.866379 | 121 | 0.594039 | 4.340636 | false | false | false | false |
androidx/androidx | camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/compat/ExternalRequestProcessor.kt | 3 | 8825 | /*
* 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:Suppress("DEPRECATION")
package androidx.camera.camera2.pipe.compat
import android.hardware.camera2.CaptureRequest
import android.view.Surface
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.CameraController
import androidx.camera.camera2.pipe.CameraGraph
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.CaptureSequence
import androidx.camera.camera2.pipe.CaptureSequenceProcessor
import androidx.camera.camera2.pipe.Metadata
import androidx.camera.camera2.pipe.Request
import androidx.camera.camera2.pipe.RequestMetadata
import androidx.camera.camera2.pipe.RequestNumber
import androidx.camera.camera2.pipe.RequestProcessor
import androidx.camera.camera2.pipe.RequestTemplate
import androidx.camera.camera2.pipe.StreamId
import androidx.camera.camera2.pipe.core.Log
import androidx.camera.camera2.pipe.graph.GraphListener
import androidx.camera.camera2.pipe.graph.GraphRequestProcessor
import kotlin.reflect.KClass
import kotlinx.atomicfu.atomic
@RequiresApi(21)
class ExternalCameraController(
private val graphConfig: CameraGraph.Config,
private val graphListener: GraphListener,
private val requestProcessor: RequestProcessor
) : CameraController {
private val sequenceProcessor = ExternalCaptureSequenceProcessor(graphConfig, requestProcessor)
private val graphProcessor: GraphRequestProcessor = GraphRequestProcessor.from(
sequenceProcessor
)
private var started = atomic(false)
override fun start() {
if (started.compareAndSet(expect = false, update = true)) {
graphListener.onGraphStarted(graphProcessor)
}
}
override fun stop() {
if (started.compareAndSet(expect = true, update = false)) {
graphListener.onGraphStopped(graphProcessor)
}
}
override fun close() {
graphProcessor.close()
}
override fun updateSurfaceMap(surfaceMap: Map<StreamId, Surface>) {
sequenceProcessor.surfaceMap = surfaceMap
}
}
@Suppress("DEPRECATION")
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
internal class ExternalCaptureSequenceProcessor(
private val graphConfig: CameraGraph.Config,
private val processor: RequestProcessor
) : CaptureSequenceProcessor<Request, ExternalCaptureSequenceProcessor.ExternalCaptureSequence> {
private val internalRequestNumbers = atomic(0L)
private val internalSequenceNumbers = atomic(0)
private val closed = atomic(false)
private var _surfaceMap: Map<StreamId, Surface>? = null
var surfaceMap: Map<StreamId, Surface>?
get() = synchronized(this) { _surfaceMap }
set(value) = synchronized(this) { _surfaceMap = value }
override fun build(
isRepeating: Boolean,
requests: List<Request>,
defaultParameters: Map<*, Any?>,
requiredParameters: Map<*, Any?>,
listeners: List<Request.Listener>,
sequenceListener: CaptureSequence.CaptureSequenceListener
): ExternalCaptureSequence? {
if (closed.value) {
return null
}
val streamToSurfaceMap = surfaceMap
if (streamToSurfaceMap == null) {
Log.warn { "Cannot create an ExternalCaptureSequence until Surfaces are available!" }
return null
}
val metadata = requests.map { request ->
val parameters = defaultParameters + request.parameters + requiredParameters
ExternalRequestMetadata(
graphConfig.defaultTemplate,
streamToSurfaceMap,
parameters,
isRepeating,
request,
RequestNumber(internalRequestNumbers.incrementAndGet())
)
}
return ExternalCaptureSequence(
graphConfig.camera,
isRepeating,
requests,
metadata,
defaultParameters,
requiredParameters,
listeners,
sequenceListener
)
}
override fun submit(captureSequence: ExternalCaptureSequence): Int {
check(!closed.value)
check(captureSequence.captureRequestList.isNotEmpty())
if (captureSequence.repeating) {
check(captureSequence.captureRequestList.size == 1)
processor.startRepeating(
captureSequence.captureRequestList.single(),
captureSequence.defaultParameters,
captureSequence.requiredParameters,
captureSequence.listeners
)
} else {
if (captureSequence.captureRequestList.size == 1) {
processor.submit(
captureSequence.captureRequestList.single(),
captureSequence.defaultParameters,
captureSequence.requiredParameters,
captureSequence.listeners
)
} else {
processor.submit(
captureSequence.captureRequestList,
captureSequence.defaultParameters,
captureSequence.requiredParameters,
captureSequence.listeners
)
}
}
return internalSequenceNumbers.incrementAndGet()
}
override fun abortCaptures() {
processor.abortCaptures()
}
override fun stopRepeating() {
processor.stopRepeating()
}
override fun close() {
if (closed.compareAndSet(expect = false, update = true)) {
processor.close()
}
}
internal class ExternalCaptureSequence(
override val cameraId: CameraId,
override val repeating: Boolean,
override val captureRequestList: List<Request>,
override val captureMetadataList: List<RequestMetadata>,
val defaultParameters: Map<*, Any?>,
val requiredParameters: Map<*, Any?>,
override val listeners: List<Request.Listener>,
override val sequenceListener: CaptureSequence.CaptureSequenceListener,
) : CaptureSequence<Request> {
@Volatile
private var _sequenceNumber: Int? = null
override var sequenceNumber: Int
get() {
if (_sequenceNumber == null) {
// If the sequence id has not been submitted, it means the call to capture or
// setRepeating has not yet returned. The callback methods should never be
// synchronously invoked, so the only case this should happen is if a second
// thread attempted to invoke one of the callbacks before the initial call
// completed. By locking against the captureSequence object here and in the
// capture call, we can block the callback thread until the sequenceId is
// available.
synchronized(this) {
return checkNotNull(_sequenceNumber) {
"SequenceNumber has not been set for $this!"
}
}
}
return checkNotNull(_sequenceNumber) {
"SequenceNumber has not been set for $this!"
}
}
set(value) {
_sequenceNumber = value
}
}
@Suppress("UNCHECKED_CAST")
internal class ExternalRequestMetadata(
override val template: RequestTemplate,
override val streams: Map<StreamId, Surface>,
private val parameters: Map<*, Any?>,
override val repeating: Boolean,
override val request: Request,
override val requestNumber: RequestNumber
) : RequestMetadata {
override fun <T> get(key: CaptureRequest.Key<T>): T? = parameters[key] as T?
override fun <T> get(key: Metadata.Key<T>): T? = parameters[key] as T?
override fun <T> getOrDefault(key: CaptureRequest.Key<T>, default: T): T =
get(key) ?: default
override fun <T> getOrDefault(key: Metadata.Key<T>, default: T): T = get(key) ?: default
override fun <T : Any> unwrapAs(type: KClass<T>): T? = null
}
} | apache-2.0 | 7b69c4658df1aa205666cf31846cc55c | 37.043103 | 99 | 0.647479 | 5.11891 | false | false | false | false |
mickele/DBFlow | dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/QueryModelDefinition.kt | 1 | 5836 | package com.raizlabs.android.dbflow.processor.definition
import com.raizlabs.android.dbflow.annotation.Column
import com.raizlabs.android.dbflow.annotation.QueryModel
import com.raizlabs.android.dbflow.processor.ClassNames
import com.raizlabs.android.dbflow.processor.ProcessorUtils
import com.raizlabs.android.dbflow.processor.definition.column.ColumnDefinition
import com.raizlabs.android.dbflow.processor.definition.CustomTypeConverterPropertyMethod
import com.raizlabs.android.dbflow.processor.definition.LoadFromCursorMethod
import com.raizlabs.android.dbflow.processor.definition.MethodDefinition
import com.raizlabs.android.dbflow.processor.ProcessorManager
import com.raizlabs.android.dbflow.processor.utils.ElementUtility
import com.raizlabs.android.dbflow.processor.ColumnValidator
import com.squareup.javapoet.*
import java.util.*
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier
import javax.lang.model.element.TypeElement
import javax.lang.model.type.MirroredTypeException
/**
* Description:
*/
class QueryModelDefinition(typeElement: Element, processorManager: ProcessorManager)
: BaseTableDefinition(typeElement, processorManager) {
var databaseTypeName: TypeName? = null
var allFields: Boolean = false
var implementsLoadFromCursorListener = false
internal var methods: Array<MethodDefinition>
init {
val queryModel = typeElement.getAnnotation(QueryModel::class.java)
if (queryModel != null) {
try {
queryModel.database
} catch (mte: MirroredTypeException) {
databaseTypeName = TypeName.get(mte.typeMirror)
}
}
elementClassName?.let { databaseTypeName?.let { it1 -> processorManager.addModelToDatabase(it, it1) } }
if (element is TypeElement) {
implementsLoadFromCursorListener = ProcessorUtils.implementsClass(manager.processingEnvironment, ClassNames.LOAD_FROM_CURSOR_LISTENER.toString(),
element as TypeElement)
}
methods = arrayOf<MethodDefinition>(LoadFromCursorMethod(this))
}
override fun prepareForWrite() {
classElementLookUpMap.clear()
columnDefinitions.clear()
packagePrivateList.clear()
val queryModel = typeElement?.getAnnotation(QueryModel::class.java)
if (queryModel != null) {
databaseDefinition = manager.getDatabaseHolderDefinition(databaseTypeName)?.databaseDefinition
setOutputClassName(databaseDefinition?.classSeparator + DBFLOW_QUERY_MODEL_TAG)
allFields = queryModel.allFields
typeElement?.let { createColumnDefinitions(it) }
}
}
override val extendsClass: TypeName?
get() = ParameterizedTypeName.get(ClassNames.QUERY_MODEL_ADAPTER, elementClassName)
override fun onWriteDefinition(typeBuilder: TypeSpec.Builder) {
elementClassName?.let { className -> columnDefinitions.forEach { it.addPropertyDefinition(typeBuilder, className) } }
val customTypeConverterPropertyMethod = CustomTypeConverterPropertyMethod(this)
customTypeConverterPropertyMethod.addToType(typeBuilder)
val constructorCode = CodeBlock.builder()
constructorCode.addStatement("super(databaseDefinition)")
customTypeConverterPropertyMethod.addCode(constructorCode)
InternalAdapterHelper.writeGetModelClass(typeBuilder, elementClassName)
typeBuilder.addMethod(MethodSpec.constructorBuilder().addParameter(ClassNames.DATABASE_HOLDER, "holder").addParameter(ClassNames.BASE_DATABASE_DEFINITION_CLASSNAME, "databaseDefinition").addCode(constructorCode.build()).addModifiers(Modifier.PUBLIC).build())
for (method in methods) {
val methodSpec = method.methodSpec
if (methodSpec != null) {
typeBuilder.addMethod(methodSpec)
}
}
typeBuilder.addMethod(MethodSpec.methodBuilder("newInstance")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.returns(elementClassName)
.addStatement("return new \$T()", elementClassName).build())
}
override fun createColumnDefinitions(typeElement: TypeElement) {
val variableElements = ElementUtility.getAllElements(typeElement, manager)
for (element in variableElements) {
classElementLookUpMap.put(element.simpleName.toString(), element)
}
val columnValidator = ColumnValidator()
for (variableElement in variableElements) {
// no private static or final fields
val isAllFields = ElementUtility.isValidAllFields(allFields, element)
// package private, will generate helper
val isPackagePrivate = ElementUtility.isPackagePrivate(element)
val isPackagePrivateNotInSamePackage = isPackagePrivate && !ElementUtility.isInSamePackage(manager, element, this.element)
if (variableElement.getAnnotation(Column::class.java) != null || isAllFields) {
val columnDefinition = ColumnDefinition(manager, variableElement, this, isPackagePrivateNotInSamePackage)
if (columnValidator.validate(manager, columnDefinition)) {
columnDefinitions.add(columnDefinition)
if (isPackagePrivate) {
packagePrivateList.add(columnDefinition)
}
}
}
}
}
override // Shouldn't include any
val primaryColumnDefinitions: List<ColumnDefinition>
get() = ArrayList()
override val propertyClassName: ClassName
get() = outputClassName
companion object {
private val DBFLOW_QUERY_MODEL_TAG = "QueryTable"
}
}
| mit | 4481ec515c7689baa15075ad31e099d8 | 38.70068 | 266 | 0.710075 | 5.169176 | false | false | false | false |
androidx/androidx | compose/material3/material3/integration-tests/material3-catalog/src/main/java/androidx/compose/material3/catalog/library/ui/component/Component.kt | 3 | 5906 | /*
* 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.compose.material3.catalog.library.ui.component
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.consumedWindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.catalog.library.R
import androidx.compose.material3.catalog.library.model.Component
import androidx.compose.material3.catalog.library.model.Example
import androidx.compose.material3.catalog.library.model.Theme
import androidx.compose.material3.catalog.library.ui.common.CatalogScaffold
import androidx.compose.material3.catalog.library.ui.example.ExampleItem
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun Component(
component: Component,
theme: Theme,
onThemeChange: (theme: Theme) -> Unit,
onExampleClick: (example: Example) -> Unit,
onBackClick: () -> Unit
) {
val ltr = LocalLayoutDirection.current
CatalogScaffold(
topBarTitle = component.name,
showBackNavigationIcon = true,
theme = theme,
guidelinesUrl = component.guidelinesUrl,
docsUrl = component.docsUrl,
sourceUrl = component.sourceUrl,
onThemeChange = onThemeChange,
onBackClick = onBackClick
) { paddingValues ->
LazyColumn(
modifier = Modifier.consumedWindowInsets(paddingValues),
contentPadding = PaddingValues(
start = paddingValues.calculateStartPadding(ltr) + ComponentPadding,
top = paddingValues.calculateTopPadding() + ComponentPadding,
end = paddingValues.calculateEndPadding(ltr) + ComponentPadding,
bottom = paddingValues.calculateBottomPadding() + ComponentPadding
)
) {
item {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = ComponentIconVerticalPadding)
) {
Image(
painter = painterResource(id = component.icon),
contentDescription = null,
modifier = Modifier
.size(ComponentIconSize)
.align(Alignment.Center),
colorFilter = if (component.tintIcon) {
ColorFilter.tint(LocalContentColor.current)
} else {
null
}
)
}
}
item {
Text(
text = stringResource(id = R.string.description),
style = MaterialTheme.typography.bodyLarge
)
Spacer(modifier = Modifier.height(ComponentPadding))
Text(
text = component.description,
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(ComponentDescriptionPadding))
}
item {
Text(
text = stringResource(id = R.string.examples),
style = MaterialTheme.typography.bodyLarge
)
Spacer(modifier = Modifier.height(ComponentPadding))
}
if (component.examples.isNotEmpty()) {
items(component.examples) { example ->
ExampleItem(
example = example,
onClick = onExampleClick
)
Spacer(modifier = Modifier.height(ExampleItemPadding))
}
} else {
item {
Text(
text = stringResource(id = R.string.no_examples),
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(ComponentPadding))
}
}
}
}
}
private val ComponentIconSize = 108.dp
private val ComponentIconVerticalPadding = 42.dp
private val ComponentPadding = 16.dp
private val ComponentDescriptionPadding = 32.dp
private val ExampleItemPadding = 8.dp
| apache-2.0 | e63779ea5b55965620133a678144bddf | 40.013889 | 84 | 0.637318 | 5.296861 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_shader_objects.kt | 1 | 27586 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val ARB_shader_objects = "ARBShaderObjects".nativeClassGL("ARB_shader_objects", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension adds API calls that are necessary to manage shader objects and program objects as defined in the OpenGL 2.0 white papers by 3Dlabs.
The generation of an executable that runs on one of OpenGL's programmable units is modeled to that of developing a typical C/C++ application. There are
one or more source files, each of which are stored by OpenGL in a shader object. Each shader object (source file) needs to be compiled and attached to a
program object. Once all shader objects are compiled successfully, the program object needs to be linked to produce an executable. This executable is
part of the program object, and can now be loaded onto the programmable units to make it part of the current OpenGL state. Both the compile and link
stages generate a text string that can be queried to get more information. This information could be, but is not limited to, compile errors, link errors,
optimization hints, etc. Values for uniform variables, declared in a shader, can be set by the application and used to control a shader's behavior.
This extension defines functions for creating shader objects and program objects, for compiling shader objects, for linking program objects, for
attaching shader objects to program objects, and for using a program object as part of current state. Functions to load uniform values are also defined.
Some house keeping functions, like deleting an object and querying object state, are also provided.
Although this extension defines the API for creating shader objects, it does not define any specific types of shader objects. It is assumed that this
extension will be implemented along with at least one such additional extension for creating a specific type of OpenGL 2.0 shader (e.g., the
${ARB_fragment_shader.link} extension or the ${ARB_vertex_shader.link} extension).
${GL20.promoted}
"""
IntConstant(
"Accepted by the {@code pname} argument of GetHandleARB.",
"PROGRAM_OBJECT_ARB"..0x8B40
)
val Parameters = IntConstant(
"Accepted by the {@code pname} parameter of GetObjectParameter{fi}vARB.",
"OBJECT_TYPE_ARB"..0x8B4E,
"OBJECT_SUBTYPE_ARB"..0x8B4F,
"OBJECT_DELETE_STATUS_ARB"..0x8B80,
"OBJECT_COMPILE_STATUS_ARB"..0x8B81,
"OBJECT_LINK_STATUS_ARB"..0x8B82,
"OBJECT_VALIDATE_STATUS_ARB"..0x8B83,
"OBJECT_INFO_LOG_LENGTH_ARB"..0x8B84,
"OBJECT_ATTACHED_OBJECTS_ARB"..0x8B85,
"OBJECT_ACTIVE_UNIFORMS_ARB"..0x8B86,
"OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB"..0x8B87,
"OBJECT_SHADER_SOURCE_LENGTH_ARB"..0x8B88
).javaDocLinks
IntConstant(
"Returned by the {@code params} parameter of GetObjectParameter{fi}vARB.",
"SHADER_OBJECT_ARB"..0x8B48
)
IntConstant(
"Returned by the {@code type} parameter of GetActiveUniformARB.",
"FLOAT_VEC2_ARB"..0x8B50,
"FLOAT_VEC3_ARB"..0x8B51,
"FLOAT_VEC4_ARB"..0x8B52,
"INT_VEC2_ARB"..0x8B53,
"INT_VEC3_ARB"..0x8B54,
"INT_VEC4_ARB"..0x8B55,
"BOOL_ARB"..0x8B56,
"BOOL_VEC2_ARB"..0x8B57,
"BOOL_VEC3_ARB"..0x8B58,
"BOOL_VEC4_ARB"..0x8B59,
"FLOAT_MAT2_ARB"..0x8B5A,
"FLOAT_MAT3_ARB"..0x8B5B,
"FLOAT_MAT4_ARB"..0x8B5C,
"SAMPLER_1D_ARB"..0x8B5D,
"SAMPLER_2D_ARB"..0x8B5E,
"SAMPLER_3D_ARB"..0x8B5F,
"SAMPLER_CUBE_ARB"..0x8B60,
"SAMPLER_1D_SHADOW_ARB"..0x8B61,
"SAMPLER_2D_SHADOW_ARB"..0x8B62,
"SAMPLER_2D_RECT_ARB"..0x8B63,
"SAMPLER_2D_RECT_SHADOW_ARB"..0x8B64
)
void(
"DeleteObjectARB",
"""
Either deletes the object, or flags it for deletion. An object that is attached to a container object is not deleted until it is no longer attached to
any container object, for any context. If it is still attached to at least one container object, the object is flagged for deletion. If the object is
part of the current rendering state, it is not deleted until it is no longer part of the current rendering state for any context. If the object is still
part of the rendering state of at least one context, it is flagged for deletion.
If an object is flagged for deletion, its Boolean status bit #OBJECT_DELETE_STATUS_ARB is set to true.
DeleteObjectARB will silently ignore the value zero.
When a container object is deleted, it will detach each attached object as part of the deletion process. When an object is deleted, all information for
the object referenced is lost. The data for the object is also deleted.
""",
GLhandleARB.IN("obj", "the shader object to delete")
)
GLhandleARB(
"GetHandleARB",
"Returns the handle to an object that is in use as part of current state.",
GLenum.IN("pname", "the state item for which the current object is to be returned", "#PROGRAM_OBJECT_ARB")
)
void(
"DetachObjectARB",
"Detaches an object from the container object it is attached to.",
GLhandleARB.IN("containerObj", "the container object"),
GLhandleARB.IN("attachedObj", "the object to detach")
)
GLhandleARB(
"CreateShaderObjectARB",
"Creates a shader object.",
GLenum.IN("shaderType", "the type of the shader object to be created", "ARBVertexShader#VERTEX_SHADER_ARB ARBFragmentShader#FRAGMENT_SHADER_ARB")
)
void(
"ShaderSourceARB",
"""
Sets the source code for the specified shader object {@code shaderObj} to the text strings in the {@code string} array. If the object previously had
source code loaded into it, it is completely replaced.
The strings that are loaded into a shader object are expected to form the source code for a valid shader as defined in the OpenGL Shading Language
Specification.
""",
GLhandleARB.IN("shaderObj", "the shader object"),
AutoSize("string", "length")..GLsizei.IN("count", "the number of strings in the array"),
PointerArray(GLcharARB_p, "string", "length")..const..GLcharARB_pp.IN("string", "an array of pointers to one or more, optionally null terminated, character strings that make up the source code"),
nullable..const..GLint_p.IN(
"length",
"""
an array with the number of charARBs in each string (the string length). Each element in this array can be set to negative one (or smaller),
indicating that its accompanying string is null terminated. If {@code length} is set to $NULL, all strings in the {@code string} argument are
considered null terminated.
"""
)
)
void(
"CompileShaderARB",
"""
Compiles a shader object. Each shader object has a Boolean status, #OBJECT_COMPILE_STATUS_ARB, that is modified as a result of compilation. This status
can be queried with #GetObjectParameteriARB(). This status will be set to GL11#TRUE if the shader {@code shaderObj} was compiled without errors and is
ready for use, and GL11#FALSE otherwise. Compilation can fail for a variety of reasons as listed in the OpenGL Shading Language Specification. If
CompileShaderARB failed, any information about a previous compile is lost and is not restored. Thus a failed compile does not restore the old state of
{@code shaderObj}. If {@code shaderObj} does not reference a shader object, the error GL11#INVALID_OPERATION is generated.
Note that changing the source code of a shader object, through ShaderSourceARB, does not change its compile status #OBJECT_COMPILE_STATUS_ARB.
Each shader object has an information log that is modified as a result of compilation. This information log can be queried with #GetInfoLogARB() to
obtain more information about the compilation attempt.
""",
GLhandleARB.IN("shaderObj", "the shader object to compile")
)
GLhandleARB(
"CreateProgramObjectARB",
"""
Creates a program object.
A program object is a container object. Shader objects are attached to a program object with the command AttachObjectARB. It is permissible to attach
shader objects to program objects before source code has been loaded into the shader object, or before the shader object has been compiled. It is
permissible to attach multiple shader objects of the same type to a single program object, and it is permissible to attach a shader object to more than
one program object.
"""
)
void(
"AttachObjectARB",
"Attaches an object to a container object.",
GLhandleARB.IN("containerObj", "the container object"),
GLhandleARB.IN("obj", "the object to attach")
)
void(
"LinkProgramARB",
"""
Links a program object.
Each program object has a Boolean status, #OBJECT_LINK_STATUS_ARB, that is modified as a result of linking. This status can be queried with
#GetObjectParameteriARB(). This status will be set to GL11#TRUE if a valid executable is created, and GL11#FALSE otherwise. Linking can fail for a
variety of reasons as specified in the OpenGL Shading Language Specification. Linking will also fail if one or more of the shader objects, attached to
{@code programObj}, are not compiled successfully, or if more active uniform or active sampler variables are used in {@code programObj} than allowed.
If LinkProgramARB failed, any information about a previous link is lost and is not restored. Thus a failed link does not restore the old state of
{@code programObj}. If {@code programObj} is not of type #PROGRAM_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated.
Each program object has an information log that is modified as a result of a link operation. This information log can be queried with #GetInfoLogARB()
to obtain more information about the link operation.
""",
GLhandleARB.IN("programObj", "the program object to link")
)
void(
"UseProgramObjectARB",
"""
Installs the executable code as part of current rendering state if the program object {@code programObj} contains valid executable code, i.e. has been
linked successfully. If UseProgramObjectARB is called with the handle set to 0, it is as if the GL had no programmable stages and the fixed
functionality paths will be used instead. If {@code programObj} cannot be made part of the current rendering state, an GL11#INVALID_OPERATION error will
be generated and the current rendering state left unmodified. This error will be set, for example, if {@code programObj} has not been linked
successfully. If {@code programObj} is not of type #PROGRAM_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated.
While a program object is in use, applications are free to modify attached shader objects, compile attached shader objects, attach additional shader
objects, and detach shader objects. This does not affect the link status #OBJECT_LINK_STATUS_ARB of the program object. This does not affect the
executable code that is part of the current state either. That executable code is only affected when the program object has been re-linked successfully.
After such a successful re-link, the #LinkProgramARB() command will install the generated executable code as part of the current rendering state if the
specified program object was already in use as a result of a previous call to UseProgramObjectARB. If this re-link failed, then the executable code part
of the current state does not change.
""",
GLhandleARB.IN("programObj", "the program object to use")
)
void(
"ValidateProgramARB",
"""
Validates the program object {@code programObj} against the GL state at that moment. Each program object has a Boolean status,
#OBJECT_VALIDATE_STATUS_ARB, that is modified as a result of validation. This status can be queried with #GetObjectParameteriARB(). If validation
succeeded this status will be set to GL11#TRUE, otherwise it will be set to GL11#FALSE. If validation succeeded the program object is guaranteed to
execute, given the current GL state. If validation failed, the program object is guaranteed to not execute, given the current GL state. If
{@code programObj} is not of type #PROGRAM_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated.
ValidateProgramARB will validate at least as much as is done when a rendering command is issued, and it could validate more. For example, it could give
a hint on how to optimize some piece of shader code.
ValidateProgramARB will store its information in the info log. This information will either be an empty string or it will contain validation information.
ValidateProgramARB is typically only useful during application development. An application should not expect different OpenGL implementations to produce
identical information.
""",
GLhandleARB.IN("programObj", "the program object to validate")
)
val uniformLocation = GLint.IN("location", "the uniform variable location")
val uniformX = "the uniform x value"
val uniformY = "the uniform y value"
val uniformZ = "the uniform z value"
val uniformW = "the uniform w value"
void(
"Uniform1fARB",
"float version of #Uniform4fARB().",
uniformLocation,
GLfloat.IN("v0", uniformX)
)
void(
"Uniform2fARB",
"vec2 version of #Uniform4fARB().",
uniformLocation,
GLfloat.IN("v0", uniformX),
GLfloat.IN("v1", uniformY)
)
void(
"Uniform3fARB",
"vec3 version of #Uniform4fARB().",
uniformLocation,
GLfloat.IN("v0", uniformX),
GLfloat.IN("v1", uniformY),
GLfloat.IN("v2", uniformZ)
)
void(
"Uniform4fARB",
"Loads a vec4 value into a uniform variable of the program object that is currently in use.",
GLint.IN("location", "the uniform variable location"),
GLfloat.IN("v0", uniformX),
GLfloat.IN("v1", uniformY),
GLfloat.IN("v2", uniformZ),
GLfloat.IN("v3", uniformW)
)
void(
"Uniform1iARB",
"int version of #Uniform1fARB().",
uniformLocation,
GLint.IN("v0", uniformX)
)
void(
"Uniform2iARB",
"ivec2 version of #Uniform2fARB().",
uniformLocation,
GLint.IN("v0", uniformX),
GLint.IN("v1", uniformY)
)
void(
"Uniform3iARB",
"ivec3 version of #Uniform3fARB().",
uniformLocation,
GLint.IN("v0", uniformX),
GLint.IN("v1", uniformY),
GLint.IN("v2", uniformZ)
)
void(
"Uniform4iARB",
"ivec4 version of #Uniform4fARB().",
uniformLocation,
GLint.IN("v0", uniformX),
GLint.IN("v1", uniformY),
GLint.IN("v2", uniformZ),
GLint.IN("v3", uniformW)
)
void(
"Uniform1fvARB",
"Loads floating-point values {@code count} times into a uniform location defined as an array of float values.",
uniformLocation,
AutoSize("value")..GLsizei.IN("count", "the number of float values to load"),
const..GLfloat_p.IN("value", "the values to load")
)
void(
"Uniform2fvARB",
"Loads floating-point values {@code count} times into a uniform location defined as an array of vec2 vectors.",
uniformLocation,
AutoSize(2, "value")..GLsizei.IN("count", "the number of vec2 vectors to load"),
const..GLfloat_p.IN("value", "the values to load")
)
void(
"Uniform3fvARB",
"Loads floating-point values {@code count} times into a uniform location defined as an array of vec3 vectors.",
uniformLocation,
AutoSize(3, "value")..GLsizei.IN("count", "the number of vec3 vectors to load"),
const..GLfloat_p.IN("value", "the values to load")
)
void(
"Uniform4fvARB",
"Loads floating-point values {@code count} times into a uniform location defined as an array of vec4 vectors.",
uniformLocation,
AutoSize(4, "value")..GLsizei.IN("count", "the number of vec4 vectors to load"),
const..GLfloat_p.IN("value", "the values to load")
)
void(
"Uniform1ivARB",
"Loads integer values {@code count} times into a uniform location defined as an array of integer values.",
uniformLocation,
AutoSize("value")..GLsizei.IN("count", "the number of integer values to load"),
const..GLint_p.IN("value", "the values to load")
)
void(
"Uniform2ivARB",
"Loads integer values {@code count} times into a uniform location defined as an array of ivec2 vectors.",
uniformLocation,
AutoSize(2, "value")..GLsizei.IN("count", "the number of ivec2 vectors to load"),
const..GLint_p.IN("value", "the values to load")
)
void(
"Uniform3ivARB",
"Loads integer values {@code count} times into a uniform location defined as an array of ivec3 vectors.",
uniformLocation,
AutoSize(3, "value")..GLsizei.IN("count", "the number of ivec3 vectors to load"),
const..GLint_p.IN("value", "the values to load")
)
void(
"Uniform4ivARB",
"Loads integer values {@code count} times into a uniform location defined as an array of ivec4 vectors.",
uniformLocation,
AutoSize(4, "value")..GLsizei.IN("count", "the number of ivec4 vectors to load"),
const..GLint_p.IN("value", "the values to load")
)
val transpose = GLboolean.IN("transpose", "if GL11#FALSE, the matrix is specified in column major order, otherwise in row major order")
void(
"UniformMatrix2fvARB",
"Loads a 2x2 matrix of floating-point values {@code count} times into a uniform location defined as a matrix or an array of matrices.",
uniformLocation,
AutoSize(2 x 2, "value")..GLsizei.IN("count", "the number of 2x2 matrices to load"),
transpose,
const..GLfloat_p.IN("value", "the matrix values to load")
)
void(
"UniformMatrix3fvARB",
"Loads a 3x3 matrix of floating-point values {@code count} times into a uniform location defined as a matrix or an array of matrices.",
uniformLocation,
AutoSize(3 x 3, "value")..GLsizei.IN("count", "the number of 3x3 matrices to load"),
transpose,
const..GLfloat_p.IN("value", "the matrix values to load")
)
void(
"UniformMatrix4fvARB",
"Loads a 4x4 matrix of floating-point values {@code count} times into a uniform location defined as a matrix or an array of matrices.",
uniformLocation,
AutoSize(4 x 4, "value")..GLsizei.IN("count", "the number of 4x4 matrices to load"),
transpose,
const..GLfloat_p.IN("value", "the matrix values to load")
)
void(
"GetObjectParameterfvARB",
"Returns object specific parameter values.",
GLhandleARB.IN("obj", "the object to query"),
GLenum.IN("pname", "the parameter to query"),
Check(1)..GLfloat_p.OUT("params", "a buffer in which to return the parameter value")
)
void(
"GetObjectParameterivARB",
"Returns object specific parameter values.",
GLhandleARB.IN("obj", "the object to query"),
GLenum.IN("pname", "the parameter to query", Parameters),
Check(1)..ReturnParam..GLint_p.OUT("params", "a buffer in which to return the parameter value")
)
void(
"GetInfoLogARB",
"""
A string that contains information about the last link or validation attempt and last compilation attempt are kept per program or shader object. This
string is called the info log and can be obtained with this command.
This string will be null terminated. The number of characters in the info log is given by #OBJECT_INFO_LOG_LENGTH_ARB, which can be queried with
#GetObjectParameteriARB(). If {@code obj} is a shader object, the returned info log will either be an empty string or it will contain
information about the last compilation attempt for that object. If {@code obj} is a program object, the returned info log will either be an empty string
or it will contain information about the last link attempt or last validation attempt for that object. If {@code obj} is not of type #PROGRAM_OBJECT_ARB
or #SHADER_OBJECT_ARB, the error GL11#INVALID_OPERATION is generated. If an error occurred, the return parameters {@code length} and {@code infoLog}
will be unmodified.
The info log is typically only useful during application development and an application should not expect different OpenGL implementations to produce
identical info logs.
""",
GLhandleARB.IN("obj", "the shader object to query"),
AutoSize("infoLog")..GLsizei.IN("maxLength", "the maximum number of characters the GL is allowed to write into {@code infoLog}"),
Check(1)..nullable..GLsizei_p.OUT(
"length",
"""
the actual number of characters written by the GL into {@code infoLog} is returned in {@code length}, excluding the null termination. If
{@code length} is $NULL then the GL ignores this parameter.
"""
),
Return(
"length",
"glGetObjectParameteriARB(obj, GL_OBJECT_INFO_LOG_LENGTH_ARB)",
heapAllocate = true
)..GLcharARB_p.OUT("infoLog", "a buffer in which to return the info log")
)
void(
"GetAttachedObjectsARB",
"""
Returns the handles of objects attached to {@code containerObj} in {@code obj}. . The number of objects attached to {@code containerObj} is given by
#OBJECT_ATTACHED_OBJECTS_ARB, which can be queried with #GetObjectParameteriARB(). If {@code containerObj} is not of type #PROGRAM_OBJECT_ARB, the
error GL11#INVALID_OPERATION is generated. If an error occurred, the return parameters {@code count} and {@code obj} will be unmodified.
""",
GLhandleARB.IN("containerObj", "the container object to query"),
AutoSize("obj")..GLsizei.IN("maxCount", "the maximum number of handles the GL is allowed to write into {@code obj}"),
Check(1)..nullable..GLsizei_p.OUT(
"count",
"a buffer in which to return the actual number of object handles written by the GL into {@code obj}. If $NULL then the GL ignores this parameter."
),
GLhandleARB_p.OUT("obj", "a buffer in which to return the attached object handles")
)
GLint(
"GetUniformLocationARB",
"""
Returns the location of uniform variable {@code name}. {@code name} has to be a null terminated string, without white space. The value of -1 will be
returned if {@code name} does not correspond to an active uniform variable name in {@code programObj} or if {@code name} starts with the reserved prefix
"gl_". If {@code programObj} has not been successfully linked, or if {@code programObj} is not of type #PROGRAM_OBJECT_ARB, the error
GL11#INVALID_OPERATION is generated. The location of a uniform variable does not change until the next link command is issued.
A valid {@code name} cannot be a structure, an array of structures, or a subcomponent of a vector or a matrix. In order to identify a valid {@code name},
the "." (dot) and "[]" operators can be used in {@code name} to operate on a structure or to operate on an array.
The first element of a uniform array is identified using the name of the uniform array appended with "[0]". Except if the last part of the string
{@code name} indicates a uniform array, then the location of the first element of that array can be retrieved by either using the name of the uniform
array, or the name of the uniform array appended with "[0]".
""",
GLhandleARB.IN("programObj", "the program object to query"),
const..GLcharARB_p.IN("name", "the name of the uniform variable whose location is to be queried")
)
void(
"GetActiveUniformARB",
"""
Determines which of the declared uniform variables are active and their sizes and types.
This command provides information about the uniform selected by {@code index}. The {@code index} of 0 selects the first active uniform, and
{@code index} of #OBJECT_ACTIVE_UNIFORMS_ARB - 1 selects the last active uniform. The value of #OBJECT_ACTIVE_UNIFORMS_ARB can be queried with
#GetObjectParameteriARB(). If {@code index} is greater than or equal to #OBJECT_ACTIVE_UNIFORMS_ARB, the error GL11#INVALID_VALUE is generated.
If an error occurred, the return parameters {@code length}, {@code size}, {@code type} and {@code name} will be unmodified.
The returned uniform name can be the name of built-in uniform state as well. The length of the longest uniform name in {@code programObj} is given by
#OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, which can be queried with #GetObjectParameteriARB().
Each uniform variable, declared in a shader, is broken down into one or more strings using the "." (dot) and "[]" operators, if necessary, to the point
that it is legal to pass each string back into #GetUniformLocationARB(). Each of these strings constitutes one active uniform, and each string is
assigned an index.
If one or more elements of an array are active, GetActiveUniformARB will return the name of the array in {@code name}, subject to the restrictions
listed above. The type of the array is returned in {@code type}. The {@code size} parameter contains the highest array element index used, plus one. The
compiler or linker determines the highest index used. There will be only one active uniform reported by the GL per uniform array.
This command will return as much information about active uniforms as possible. If no information is available, {@code length} will be set to zero and
{@code name} will be an empty string. This situation could arise if GetActiveUniformARB is issued after a failed link.
""",
GLhandleARB.IN(
"programObj",
"""
a handle to a program object for which the command #LinkProgramARB() has been issued in the past. It is not necessary for {@code programObj} to have
been linked successfully. The link could have failed because the number of active uniforms exceeded the limit.
"""
),
GLuint.IN("index", "the uniform index"),
AutoSize("name")..GLsizei.IN("maxLength", "the maximum number of characters the GL is allowed to write into {@code name}."),
Check(1)..nullable..GLsizei_p.IN(
"length",
"""
a buffer in which to return the actual number of characters written by the GL into {@code name}. This count excludes the null termination. If
{@code length} is $NULL then the GL ignores this parameter.
"""
),
Check(1)..GLint_p.OUT("size", "a buffer in which to return the uniform size. The size is in units of the type returned in {@code type}."),
Check(1)..GLenum_p.OUT("type", "a buffer in which to return the uniform type"),
Return(
"length",
"glGetObjectParameteriARB(programObj, GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB)"
)..GLcharARB_p.OUT("name", "a buffer in which to return the uniform name")
)
void(
"GetUniformfvARB",
"Returns the floating-point value or values of a uniform.",
GLhandleARB.IN("programObj", "the program object to query"),
uniformLocation,
Check(1)..ReturnParam..GLfloat_p.OUT("params", "a buffer in which to return the uniform values")
)
void(
"GetUniformivARB",
"Returns the integer value or values of a uniform.",
GLhandleARB.IN("programObj", "the program object to query"),
uniformLocation,
Check(1)..ReturnParam..GLint_p.OUT("params", "a buffer in which to return the uniform values")
)
void(
"GetShaderSourceARB",
"""
Returns the string making up the source code for a shader object.
The string {@code source} is a concatenation of the strings passed to OpenGL using #ShaderSourceARB(). The length of this concatenation is given by
#OBJECT_SHADER_SOURCE_LENGTH_ARB, which can be queried with #GetObjectParameteriARB(). If {@code obj} is not of type #SHADER_OBJECT_ARB, the error
GL11#INVALID_OPERATION is generated. If an error occurred, the return parameters {@code length} and {@code source} will be unmodified.
""",
GLhandleARB.IN("obj", "the shader object to query"),
AutoSize("source")..GLsizei.IN("maxLength", "the maximum number of characters the GL is allowed to write into {@code source}"),
Check(1)..nullable..GLsizei_p.OUT(
"length",
"""
a buffer in which to return the actual number of characters written by the GL into {@code source}, excluding the null termination. If
{@code length} is $NULL then the GL ignores this parameter.
"""
),
Return(
"length",
"glGetObjectParameteriARB(obj, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB)",
heapAllocate = true
)..GLcharARB_p.OUT("source", "a buffer in which to return the shader object source")
)
} | bsd-3-clause | d65da1562f335a46b2d7bbb65f41a1ee | 43.639159 | 197 | 0.737041 | 3.751156 | false | false | false | false |
dropbox/Store | store-rx3/src/main/kotlin/com/dropbox/store/rx3/RxSourceOfTruth.kt | 1 | 2573 | package com.dropbox.store.rx3
import com.dropbox.android.external.store4.SourceOfTruth
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.rx3.await
/**
* Creates a [Maybe] source of truth that is accessible via [reader], [writer], [delete] and
* [deleteAll].
*
* @param reader function for reading records from the source of truth
* @param writer function for writing updates to the backing source of truth
* @param delete function for deleting records in the source of truth for the given key
* @param deleteAll function for deleting all records in the source of truth
*
*/
fun <Key : Any, Input : Any, Output : Any> SourceOfTruth.Companion.ofMaybe(
reader: (Key) -> Maybe<Output>,
writer: (Key, Input) -> Completable,
delete: ((Key) -> Completable)? = null,
deleteAll: (() -> Completable)? = null
): SourceOfTruth<Key, Input, Output> {
val deleteFun: (suspend (Key) -> Unit)? =
if (delete != null) { key -> delete(key).await() } else null
val deleteAllFun: (suspend () -> Unit)? = deleteAll?.let { { deleteAll().await() } }
return of(
nonFlowReader = { key -> reader.invoke(key).await() },
writer = { key, output -> writer.invoke(key, output).await() },
delete = deleteFun,
deleteAll = deleteAllFun
)
}
/**
* Creates a ([Flowable]) source of truth that is accessed via [reader], [writer], [delete] and
* [deleteAll].
*
* @param reader function for reading records from the source of truth
* @param writer function for writing updates to the backing source of truth
* @param delete function for deleting records in the source of truth for the given key
* @param deleteAll function for deleting all records in the source of truth
*
*/
fun <Key : Any, Input : Any, Output : Any> SourceOfTruth.Companion.ofFlowable(
reader: (Key) -> Flowable<Output>,
writer: (Key, Input) -> Completable,
delete: ((Key) -> Completable)? = null,
deleteAll: (() -> Completable)? = null
): SourceOfTruth<Key, Input, Output> {
val deleteFun: (suspend (Key) -> Unit)? =
if (delete != null) { key -> delete(key).await() } else null
val deleteAllFun: (suspend () -> Unit)? = deleteAll?.let { { deleteAll().await() } }
return of(
reader = { key -> reader.invoke(key).asFlow() },
writer = { key, output -> writer.invoke(key, output).await() },
delete = deleteFun,
deleteAll = deleteAllFun
)
}
| apache-2.0 | 128400964f4b95f2f74b48857c9ec346 | 40.5 | 95 | 0.667703 | 3.922256 | false | false | false | false |
esofthead/mycollab | mycollab-scheduler/src/main/java/com/mycollab/module/project/schedule/email/service/ComponentRelayEmailNotificationActionImpl.kt | 3 | 8499 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.schedule.email.service
import com.hp.gagawa.java.elements.A
import com.hp.gagawa.java.elements.Span
import com.mycollab.common.MonitorTypeConstants
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.common.i18n.OptionI18nEnum
import com.mycollab.core.MyCollabException
import com.mycollab.core.utils.StringUtils
import com.mycollab.html.FormatUtils
import com.mycollab.html.LinkUtils
import com.mycollab.module.mail.MailUtils
import com.mycollab.module.project.ProjectLinkGenerator
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.domain.ProjectRelayEmailNotification
import com.mycollab.module.project.i18n.ComponentI18nEnum
import com.mycollab.module.project.domain.Component.Field
import com.mycollab.module.project.domain.SimpleComponent
import com.mycollab.module.project.service.ComponentService
import com.mycollab.module.user.AccountLinkGenerator
import com.mycollab.module.user.service.UserService
import com.mycollab.schedule.email.ItemFieldMapper
import com.mycollab.schedule.email.MailContext
import com.mycollab.schedule.email.format.FieldFormat
import com.mycollab.schedule.email.format.I18nFieldFormat
import com.mycollab.schedule.email.project.ComponentRelayEmailNotificationAction
import com.mycollab.spring.AppContextUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class ComponentRelayEmailNotificationActionImpl : SendMailToAllMembersAction<SimpleComponent>(), ComponentRelayEmailNotificationAction {
@Autowired private lateinit var componentService: ComponentService
private val mapper = ComponentFieldNameMapper()
override fun buildExtraTemplateVariables(context: MailContext<SimpleComponent>) {
val emailNotification = context.emailNotification
val summary = bean!!.name
val summaryLink = ProjectLinkGenerator.generateComponentPreviewFullLink(siteUrl, bean!!.projectid, bean!!.id)
val avatarId = if (projectMember != null) projectMember!!.memberAvatarId else ""
val userAvatar = LinkUtils.newAvatar(avatarId)
val makeChangeUser = "${userAvatar.write()} ${emailNotification.changeByUserFullName}"
val actionEnum = when (emailNotification.action) {
MonitorTypeConstants.CREATE_ACTION -> ComponentI18nEnum.MAIL_CREATE_ITEM_HEADING
MonitorTypeConstants.UPDATE_ACTION -> ComponentI18nEnum.MAIL_UPDATE_ITEM_HEADING
MonitorTypeConstants.ADD_COMMENT_ACTION -> ComponentI18nEnum.MAIL_COMMENT_ITEM_HEADING
else -> throw MyCollabException("Not support action ${emailNotification.action}")
}
contentGenerator.putVariable("projectName", bean!!.projectName)
contentGenerator.putVariable("projectNotificationUrl", ProjectLinkGenerator.generateProjectSettingFullLink(siteUrl, bean!!.projectid))
contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser))
contentGenerator.putVariable("name", summary)
contentGenerator.putVariable("summaryLink", summaryLink)
}
override fun getBeanInContext(notification: ProjectRelayEmailNotification): SimpleComponent? =
componentService.findById(notification.typeid.toInt(), notification.saccountid)
override fun getItemName(): String = StringUtils.trim(bean!!.description, 100)
override fun getProjectName(): String = bean!!.projectName
override fun getCreateSubject(context: MailContext<SimpleComponent>): String = context.getMessage(
ComponentI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCreateSubjectNotification(context: MailContext<SimpleComponent>): String = context.getMessage(
ComponentI18nEnum.MAIL_CREATE_ITEM_SUBJECT, projectLink(), userLink(context), componentLink())
override fun getUpdateSubject(context: MailContext<SimpleComponent>): String = context.getMessage(
ComponentI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getUpdateSubjectNotification(context: MailContext<SimpleComponent>): String = context.getMessage(
ComponentI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, projectLink(), userLink(context), componentLink())
override fun getCommentSubject(context: MailContext<SimpleComponent>): String = context.getMessage(
ComponentI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCommentSubjectNotification(context: MailContext<SimpleComponent>): String = context.getMessage(
ComponentI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, projectLink(), userLink(context), componentLink())
private fun projectLink() = A(ProjectLinkGenerator.generateProjectLink(bean!!.projectid)).appendText(bean!!.projectName).write()
private fun userLink(context: MailContext<SimpleComponent>) = A(AccountLinkGenerator.generateUserLink(context.user.username)).appendText(context.changeByUserFullName).write()
private fun componentLink() = A(ProjectLinkGenerator.generateComponentPreviewLink(bean!!.projectid, bean!!.id)).appendText(getItemName()).write()
override fun getItemFieldMapper(): ItemFieldMapper = mapper
override fun getType(): String = ProjectTypeConstants.COMPONENT
override fun getTypeId(): String = "${bean!!.id}"
class ComponentFieldNameMapper : ItemFieldMapper() {
init {
put(Field.description, GenericI18Enum.FORM_DESCRIPTION, true)
put(Field.status, I18nFieldFormat(Field.status.name, GenericI18Enum.FORM_STATUS,
OptionI18nEnum.StatusI18nEnum::class.java))
put(Field.userlead, LeadFieldFormat(Field.userlead.name, ComponentI18nEnum.FORM_LEAD))
}
}
class LeadFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) {
override fun formatField(context: MailContext<*>): String {
val component = context.wrappedBean as SimpleComponent
return if (component.userlead != null) {
val userAvatarLink = MailUtils.getAvatarLink(component.userLeadAvatarId, 16)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(component.saccountid),
component.userlead)
val link = FormatUtils.newA(userLink, component.userLeadFullName!!)
FormatUtils.newLink(img, link).write()
} else Span().write()
}
override fun formatField(context: MailContext<*>, value: String): String {
if (StringUtils.isBlank(value)) {
return Span().write()
}
val userService = AppContextUtil.getSpringBean(UserService::class.java)
val user = userService.findUserByUserNameInAccount(value, context.saccountid)
return if (user != null) {
val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(context.saccountid),
user.username)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val link = FormatUtils.newA(userLink, user.displayName!!)
FormatUtils.newLink(img, link).write()
} else value
}
}
} | agpl-3.0 | fb96999f31529b9b2e1d2cf3a266dc1c | 52.45283 | 178 | 0.748882 | 4.883908 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/merakiscans/src/eu/kanade/tachiyomi/extension/en/merakiscans/MerakiScans.kt | 1 | 5436 | package eu.kanade.tachiyomi.extension.en.merakiscans
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.OkHttpClient
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
class MerakiScans : ParsedHttpSource() {
override val name = "MerakiScans"
override val baseUrl = "https://merakiscans.com"
override val lang = "en"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
companion object {
val dateFormat by lazy {
SimpleDateFormat("MMM dd, yyyy", Locale.US)
}
}
override fun popularMangaSelector() = "#all > #listitem > a"
override fun latestUpdatesSelector() = "#mangalisthome > #mangalistitem > #mangaitem > #manganame > a"
override fun popularMangaRequest(page: Int) =
GET("$baseUrl/manga", headers)
override fun latestUpdatesRequest(page: Int) =
GET(baseUrl, headers)
override fun popularMangaFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.attr("href"))
title = element.select("h1.title").text().trim()
}
override fun latestUpdatesFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.attr("href"))
title = element.text().trim()
}
override fun popularMangaNextPageSelector(): String? = null
override fun latestUpdatesNextPageSelector(): String? = null
override fun searchMangaRequest(page: Int, query: String, filters: FilterList) =
GET("$baseUrl/manga", headers)
override fun searchMangaSelector() = popularMangaSelector()
// This makes it so that if somebody searches for "views" it lists everything, also includes #'s.
private fun searchMangaSelector(query: String) = "#all > #listitem > a:contains($query)"
override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaNextPageSelector(): String? = null
private fun searchMangaParse(response: Response, query: String): MangasPage {
val document = response.asJsoup()
val mangas = document.select(searchMangaSelector(query)).map { element ->
searchMangaFromElement(element)
}
return MangasPage(mangas, false)
}
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return client.newCall(searchMangaRequest(page, query, filters))
.asObservableSuccess()
.map { response ->
searchMangaParse(response, query)
}
}
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
val infoElement = document.select("#content2")
author = infoElement.select("#detail_list > li:nth-child(5)").text().replace("Author:", "").trim()
artist = infoElement.select("#detail_list > li:nth-child(7)").text().replace("Artist:", "").trim()
genre = infoElement.select("#detail_list > li:nth-child(11) > a").joinToString { it.text().trim() }
status = infoElement.select("#detail_list > li:nth-child(9)").text().replace("Status:", "").trim().let {
parseStatus(it)
}
description = infoElement.select("#detail_list > span").text().trim()
thumbnail_url = infoElement.select("#info > #image > #cover_img").attr("abs:src")
}
private fun parseStatus(status: String) = when {
status.contains("Ongoing") -> SManga.ONGOING
status.contains("Completed") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "#chapter_table > tbody > #chapter-head"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
setUrlWithoutDomain(element.attr("data-href"))
name = element.select("td:nth-child(1)").text().trim()
date_upload = element.select("td:nth-child(2)").text().trim().let { parseChapterDate(it) }
}
private fun parseChapterDate(date: String): Long {
return try {
dateFormat.parse(date.replace(Regex("(st|nd|rd|th)"), ""))?.time ?: 0L
} catch (e: ParseException) {
0L
}
}
override fun pageListParse(document: Document): List<Page> {
val doc = document.toString()
val imgarray = doc.substringAfter("var images = [").substringBefore("];").split(",").map { it.replace("\"", "") }
val mangaslug = doc.substringAfter("var manga_slug = \"").substringBefore("\";")
val chapnum = doc.substringAfter("var viewschapter = \"").substringBefore("\";")
return imgarray.mapIndexed { i, image ->
Page(i, "", "$baseUrl/manga/$mangaslug/$chapnum/$image")
}
}
override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("Not used")
override fun getFilterList() = FilterList()
}
| apache-2.0 | 67602132d3d74a7e4bb127b55f77078e | 37.828571 | 121 | 0.675313 | 4.53 | false | false | false | false |
ligee/kotlin-jupyter | jupyter-lib/api-annotations/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/annotations/JupyterSymbolProcessor.kt | 1 | 2989 | package org.jetbrains.kotlinx.jupyter.api.annotations
import com.google.devtools.ksp.getAllSuperTypes
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import java.io.File
import java.util.Spliterators
import java.util.concurrent.locks.ReentrantLock
import java.util.stream.Stream
import java.util.stream.StreamSupport
import kotlin.concurrent.withLock
class JupyterSymbolProcessor(
private val logger: KSPLogger,
private val generatedFilesPath: File
) : SymbolProcessor {
private val fqnMap = mapOf(
"org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinitionProducer" to "producers",
"org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinition" to "definitions"
)
private val annotationFqn = JupyterLibrary::class.qualifiedName!!
private val annotationSimpleName = JupyterLibrary::class.simpleName!!
private val fileLock = ReentrantLock()
override fun process(resolver: Resolver): List<KSAnnotated> {
generatedFilesPath.deleteRecursively()
generatedFilesPath.mkdirs()
resolver
.getAllFiles()
.flatMap { it.declarations }
.filterIsInstance<KSClassDeclaration>()
.asParallelStream()
.forEach(::processClass)
return emptyList()
}
private fun processClass(clazz: KSClassDeclaration) {
if (!hasLibraryAnnotation(clazz)) return
val classFqn = clazz.qualifiedName?.asString()
?: throw Exception("Class $clazz was marked with $annotationSimpleName, but it has no qualified name (anonymous?).")
logger.info("Class $classFqn has $annotationSimpleName annotation")
val supertypes = clazz.getAllSuperTypes().mapNotNull { it.declaration.qualifiedName }.map { it.asString() }
val significantSupertypes = supertypes.filter { it in fqnMap }.toList()
if (significantSupertypes.isEmpty()) {
logger.warn(
"Class $classFqn has $annotationSimpleName annotation, " +
"but doesn't implement one of Jupyter integration interfaces"
)
return
}
fileLock.withLock {
for (fqn in significantSupertypes) {
val fileName = fqnMap[fqn]!!
val file = generatedFilesPath.resolve(fileName)
file.appendText(classFqn + "\n")
}
}
}
private fun hasLibraryAnnotation(clazz: KSClassDeclaration): Boolean {
return clazz.annotations.any { it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationFqn }
}
private fun <T> Sequence<T>.asParallelStream(): Stream<T> {
return StreamSupport.stream({ Spliterators.spliteratorUnknownSize(iterator(), 0) }, 0, true)
}
}
| apache-2.0 | 59487d7f163726086c24844a95445b64 | 37.320513 | 128 | 0.693543 | 4.820968 | false | false | false | false |
luanalbineli/popularmovies | app/src/main/java/com/themovielist/moviedetail/review/MovieReviewListDialogPresenter.kt | 1 | 2083 | package com.themovielist.moviedetail.review
import com.themovielist.model.MovieReviewModel
import com.themovielist.model.response.PaginatedArrayResponseModel
import com.themovielist.repository.movie.MovieRepository
import io.reactivex.disposables.Disposable
import timber.log.Timber
import javax.inject.Inject
class MovieReviewListDialogPresenter @Inject
internal constructor(private val mMovieRepository: MovieRepository) : MovieReviewListDialogContract.Presenter {
private lateinit var mView: MovieReviewListDialogContract.View
private var mPageIndex: Int = 0
private var mSubscription: Disposable? = null
private var mMovieId: Int = 0
override fun setView(view: MovieReviewListDialogContract.View) {
mView = view
}
override fun start(movieReviewList: List<MovieReviewModel>, movieId: Int, hasMore: Boolean) {
mView.addReviewsToList(movieReviewList)
if (hasMore) {
mView.enableLoadMoreListener()
}
mMovieId = movieId
}
override fun onListEndReached() {
if (mSubscription != null) {
return
}
mView.showLoadingIndicator()
mPageIndex++
val observable = mMovieRepository.getReviewsByMovieId(mPageIndex, mMovieId)
mSubscription = observable.subscribe({ response ->
this.handleSuccessLoadMovieReview(response)
}, { error -> this.handleErrorLoadMovieReview(error) })
}
private fun handleSuccessLoadMovieReview(response: PaginatedArrayResponseModel<MovieReviewModel>) {
mView.addReviewsToList(response.results)
if (!response.hasMorePages()) {
mView.disableLoadMoreListener()
}
mSubscription = null
}
private fun handleErrorLoadMovieReview(throwable: Throwable) {
Timber.e(throwable, "An error occurred while tried to get the movie reviews for page: " + mPageIndex)
mPageIndex--
mView.showErrorLoadingReviews()
mSubscription = null
}
override fun tryLoadReviewsAgain() {
onListEndReached()
}
}
| apache-2.0 | 845f7f453459ea83983d3c258f27fe6e | 30.089552 | 111 | 0.709073 | 4.936019 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/run/execution/ui/QueryResultTable.kt | 1 | 3828 | /*
* Copyright (C) 2019-2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.processor.run.execution.ui
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.ui.table.TableView
import uk.co.reecedunn.intellij.plugin.core.ui.layout.columnInfo
import uk.co.reecedunn.intellij.plugin.core.ui.layout.columns
import uk.co.reecedunn.intellij.plugin.processor.query.QueryResult
import uk.co.reecedunn.intellij.plugin.processor.resources.PluginApiBundle
import javax.swing.JScrollPane
data class QueryResultReference(private val textOffset: Int, internal var element: PsiElement? = null) {
val offset: Int
get() = element?.textOffset ?: textOffset
}
private val RESULT_INDEX_COLUMN = columnInfo<Pair<QueryResult, QueryResultReference>, Long>(
heading = PluginApiBundle.message("query.result.table.index.column.label"),
getter = { (first) -> first.position },
sortable = false
)
private val RESULT_ITEM_TYPE_COLUMN = columnInfo<Pair<QueryResult, QueryResultReference>, String>(
heading = PluginApiBundle.message("query.result.table.item-type.column.label"),
getter = { (first) -> first.type },
sortable = false
)
private val RESULT_MIME_TYPE_COLUMN = columnInfo<Pair<QueryResult, QueryResultReference>, String>(
heading = PluginApiBundle.message("query.result.table.mime-type.column.label"),
getter = { (first) -> first.mimetype },
sortable = false
)
class QueryResultTable : TableView<Pair<QueryResult, QueryResultReference>>(), QueryTable {
init {
columns {
add(RESULT_INDEX_COLUMN)
add(RESULT_ITEM_TYPE_COLUMN)
add(RESULT_MIME_TYPE_COLUMN)
}
setEnableAntialiasing(true)
updateEmptyText(running = false, exception = false)
}
private fun updateEmptyText(running: Boolean, exception: Boolean) {
when {
exception -> emptyText.text = PluginApiBundle.message("query.result.table.has-exception")
running -> emptyText.text = runningText
else -> emptyText.text = PluginApiBundle.message("query.result.table.no-results")
}
}
override var runningText: String = PluginApiBundle.message("query.result.table.results-pending")
set(value) {
field = value
updateEmptyText(isRunning, hasException)
}
override var isRunning: Boolean = false
set(value) {
field = value
updateEmptyText(isRunning, hasException)
}
override var hasException: Boolean = false
set(value) {
field = value
updateEmptyText(isRunning, hasException)
}
override val itemCount: Int
get() = rowCount
fun addRow(entry: QueryResult, offset: Int) {
listTableModel.addRow(Pair(entry, QueryResultReference(offset)))
}
fun updateQueryReferences(psiFile: PsiFile) {
(0 until itemCount).forEach {
val item = listTableModel.getItem(it)
item.second.element = psiFile.findElementAt(item.second.offset)
}
}
}
fun JScrollPane.queryResultTable(init: QueryResultTable.() -> Unit): QueryResultTable {
val view = QueryResultTable()
view.init()
setViewportView(view)
return view
}
| apache-2.0 | a3419ad3e6c3e4bf45d77ca16127ea28 | 34.444444 | 104 | 0.694357 | 4.211221 | false | false | false | false |
kamontat/CheckIDNumberA | app/src/main/java/com/kamontat/checkidnumber/model/strategy/idnumber/ThailandIDNumberStrategy.kt | 1 | 1232 | package com.kamontat.checkidnumber.model.strategy.idnumber
import com.kamontat.checkidnumber.api.constants.Status
/**
* @author kamontat
* *
* @version 1.0
* *
* @since Thu 11/May/2017 - 11:47 PM
*/
class ThailandIDNumberStrategy : IDNumberStrategy {
override val idLength: Int
get() = 13
override fun checking(id: String?): Status {
if (id == null || id == "") return Status.NOT_CREATE
val splitID = id.toCharArray()
when {
splitID[0] == '9' -> return Status.NOT_NINE
splitID.size != idLength -> return Status.UNMATCHED_LENGTH
else -> {
var total: Int = 0
(1..12).forEach { i ->
val digit = Character.getNumericValue(splitID[i - 1])
total += (14 - i) * digit
}
total %= 11
val lastDigit = Character.getNumericValue(splitID[splitID.size - 1])
when {
total <= 1 -> if (lastDigit == 1 - total) return Status.OK
else -> if (total > 1) if (lastDigit == 11 - total) return Status.OK
}
return Status.UNCORRECTED
}
}
}
}
| mit | 768e68f5ede876b2c25115cc28e86823 | 30.589744 | 88 | 0.51461 | 4.066007 | false | false | false | false |
paslavsky/music-sync-manager | msm-server/src/main/kotlin/net/paslavsky/msm/domain/DomainObject.kt | 1 | 808 | package net.paslavsky.msm.domain
import javax.persistence.MappedSuperclass
import javax.persistence.EmbeddedId
import javax.persistence.Version
/**
* Abstract class that represent Domain objects of the MSM
*
* @author Andrey Paslavsky
* @version 1.0
*/
MappedSuperclass
public abstract class DomainObject {
public EmbeddedId var id: ID = ID()
public Version var version: Int = -1
override fun toString(): String = "${javaClass.getSimpleName()}#$id"
override fun hashCode(): Int = 37 + 17 * (id xor (id shl 32)).toInt()
override fun equals(other: Any?): Boolean = when {
other == null -> false
this identityEquals other -> true
other is DomainObject && javaClass == other.javaClass -> id == other.id && version == other.version
else -> false
}
} | apache-2.0 | 58ee7ef347b36711041c525742a8eb5c | 30.115385 | 107 | 0.681931 | 4.344086 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/webview/events/TopHttpErrorEvent.kt | 2 | 784 | package abi42_0_0.host.exp.exponent.modules.api.components.webview.events
import abi42_0_0.com.facebook.react.bridge.WritableMap
import abi42_0_0.com.facebook.react.uimanager.events.Event
import abi42_0_0.com.facebook.react.uimanager.events.RCTEventEmitter
/**
* Event emitted when a http error is received from the server.
*/
class TopHttpErrorEvent(viewId: Int, private val mEventData: WritableMap) :
Event<TopHttpErrorEvent>(viewId) {
companion object {
const val EVENT_NAME = "topHttpError"
}
override fun getEventName(): String = EVENT_NAME
override fun canCoalesce(): Boolean = false
override fun getCoalescingKey(): Short = 0
override fun dispatch(rctEventEmitter: RCTEventEmitter) =
rctEventEmitter.receiveEvent(viewTag, eventName, mEventData)
}
| bsd-3-clause | 54a58ec74a9261357fb50b13ad5c59ad | 31.666667 | 75 | 0.772959 | 4 | false | false | false | false |
google/where-am-i | app/src/main/java/com/google/wear/whereami/kt/builders.kt | 1 | 3058 | // Copyright 2021 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.google.wear.whereami.kt
import androidx.wear.tiles.*
fun text(fn: LayoutElementBuilders.Text.Builder.() -> Unit): LayoutElementBuilders.Text {
val builder = LayoutElementBuilders.Text.Builder()
fn(builder)
return builder.build()
}
fun modifiers(fn: ModifiersBuilders.Modifiers.Builder.() -> Unit): ModifiersBuilders.Modifiers {
val builder = ModifiersBuilders.Modifiers.Builder()
fn(builder)
return builder.build()
}
fun activityClickable(
packageName: String,
activity: String
) = ModifiersBuilders.Clickable.Builder()
.setOnClick(
ActionBuilders.LaunchAction.Builder()
.setAndroidActivity(
ActionBuilders.AndroidActivity.Builder()
.setPackageName(packageName)
.setClassName(activity)
.build()
)
.build()
).build()
fun fontStyle(fn: LayoutElementBuilders.FontStyle.Builder.() -> Unit): LayoutElementBuilders.FontStyle {
val builder = LayoutElementBuilders.FontStyle.Builder()
fn(builder)
return builder.build()
}
fun TimelineBuilders.TimelineEntry.Builder.layout(fn: () -> LayoutElementBuilders.LayoutElement) {
setLayout(LayoutElementBuilders.Layout.Builder().setRoot(fn()).build())
}
fun tile(fn: TileBuilders.Tile.Builder.() -> Unit): TileBuilders.Tile {
val builder = TileBuilders.Tile.Builder()
fn(builder)
return builder.build()
}
fun TileBuilders.Tile.Builder.timeline(fn: TimelineBuilders.Timeline.Builder.() -> Unit) {
val builder = TimelineBuilders.Timeline.Builder()
builder.fn()
setTimeline(builder.build())
}
fun column(fn: LayoutElementBuilders.Column.Builder.() -> Unit): LayoutElementBuilders.Column {
val builder = LayoutElementBuilders.Column.Builder()
builder.fn()
return builder.build()
}
fun TimelineBuilders.Timeline.Builder.timelineEntry(fn: TimelineBuilders.TimelineEntry.Builder.() -> Unit) {
val builder = TimelineBuilders.TimelineEntry.Builder()
fn(builder)
addTimelineEntry(builder.build())
}
fun Float.toSpProp() = DimensionBuilders.SpProp.Builder().setValue(this).build()
fun Float.toDpProp() = DimensionBuilders.DpProp.Builder().setValue(this).build()
fun Int.toColorProp(): ColorBuilders.ColorProp =
ColorBuilders.ColorProp.Builder().setArgb(this).build()
fun String.toContentDescription() =
ModifiersBuilders.Semantics.Builder().setContentDescription(
this
).build() | apache-2.0 | d039332b50cfa15be9c385a1b3bb3984 | 33.370787 | 108 | 0.716808 | 4.331445 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/media/playback/CastPlayback.kt | 1 | 7799 | /*
* Copyright (C) 2014 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.sjn.stamp.media.playback
import android.content.Context
import android.net.Uri
import android.support.v4.media.session.MediaSessionCompat.QueueItem
import android.support.v4.media.session.PlaybackStateCompat
import android.text.TextUtils
import com.google.android.gms.cast.MediaStatus
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.media.RemoteMediaClient
import com.sjn.stamp.utils.LogHelper
import com.sjn.stamp.utils.MediaIDHelper
import com.sjn.stamp.utils.MediaItemHelper
import org.json.JSONException
import org.json.JSONObject
/**
* An implementation of Playback that talks to Cast.
*/
open class CastPlayback(internal val context: Context, private val callback: Playback.Callback, initialStreamPosition: Int, override var currentMediaId: String?) : Playback {
internal val remoteMediaClient: RemoteMediaClient = CastContext.getSharedInstance(this.context).sessionManager.currentCastSession.remoteMediaClient
private val remoteMediaClientListener: RemoteMediaClient.Listener = CastMediaClientListener()
private var currentPosition: Int = initialStreamPosition
override var state: Int = 0
override val isConnected: Boolean
get() = CastContext.getSharedInstance(context).sessionManager.currentCastSession?.isConnected
?: false
override val isPlaying: Boolean get() = isConnected && remoteMediaClient.isPlaying
override val currentStreamPosition: Int get() = if (!isConnected) currentPosition else remoteMediaClient.approximateStreamPosition.toInt()
override fun start() = remoteMediaClient.addListener(remoteMediaClientListener)
override fun stop(notifyListeners: Boolean) {
remoteMediaClient.removeListener(remoteMediaClientListener)
state = PlaybackStateCompat.STATE_STOPPED
if (notifyListeners) callback.onPlaybackStatusChanged(state)
}
override fun updateLastKnownStreamPosition() {
currentPosition = currentStreamPosition
}
override fun play(item: QueueItem) {
playItem(item)
state = PlaybackStateCompat.STATE_BUFFERING
callback.onPlaybackStatusChanged(state)
}
override fun pause() {
if (remoteMediaClient.hasMediaSession()) {
remoteMediaClient.pause()
currentPosition = remoteMediaClient.approximateStreamPosition.toInt()
}
}
override fun seekTo(position: Int) {
if (currentMediaId == null) {
callback.onError("seekTo cannot be calling in the absence of mediaId.")
return
}
if (remoteMediaClient.hasMediaSession()) {
remoteMediaClient.seek(position.toLong())
currentPosition = position
}
}
open fun playItem(item: QueueItem) {
send(item, true, item.description.mediaUri.toString(), Uri.Builder().encodedPath(item.description.iconUri.toString()).build())
}
@Throws(JSONException::class)
protected fun send(item: QueueItem, autoPlay: Boolean, mediaUri: String, iconUri: Uri) {
val mediaId = item.description.mediaId
if (mediaId == null || mediaId.isEmpty()) {
throw IllegalArgumentException("Invalid mediaId")
}
val musicId = MediaIDHelper.extractMusicIDFromMediaID(mediaId)
if (musicId == null || musicId.isEmpty()) {
throw IllegalArgumentException("Invalid mediaId")
}
if (!TextUtils.equals(mediaId, currentMediaId) || state != PlaybackStateCompat.STATE_PAUSED) {
currentMediaId = mediaId
currentPosition = 0
}
val customData = JSONObject()
try {
customData.put(ITEM_ID, mediaId)
} catch (e: JSONException) {
LogHelper.e(TAG, "Exception loading media ", e, null)
e.message?.let { callback.onError(it) }
}
remoteMediaClient.load(MediaItemHelper.convertToMediaInfo(
item, customData, mediaUri, iconUri), autoPlay, currentPosition.toLong(), customData)
}
private fun setMetadataFromRemote() {
// Sync: We get the customData from the remote media information and update the local
// metadata if it happens to be different from the one we are currently using.
// This can happen when the app was either restarted/disconnected + connected, or if the
// app joins an existing session while the Chromecast was playing a queue.
try {
val mediaInfo = remoteMediaClient.mediaInfo ?: return
val customData = mediaInfo.customData
if (customData != null && customData.has(ITEM_ID)) {
val remoteMediaId = customData.getString(ITEM_ID)
if (!TextUtils.equals(currentMediaId, remoteMediaId)) {
currentMediaId = remoteMediaId
callback.setCurrentMediaId(remoteMediaId)
updateLastKnownStreamPosition()
}
}
} catch (e: JSONException) {
LogHelper.e(TAG, e, "Exception processing update metadata")
}
}
private fun updatePlaybackState() {
val status = remoteMediaClient.playerState
LogHelper.d(TAG, "onRemoteMediaPlayerStatusUpdated ", status)
// Convert the remote playback states to media playback states.
when (status) {
MediaStatus.PLAYER_STATE_IDLE -> if (remoteMediaClient.idleReason == MediaStatus.IDLE_REASON_FINISHED) {
callback.onCompletion()
}
MediaStatus.PLAYER_STATE_BUFFERING -> {
state = PlaybackStateCompat.STATE_BUFFERING
callback.onPlaybackStatusChanged(state)
}
MediaStatus.PLAYER_STATE_PLAYING -> {
state = PlaybackStateCompat.STATE_PLAYING
setMetadataFromRemote()
callback.onPlaybackStatusChanged(state)
}
MediaStatus.PLAYER_STATE_PAUSED -> {
state = PlaybackStateCompat.STATE_PAUSED
setMetadataFromRemote()
callback.onPlaybackStatusChanged(state)
}
else // case unknown
-> LogHelper.d(TAG, "State default : ", status)
}
}
private inner class CastMediaClientListener : RemoteMediaClient.Listener {
private var lastStatus = -1
override fun onMetadataUpdated() {
LogHelper.d(TAG, "RemoteMediaClient.onMetadataUpdated")
setMetadataFromRemote()
}
override fun onStatusUpdated() {
LogHelper.d(TAG, "RemoteMediaClient.onStatusUpdated")
if (lastStatus != remoteMediaClient.playerState) {
updatePlaybackState()
}
lastStatus = remoteMediaClient.playerState
}
override fun onSendingRemoteMediaRequest() {}
override fun onAdBreakStatusUpdated() {}
override fun onQueueStatusUpdated() {}
override fun onPreloadStatusUpdated() {}
}
companion object {
private val TAG = LogHelper.makeLogTag(CastPlayback::class.java)
const val ITEM_ID = "itemId"
}
}
| apache-2.0 | a0fc84dea77dc3cfd5521338705488e5 | 39.201031 | 174 | 0.670855 | 5.04137 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemovePartsFromPropertyFix.kt | 2 | 3986 | // 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.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.compilerPreferences.KotlinBaseCompilerConfigurationUiBundle
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtProperty
open class RemovePartsFromPropertyFix(
element: KtProperty,
private val removeInitializer: Boolean,
private val removeGetter: Boolean,
private val removeSetter: Boolean
) : KotlinQuickFixAction<KtProperty>(element) {
override fun getText(): String {
val chunks = ArrayList<String>(3).apply {
if (removeGetter) add(KotlinBundle.message("text.getter"))
if (removeSetter) add(KotlinBundle.message("text.setter"))
if (removeInitializer) add(KotlinBundle.message("text.initializer"))
}
fun concat(head: String, tail: String): String {
return head + " " + KotlinBaseCompilerConfigurationUiBundle.message("configuration.text.and") + " " + tail
}
val partsText = when (chunks.size) {
0 -> ""
1 -> chunks.single()
2 -> concat(chunks[0], chunks[1])
else -> concat(chunks.dropLast(1).joinToString(", "), chunks.last())
}
return KotlinBundle.message("remove.0.from.property", partsText)
}
override fun getFamilyName(): String = KotlinBundle.message("remove.parts.from.property")
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = this.element ?: return
if (removeInitializer) {
val initializer = element.initializer
if (initializer != null) {
if (element.typeReference == null) {
val type = SpecifyTypeExplicitlyIntention.getTypeForDeclaration(element)
SpecifyTypeExplicitlyIntention.addTypeAnnotation(null, element, type)
}
element.deleteChildRange(element.equalsToken ?: initializer, initializer)
}
}
if (removeGetter) {
element.getter?.delete()
}
if (removeSetter) {
element.setter?.delete()
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtProperty>? {
val element = diagnostic.psiElement
val property = PsiTreeUtil.getParentOfType(element, KtProperty::class.java) ?: return null
return RemovePartsFromPropertyFix(
property,
removeInitializer = property.hasInitializer(),
removeGetter = property.getter?.bodyExpression != null,
removeSetter = property.setter?.bodyExpression != null
)
}
}
object LateInitFactory : KotlinSingleIntentionActionFactory() {
public override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtProperty>? {
val property = Errors.INAPPLICABLE_LATEINIT_MODIFIER.cast(diagnostic).psiElement as? KtProperty ?: return null
val hasInitializer = property.hasInitializer()
val hasGetter = property.getter?.bodyExpression != null
val hasSetter = property.setter?.bodyExpression != null
if (!hasInitializer && !hasGetter && !hasSetter) {
return null
}
return RemovePartsFromPropertyFix(property, hasInitializer, hasGetter, hasSetter)
}
}
}
| apache-2.0 | abf2e151226b770961dd7b168ac89b87 | 40.520833 | 158 | 0.664827 | 5.116816 | false | false | false | false |
onoderis/failchat | src/test/kotlin/failchat/experiment/JsonParsing.kt | 2 | 4594 | package failchat.experiment
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import failchat.twitch.TwitchEmoticon
import failchat.twitch.TwitchEmoticonUrlFactory
import failchat.util.nextNonNullToken
import failchat.util.validate
import org.junit.Test
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.nio.file.Files
import java.nio.file.Paths
class JsonParsing {
@Test
fun streamParsingTest() {
val jsonFile = Paths.get("""docs/integration/twitch/twitch-emoticons-slice.json""")
// val json = """{"name":"Tom","age":25,"address":["Poland","5th avenue"]}"""
val jsonFactory = JsonFactory()
val parser = jsonFactory.createParser(Files.newInputStream(jsonFile))
val emoticons: MutableList<TwitchEmoticon> = ArrayList()
parser.nextNonNullToken() // root object
parser.nextNonNullToken() // 'emoticons' field
var token = parser.nextNonNullToken() //START_ARRAY
while (token != JsonToken.END_ARRAY) {
token = parser.nextNonNullToken() //START_OBJECT
var id: Long? = null
var code: String? = null
while (token != JsonToken.END_OBJECT) {
parser.nextNonNullToken() // FIELD_NAME
val fieldName = parser.currentName
parser.nextNonNullToken()
when (fieldName) {
"id" -> {
id = parser.longValue
}
"code" -> {
code = parser.text
}
}
token = parser.nextNonNullToken() // END_OBJECT
}
emoticons.add(TwitchEmoticon(
requireNotNull(id) { "'id' not found" },
requireNotNull(code) { "'code' not found" },
TwitchEmoticonUrlFactory("pr", "sf")
))
token = parser.nextNonNullToken()
}
parser.close()
emoticons.forEach { println("${it.code}: ${it.twitchId}") }
/*
var parsedName: String? = null
var parsedAge: Int? = null
val addresses = LinkedList<String>()
while (parser.nextToken() != JsonToken.END_OBJECT) {
val fieldname = parser.currentName
if ("name" == fieldname) {
parser.nextToken()
parsedName = parser.text
}
if ("age" == fieldname) {
parser.nextToken()
parsedAge = parser.intValue
}
if ("address" == fieldname) {
parser.nextToken()
while (parser.nextToken() !== JsonToken.END_ARRAY) {
addresses.add(parser.getText())
}
}
}
parser.close()
*/
}
@Test
fun streamParsingTestV2() {
val jsonFile = Paths.get("""docs/integration/twitch/twitch-emoticons-slice.json""")
val jsonFactory = JsonFactory()
jsonFactory.codec = ObjectMapper()
val parser = jsonFactory.createParser(Files.newInputStream(jsonFile))
val emoticons: MutableList<TwitchEmoticon> = ArrayList()
parser.nextNonNullToken().validate(JsonToken.START_OBJECT) // root object
parser.nextNonNullToken().validate(JsonToken.FIELD_NAME) // 'emoticons' field
parser.nextNonNullToken().validate(JsonToken.START_ARRAY) // 'emoticons' array
var token = parser.nextNonNullToken().validate(JsonToken.START_OBJECT) // emoticon object
while (token != JsonToken.END_ARRAY) {
val node: ObjectNode = parser.readValueAsTree()
emoticons.add(TwitchEmoticon(
node.get("id").longValue(),
node.get("code").textValue(),
TwitchEmoticonUrlFactory("pr", "sf")
))
token = parser.nextNonNullToken()
}
parser.close()
emoticons.forEach { println("${it.code}: ${it.twitchId}") }
}
@Test
fun noDataAvailableTest() {
val inStream = PipedInputStream()
val outStream = PipedOutputStream(inStream)
outStream.write("""{"name":"value ...""".toByteArray())
val jsonFactory = JsonFactory()
val parser = jsonFactory.createParser(inStream)
while (true) {
println(parser.nextToken()) //thread will block here
}
}
}
| gpl-3.0 | 55de7681c102736a233806a646fd8630 | 30.465753 | 97 | 0.573792 | 4.795407 | false | false | false | false |
filpgame/kotlinx-examples | app/src/main/java/com/filpgame/kotlinx/ui/list/UserAdapter.kt | 1 | 1243 | package com.filpgame.kotlinx.ui.list
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.filpgame.kotlinx.R
import kotlinx.android.synthetic.main.list_row_user.view.*
/**
* @author Felipe Rodrigues
* @since 13/02/2017
*/
class UserAdapter(users: MutableList<User>? = null) : RecyclerView.Adapter<UserAdapter.UserViewHolder>() {
val users = users ?: mutableListOf<User>()
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
holder.view.userNameTextView.text = users[position].name
holder.view.userOccupationTextView.text = users[position].occupation
holder.view.userPictureImageView.setImageDrawable(ContextCompat.getDrawable(holder.view.context, users[position].picture))
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): UserViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.list_row_user, parent, false)
return UserViewHolder(view)
}
override fun getItemCount(): Int = users.count()
class UserViewHolder(val view: View) : RecyclerView.ViewHolder(view)
} | mit | 300a83a3ff3b13adf9be54e2cb86a5fe | 36.69697 | 130 | 0.757844 | 4.129568 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/PackaddCommand.kt | 1 | 1225 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
// Currently support only matchit
class PackaddCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) {
override val argFlags = flags(RangeFlag.RANGE_FORBIDDEN, ArgumentFlag.ARGUMENT_REQUIRED, Access.READ_ONLY)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
if (argument == "matchit" || (argument.startsWith("!") && argument.drop(1).trim() == "matchit")) {
injector.optionService.setOption(OptionScope.GLOBAL, "matchit")
}
return ExecutionResult.Success
}
}
| mit | 73bc22f6fef808b919c69cb79a277c29 | 41.241379 | 132 | 0.778776 | 4.056291 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/attention/attentionmechanism/AttentionMechanismLayer.kt | 1 | 2816 | /* 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.attention.attentionmechanism
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.activations.SoftmaxBase
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.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
* The Attention Mechanism Layer Structure.
*
* @property inputArrays the input arrays of the layer
* @param inputType the input array type (default Dense)
* @param params the parameters which connect the input to the output
* @param activation the activation function of the layer (default SoftmaxBase)
*/
internal class AttentionMechanismLayer(
val inputArrays: List<AugmentedArray<DenseNDArray>>,
inputType: LayerType.Input,
override val params: AttentionMechanismLayerParameters,
activation: ActivationFunction? = SoftmaxBase()
) : Layer<DenseNDArray>(
inputArray = AugmentedArray(params.inputSize), // empty array (it should not be used)
inputType = inputType,
outputArray = AugmentedArray(inputArrays.size),
params = params,
activationFunction = activation,
dropout = 0.0
) {
/**
* A matrix containing the attention arrays as rows.
*/
internal val attentionMatrix: AugmentedArray<DenseNDArray> = AugmentedArray(
DenseNDArrayFactory.fromRows(this.inputArrays.map { it.values })
)
/**
* The helper which executes the forward.
*/
override val forwardHelper = AttentionMechanismForwardHelper(layer = this)
/**
* The helper which executes the backward.
*/
override val backwardHelper = AttentionMechanismBackwardHelper(layer = this)
/**
* The helper which calculates the relevance.
*/
override val relevanceHelper: RelevanceHelper? = null
/**
* Initialization: set the activation function of the output array.
*/
init {
require(this.inputArrays.isNotEmpty()) { "The attention sequence cannot be empty." }
require(this.inputArrays.all { it.values.length == this.params.inputSize }) {
"The input arrays must have the expected size (${this.params.inputSize})."
}
if (activation != null)
this.outputArray.setActivation(activation)
}
}
| mpl-2.0 | 34db2d267ce2667fa0b7a83fb75b4a5e | 36.052632 | 88 | 0.742543 | 4.586319 | false | false | false | false |