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
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/visitor/KotlinMatchingVisitor.kt
3
65372
// 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.structuralsearch.visitor import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.elementType import com.intellij.structuralsearch.StructuralSearchUtil import com.intellij.structuralsearch.impl.matcher.CompiledPattern import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor import com.intellij.structuralsearch.impl.matcher.handlers.LiteralWithSubstitutionHandler import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler import com.intellij.util.containers.reverse import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassifierDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.core.resolveType import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.intentions.calleeName import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.structuralsearch.* import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchCompanionObjectPredicate import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchValVarPredicate import org.jetbrains.kotlin.kdoc.lexer.KDocTokens import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.kdoc.psi.impl.KDocImpl import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.psi.psiUtil.referenceExpression import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.util.OperatorNameConventions class KotlinMatchingVisitor(private val myMatchingVisitor: GlobalMatchingVisitor) : SSRKtVisitor() { /** Gets the next element in the query tree and removes unnecessary parentheses. */ private inline fun <reified T> getTreeElementDepar(): T? = when (val element = myMatchingVisitor.element) { is KtParenthesizedExpression -> { val deparenthesized = element.deparenthesize() if (deparenthesized is T) deparenthesized else { myMatchingVisitor.result = false null } } else -> getTreeElement<T>() } /** Gets the next element in the tree */ private inline fun <reified T> getTreeElement(): T? = when (val element = myMatchingVisitor.element) { is T -> element else -> { myMatchingVisitor.result = false null } } private inline fun <reified T:KtElement> factory(context: PsiElement, f: KtPsiFactory.() -> T): T { val psiFactory = KtPsiFactory(context, true) val result = psiFactory.f() (result.containingFile as KtFile).analysisContext = context return result } private fun GlobalMatchingVisitor.matchSequentially(elements: List<PsiElement?>, elements2: List<PsiElement?>) = matchSequentially(elements.toTypedArray(), elements2.toTypedArray()) private fun GlobalMatchingVisitor.matchInAnyOrder(elements: List<PsiElement?>, elements2: List<PsiElement?>) = matchInAnyOrder(elements.toTypedArray(), elements2.toTypedArray()) private fun GlobalMatchingVisitor.matchNormalized( element: KtExpression?, element2: KtExpression?, returnExpr: Boolean = false ): Boolean { val (e1, e2) = if (element is KtBlockExpression && element2 is KtBlockExpression) element to element2 else normalizeExpressions(element, element2, returnExpr) val impossible = e1?.let { val handler = getHandler(it) e2 !is KtBlockExpression && handler is SubstitutionHandler && handler.minOccurs > 1 } ?: false return !impossible && match(e1, e2) } private fun getHandler(element: PsiElement) = myMatchingVisitor.matchContext.pattern.getHandler(element) private fun matchTextOrVariable(el1: PsiElement?, el2: PsiElement?): Boolean { if (el1 == null) return true if (el2 == null) return false return substituteOrMatchText(el1, el2) } private fun matchTextOrVariableEq(el1: PsiElement?, el2: PsiElement?): Boolean { if (el1 == null && el2 == null) return true if (el1 == null) return false if (el2 == null) return false return substituteOrMatchText(el1, el2) } private fun substituteOrMatchText(el1: PsiElement, el2: PsiElement): Boolean { return when (val handler = getHandler(el1)) { is SubstitutionHandler -> handler.validate(el2, myMatchingVisitor.matchContext) else -> myMatchingVisitor.matchText(el1, el2) } } override fun visitLeafPsiElement(leafPsiElement: LeafPsiElement) { val other = getTreeElementDepar<LeafPsiElement>() ?: return // Match element type if (!myMatchingVisitor.setResult(leafPsiElement.elementType == other.elementType)) return when (leafPsiElement.elementType) { KDocTokens.TEXT -> { myMatchingVisitor.result = when (val handler = leafPsiElement.getUserData(CompiledPattern.HANDLER_KEY)) { is LiteralWithSubstitutionHandler -> handler.match(leafPsiElement, other, myMatchingVisitor.matchContext) else -> substituteOrMatchText(leafPsiElement, other) } } KDocTokens.TAG_NAME, KtTokens.IDENTIFIER -> myMatchingVisitor.result = substituteOrMatchText(leafPsiElement, other) } } override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) { val other = getTreeElementDepar<KtExpression>() ?: return myMatchingVisitor.result = when (other) { is KtArrayAccessExpression -> myMatchingVisitor.match(expression.arrayExpression, other.arrayExpression) && myMatchingVisitor.matchSons(expression.indicesNode, other.indicesNode) is KtDotQualifiedExpression -> myMatchingVisitor.match(expression.arrayExpression, other.receiverExpression) && other.calleeName == "${OperatorNameConventions.GET}" && myMatchingVisitor.matchSequentially( expression.indexExpressions, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!! ) else -> false } } /** Matches binary expressions including translated operators. */ override fun visitBinaryExpression(expression: KtBinaryExpression) { fun KtBinaryExpression.match(other: KtBinaryExpression) = operationToken == other.operationToken && myMatchingVisitor.match(left, other.left) && myMatchingVisitor.match(right, other.right) fun KtQualifiedExpression.match(name: Name?, receiver: KtExpression?, callEntry: KtExpression?): Boolean { val callExpr = callExpression return callExpr is KtCallExpression && calleeName == "$name" && myMatchingVisitor.match(receiver, receiverExpression) && myMatchingVisitor.match(callEntry, callExpr.valueArguments.first().getArgumentExpression()) } fun KtBinaryExpression.matchEq(other: KtBinaryExpression): Boolean { val otherLeft = other.left?.deparenthesize() val otherRight = other.right?.deparenthesize() return otherLeft is KtSafeQualifiedExpression && otherLeft.match(OperatorNameConventions.EQUALS, left, right) && other.operationToken == KtTokens.ELVIS && otherRight is KtBinaryExpression && myMatchingVisitor.match(right, otherRight.left) && otherRight.operationToken == KtTokens.EQEQEQ && myMatchingVisitor.match(factory(other) {createExpression("null")}, otherRight.right) } val other = getTreeElementDepar<KtExpression>() ?: return when (other) { is KtBinaryExpression -> { if (expression.operationToken == KtTokens.IDENTIFIER) { myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.left) && myMatchingVisitor.match(expression.right, other.right) && myMatchingVisitor.match(expression.operationReference, other.operationReference) return } if (myMatchingVisitor.setResult(expression.match(other))) return when (expression.operationToken) { // semantical matching KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ -> { // a.compareTo(b) OP 0 val left = other.left?.deparenthesize() myMatchingVisitor.result = left is KtDotQualifiedExpression && left.match(OperatorNameConventions.COMPARE_TO, expression.left, expression.right) && expression.operationToken == other.operationToken && myMatchingVisitor.match(other.right, factory(other) {createExpression("0")}) } in augmentedAssignmentsMap.keys -> { // x OP= y with x = x OP y if (other.operationToken == KtTokens.EQ) { val right = other.right?.deparenthesize() val left = other.left?.deparenthesize() myMatchingVisitor.result = right is KtBinaryExpression && augmentedAssignmentsMap[expression.operationToken] == right.operationToken && myMatchingVisitor.match(expression.left, left) && myMatchingVisitor.match(expression.left, right.left) && myMatchingVisitor.match(expression.right, right.right) } } KtTokens.EQ -> { // x = x OP y with x OP= y val right = expression.right?.deparenthesize() if (right is KtBinaryExpression && right.operationToken == augmentedAssignmentsMap[other.operationToken]) { myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.left) && myMatchingVisitor.match(right.left, other.left) && myMatchingVisitor.match(right.right, other.right) } } KtTokens.EQEQ -> { // a?.equals(b) ?: (b === null) myMatchingVisitor.result = expression.matchEq(other) } } } is KtDotQualifiedExpression -> { // translated matching val token = expression.operationToken val left = expression.left val right = expression.right when { token == KtTokens.IN_KEYWORD -> { // b.contains(a) val parent = other.parent val isNotNegated = if (parent is KtPrefixExpression) parent.operationToken != KtTokens.EXCL else true myMatchingVisitor.result = isNotNegated && other.match(OperatorNameConventions.CONTAINS, right, left) } token == KtTokens.NOT_IN -> myMatchingVisitor.result = false // already matches with prefix expression token == KtTokens.EQ && left is KtArrayAccessExpression -> { // a[x] = expression val matchedArgs = left.indexExpressions.apply { add(right) } myMatchingVisitor.result = myMatchingVisitor.match(left.arrayExpression, other.receiverExpression) && other.calleeName == "${OperatorNameConventions.SET}" && myMatchingVisitor.matchSequentially( matchedArgs, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!! ) } else -> { // a.plus(b) all arithmetic operators val selector = other.selectorExpression if (expression.operationToken == KtTokens.EQ && right is KtBinaryExpression) { // Matching x = x + y with x.plusAssign(y) val opName = augmentedAssignmentsMap.reverse()[right.operationToken]?.binaryExprOpName() myMatchingVisitor.result = selector is KtCallExpression && myMatchingVisitor.match(left, other.receiverExpression) && other.match(opName, right.left, right.right) } else { myMatchingVisitor.result = selector is KtCallExpression && other.match( expression.operationToken.binaryExprOpName(), left, right ) } } } } is KtPrefixExpression -> { // translated matching val baseExpr = other.baseExpression?.deparenthesize() when (expression.operationToken) { KtTokens.NOT_IN -> { // !b.contains(a) myMatchingVisitor.result = other.operationToken == KtTokens.EXCL && baseExpr is KtDotQualifiedExpression && baseExpr.match(OperatorNameConventions.CONTAINS, expression.right, expression.left) } KtTokens.EXCLEQ -> { // !(a?.equals(b) ?: (b === null)) myMatchingVisitor.result = other.operationToken == KtTokens.EXCL && baseExpr is KtBinaryExpression && expression.matchEq(baseExpr) } } } else -> myMatchingVisitor.result = false } } override fun visitBlockExpression(expression: KtBlockExpression) { val other = getTreeElementDepar<KtBlockExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.statements, other.statements) } override fun visitUnaryExpression(expression: KtUnaryExpression) { val other = getTreeElementDepar<KtExpression>() ?: return myMatchingVisitor.result = when (other) { is KtDotQualifiedExpression -> { myMatchingVisitor.match(expression.baseExpression, other.receiverExpression) && OperatorConventions.UNARY_OPERATION_NAMES[expression.operationToken].toString() == other.calleeName } is KtUnaryExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression) && myMatchingVisitor.match(expression.operationReference, other.operationReference) else -> false } } override fun visitParenthesizedExpression(expression: KtParenthesizedExpression) { fun KtExpression.countParenthesize(initial: Int = 0): Int { val parentheses = children.firstOrNull { it is KtParenthesizedExpression } as KtExpression? return parentheses?.countParenthesize(initial + 1) ?: initial } val other = getTreeElement<KtParenthesizedExpression>() ?: return if (!myMatchingVisitor.setResult(expression.countParenthesize() == other.countParenthesize())) return myMatchingVisitor.result = myMatchingVisitor.match(expression.deparenthesize(), other.deparenthesize()) } override fun visitConstantExpression(expression: KtConstantExpression) { val other = getTreeElementDepar<KtExpression>() ?: return myMatchingVisitor.result = substituteOrMatchText(expression, other) } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val other = getTreeElementDepar<PsiElement>() ?: return val exprHandler = getHandler(expression) if (other is KtReferenceExpression && exprHandler is SubstitutionHandler) { val ref = other.mainReference val bindingContext = ref.element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val referenced = ref.resolveToDescriptors(bindingContext).firstOrNull()?.let { if (it is ConstructorDescriptor) it.constructedClass else it } if (referenced is ClassifierDescriptor) { val fqName = referenced.fqNameOrNull() val predicate = exprHandler.findRegExpPredicate() if (predicate != null && fqName != null && predicate.doMatch(fqName.asString(), myMatchingVisitor.matchContext, other)) { myMatchingVisitor.result = true exprHandler.addResult(other, myMatchingVisitor.matchContext) return } } } // Match Int::class with X.Int::class val skipReceiver = other.parent is KtDoubleColonExpression && other is KtDotQualifiedExpression && myMatchingVisitor.match(expression, other.selectorExpression) myMatchingVisitor.result = skipReceiver || substituteOrMatchText( expression.getReferencedNameElement(), if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other ) val handler = getHandler(expression.getReferencedNameElement()) if (myMatchingVisitor.result && handler is SubstitutionHandler) { myMatchingVisitor.result = handler.handle( if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other, myMatchingVisitor.matchContext ) } } override fun visitContinueExpression(expression: KtContinueExpression) { val other = getTreeElementDepar<KtContinueExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) } override fun visitBreakExpression(expression: KtBreakExpression) { val other = getTreeElementDepar<KtBreakExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) } override fun visitThisExpression(expression: KtThisExpression) { val other = getTreeElementDepar<KtThisExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) } override fun visitSuperExpression(expression: KtSuperExpression) { val other = getTreeElementDepar<KtSuperExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) && myMatchingVisitor.match(expression.superTypeQualifier, other.superTypeQualifier) } override fun visitReturnExpression(expression: KtReturnExpression) { val other = getTreeElementDepar<KtReturnExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel()) && myMatchingVisitor.match(expression.returnedExpression, other.returnedExpression) } override fun visitFunctionType(type: KtFunctionType) { val other = getTreeElementDepar<KtFunctionType>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(type.receiverTypeReference, other.receiverTypeReference) && myMatchingVisitor.match(type.parameterList, other.parameterList) && myMatchingVisitor.match(type.returnTypeReference, other.returnTypeReference) } override fun visitUserType(type: KtUserType) { val other = myMatchingVisitor.element myMatchingVisitor.result = when (other) { is KtUserType -> { type.qualifier?.let { typeQualifier -> // if query has fq type myMatchingVisitor.match(typeQualifier, other.qualifier) // recursively match qualifiers && myMatchingVisitor.match(type.referenceExpression, other.referenceExpression) && myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList) } ?: let { // no fq type myMatchingVisitor.match(type.referenceExpression, other.referenceExpression) && myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList) } } is KtTypeElement -> matchTextOrVariable(type.referenceExpression, other) else -> false } } override fun visitNullableType(nullableType: KtNullableType) { val other = getTreeElementDepar<KtNullableType>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(nullableType.innerType, other.innerType) } override fun visitDynamicType(type: KtDynamicType) { myMatchingVisitor.result = myMatchingVisitor.element is KtDynamicType } override fun visitTypeReference(typeReference: KtTypeReference) { val other = getTreeElementDepar<KtTypeReference>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSons(typeReference, other) } override fun visitQualifiedExpression(expression: KtQualifiedExpression) { val other = getTreeElementDepar<KtQualifiedExpression>() ?: return myMatchingVisitor.result = expression.operationSign == other.operationSign && myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression) && myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression) } override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) { val other = getTreeElementDepar<KtExpression>() ?: return val receiverHandler = getHandler(expression.receiverExpression) if (receiverHandler is SubstitutionHandler && receiverHandler.minOccurs == 0) { // can match without receiver myMatchingVisitor.result = other !is KtDotQualifiedExpression && other.parent !is KtDotQualifiedExpression && other.parent !is KtCallExpression && myMatchingVisitor.match(expression.selectorExpression, other) } else { myMatchingVisitor.result = other is KtDotQualifiedExpression && myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression) && myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression) } } override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) { val other = getTreeElementDepar<KtLambdaExpression>() ?: return val lambdaVP = lambdaExpression.valueParameters val otherVP = other.valueParameters myMatchingVisitor.result = (!lambdaExpression.functionLiteral.hasParameterSpecification() || myMatchingVisitor.matchSequentially(lambdaVP, otherVP) || lambdaVP.map { p -> getHandler(p).let { if (it is SubstitutionHandler) it.minOccurs else 1 } }.sum() == 1 && !other.functionLiteral.hasParameterSpecification() && (other.functionLiteral.descriptor as AnonymousFunctionDescriptor).valueParameters.size == 1) && myMatchingVisitor.match(lambdaExpression.bodyExpression, other.bodyExpression) } override fun visitTypeProjection(typeProjection: KtTypeProjection) { val other = getTreeElementDepar<KtTypeProjection>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(typeProjection.typeReference, other.typeReference) && myMatchingVisitor.match(typeProjection.modifierList, other.modifierList) && typeProjection.projectionKind == other.projectionKind } override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) { val other = getTreeElementDepar<KtTypeArgumentList>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(typeArgumentList.arguments, other.arguments) } override fun visitArgument(argument: KtValueArgument) { val other = getTreeElementDepar<KtValueArgument>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(argument.getArgumentExpression(), other.getArgumentExpression()) && (!argument.isNamed() || !other.isNamed() || matchTextOrVariable( argument.getArgumentName(), other.getArgumentName() )) } private fun MutableList<KtValueArgument>.addDefaultArguments(parameters: List<KtParameter?>) { if (parameters.isEmpty()) return val params = parameters.toTypedArray() var i = 0 while (i < size) { val arg = get(i) if (arg.isNamed()) { params[parameters.indexOfFirst { it?.nameAsName == arg.getArgumentName()?.asName }] = null i++ } else { val curParam = params[i] ?: throw IllegalStateException( KotlinBundle.message("error.param.can.t.be.null.at.index.0.in.1", i, params.map { it?.text }) ) params[i] = null if (curParam.isVarArg) { val varArgType = arg.getArgumentExpression()?.resolveType() var curArg: KtValueArgument? = arg while (varArgType != null && varArgType == curArg?.getArgumentExpression()?.resolveType() || curArg?.isSpread == true) { i++ curArg = getOrNull(i) } } else i++ } } params.filterNotNull().forEach { add(factory(myMatchingVisitor.element) {createArgument(it.defaultValue, it.nameAsName, reformat = false) }) } } private fun matchValueArguments( parameters: List<KtParameter>, valueArgList: KtValueArgumentList?, otherValueArgList: KtValueArgumentList?, lambdaArgList: List<KtLambdaArgument>, otherLambdaArgList: List<KtLambdaArgument> ): Boolean { if (valueArgList != null) { val handler = getHandler(valueArgList) val normalizedOtherArgs = otherValueArgList?.arguments?.toMutableList() ?: mutableListOf() normalizedOtherArgs.addAll(otherLambdaArgList) normalizedOtherArgs.addDefaultArguments(parameters) if (normalizedOtherArgs.isEmpty() && handler is SubstitutionHandler && handler.minOccurs == 0) { return myMatchingVisitor.matchSequentially(lambdaArgList, otherLambdaArgList) } val normalizedArgs = valueArgList.arguments.toMutableList() normalizedArgs.addAll(lambdaArgList) return matchValueArguments(normalizedArgs, normalizedOtherArgs) } return matchValueArguments(lambdaArgList, otherLambdaArgList) } private fun matchValueArguments(queryArgs: List<KtValueArgument>, codeArgs: List<KtValueArgument>): Boolean { var queryIndex = 0 var codeIndex = 0 while (queryIndex < queryArgs.size) { val queryArg = queryArgs[queryIndex] val codeArg = codeArgs.getOrElse(codeIndex) { return@matchValueArguments false } if (getHandler(queryArg) is SubstitutionHandler) { return myMatchingVisitor.matchSequentially( queryArgs.subList(queryIndex, queryArgs.lastIndex + 1), codeArgs.subList(codeIndex, codeArgs.lastIndex + 1) ) } // varargs declared in call matching with one-to-one argument passing if (queryArg.isSpread && !codeArg.isSpread) { val spreadArgExpr = queryArg.getArgumentExpression() if (spreadArgExpr is KtCallExpression) { spreadArgExpr.valueArguments.forEach { spreadedArg -> if (!myMatchingVisitor.match(spreadedArg, codeArgs[codeIndex++])) return@matchValueArguments false } queryIndex++ continue } // can't match array that is not created in the call itself myMatchingVisitor.result = false return myMatchingVisitor.result } if (!queryArg.isSpread && codeArg.isSpread) { val spreadArgExpr = codeArg.getArgumentExpression() if (spreadArgExpr is KtCallExpression) { spreadArgExpr.valueArguments.forEach { spreadedArg -> if (!myMatchingVisitor.match(queryArgs[queryIndex++], spreadedArg)) return@matchValueArguments false } codeIndex++ continue } return false// can't match array that is not created in the call itself } // normal argument matching if (!myMatchingVisitor.match(queryArg, codeArg)) { return if (queryArg.isNamed() || codeArg.isNamed()) { // start comparing for out of order arguments myMatchingVisitor.matchInAnyOrder( queryArgs.subList(queryIndex, queryArgs.lastIndex + 1), codeArgs.subList(codeIndex, codeArgs.lastIndex + 1) ) } else false } queryIndex++ codeIndex++ } if (codeIndex != codeArgs.size) return false return true } private fun resolveParameters(other: KtElement): List<KtParameter> { return other.resolveToCall()?.candidateDescriptor?.original?.valueParameters?.mapNotNull { it.source.getPsi() as? KtParameter } ?: emptyList() } override fun visitCallExpression(expression: KtCallExpression) { val other = getTreeElementDepar<KtExpression>() ?: return val parameters = resolveParameters(other) myMatchingVisitor.result = when (other) { is KtCallExpression -> { myMatchingVisitor.match(expression.calleeExpression, other.calleeExpression) && myMatchingVisitor.match(expression.typeArgumentList, other.typeArgumentList) && matchValueArguments( parameters, expression.valueArgumentList, other.valueArgumentList, expression.lambdaArguments, other.lambdaArguments ) } is KtDotQualifiedExpression -> other.callExpression is KtCallExpression && myMatchingVisitor.match(expression.calleeExpression, other.receiverExpression) && other.calleeName == "${OperatorNameConventions.INVOKE}" && matchValueArguments( parameters, expression.valueArgumentList, other.callExpression?.valueArgumentList, expression.lambdaArguments, other.callExpression?.lambdaArguments ?: emptyList() ) else -> false } } override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) { val other = getTreeElementDepar<KtCallableReferenceExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.callableReference, other.callableReference) && myMatchingVisitor.matchOptionally(expression.receiverExpression, other.receiverExpression) } override fun visitTypeParameter(parameter: KtTypeParameter) { val other = getTreeElementDepar<KtTypeParameter>() ?: return myMatchingVisitor.result = substituteOrMatchText(parameter.firstChild, other.firstChild) // match generic identifier && myMatchingVisitor.match(parameter.extendsBound, other.extendsBound) && parameter.variance == other.variance parameter.nameIdentifier?.let { nameIdentifier -> val handler = getHandler(nameIdentifier) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } } override fun visitParameter(parameter: KtParameter) { val other = getTreeElementDepar<KtParameter>() ?: return val otherNameIdentifier = if (getHandler(parameter) is SubstitutionHandler && parameter.nameIdentifier != null && other.nameIdentifier == null ) other else other.nameIdentifier myMatchingVisitor.result = myMatchingVisitor.match(parameter.typeReference, other.typeReference) && myMatchingVisitor.match(parameter.defaultValue, other.defaultValue) && (parameter.isVarArg == other.isVarArg || getHandler(parameter) is SubstitutionHandler) && myMatchingVisitor.match(parameter.valOrVarKeyword, other.valOrVarKeyword) && (parameter.nameIdentifier == null || matchTextOrVariable(parameter.nameIdentifier, otherNameIdentifier)) && myMatchingVisitor.match(parameter.modifierList, other.modifierList) && myMatchingVisitor.match(parameter.destructuringDeclaration, other.destructuringDeclaration) parameter.nameIdentifier?.let { nameIdentifier -> val handler = getHandler(nameIdentifier) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } } override fun visitTypeParameterList(list: KtTypeParameterList) { val other = getTreeElementDepar<KtTypeParameterList>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters) } override fun visitParameterList(list: KtParameterList) { val other = getTreeElementDepar<KtParameterList>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters) } override fun visitConstructorDelegationCall(call: KtConstructorDelegationCall) { val other = getTreeElementDepar<KtConstructorDelegationCall>() ?: return val parameters = resolveParameters(other) myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression) && myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList) && matchValueArguments( parameters, call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments ) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { val other = getTreeElementDepar<KtSecondaryConstructor>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList) && myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList) && myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList) && myMatchingVisitor.match(constructor.getDelegationCallOrNull(), other.getDelegationCallOrNull()) && myMatchingVisitor.match(constructor.bodyExpression, other.bodyExpression) } override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) { val other = getTreeElementDepar<KtPrimaryConstructor>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList) && myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList) && myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList) } override fun visitAnonymousInitializer(initializer: KtAnonymousInitializer) { val other = getTreeElementDepar<KtAnonymousInitializer>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(initializer.body, other.body) } override fun visitClassBody(classBody: KtClassBody) { val other = getTreeElementDepar<KtClassBody>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(classBody, other) } override fun visitSuperTypeCallEntry(call: KtSuperTypeCallEntry) { val other = getTreeElementDepar<KtSuperTypeCallEntry>() ?: return val parameters = resolveParameters(other) myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression) && myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList) && matchValueArguments( parameters, call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments ) } override fun visitSuperTypeEntry(specifier: KtSuperTypeEntry) { val other = getTreeElementDepar<KtSuperTypeEntry>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(specifier.typeReference, other.typeReference) } private fun matchTypeAgainstElement( type: String, element: PsiElement, other: PsiElement ): Boolean { return when (val predicate = (getHandler(element) as? SubstitutionHandler)?.findRegExpPredicate()) { null -> element.text == type // Ignore type parameters if absent from the pattern || !element.text.contains('<') && element.text == type.removeTypeParameters() else -> predicate.doMatch(type, myMatchingVisitor.matchContext, other) } } override fun visitSuperTypeList(list: KtSuperTypeList) { val other = getTreeElementDepar<KtSuperTypeList>() ?: return val withinHierarchyEntries = list.entries.filter { val type = it.typeReference; type is KtTypeReference && getHandler(type).withinHierarchyTextFilterSet } (other.parent as? KtClassOrObject)?.let { klass -> val supertypes = (klass.descriptor as ClassDescriptor).toSimpleType().supertypes() withinHierarchyEntries.forEach { entry -> val typeReference = entry.typeReference if (!matchTextOrVariable(typeReference, klass.nameIdentifier) && typeReference != null && supertypes.none { it.renderNames().any { type -> matchTypeAgainstElement(type, typeReference, other) } }) { myMatchingVisitor.result = false return@visitSuperTypeList } } } myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(list.entries.filter { it !in withinHierarchyEntries }, other.entries) } override fun visitClass(klass: KtClass) { val other = getTreeElementDepar<KtClass>() ?: return val otherDescriptor = other.descriptor ?: return val identifier = klass.nameIdentifier val otherIdentifier = other.nameIdentifier var matchNameIdentifiers = matchTextOrVariable(identifier, otherIdentifier) || identifier != null && otherIdentifier != null && matchTypeAgainstElement( (otherDescriptor as LazyClassDescriptor).defaultType.fqName.toString(), identifier, otherIdentifier ) // Possible match if "within hierarchy" is set if (!matchNameIdentifiers && identifier != null && otherIdentifier != null) { val identifierHandler = getHandler(identifier) val checkHierarchyDown = identifierHandler.withinHierarchyTextFilterSet if (checkHierarchyDown) { // Check hierarchy down (down of pattern element = supertypes of code element) matchNameIdentifiers = (otherDescriptor as ClassDescriptor).toSimpleType().supertypes().any { type -> type.renderNames().any { renderedType -> matchTypeAgainstElement(renderedType, identifier, otherIdentifier) } } } else if (identifier.getUserData(KotlinCompilingVisitor.WITHIN_HIERARCHY) == true) { // Check hierarchy up (up of pattern element = inheritors of code element) matchNameIdentifiers = HierarchySearchRequest( other, GlobalSearchScope.allScope(other.project), true ).searchInheritors().any { psiClass -> arrayOf(psiClass.name, psiClass.qualifiedName).filterNotNull().any { renderedType -> matchTypeAgainstElement(renderedType, identifier, otherIdentifier) } } } } myMatchingVisitor.result = myMatchingVisitor.match(klass.getClassOrInterfaceKeyword(), other.getClassOrInterfaceKeyword()) && myMatchingVisitor.match(klass.modifierList, other.modifierList) && matchNameIdentifiers && myMatchingVisitor.match(klass.typeParameterList, other.typeParameterList) && myMatchingVisitor.match(klass.primaryConstructor, other.primaryConstructor) && myMatchingVisitor.matchInAnyOrder(klass.secondaryConstructors, other.secondaryConstructors) && myMatchingVisitor.match(klass.getSuperTypeList(), other.getSuperTypeList()) && myMatchingVisitor.match(klass.body, other.body) && myMatchingVisitor.match(klass.docComment, other.docComment) val handler = getHandler(klass.nameIdentifier!!) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) { val other = getTreeElementDepar<KtObjectLiteralExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.objectDeclaration, other.objectDeclaration) } override fun visitObjectDeclaration(declaration: KtObjectDeclaration) { val other = getTreeElementDepar<KtObjectDeclaration>() ?: return val inferredNameIdentifier = declaration.nameIdentifier ?: if (declaration.isCompanion()) (declaration.parent.parent as KtClass).nameIdentifier else null val handler = inferredNameIdentifier?.let { getHandler(inferredNameIdentifier) } val matchIdentifier = if (handler is SubstitutionHandler && handler.maxOccurs > 0 && handler.minOccurs == 0) { true // match count filter with companion object without identifier } else matchTextOrVariableEq(declaration.nameIdentifier, other.nameIdentifier) myMatchingVisitor.result = (declaration.isCompanion() == other.isCompanion() || (handler is SubstitutionHandler && handler.predicate is KotlinAlsoMatchCompanionObjectPredicate)) && myMatchingVisitor.match(declaration.modifierList, other.modifierList) && matchIdentifier && myMatchingVisitor.match(declaration.getSuperTypeList(), other.getSuperTypeList()) && myMatchingVisitor.match(declaration.body, other.body) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } private fun normalizeExpressionRet(expression: KtExpression?): KtExpression? = when { expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement?.let { if (it is KtReturnExpression) it.returnedExpression else it } else -> expression } private fun normalizeExpression(expression: KtExpression?): KtExpression? = when { expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement else -> expression } private fun normalizeExpressions( patternExpr: KtExpression?, codeExpr: KtExpression?, returnExpr: Boolean ): Pair<KtExpression?, KtExpression?> { val normalizedExpr = if (returnExpr) normalizeExpressionRet(patternExpr) else normalizeExpression(patternExpr) val normalizedCodeExpr = if (returnExpr) normalizeExpressionRet(codeExpr) else normalizeExpression(codeExpr) return when { normalizedExpr is KtBlockExpression || normalizedCodeExpr is KtBlockExpression -> patternExpr to codeExpr else -> normalizedExpr to normalizedCodeExpr } } override fun visitNamedFunction(function: KtNamedFunction) { val other = getTreeElementDepar<KtNamedFunction>() ?: return val (patternBody, codeBody) = normalizeExpressions(function.bodyBlockExpression, other.bodyBlockExpression, true) val bodyHandler = patternBody?.let(::getHandler) val bodyMatch = when { patternBody is KtNameReferenceExpression && codeBody == null -> bodyHandler is SubstitutionHandler && bodyHandler.minOccurs <= 1 && bodyHandler.maxOccurs >= 1 && myMatchingVisitor.match(patternBody, other.bodyExpression) patternBody is KtNameReferenceExpression -> myMatchingVisitor.match( function.bodyBlockExpression, other.bodyBlockExpression ) patternBody == null && codeBody == null -> myMatchingVisitor.match(function.bodyExpression, other.bodyExpression) patternBody == null -> function.bodyExpression == null || codeBody !is KtBlockExpression && myMatchingVisitor.match(function.bodyExpression, codeBody) codeBody == null -> patternBody !is KtBlockExpression && myMatchingVisitor.match(patternBody, other.bodyExpression) else -> myMatchingVisitor.match(function.bodyBlockExpression, other.bodyBlockExpression) } myMatchingVisitor.result = myMatchingVisitor.match(function.modifierList, other.modifierList) && matchTextOrVariable(function.nameIdentifier, other.nameIdentifier) && myMatchingVisitor.match(function.typeParameterList, other.typeParameterList) && myMatchingVisitor.match(function.typeReference, other.typeReference) && myMatchingVisitor.match(function.valueParameterList, other.valueParameterList) && myMatchingVisitor.match(function.receiverTypeReference, other.receiverTypeReference) && bodyMatch function.nameIdentifier?.let { nameIdentifier -> val handler = getHandler(nameIdentifier) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } } override fun visitModifierList(list: KtModifierList) { val other = getTreeElementDepar<KtModifierList>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(list, other) } override fun visitIfExpression(expression: KtIfExpression) { val other = getTreeElementDepar<KtIfExpression>() ?: return val elseBranch = normalizeExpression(expression.`else`) myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition) && myMatchingVisitor.matchNormalized(expression.then, other.then) && (elseBranch == null || myMatchingVisitor.matchNormalized(expression.`else`, other.`else`)) } override fun visitForExpression(expression: KtForExpression) { val other = getTreeElementDepar<KtForExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.loopParameter, other.loopParameter) && myMatchingVisitor.match(expression.loopRange, other.loopRange) && myMatchingVisitor.matchNormalized(expression.body, other.body) } override fun visitWhileExpression(expression: KtWhileExpression) { val other = getTreeElementDepar<KtWhileExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition) && myMatchingVisitor.matchNormalized(expression.body, other.body) } override fun visitDoWhileExpression(expression: KtDoWhileExpression) { val other = getTreeElementDepar<KtDoWhileExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition) && myMatchingVisitor.matchNormalized(expression.body, other.body) } override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) { val other = getTreeElementDepar<KtWhenConditionInRange>() ?: return myMatchingVisitor.result = condition.isNegated == other.isNegated && myMatchingVisitor.match(condition.rangeExpression, other.rangeExpression) } override fun visitWhenConditionIsPattern(condition: KtWhenConditionIsPattern) { val other = getTreeElementDepar<KtWhenConditionIsPattern>() ?: return myMatchingVisitor.result = condition.isNegated == other.isNegated && myMatchingVisitor.match(condition.typeReference, other.typeReference) } override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) { val other = getTreeElementDepar<PsiElement>() ?: return val handler = getHandler(condition) if (handler is SubstitutionHandler) { myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext) } else { myMatchingVisitor.result = other is KtWhenConditionWithExpression && myMatchingVisitor.match(condition.expression, other.expression) } } override fun visitWhenEntry(ktWhenEntry: KtWhenEntry) { val other = getTreeElementDepar<KtWhenEntry>() ?: return // $x$ -> $y$ should match else branches val bypassElseTest = ktWhenEntry.firstChild is KtWhenConditionWithExpression && ktWhenEntry.firstChild.children.size == 1 && ktWhenEntry.firstChild.firstChild is KtNameReferenceExpression myMatchingVisitor.result = (bypassElseTest && other.isElse || myMatchingVisitor.matchInAnyOrder(ktWhenEntry.conditions, other.conditions)) && myMatchingVisitor.match(ktWhenEntry.expression, other.expression) && (bypassElseTest || ktWhenEntry.isElse == other.isElse) } override fun visitWhenExpression(expression: KtWhenExpression) { val other = getTreeElementDepar<KtWhenExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.subjectExpression, other.subjectExpression) && myMatchingVisitor.matchInAnyOrder(expression.entries, other.entries) } override fun visitFinallySection(finallySection: KtFinallySection) { val other = getTreeElementDepar<KtFinallySection>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(finallySection.finalExpression, other.finalExpression) } override fun visitCatchSection(catchClause: KtCatchClause) { val other = getTreeElementDepar<KtCatchClause>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(catchClause.parameterList, other.parameterList) && myMatchingVisitor.match(catchClause.catchBody, other.catchBody) } override fun visitTryExpression(expression: KtTryExpression) { val other = getTreeElementDepar<KtTryExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.tryBlock, other.tryBlock) && myMatchingVisitor.matchInAnyOrder(expression.catchClauses, other.catchClauses) && myMatchingVisitor.match(expression.finallyBlock, other.finallyBlock) } override fun visitTypeAlias(typeAlias: KtTypeAlias) { val other = getTreeElementDepar<KtTypeAlias>() ?: return myMatchingVisitor.result = matchTextOrVariable(typeAlias.nameIdentifier, other.nameIdentifier) && myMatchingVisitor.match(typeAlias.getTypeReference(), other.getTypeReference()) && myMatchingVisitor.matchInAnyOrder(typeAlias.annotationEntries, other.annotationEntries) val handler = getHandler(typeAlias.nameIdentifier!!) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } override fun visitConstructorCalleeExpression(constructorCalleeExpression: KtConstructorCalleeExpression) { val other = getTreeElementDepar<KtConstructorCalleeExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match( constructorCalleeExpression.constructorReferenceExpression, other.constructorReferenceExpression ) } override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) { val other = getTreeElementDepar<KtAnnotationEntry>() ?: return val parameters = resolveParameters(other) myMatchingVisitor.result = myMatchingVisitor.match(annotationEntry.calleeExpression, other.calleeExpression) && myMatchingVisitor.match(annotationEntry.typeArgumentList, other.typeArgumentList) && matchValueArguments( parameters, annotationEntry.valueArgumentList, other.valueArgumentList, annotationEntry.lambdaArguments, other.lambdaArguments ) && matchTextOrVariable(annotationEntry.useSiteTarget, other.useSiteTarget) } override fun visitAnnotatedExpression(expression: KtAnnotatedExpression) { myMatchingVisitor.result = when (val other = myMatchingVisitor.element) { is KtAnnotatedExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression) && myMatchingVisitor.matchInAnyOrder(expression.annotationEntries, other.annotationEntries) else -> myMatchingVisitor.match(expression.baseExpression, other) && expression.annotationEntries.all { val handler = getHandler(it); handler is SubstitutionHandler && handler.minOccurs == 0 } } } override fun visitProperty(property: KtProperty) { val other = getTreeElementDepar<KtProperty>() ?: return val handler = getHandler(property.nameIdentifier!!) myMatchingVisitor.result = ( property.isVar == other.isVar || (handler is SubstitutionHandler && handler.predicate is KotlinAlsoMatchValVarPredicate) ) && myMatchingVisitor.match(property.typeReference, other.typeReference) && myMatchingVisitor.match(property.modifierList, other.modifierList) && matchTextOrVariable(property.nameIdentifier, other.nameIdentifier) && myMatchingVisitor.match(property.docComment, other.docComment) && myMatchingVisitor.matchOptionally(property.delegateExpressionOrInitializer, other.delegateExpressionOrInitializer) && myMatchingVisitor.match(property.getter, other.getter) && myMatchingVisitor.match(property.setter, other.setter) && myMatchingVisitor.match(property.receiverTypeReference, other.receiverTypeReference) if (myMatchingVisitor.result && handler is SubstitutionHandler) { handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext) } } override fun visitPropertyAccessor(accessor: KtPropertyAccessor) { val other = getTreeElementDepar<KtPropertyAccessor>() ?: return val accessorBody = if (accessor.hasBlockBody()) accessor.bodyBlockExpression else accessor.bodyExpression val otherBody = if (other.hasBlockBody()) other.bodyBlockExpression else other.bodyExpression myMatchingVisitor.result = myMatchingVisitor.match(accessor.modifierList, other.modifierList) && myMatchingVisitor.matchNormalized(accessorBody, otherBody, true) } override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) { val other = getTreeElementDepar<KtStringTemplateExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.entries, other.entries) } override fun visitSimpleNameStringTemplateEntry(entry: KtSimpleNameStringTemplateEntry) { val other = getTreeElement<KtStringTemplateEntry>() ?: return val handler = getHandler(entry) if (handler is SubstitutionHandler) { myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext) return } myMatchingVisitor.result = when (other) { is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry -> myMatchingVisitor.match(entry.expression, other.expression) else -> false } } override fun visitLiteralStringTemplateEntry(entry: KtLiteralStringTemplateEntry) { val other = myMatchingVisitor.element myMatchingVisitor.result = when (val handler = entry.getUserData(CompiledPattern.HANDLER_KEY)) { is LiteralWithSubstitutionHandler -> handler.match(entry, other, myMatchingVisitor.matchContext) else -> substituteOrMatchText(entry, other) } } override fun visitBlockStringTemplateEntry(entry: KtBlockStringTemplateEntry) { val other = getTreeElementDepar<KtBlockStringTemplateEntry>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(entry.expression, other.expression) } override fun visitEscapeStringTemplateEntry(entry: KtEscapeStringTemplateEntry) { val other = getTreeElementDepar<KtEscapeStringTemplateEntry>() ?: return myMatchingVisitor.result = substituteOrMatchText(entry, other) } override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) { val other = getTreeElementDepar<KtBinaryExpressionWithTypeRHS>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.operationReference, other.operationReference) && myMatchingVisitor.match(expression.left, other.left) && myMatchingVisitor.match(expression.right, other.right) } override fun visitIsExpression(expression: KtIsExpression) { val other = getTreeElementDepar<KtIsExpression>() ?: return myMatchingVisitor.result = expression.isNegated == other.isNegated && myMatchingVisitor.match(expression.leftHandSide, other.leftHandSide) && myMatchingVisitor.match(expression.typeReference, other.typeReference) } override fun visitDestructuringDeclaration(destructuringDeclaration: KtDestructuringDeclaration) { val other = getTreeElementDepar<KtDestructuringDeclaration>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchSequentially(destructuringDeclaration.entries, other.entries) && myMatchingVisitor.match(destructuringDeclaration.initializer, other.initializer) && myMatchingVisitor.match(destructuringDeclaration.docComment, other.docComment) } override fun visitDestructuringDeclarationEntry(multiDeclarationEntry: KtDestructuringDeclarationEntry) { val other = getTreeElementDepar<KtDestructuringDeclarationEntry>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(multiDeclarationEntry.typeReference, other.typeReference) && myMatchingVisitor.match(multiDeclarationEntry.modifierList, other.modifierList) && multiDeclarationEntry.isVar == other.isVar && matchTextOrVariable(multiDeclarationEntry.nameIdentifier, other.nameIdentifier) } override fun visitThrowExpression(expression: KtThrowExpression) { val other = getTreeElementDepar<KtThrowExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.referenceExpression(), other.referenceExpression()) } override fun visitClassLiteralExpression(expression: KtClassLiteralExpression) { val other = getTreeElementDepar<KtClassLiteralExpression>() ?: return myMatchingVisitor.result = myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression) } override fun visitComment(comment: PsiComment) { val other = getTreeElementDepar<PsiComment>() ?: return when (val handler = comment.getUserData(CompiledPattern.HANDLER_KEY)) { is LiteralWithSubstitutionHandler -> { if (other is KDocImpl) { myMatchingVisitor.result = handler.match(comment, other, myMatchingVisitor.matchContext) } else { val offset = 2 + other.text.substring(2).indexOfFirst { it > ' ' } myMatchingVisitor.result = handler.match(other, getCommentText(other), offset, myMatchingVisitor.matchContext) } } is SubstitutionHandler -> { handler.findRegExpPredicate()?.let { it.setNodeTextGenerator { comment -> getCommentText(comment as PsiComment) } } myMatchingVisitor.result = handler.handle( other, 2, other.textLength - if (other.tokenType == KtTokens.EOL_COMMENT) 0 else 2, myMatchingVisitor.matchContext ) } else -> myMatchingVisitor.result = myMatchingVisitor.matchText( StructuralSearchUtil.normalize(getCommentText(comment)), StructuralSearchUtil.normalize(getCommentText(other)) ) } } override fun visitKDoc(kDoc: KDoc) { val other = getTreeElementDepar<KDoc>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder( kDoc.getChildrenOfType<KDocSection>(), other.getChildrenOfType<KDocSection>() ) } override fun visitKDocSection(section: KDocSection) { val other = getTreeElementDepar<KDocSection>() ?: return val important: (PsiElement) -> Boolean = { it.elementType != KDocTokens.LEADING_ASTERISK && !(it.elementType == KDocTokens.TEXT && it.text.trim().isEmpty()) } myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder( section.allChildren.filter(important).toList(), other.allChildren.filter(important).toList() ) } override fun visitKDocTag(tag: KDocTag) { val other = getTreeElementDepar<KDocTag>() ?: return myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(tag.getChildrenOfType(), other.getChildrenOfType()) } override fun visitKDocLink(link: KDocLink) { val other = getTreeElementDepar<KDocLink>() ?: return myMatchingVisitor.result = substituteOrMatchText(link, other) } companion object { private val augmentedAssignmentsMap = mapOf( KtTokens.PLUSEQ to KtTokens.PLUS, KtTokens.MINUSEQ to KtTokens.MINUS, KtTokens.MULTEQ to KtTokens.MUL, KtTokens.DIVEQ to KtTokens.DIV, KtTokens.PERCEQ to KtTokens.PERC ) } }
apache-2.0
6388b2d79c233fc368e92a7950474878
53.796312
162
0.670975
5.701875
false
false
false
false
jwren/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/roots/GradleBuildRootDataSerializer.kt
4
5445
// 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.gradleJava.scripting.roots import com.intellij.openapi.util.IntellijInternalApi import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.FileAttribute import org.jetbrains.kotlin.idea.core.util.readNullable import org.jetbrains.kotlin.idea.core.util.readString import org.jetbrains.kotlin.idea.core.util.writeNullable import org.jetbrains.kotlin.idea.core.util.writeString import org.jetbrains.kotlin.idea.gradle.scripting.LastModifiedFiles import org.jetbrains.kotlin.idea.gradleJava.scripting.GradleKotlinScriptConfigurationInputs import org.jetbrains.kotlin.idea.gradleJava.scripting.importing.KotlinDslScriptModel import java.io.DataInput import java.io.DataInputStream import java.io.DataOutput internal object GradleBuildRootDataSerializer { private val attribute = FileAttribute("kotlin-dsl-script-models", 8, false) fun read(buildRoot: VirtualFile): GradleBuildRootData? { return attribute.readFileAttribute(buildRoot)?.use { it.readNullable { readKotlinDslScriptModels(it, buildRoot.path) } } } fun write(buildRoot: VirtualFile, data: GradleBuildRootData?) { attribute.writeFileAttribute(buildRoot).use { it.writeNullable(data) { writeKotlinDslScriptModels(this, it) } } } fun remove(buildRoot: VirtualFile) { write(buildRoot, null) LastModifiedFiles.remove(buildRoot) } } @IntellijInternalApi fun writeKotlinDslScriptModels(output: DataOutput, data: GradleBuildRootData) { val strings = StringsPool.writer(output) strings.addStrings(data.projectRoots) strings.addString(data.gradleHome) strings.addString(data.javaHome) data.models.forEach { strings.addString(it.file) strings.addStrings(it.classPath) strings.addStrings(it.sourcePath) strings.addStrings(it.imports) } strings.writeHeader() output.writeLong(data.importTs) strings.writeStringIds(data.projectRoots) strings.writeStringId(data.gradleHome) strings.writeStringId(data.javaHome) output.writeList(data.models) { strings.writeStringId(it.file) output.writeString(it.inputs.sections) output.writeLong(it.inputs.lastModifiedTs) strings.writeStringIds(it.classPath) strings.writeStringIds(it.sourcePath) strings.writeStringIds(it.imports) } } @IntellijInternalApi fun readKotlinDslScriptModels(input: DataInputStream, buildRoot: String): GradleBuildRootData { val strings = StringsPool.reader(input) val importTs = input.readLong() val projectRoots = strings.readStrings() val gradleHome = strings.readString() val javaHome = strings.readNullableString() val models = input.readList { KotlinDslScriptModel( strings.readString(), GradleKotlinScriptConfigurationInputs(input.readString(), input.readLong(), buildRoot), strings.readStrings(), strings.readStrings(), strings.readStrings(), listOf() ) } return GradleBuildRootData(importTs, projectRoots, gradleHome, javaHome, models) } private object StringsPool { fun writer(output: DataOutput) = Writer(output) class Writer(val output: DataOutput) { var freeze = false val ids = mutableMapOf<String, Int>() fun getStringId(string: String) = ids.getOrPut(string) { check(!freeze) ids.size } fun addString(string: String?) { getStringId(string ?: "null") } fun addStrings(list: Collection<String>) { list.forEach { addString(it) } } fun writeHeader() { freeze = true output.writeInt(ids.size) // sort for optimal performance and compression ids.keys.sorted().forEachIndexed { index, s -> ids[s] = index output.writeString(s) } } fun writeStringId(it: String?) { output.writeInt(getStringId(it ?: "null")) } fun writeStringIds(strings: Collection<String>) { output.writeInt(strings.size) strings.forEach { writeStringId(it) } } } fun reader(input: DataInputStream): Reader { val strings = input.readList { input.readString() } return Reader(input, strings) } class Reader(val input: DataInputStream, val strings: List<String>) { fun getString(id: Int) = strings[id] fun readString() = getString(input.readInt()) fun readNullableString(): String? { val string = getString(input.readInt()) if (string == "null") return null return string } fun readStrings(): List<String> = input.readList { readString() } } } private inline fun <T> DataOutput.writeList(list: Collection<T>, write: (T) -> Unit) { writeInt(list.size) list.forEach { write(it) } } private inline fun <T> DataInput.readList(read: () -> T): List<T> { val n = readInt() val result = ArrayList<T>(n) repeat(n) { result.add(read()) } return result }
apache-2.0
bb514b67aa0b1ee46599a97f399f3b5b
31.410714
158
0.662075
4.36648
false
true
false
false
GunoH/intellij-community
python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeHintsInspection.kt
2
47488
// 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.jetbrains.python.inspections import com.intellij.codeInsight.controlflow.ControlFlowUtil import com.intellij.codeInspection.* import com.intellij.codeInspection.util.InspectionMessage import com.intellij.codeInspection.util.IntentionFamilyName import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFileFactory import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.QualifiedName import com.jetbrains.python.PyNames import com.jetbrains.python.PyPsiBundle import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache import com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction import com.jetbrains.python.codeInsight.controlflow.ScopeOwner import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil import com.jetbrains.python.codeInsight.functionTypeComments.PyFunctionTypeAnnotationDialect import com.jetbrains.python.codeInsight.imports.AddImportHelper import com.jetbrains.python.codeInsight.imports.AddImportHelper.ImportPriority import com.jetbrains.python.codeInsight.typeHints.PyTypeHintFile import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.isBitwiseOrUnionAvailable import com.jetbrains.python.documentation.PythonDocumentationProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.impl.PyEvaluator import com.jetbrains.python.psi.impl.PyPsiUtils import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.PyResolveUtil import com.jetbrains.python.psi.types.* import com.jetbrains.python.sdk.PythonSdkUtil class PyTypeHintsInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, PyInspectionVisitor.getContext(session)) private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { private val genericQName = QualifiedName.fromDottedString(PyTypingTypeProvider.GENERIC) override fun visitPyCallExpression(node: PyCallExpression) { super.visitPyCallExpression(node) val callee = node.callee as? PyReferenceExpression val calleeQName = callee?.let { PyResolveUtil.resolveImportedElementQNameLocally(it) } ?: emptyList() if (QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_VAR) in calleeQName) { val target = getTargetFromAssignment(node) checkTypeVarPlacement(node, target) checkTypeVarArguments(node, target) checkTypeVarRedefinition(target) } if (QualifiedName.fromDottedString(PyTypingTypeProvider.TYPING_PARAM_SPEC) in calleeQName) { val target = getTargetFromAssignment(node) checkParamSpecArguments(node, target) } checkInstanceAndClassChecks(node) checkParenthesesOnGenerics(node) } private fun getTargetFromAssignment(node: PyCallExpression): PyExpression? { val assignmentStatement = node.parent as? PyAssignmentStatement if (assignmentStatement == null) return null return assignmentStatement.targetsToValuesMapping.firstOrNull { it.second == node }?.first } override fun visitPyClass(node: PyClass) { super.visitPyClass(node) val superClassExpressions = node.superClassExpressions.asList() checkPlainGenericInheritance(superClassExpressions) checkGenericDuplication(superClassExpressions) checkGenericCompleteness(node) } override fun visitPySubscriptionExpression(node: PySubscriptionExpression) { super.visitPySubscriptionExpression(node) checkParameters(node) checkParameterizedBuiltins(node) } private fun checkParameterizedBuiltins(node: PySubscriptionExpression) { if (LanguageLevel.forElement(node).isAtLeast(LanguageLevel.PYTHON39)) return val qualifier = node.qualifier if (qualifier is PyReferenceExpression) { val hasImportFromFuture = (node.containingFile as? PyFile)?.hasImportFromFuture(FutureFeature.ANNOTATIONS) ?: false if (PyBuiltinCache.isInBuiltins(qualifier) && qualifier.name in PyTypingTypeProvider.TYPING_BUILTINS_GENERIC_ALIASES && !hasImportFromFuture) { registerProblem(node, PyPsiBundle.message("INSP.type.hints.builtin.cannot.be.parameterized.directly", qualifier.name), ReplaceWithTypingGenericAliasQuickFix()) } } } override fun visitPyReferenceExpression(node: PyReferenceExpression) { super.visitPyReferenceExpression(node) if (!PyTypingTypeProvider.isInsideTypeHint(node, myTypeEvalContext)) { return } if (node.referencedName == PyNames.CANONICAL_SELF) { val typeName = myTypeEvalContext.getType(node)?.name if (typeName != null && typeName != PyNames.CANONICAL_SELF) { registerProblem(node, PyPsiBundle.message("INSP.type.hints.invalid.type.self"), ProblemHighlightType.GENERIC_ERROR, null, ReplaceWithTypeNameQuickFix(typeName)) } } val isTopLevelTypeHint = node.parent is PyAnnotation || node.parent is PyExpressionStatement && node.parent.parent is PyTypeHintFile if (isTopLevelTypeHint) { if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.LITERAL, PyTypingTypeProvider.LITERAL_EXT)) { registerProblem(node, PyPsiBundle.message("INSP.type.hints.literal.must.have.at.least.one.parameter")) } if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.ANNOTATED, PyTypingTypeProvider.ANNOTATED_EXT)) { registerProblem(node, PyPsiBundle.message("INSP.type.hints.annotated.must.be.called.with.at.least.two.arguments")) } } else if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.TYPE_ALIAS, PyTypingTypeProvider.TYPE_ALIAS_EXT)) { registerProblem(node, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.used.as.standalone.type.hint")) } } override fun visitPyFile(node: PyFile) { super.visitPyFile(node) if (node is PyTypeHintFile && PyTypingTypeProvider.isInsideTypeHint(node, myTypeEvalContext)) { node.children.singleOrNull().also { if (it is PyExpressionStatement) checkTupleMatching(it.expression) } } } override fun visitPyElement(node: PyElement) { super.visitPyElement(node) if (node is PyTypeCommentOwner && node is PyAnnotationOwner && node.typeComment?.text.let { it != null && !PyTypingTypeProvider.TYPE_IGNORE_PATTERN.matcher(it).matches() }) { val message = PyPsiBundle.message("INSP.type.hints.type.specified.both.in.type.comment.and.annotation") if (node is PyFunction) { if (node.annotationValue != null || node.parameterList.parameters.any { it is PyNamedParameter && it.annotationValue != null }) { registerProblem(node.typeComment, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.type.comment"))) registerProblem(node.nameIdentifier, message, RemoveFunctionAnnotations()) } } else if (node.annotationValue != null) { registerProblem(node.typeComment, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.type.comment"))) registerProblem(node.annotation, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.annotation"))) } } } override fun visitPyAnnotation(node: PyAnnotation) { fun PyAnnotation.findSelvesInAnnotation(context: TypeEvalContext): List<PyReferenceExpression> = PsiTreeUtil.findChildrenOfAnyType(this.value, false, PyReferenceExpression::class.java).filter { refExpr -> PyTypingTypeProvider.resolveToQualifiedNames(refExpr, context).any { PyTypingTypeProvider.SELF == it || PyTypingTypeProvider.SELF_EXT == it } } val selves = node.findSelvesInAnnotation(myTypeEvalContext) if (selves.isEmpty()) { return } fun registerProblemForSelves(message: String) { selves.forEach { registerProblem(it, message) } } val classParent = PsiTreeUtil.getParentOfType(node, PyClass::class.java) if (classParent == null) { registerProblemForSelves(PyPsiBundle.message("INSP.type.hints.self.use.outside.class")) } val functionParent = PsiTreeUtil.getParentOfType(node, PyFunction::class.java) if (functionParent != null) { if (PyFunction.Modifier.STATICMETHOD == functionParent.modifier) { registerProblemForSelves(PyPsiBundle.message("INSP.type.hints.self.use.in.staticmethod")) } val parameters = functionParent.parameterList.parameters if (parameters.isNotEmpty()) { val firstParameter = parameters[0] val annotation = (firstParameter as? PyNamedParameter)?.annotation if (annotation != null && firstParameter.isSelf && annotation.findSelvesInAnnotation(myTypeEvalContext).isEmpty()) { val message = if (PyFunction.Modifier.CLASSMETHOD == functionParent.modifier) PyPsiBundle.message("INSP.type.hints.self.use.for.cls.parameter.with.self.annotation") else PyPsiBundle.message("INSP.type.hints.self.use.for.self.parameter.with.self.annotation") registerProblemForSelves(message) } } } } override fun visitPyFunction(node: PyFunction) { super.visitPyFunction(node) checkTypeCommentAndParameters(node) } override fun visitPyTargetExpression(node: PyTargetExpression) { super.visitPyTargetExpression(node) checkAnnotatedNonSelfAttribute(node) checkTypeAliasTarget(node) } private fun checkTypeAliasTarget(target: PyTargetExpression) { val parent = target.parent if (parent is PyTypeDeclarationStatement) { val annotation = target.annotation?.value if (annotation is PyReferenceExpression && resolvesToAnyOfQualifiedNames(annotation, PyTypingTypeProvider.TYPE_ALIAS, PyTypingTypeProvider.TYPE_ALIAS_EXT)) { registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.immediately.initialized")) } } else if (parent is PyAssignmentStatement && PyTypingTypeProvider.isExplicitTypeAlias(parent, myTypeEvalContext) && !PyUtil.isTopLevel(parent)) { registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.top.level.declaration")) } } private fun checkTypeVarPlacement(call: PyCallExpression, target: PyExpression?) { if (target == null) { registerProblem(call, PyPsiBundle.message("INSP.type.hints.typevar.expression.must.be.always.directly.assigned.to.variable")) } } private fun checkTypeVarRedefinition(target: PyExpression?) { val scopeOwner = ScopeUtil.getScopeOwner(target) ?: return val name = target?.name ?: return val instructions = ControlFlowCache.getControlFlow(scopeOwner).instructions val startInstruction = ControlFlowUtil.findInstructionNumberByElement(instructions, target) ControlFlowUtil.iteratePrev(startInstruction, instructions) { instruction -> if (instruction is ReadWriteInstruction && instruction.num() != startInstruction && name == instruction.name && instruction.access.isWriteAccess) { registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.variables.must.not.be.redefined")) ControlFlowUtil.Operation.BREAK } else { ControlFlowUtil.Operation.NEXT } } } private fun checkParamSpecArguments(call: PyCallExpression, target: PyExpression?) { processMatchedArgument(call) { name, argument -> if (name == "name") { checkNameIsTheSameAsTarget(argument, target, PyPsiBundle.message("INSP.type.hints.paramspec.expects.string.literal.as.first.argument"), PyPsiBundle.message("INSP.type.hints.argument.to.paramspec.must.be.string.equal.to.variable.name")) } } } private fun checkTypeVarArguments(call: PyCallExpression, target: PyExpression?) { var covariant = false var contravariant = false var bound: PyExpression? = null val constraints = mutableListOf<PyExpression?>() processMatchedArgument(call) { name, argument -> when (name) { "name" -> checkNameIsTheSameAsTarget(argument, target, PyPsiBundle.message("INSP.type.hints.typevar.expects.string.literal.as.first.argument"), PyPsiBundle.message("INSP.type.hints.argument.to.typevar.must.be.string.equal.to.variable.name")) "covariant" -> covariant = PyEvaluator.evaluateAsBoolean(argument, false) "contravariant" -> contravariant = PyEvaluator.evaluateAsBoolean(argument, false) "bound" -> bound = argument "constraints" -> constraints.add(argument) } } if (covariant && contravariant) { registerProblem(call, PyPsiBundle.message("INSP.type.hints.bivariant.type.variables.are.not.supported"), ProblemHighlightType.GENERIC_ERROR) } if (constraints.isNotEmpty() && bound != null) { registerProblem(call, PyPsiBundle.message("INSP.type.hints.typevar.constraints.cannot.be.combined.with.bound"), ProblemHighlightType.GENERIC_ERROR) } if (constraints.size == 1) { registerProblem(call, PyPsiBundle.message("INSP.type.hints.single.typevar.constraint.not.allowed"), ProblemHighlightType.GENERIC_ERROR) } constraints.asSequence().plus(bound).forEach { if (it != null) { val type = PyTypingTypeProvider.getType(it, myTypeEvalContext)?.get() if (PyTypeChecker.hasGenerics(type, myTypeEvalContext)) { registerProblem(it, PyPsiBundle.message("INSP.type.hints.typevar.constraints.cannot.be.parametrized.by.type.variables")) } } } } private fun checkNameIsTheSameAsTarget(argument: PyExpression?, target: PyExpression?, @InspectionMessage notStringLiteralMessage: String, @InspectionMessage notEqualMessage: String) { if (argument !is PyStringLiteralExpression) { registerProblem(argument, notStringLiteralMessage) } else { val targetName = target?.name if (targetName != null && targetName != argument.stringValue) { registerProblem(argument, notEqualMessage, ReplaceWithTargetNameQuickFix(targetName)) } } } private fun processMatchedArgument(call: PyCallExpression, processor: (name: String?, argument: PyExpression?) -> Unit) { val resolveContext = PyResolveContext.defaultContext(myTypeEvalContext) call .multiMapArguments(resolveContext) .firstOrNull { it.unmappedArguments.isEmpty() && it.unmappedParameters.isEmpty() } ?.let { mapping -> mapping.mappedParameters.entries.forEach { val name = it.value.name val argument = PyUtil.peelArgument(it.key) processor(name, argument) } } } private fun checkInstanceAndClassChecks(call: PyCallExpression) { if (call.isCalleeText(PyNames.ISINSTANCE, PyNames.ISSUBCLASS)) { val base = call.arguments.getOrNull(1) ?: return checkInstanceAndClassChecksOn(base) } } private fun checkInstanceAndClassChecksOn(base: PyExpression) { if (base is PyBinaryExpression && base.operator == PyTokenTypes.OR) { if (isBitwiseOrUnionAvailable(base)) { val left = base.leftExpression val right = base.rightExpression if (left != null) checkInstanceAndClassChecksOn(left) if (right != null) checkInstanceAndClassChecksOn(right) } return } checkInstanceAndClassChecksOnTypeVar(base) checkInstanceAndClassChecksOnReference(base) checkInstanceAndClassChecksOnSubscription(base) } private fun checkInstanceAndClassChecksOnTypeVar(base: PyExpression) { val type = myTypeEvalContext.getType(base) if (type is PyGenericType && !type.isDefinition || type is PyCollectionType && type.elementTypes.any { it is PyGenericType } && !type.isDefinition) { registerProblem(base, PyPsiBundle.message("INSP.type.hints.type.variables.cannot.be.used.with.instance.class.checks"), ProblemHighlightType.GENERIC_ERROR) } } private fun checkInstanceAndClassChecksOnReference(base: PyExpression) { if (base is PyReferenceExpression) { val resolvedBase = multiFollowAssignmentsChain(base) resolvedBase .asSequence() .filterIsInstance<PyQualifiedNameOwner>() .mapNotNull { it.qualifiedName } .forEach { when (it) { PyTypingTypeProvider.ANY, PyTypingTypeProvider.UNION, PyTypingTypeProvider.GENERIC, PyTypingTypeProvider.OPTIONAL, PyTypingTypeProvider.CLASS_VAR, PyTypingTypeProvider.NO_RETURN, PyTypingTypeProvider.FINAL, PyTypingTypeProvider.FINAL_EXT, PyTypingTypeProvider.LITERAL, PyTypingTypeProvider.LITERAL_EXT, PyTypingTypeProvider.ANNOTATED, PyTypingTypeProvider.ANNOTATED_EXT, PyTypingTypeProvider.TYPE_ALIAS, PyTypingTypeProvider.TYPE_ALIAS_EXT, PyTypingTypeProvider.SELF, PyTypingTypeProvider.SELF_EXT -> { val shortName = it.substringAfterLast('.') registerProblem(base, PyPsiBundle.message("INSP.type.hints.type.cannot.be.used.with.instance.class.checks", shortName), ProblemHighlightType.GENERIC_ERROR) } } } resolvedBase .asSequence() .filterIsInstance<PySubscriptionExpression>() .filter { myTypeEvalContext.maySwitchToAST(it) } .forEach { checkInstanceAndClassChecksOnSubscriptionOperand(base, it.operand) } } } private fun checkInstanceAndClassChecksOnSubscription(base: PyExpression) { if (base is PySubscriptionExpression) { checkInstanceAndClassChecksOnSubscriptionOperand(base, base.operand) } } private fun checkInstanceAndClassChecksOnSubscriptionOperand(base: PyExpression, operand: PyExpression) { if (operand is PyReferenceExpression) { multiFollowAssignmentsChain(operand) .forEach { if (it is PyQualifiedNameOwner) { when (val qName = it.qualifiedName) { PyTypingTypeProvider.GENERIC, PyTypingTypeProvider.CLASS_VAR, PyTypingTypeProvider.FINAL, PyTypingTypeProvider.FINAL_EXT, PyTypingTypeProvider.LITERAL, PyTypingTypeProvider.LITERAL_EXT, PyTypingTypeProvider.ANNOTATED, PyTypingTypeProvider.ANNOTATED_EXT -> { registerParametrizedGenericsProblem(qName, base) return@forEach } PyTypingTypeProvider.UNION, PyTypingTypeProvider.OPTIONAL -> { if (!isBitwiseOrUnionAvailable(base)) { registerParametrizedGenericsProblem(qName, base) } else if (base is PySubscriptionExpression) { val indexExpr = base.indexExpression if (indexExpr is PyTupleExpression) { indexExpr.elements.forEach { tupleElement -> checkInstanceAndClassChecksOn(tupleElement) } } else if (indexExpr != null) { checkInstanceAndClassChecksOn(indexExpr) } } } PyTypingTypeProvider.CALLABLE, PyTypingTypeProvider.TYPE, PyTypingTypeProvider.PROTOCOL, PyTypingTypeProvider.PROTOCOL_EXT -> { registerProblem(base, PyPsiBundle.message("INSP.type.hints.parameterized.generics.cannot.be.used.with.instance.class.checks"), ProblemHighlightType.GENERIC_ERROR, null, if (base is PySubscriptionExpression) RemoveGenericParametersQuickFix() else null) return@forEach } } } if (it is PyTypedElement) { val type = myTypeEvalContext.getType(it) if (type is PyWithAncestors && PyTypingTypeProvider.isGeneric(type, myTypeEvalContext)) { registerProblem(base, PyPsiBundle.message("INSP.type.hints.parameterized.generics.cannot.be.used.with.instance.class.checks"), ProblemHighlightType.GENERIC_ERROR, null, if (base is PySubscriptionExpression) RemoveGenericParametersQuickFix() else null) } } } } } private fun registerParametrizedGenericsProblem(qName: String, base: PsiElement) { val shortName = qName.substringAfterLast('.') registerProblem(base, PyPsiBundle.message("INSP.type.hints.type.cannot.be.used.with.instance.class.checks", shortName), ProblemHighlightType.GENERIC_ERROR) } private fun checkParenthesesOnGenerics(call: PyCallExpression) { val callee = call.callee if (callee is PyReferenceExpression) { if (PyResolveUtil.resolveImportedElementQNameLocally(callee).any { PyTypingTypeProvider.GENERIC_CLASSES.contains(it.toString()) }) { registerProblem(call, PyPsiBundle.message("INSP.type.hints.generics.should.be.specified.through.square.brackets"), ProblemHighlightType.GENERIC_ERROR, null, ReplaceWithSubscriptionQuickFix()) } else if (PyTypingTypeProvider.isInsideTypeHint(call, myTypeEvalContext)) { multiFollowAssignmentsChain(callee) .asSequence() .map { if (it is PyFunction) it.containingClass else it } .any { it is PyWithAncestors && PyTypingTypeProvider.isGeneric(it, myTypeEvalContext) } .also { if (it) registerProblem(call, PyPsiBundle.message("INSP.type.hints.generics.should.be.specified.through.square.brackets"), ReplaceWithSubscriptionQuickFix()) } } } } private fun checkPlainGenericInheritance(superClassExpressions: List<PyExpression>) { superClassExpressions .asSequence() .filterIsInstance<PyReferenceExpression>() .filter { genericQName in PyResolveUtil.resolveImportedElementQNameLocally(it) } .forEach { registerProblem(it, PyPsiBundle.message("INSP.type.hints.cannot.inherit.from.plain.generic"), ProblemHighlightType.GENERIC_ERROR) } } private fun checkGenericDuplication(superClassExpressions: List<PyExpression>) { superClassExpressions .asSequence() .filter { superClass -> val resolved = if (superClass is PyReferenceExpression) multiFollowAssignmentsChain(superClass) else listOf(superClass) resolved .asSequence() .filterIsInstance<PySubscriptionExpression>() .filter { myTypeEvalContext.maySwitchToAST(it) } .mapNotNull { it.operand as? PyReferenceExpression } .any { genericQName in PyResolveUtil.resolveImportedElementQNameLocally(it) } } .drop(1) .forEach { registerProblem(it, PyPsiBundle.message("INSP.type.hints.cannot.inherit.from.generic.multiple.times"), ProblemHighlightType.GENERIC_ERROR) } } private fun checkGenericCompleteness(cls: PyClass) { var seenGeneric = false val genericTypeVars = linkedSetOf<PsiElement>() val nonGenericTypeVars = linkedSetOf<PsiElement>() cls.superClassExpressions.forEach { superClass -> val generics = collectGenerics(superClass) generics.first?.let { genericTypeVars.addAll(it) seenGeneric = true } nonGenericTypeVars.addAll(generics.second) } if (seenGeneric && (nonGenericTypeVars - genericTypeVars).isNotEmpty()) { val nonGenericTypeVarsNames = nonGenericTypeVars .asSequence() .filterIsInstance<PyTargetExpression>() .mapNotNull { it.name } .joinToString(", ") val genericTypeVarsNames = genericTypeVars .asSequence() .filterIsInstance<PyTargetExpression>() .mapNotNull { it.name } .joinToString(", ") registerProblem(cls.superClassExpressionList, PyPsiBundle.message("INSP.type.hints.some.type.variables.are.not.listed.in.generic", nonGenericTypeVarsNames, genericTypeVarsNames), ProblemHighlightType.GENERIC_ERROR) } } private fun collectGenerics(superClassExpression: PyExpression): Pair<Set<PsiElement>?, Set<PsiElement>> { val resolvedSuperClass = if (superClassExpression is PyReferenceExpression) multiFollowAssignmentsChain(superClassExpression) else listOf(superClassExpression) var seenGeneric = false val genericTypeVars = linkedSetOf<PsiElement>() val nonGenericTypeVars = linkedSetOf<PsiElement>() resolvedSuperClass .asSequence() .filterIsInstance<PySubscriptionExpression>() .filter { myTypeEvalContext.maySwitchToAST(it) } .forEach { superSubscription -> val operand = superSubscription.operand val generic = operand is PyReferenceExpression && genericQName in PyResolveUtil.resolveImportedElementQNameLocally(operand) val index = superSubscription.indexExpression val parameters = (index as? PyTupleExpression)?.elements ?: arrayOf(index) val superClassTypeVars = parameters .asSequence() .filterIsInstance<PyReferenceExpression>() .flatMap { multiFollowAssignmentsChain(it, this::followNotTypeVar).asSequence() } .filterIsInstance<PyTargetExpression>() .filter { myTypeEvalContext.getType(it) is PyGenericType } .toSet() if (generic) genericTypeVars.addAll(superClassTypeVars) else nonGenericTypeVars.addAll(superClassTypeVars) seenGeneric = seenGeneric || generic } return Pair(if (seenGeneric) genericTypeVars else null, nonGenericTypeVars) } private fun checkParameters(node: PySubscriptionExpression) { val operand = node.operand as? PyReferenceExpression ?: return val index = node.indexExpression ?: return val callableQName = QualifiedName.fromDottedString(PyTypingTypeProvider.CALLABLE) val literalQName = QualifiedName.fromDottedString(PyTypingTypeProvider.LITERAL) val literalExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.LITERAL_EXT) val annotatedQName = QualifiedName.fromDottedString(PyTypingTypeProvider.ANNOTATED) val annotatedExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.ANNOTATED_EXT) val typeAliasQName = QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_ALIAS) val typeAliasExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_ALIAS_EXT) val typingSelf = QualifiedName.fromDottedString(PyTypingTypeProvider.SELF) val typingExtSelf = QualifiedName.fromDottedString(PyTypingTypeProvider.SELF_EXT) val qNames = PyResolveUtil.resolveImportedElementQNameLocally(operand) var typingOnly = true var callableExists = false qNames.forEach { when (it) { genericQName -> checkGenericParameters(index) literalQName, literalExtQName -> checkLiteralParameter(index) annotatedQName, annotatedExtQName -> checkAnnotatedParameter(index) typeAliasQName, typeAliasExtQName -> reportParameterizedTypeAlias(index) typingSelf, typingExtSelf -> reportParameterizedSelf(index) callableQName -> { callableExists = true checkCallableParameters(index) } } typingOnly = typingOnly && it.firstComponent == PyTypingTypeProvider.TYPING } if (qNames.isNotEmpty() && typingOnly) { checkTypingMemberParameters(index, callableExists) } } private fun reportParameterizedTypeAlias(index: PyExpression) { // There is another warning in the type hint context if (!PyTypingTypeProvider.isInsideTypeHint(index, myTypeEvalContext)) { registerProblem(index, PyPsiBundle.message("INSP.type.hints.type.alias.cannot.be.parameterized"), ProblemHighlightType.GENERIC_ERROR) } } private fun reportParameterizedSelf(index: PyExpression) { registerProblem(index, PyPsiBundle.message("INSP.type.hints.typing.self.cannot.be.parameterized"), ProblemHighlightType.GENERIC_ERROR) } private fun checkLiteralParameter(index: PyExpression) { val subParameter = if (index is PySubscriptionExpression) index.operand else null if (subParameter is PyReferenceExpression && PyResolveUtil .resolveImportedElementQNameLocally(subParameter) .any { qName -> qName.toString().let { it == PyTypingTypeProvider.LITERAL || it == PyTypingTypeProvider.LITERAL_EXT } }) { // if `index` is like `typing.Literal[...]` and has invalid form, // outer `typing.Literal[...]` won't be highlighted return } if (PyLiteralType.fromLiteralParameter(index, myTypeEvalContext) == null) { registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.literal.parameter")) } } private fun checkAnnotatedParameter(index: PyExpression) { if (index !is PyTupleExpression) { registerProblem(index, PyPsiBundle.message("INSP.type.hints.annotated.must.be.called.with.at.least.two.arguments")) } } private fun checkGenericParameters(index: PyExpression) { val parameters = (index as? PyTupleExpression)?.elements ?: arrayOf(index) val genericParameters = mutableSetOf<PsiElement>() parameters.forEach { if (it !is PyReferenceExpression) { registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.type.variables"), ProblemHighlightType.GENERIC_ERROR) } else { val type = myTypeEvalContext.getType(it) if (type != null) { if (type is PyGenericType || isParamSpecOrConcatenate(it, myTypeEvalContext)) { if (!genericParameters.addAll(multiFollowAssignmentsChain(it))) { registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.unique"), ProblemHighlightType.GENERIC_ERROR) } } else { registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.type.variables"), ProblemHighlightType.GENERIC_ERROR) } } } } } private fun checkCallableParameters(index: PyExpression) { if (index !is PyTupleExpression) { registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.callable.format"), ProblemHighlightType.GENERIC_ERROR) return } val parameters = index.elements if (parameters.size > 2) { val possiblyLastParameter = parameters[parameters.size - 2] registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.callable.format"), ProblemHighlightType.GENERIC_ERROR, null, TextRange.create(0, possiblyLastParameter.startOffsetInParent + possiblyLastParameter.textLength), SurroundElementsWithSquareBracketsQuickFix()) } else if (parameters.size < 2) { registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.callable.format"), ProblemHighlightType.GENERIC_ERROR) } else { val first = parameters.first() if (!isSdkAvailable(first) || isParamSpecOrConcatenate(first, myTypeEvalContext)) return if (first !is PyListLiteralExpression && !(first is PyNoneLiteralExpression && first.isEllipsis)) { registerProblem(first, PyPsiBundle.message("INSP.type.hints.illegal.first.parameter"), ProblemHighlightType.GENERIC_ERROR, null, if (first is PyParenthesizedExpression) ReplaceWithListQuickFix() else SurroundElementWithSquareBracketsQuickFix()) } } } private fun isSdkAvailable(element: PsiElement): Boolean = PythonSdkUtil.findPythonSdk(ModuleUtilCore.findModuleForPsiElement(element)) != null private fun isParamSpecOrConcatenate(expression: PyExpression, context: TypeEvalContext) : Boolean = PyTypingTypeProvider.isConcatenate(expression, context) || PyTypingTypeProvider.isParamSpec(expression, context) private fun checkTypingMemberParameters(index: PyExpression, isCallable: Boolean) { val parameters = if (index is PyTupleExpression) index.elements else arrayOf(index) parameters .asSequence() .drop(if (isCallable) 1 else 0) .forEach { if (it is PyListLiteralExpression) { registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.types.must.be.types"), ProblemHighlightType.GENERIC_ERROR, null, RemoveSquareBracketsQuickFix()) } else if (it is PyReferenceExpression && multiFollowAssignmentsChain(it).any { resolved -> resolved is PyListLiteralExpression }) { registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.types.must.be.types"), ProblemHighlightType.GENERIC_ERROR) } } } private fun checkTupleMatching(expression: PyExpression) { if (expression !is PyTupleExpression) return val assignment = PyPsiUtils.getRealContext(expression).parent as? PyAssignmentStatement ?: return val lhs = assignment.leftHandSideExpression ?: return if (PyTypingTypeProvider.mapTargetsToAnnotations(lhs, expression).isEmpty() && (expression.elements.isNotEmpty() || assignment.rawTargets.isNotEmpty())) { registerProblem(expression, PyPsiBundle.message("INSP.type.hints.type.comment.cannot.be.matched.with.unpacked.variables")) } } private fun checkTypeCommentAndParameters(node: PyFunction) { val functionTypeAnnotation = PyTypingTypeProvider.getFunctionTypeAnnotation(node) ?: return val parameterTypes = functionTypeAnnotation.parameterTypeList.parameterTypes if (parameterTypes.singleOrNull().let { it is PyNoneLiteralExpression && it.isEllipsis }) return val actualParametersSize = node.parameterList.parameters.size val commentParametersSize = parameterTypes.size val cls = node.containingClass val modifier = node.modifier val hasSelf = cls != null && modifier != PyFunction.Modifier.STATICMETHOD if (commentParametersSize < actualParametersSize - if (hasSelf) 1 else 0) { registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.signature.has.too.few.arguments")) } else if (commentParametersSize > actualParametersSize) { registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.signature.has.too.many.arguments")) } else if (hasSelf && actualParametersSize == commentParametersSize) { val actualSelfType = (myTypeEvalContext.getType(cls!!) as? PyInstantiableType<*>) ?.let { if (modifier == PyFunction.Modifier.CLASSMETHOD) it.toClass() else it.toInstance() } ?: return val commentSelfType = parameterTypes.firstOrNull() ?.let { PyTypingTypeProvider.getType(it, myTypeEvalContext) } ?.get() ?: return if (!PyTypeChecker.match(commentSelfType, actualSelfType, myTypeEvalContext)) { val actualSelfTypeDescription = PythonDocumentationProvider.getTypeDescription(actualSelfType, myTypeEvalContext) val commentSelfTypeDescription = PythonDocumentationProvider.getTypeDescription(commentSelfType, myTypeEvalContext) registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.self.not.supertype.its.class", commentSelfTypeDescription, actualSelfTypeDescription)) } } } private fun checkAnnotatedNonSelfAttribute(node: PyTargetExpression) { val qualifier = node.qualifier ?: return if (node.annotation == null && node.typeComment == null) return val scopeOwner = ScopeUtil.getScopeOwner(node) if (scopeOwner !is PyFunction) { registerProblem(node, PyPsiBundle.message("INSP.type.hints.non.self.attribute.could.not.be.type.hinted")) return } val self = scopeOwner.parameterList.parameters.firstOrNull()?.takeIf { it.isSelf } if (self == null || PyUtil.multiResolveTopPriority(qualifier, resolveContext).let { it.isNotEmpty() && it.all { e -> e != self } }) { registerProblem(node, PyPsiBundle.message("INSP.type.hints.non.self.attribute.could.not.be.type.hinted")) } } private fun followNotTypingOpaque(target: PyTargetExpression): Boolean { return !PyTypingTypeProvider.OPAQUE_NAMES.contains(target.qualifiedName) } private fun followNotTypeVar(target: PyTargetExpression): Boolean { return !myTypeEvalContext.maySwitchToAST(target) || target.findAssignedValue() !is PyCallExpression } private fun multiFollowAssignmentsChain(referenceExpression: PyReferenceExpression, follow: (PyTargetExpression) -> Boolean = this::followNotTypingOpaque): List<PsiElement> { return referenceExpression.multiFollowAssignmentsChain(resolveContext, follow).mapNotNull { it.element } } private fun resolvesToAnyOfQualifiedNames(referenceExpr: PyReferenceExpression, vararg names: String): Boolean { return multiFollowAssignmentsChain(referenceExpr) .filterIsInstance<PyQualifiedNameOwner>() .mapNotNull { it.qualifiedName } .any { names.contains(it) } } } companion object { private class ReplaceWithTypeNameQuickFix(private val typeName: String) : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.type.name") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? PyReferenceExpression ?: return element.reference.handleElementRename(typeName) } } private class RemoveElementQuickFix(@IntentionFamilyName private val description: String) : LocalQuickFix { override fun getFamilyName() = description override fun applyFix(project: Project, descriptor: ProblemDescriptor) = descriptor.psiElement.delete() } private class RemoveFunctionAnnotations : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.function.annotations") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val function = (descriptor.psiElement.parent as? PyFunction) ?: return function.annotation?.delete() function.parameterList.parameters .asSequence() .filterIsInstance<PyNamedParameter>() .mapNotNull { it.annotation } .forEach { it.delete() } } } private class ReplaceWithTargetNameQuickFix(private val targetName: String) : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.target.name") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val old = descriptor.psiElement as? PyStringLiteralExpression ?: return val new = PyElementGenerator.getInstance(project).createStringLiteral(old, targetName) ?: return old.replace(new) } } private class RemoveGenericParametersQuickFix : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.generic.parameters") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val old = descriptor.psiElement as? PySubscriptionExpression ?: return old.replace(old.operand) } } private class ReplaceWithSubscriptionQuickFix : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.square.brackets") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? PyCallExpression ?: return val callee = element.callee?.text ?: return val argumentList = element.argumentList ?: return val index = argumentList.text.let { it.substring(1, it.length - 1) } val language = element.containingFile.language val text = if (language == PyFunctionTypeAnnotationDialect.INSTANCE) "() -> $callee[$index]" else "$callee[$index]" PsiFileFactory .getInstance(project) // it's important to create file with same language as element's file to have correct behaviour in injections .createFileFromText(language, text) ?.let { it.firstChild.lastChild as? PySubscriptionExpression } ?.let { element.replace(it) } } } private class SurroundElementsWithSquareBracketsQuickFix : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.surround.with.square.brackets") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? PyTupleExpression ?: return val list = PyElementGenerator.getInstance(project).createListLiteral() val originalElements = element.elements originalElements.dropLast(1).forEach { list.add(it) } originalElements.dropLast(2).forEach { it.delete() } element.elements.first().replace(list) } } private class SurroundElementWithSquareBracketsQuickFix : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.surround.with.square.brackets") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement val list = PyElementGenerator.getInstance(project).createListLiteral() list.add(element) element.replace(list) } } private class ReplaceWithListQuickFix : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.square.brackets") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement val expression = (element as? PyParenthesizedExpression)?.containedExpression ?: return val elements = expression.let { if (it is PyTupleExpression) it.elements else arrayOf(it) } val list = PyElementGenerator.getInstance(project).createListLiteral() elements.forEach { list.add(it) } element.replace(list) } } private class RemoveSquareBracketsQuickFix : LocalQuickFix { override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.square.brackets") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? PyListLiteralExpression ?: return val subscription = PsiTreeUtil.getParentOfType(element, PySubscriptionExpression::class.java, true, ScopeOwner::class.java) val index = subscription?.indexExpression ?: return val newIndexElements = if (index is PyTupleExpression) { index.elements.flatMap { if (it == element) element.elements.asList() else listOf(it) } } else { element.elements.asList() } if (newIndexElements.size == 1) { index.replace(newIndexElements.first()) } else { val newIndexText = newIndexElements.joinToString(prefix = "(", postfix = ")") { it.text } val expression = PyElementGenerator.getInstance(project).createExpressionFromText(LanguageLevel.forElement(element), newIndexText) val newIndex = (expression as? PyParenthesizedExpression)?.containedExpression as? PyTupleExpression ?: return index.replace(newIndex) } } } private class ReplaceWithTypingGenericAliasQuickFix : LocalQuickFix { override fun getFamilyName(): String = PyPsiBundle.message("QFIX.replace.with.typing.alias") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val subscription = descriptor.psiElement as? PySubscriptionExpression ?: return val refExpr = subscription.operand as? PyReferenceExpression ?: return val alias = PyTypingTypeProvider.TYPING_BUILTINS_GENERIC_ALIASES[refExpr.name] ?: return val languageLevel = LanguageLevel.forElement(subscription) val priority = if (languageLevel.isAtLeast(LanguageLevel.PYTHON35)) ImportPriority.THIRD_PARTY else ImportPriority.BUILTIN AddImportHelper.addOrUpdateFromImportStatement(subscription.containingFile, "typing", alias, null, priority, subscription) val newRefExpr = PyElementGenerator.getInstance(project).createExpressionFromText(languageLevel, alias) refExpr.replace(newRefExpr) } } } }
apache-2.0
7451488fd30e01d3ca6d8cb23f0ddb73
43.757776
142
0.67575
5.231108
false
false
false
false
GunoH/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLinesProvider.kt
2
1956
package org.jetbrains.plugins.notebooks.visualization import com.intellij.lang.Language import com.intellij.lang.LanguageExtension import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.Key import com.intellij.psi.PsiDocumentManager private const val ID: String = "org.jetbrains.plugins.notebooks.notebookCellLinesProvider" interface NotebookCellLinesProvider : IntervalsGenerator { fun create(document: Document): NotebookCellLines companion object : LanguageExtension<NotebookCellLinesProvider>(ID) { private val key = Key.create<NotebookCellLinesProvider>(NotebookCellLinesProvider::class.java.name) fun install(editor: Editor): NotebookCellLinesProvider? { get(editor.document)?.let { return it } val language = getLanguage(editor) ?: return null val provider = forLanguage(language) ?: return null key.set(editor.document, provider) return provider } fun get(document: Document): NotebookCellLinesProvider? { return document.getUserData(key) } } } interface IntervalsGenerator { fun makeIntervals(document: Document): List<NotebookCellLines.Interval> } open class NonIncrementalCellLinesProvider protected constructor(private val intervalsGenerator: IntervalsGenerator) : NotebookCellLinesProvider, IntervalsGenerator { override fun create(document: Document): NotebookCellLines = NonIncrementalCellLines.get(document, intervalsGenerator) /* If NotebookCellLines doesn't exist, parse document once and don't create NotebookCellLines instance */ override fun makeIntervals(document: Document): List<NotebookCellLines.Interval> = NonIncrementalCellLines.getOrNull(document)?.intervals ?: intervalsGenerator.makeIntervals(document) } internal fun getLanguage(editor: Editor): Language? = editor .project ?.let(PsiDocumentManager::getInstance) ?.getPsiFile(editor.document) ?.language
apache-2.0
e9657d0713ee4f59694c79ba29ba3be7
38.12
166
0.788344
4.989796
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/branched/ifThenToSafeAccess/resultCall.kt
9
227
// DISABLE-ERRORS // WITH_STDLIB val someNullableString: String? = "" fun String.bar(): Result<String> = Result.success("") val result = if<caret> (someNullableString == null) { null } else { someNullableString.bar() }
apache-2.0
81952fae86e3ec52d612699cef7b6b9d
21.8
53
0.678414
3.603175
false
false
false
false
smmribeiro/intellij-community
java/idea-ui/src/com/intellij/ide/SetupJavaProjectFromSourcesActivity.kt
1
9202
// Copyright 2000-2021 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.ide import com.google.common.collect.ArrayListMultimap import com.google.common.collect.Multimap import com.intellij.ide.impl.NewProjectUtil.setCompilerOutputPath import com.intellij.ide.impl.ProjectViewSelectInTarget import com.intellij.ide.projectView.impl.ProjectViewPane import com.intellij.ide.util.DelegatingProgressIndicator import com.intellij.ide.util.importProject.JavaModuleInsight import com.intellij.ide.util.importProject.LibrariesDetectionStep import com.intellij.ide.util.importProject.RootDetectionProcessor import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ide.util.projectWizard.importSources.impl.ProjectFromSourcesBuilderImpl import com.intellij.notification.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.ex.JavaSdkUtil import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.roots.ui.configuration.findAndSetupSdk import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.* import com.intellij.platform.PlatformProjectOpenProcessor import com.intellij.platform.PlatformProjectOpenProcessor.Companion.isOpenedByPlatformProcessor import com.intellij.projectImport.ProjectOpenProcessor import com.intellij.util.SystemProperties import java.io.File import javax.swing.event.HyperlinkEvent private val NOTIFICATION_GROUP = NotificationGroupManager.getInstance().getNotificationGroup("Build Script Found") private val SETUP_JAVA_PROJECT_IS_DISABLED = SystemProperties.getBooleanProperty("idea.java.project.setup.disabled", false) private const val SCAN_DEPTH_LIMIT = 5 private const val MAX_ROOTS_IN_TRIVIAL_PROJECT_STRUCTURE = 3 private val LOG = logger<SetupJavaProjectFromSourcesActivity>() internal class SetupJavaProjectFromSourcesActivity : StartupActivity { override fun runActivity(project: Project) { if (ApplicationManager.getApplication().isHeadlessEnvironment || SETUP_JAVA_PROJECT_IS_DISABLED) { return } if (!project.isOpenedByPlatformProcessor()) { return } // todo get current project structure, and later setup from sources only if it wasn't manually changed by the user val title = JavaUiBundle.message("task.searching.for.project.sources") ProgressManager.getInstance().run(object: Task.Backgroundable(project, title, true) { override fun run(indicator: ProgressIndicator) { val projectDir = project.baseDir val importers = searchImporters(projectDir) if (!importers.isEmpty) { showNotificationToImport(project, projectDir, importers) } else { setupFromSources(project, projectDir, indicator) } } }) } private fun searchImporters(projectDirectory: VirtualFile): ArrayListMultimap<ProjectOpenProcessor, VirtualFile> { val providersAndFiles = ArrayListMultimap.create<ProjectOpenProcessor, VirtualFile>() VfsUtil.visitChildrenRecursively(projectDirectory, object : VirtualFileVisitor<Void>(NO_FOLLOW_SYMLINKS, limit(SCAN_DEPTH_LIMIT)) { override fun visitFileEx(file: VirtualFile): Result { if (file.isDirectory && FileTypeRegistry.getInstance().isFileIgnored(file)) { return SKIP_CHILDREN } val providers = ProjectOpenProcessor.EXTENSION_POINT_NAME.extensionList.filter { provider -> provider.canOpenProject(file) && provider !is PlatformProjectOpenProcessor } for (provider in providers) { val files = providersAndFiles.get(provider) if (files.isEmpty()) { files.add(file) } else if (!VfsUtilCore.isAncestor(files.last(), file, true)) { // add only top-level file/folders for each of providers files.add(file) } } return CONTINUE } }) return providersAndFiles } private fun showNotificationToImport(project: Project, projectDirectory: VirtualFile, providersAndFiles: ArrayListMultimap<ProjectOpenProcessor, VirtualFile>) { val showFileInProjectViewListener = object : NotificationListener.Adapter() { override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) { val file = LocalFileSystem.getInstance().findFileByPath(e.description) ProjectViewSelectInTarget.select(project, file, ProjectViewPane.ID, null, file, true) } } val title: String val content: String if (providersAndFiles.keySet().size == 1) { val processor = providersAndFiles.keySet().single() val files = providersAndFiles[processor] title = JavaUiBundle.message("build.script.found.notification", processor.name, files.size) content = filesToLinks(files, projectDirectory) } else { title = JavaUiBundle.message("build.scripts.from.multiple.providers.found.notification") content = formatContent(providersAndFiles, projectDirectory) } val notification = NOTIFICATION_GROUP.createNotification(title, content, NotificationType.INFORMATION).setListener(showFileInProjectViewListener) if (providersAndFiles.keySet().all { it.canImportProjectAfterwards() }) { val actionName = JavaUiBundle.message("build.script.found.notification.import", providersAndFiles.keySet().size) notification.addAction(NotificationAction.createSimpleExpiring(actionName) { for ((provider, files) in providersAndFiles.asMap()) { for (file in files) { provider.importProjectAfterwards(project, file) } } }) } notification.notify(project) } @NlsSafe private fun formatContent(providersAndFiles: Multimap<ProjectOpenProcessor, VirtualFile>, projectDirectory: VirtualFile): String { return providersAndFiles.asMap().entries.joinToString("<br/>") { (provider, files) -> provider.name + ": " + filesToLinks(files, projectDirectory) } } @NlsSafe private fun filesToLinks(files: MutableCollection<VirtualFile>, projectDirectory: VirtualFile) = files.joinToString { file -> "<a href='${file.path}'>${VfsUtil.getRelativePath(file, projectDirectory)}</a>" } private fun setupFromSources(project: Project, projectDir: VirtualFile, indicator: ProgressIndicator) { val builder = ProjectFromSourcesBuilderImpl(WizardContext(project, project), ModulesProvider.EMPTY_MODULES_PROVIDER) val projectPath = projectDir.path builder.baseProjectPath = projectPath val roots = RootDetectionProcessor.detectRoots(File(projectPath)) val rootsMap = RootDetectionProcessor.createRootsMap(roots) builder.setupProjectStructure(rootsMap) for (detector in rootsMap.keySet()) { val descriptor = builder.getProjectDescriptor(detector) val moduleInsight = JavaModuleInsight(DelegatingProgressIndicator(), builder.existingModuleNames, builder.existingProjectLibraryNames) descriptor.libraries = LibrariesDetectionStep.calculate(moduleInsight, builder) moduleInsight.scanModules() descriptor.modules = moduleInsight.suggestedModules } ApplicationManager.getApplication().invokeAndWait { builder.commit(project) val compileOutput = if (projectPath.endsWith('/')) "${projectPath}out" else "$projectPath/out" setCompilerOutputPath(project, compileOutput) } val modules = ModuleManager.getInstance(project).modules if (modules.any { it is JavaModuleType }) { findAndSetupSdk(project, indicator, JavaSdk.getInstance()) { JavaSdkUtil.applyJdkToProject(project, it) } } if (roots.size > MAX_ROOTS_IN_TRIVIAL_PROJECT_STRUCTURE) { notifyAboutAutomaticProjectStructure(project) } } private fun notifyAboutAutomaticProjectStructure(project: Project) { NOTIFICATION_GROUP.createNotification(JavaUiBundle.message("project.structure.automatically.detected.notification"), NotificationType.INFORMATION) .addAction(NotificationAction.createSimpleExpiring(JavaUiBundle.message("project.structure.automatically.detected.notification.gotit.action")) {}) .addAction(NotificationAction.createSimpleExpiring(JavaUiBundle.message("project.structure.automatically.detected.notification.configure.action")) { ProjectSettingsService.getInstance(project).openProjectSettings() }) .notify(project) } }
apache-2.0
f5aeb2e52ba66b31d5f8acbdd6a2db68
45.01
154
0.749402
4.912974
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/trailingCommaOn/LambdaValueParameters.kt
26
1669
fun main() { val x: ( y: Comparable<Comparable<Number>>, z: Iterable<Iterable<Number>> // trailing comma ) -> Int = { 10 } val x: ( y: Comparable<Comparable<Number>>, z: Iterable<Iterable<Number>> ) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>>, z: Iterable<Iterable<Number>>) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>>, z: Iterable<Iterable<Number>>,) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>>, z: Iterable<Iterable<Number>>, ) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>>) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>>,) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>> ) -> Int = { 10 } val x: ( y: Comparable<Comparable<Number>>) -> Int = { 10 } val x: ( y: Comparable<Comparable<Number>>, // z: Iterable<Iterable<Number>> // /**/ ) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>>, z: Iterable<Iterable<Number>> // wd ) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>>/* */, z: Iterable<Iterable<Number>>, /* // */) -> Int = { 10 } val x: (/**/y: Comparable<Comparable<Number>>/**/) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>>/**/,) -> Int = { 10 } val x: (y: Comparable<Comparable<Number>> ) -> Int = { 10 } val x: ( /* */y: Comparable<Comparable<Number>>) -> Int = { 10 } }
apache-2.0
0a044b2796d956b55869736d7599da82
19.108434
89
0.468544
3.684327
false
false
false
false
psenchanka/comant
comant-site/src/main/kotlin/com/psenchanka/comant/controller/LocalSettingsController.kt
1
997
package com.psenchanka.comant.controller import com.psenchanka.comant.dto.SiteSettingsDto import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiResponse import io.swagger.annotations.ApiResponses import org.springframework.beans.factory.annotation.Value import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/site-settings") class LocalSettingsController { @Value("\${comant.sitename}") private lateinit var siteName: String; @RequestMapping("", method = arrayOf(RequestMethod.GET)) @ApiOperation("Get site local settings", notes = "Returns preferences that differ between comant installations like site name or icon.") @ApiResponses( ApiResponse(code = 200, message = "OK") ) fun getSiteSettings(): SiteSettingsDto = SiteSettingsDto(siteName) }
mit
e76154f0d602ecd1af624c215a89bcb2
37.384615
113
0.778335
4.680751
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/function/java8MRKFunctionExpectedType.kt
13
2753
package test internal class Test { fun memberFun(): Int { return 1 } companion object { var field = Java8Class() fun staticFun(): Java8Class { return Java8Class() } fun testOverloads(): String { return "1" } fun testOverloads(i: Int): String { return "2" } } } internal class Java8Class { private val field = Java8Class() fun testStaticFunction() { val staticFunFromSameClass: Function0<*> = { staticFun() } staticFunFromSameClass.invoke() val staticFunFromAnotherClass: Function0<*> = { Test.staticFun() } staticFunFromAnotherClass.invoke() } fun testMemberFunctionThroughClass() { val memberFunFromClass = { obj: Java8Class -> obj.memberFun() } memberFunFromClass.invoke(Java8Class()) } fun testMemberFunctionThroughObject() { val obj = Java8Class() val memberFunFromSameClass: Function0<*> = { obj.memberFun() } memberFunFromSameClass.invoke() val anotherObj = Test() val memFunFromAnotherClass: Function0<*> = { anotherObj.memberFun() } memFunFromAnotherClass.invoke() val memberFunThroughObj1: Function0<*> = { field.memberFun() } memberFunThroughObj1.invoke() val memberFunThroughObj2: Function0<*> = { Test.field.memberFun() } memberFunThroughObj2.invoke() val memberFunThroughObj3: Function0<*> = { Test.staticFun().memberFun() } memberFunThroughObj3.invoke() } fun testConstructor() { val constructorSameClass: Function0<*> = { Java8Class() } constructorSameClass.invoke() val qualifiedConstructorSameClass: Function0<*> = { Java8Class() } qualifiedConstructorSameClass.invoke() val constructorAnotherClass: Function0<*> = { Test() } constructorAnotherClass.invoke() val qualifiedConstructorAnotherClass: Function0<*> = { Test() } qualifiedConstructorAnotherClass.invoke() } fun testLibraryFunctions() { val memberFunFromClass = { obj: String -> obj.length } memberFunFromClass.invoke("str") } fun testOverloads() { val constructorWithoutParams = { Test.testOverloads() } constructorWithoutParams.invoke() val constructorWithParam = { i: Int -> Test.testOverloads(i) } constructorWithParam.invoke(2) + 42 } fun testGenericFunctions() { val emptyList: Function0<List<String>> = { emptyList() } val list = emptyList.invoke() list[0] } fun memberFun(): Int { return 1 } companion object { fun staticFun(): Int { return 1 } } }
apache-2.0
5d8a33868ef256e27232f0fdb33dc07a
29.263736
81
0.615692
4.461912
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddBracesIntention.kt
2
5960
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.getLineNumber import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.j2k.isInSingleLine import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* class AddBracesIntention : SelfTargetingIntention<KtElement>(KtElement::class.java, KotlinBundle.lazyMessage("add.braces")) { override fun isApplicableTo(element: KtElement, caretOffset: Int): Boolean { val expression = element.getTargetExpression(caretOffset) ?: return false if (expression is KtBlockExpression) return false return when (val parent = expression.parent) { is KtContainerNode -> { val description = parent.description() ?: return false setTextGetter(KotlinBundle.lazyMessage("add.braces.to.0.statement", description)) true } is KtWhenEntry -> { setTextGetter(KotlinBundle.lazyMessage("add.braces.to.when.entry")) true } else -> { false } } } override fun applyTo(element: KtElement, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val expression = element.getTargetExpression(editor.caretModel.offset) ?: return addBraces(element, expression) } private fun KtElement.getTargetExpression(caretLocation: Int): KtExpression? { return when (this) { is KtIfExpression -> { val thenExpr = then ?: return null val elseExpr = `else` if (elseExpr != null && caretLocation >= (elseKeyword?.startOffset ?: return null)) { elseExpr } else { thenExpr } } is KtLoopExpression -> body is KtWhenEntry -> expression else -> null } } companion object { fun addBraces(element: KtElement, expression: KtExpression) { var isCommentBeneath = false var isCommentInside = false val psiFactory = KtPsiFactory(element) val semicolon = element.getNextSiblingIgnoringWhitespaceAndComments()?.takeIf { it.node.elementType == KtTokens.SEMICOLON } if (semicolon != null) { val afterSemicolon = semicolon.getNextSiblingIgnoringWhitespace() if (semicolon.getLineNumber() == afterSemicolon?.getLineNumber()) semicolon.replace(psiFactory.createNewLine()) else semicolon.delete() } if (element is KtIfExpression) { // Check if a comment is actually underneath (\n) the expression val allElements = element.siblings(withItself = false).filterIsInstance<PsiElement>() val sibling = allElements.firstOrNull { it is PsiComment } if (sibling is PsiComment) { // Check if \n before first received comment sibling // if false, the normal procedure of adding braces occurs. isCommentBeneath = sibling.prevSibling is PsiWhiteSpace && sibling.prevSibling.textContains('\n') && (sibling.prevSibling.prevSibling is PsiComment || sibling.prevSibling.prevSibling is PsiElement) } } // Check for nested if/else if (element is KtIfExpression && expression.isInSingleLine() && element.`else` != null && element.parent.nextSibling is PsiWhiteSpace && element.parent.nextSibling.nextSibling is PsiComment ) { isCommentInside = true } val nextComment = when { element is KtDoWhileExpression -> null // bound to the closing while element is KtIfExpression && expression === element.then && element.`else` != null -> null // bound to else else -> element.getNextSiblingIgnoringWhitespace().takeIf { it is PsiComment && it.getLineNumber() == element.getLineNumber(start = false) } } val saver = when { isCommentInside -> { CommentSaver(element.parent.nextSibling.nextSibling) } else -> if (nextComment == null) CommentSaver(element) else CommentSaver(PsiChildRange(element, nextComment)) } if (isCommentInside) { element.parent.nextSibling.nextSibling.delete() } element.allChildren.filterIsInstance<PsiComment>().toList().forEach { it.delete() } nextComment?.delete() val result = expression.replace(psiFactory.createSingleStatementBlock(expression)) when (element) { is KtDoWhileExpression -> // remove new line between '}' and while (element.body?.parent?.nextSibling as? PsiWhiteSpace)?.delete() is KtIfExpression -> (result?.parent?.nextSibling as? PsiWhiteSpace)?.delete() } // Check for single line expression with comment beneath. saver.restore(result, isCommentBeneath, isCommentInside, forceAdjustIndent = false) } } }
apache-2.0
7c32caad264a013c969a99c19efb6c4c
42.50365
158
0.59547
5.758454
false
false
false
false
miketrewartha/positional
app/src/main/kotlin/io/trewartha/positional/ui/sun/SunViewModel.kt
1
4542
package io.trewartha.positional.ui.sun import android.app.Application import android.location.Location import android.os.Looper import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.asLiveData import ca.rmen.sunrisesunset.SunriseSunset import com.google.android.gms.location.* import dagger.hilt.android.lifecycle.HiltViewModel import io.trewartha.positional.R import io.trewartha.positional.ui.utils.DateTimeFormatter import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.map import org.threeten.bp.Instant import timber.log.Timber import java.util.* import javax.inject.Inject @OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class) @HiltViewModel class SunViewModel @Inject constructor( app: Application, private val dateTimeFormatter: DateTimeFormatter, private val fusedLocationProviderClient: FusedLocationProviderClient ) : AndroidViewModel(app) { val sunState: LiveData<SunState> = callbackFlow<Location> { val locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult?) { val location = locationResult?.lastLocation ?: return Timber.d("Received location update") offer(location) } override fun onLocationAvailability(locationAvailability: LocationAvailability) { Timber.d("Location availability changed to $locationAvailability") } } try { val locationRequest = LocationRequest.create() .setPriority(LOCATION_UPDATE_PRIORITY) .setInterval(LOCATION_UPDATE_INTERVAL_MS) Timber.i("Requesting location updates: $locationRequest") fusedLocationProviderClient.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper() ) } catch (e: SecurityException) { Timber.w(e, "Don't have location permissions, no location updates will be received") } awaitClose { Timber.i("Suspending location updates") fusedLocationProviderClient.removeLocationUpdates(locationCallback) } }.map { val calendar = Calendar.getInstance().apply { timeInMillis = it.time } val latitude = it.latitude val longitude = it.longitude val sunriseSunset = SunriseSunset.getSunriseSunset(calendar, latitude, longitude) val civilTwilights = SunriseSunset.getCivilTwilight(calendar, latitude, longitude) val nauticalTwilights = SunriseSunset.getNauticalTwilight(calendar, latitude, longitude) val astronomicalTwilights = SunriseSunset.getAstronomicalTwilight(calendar, latitude, longitude) SunState( formatDate(it.time), formatTime(astronomicalTwilights[0]?.timeInMillis), formatTime(nauticalTwilights[0]?.timeInMillis), formatTime(civilTwilights[0]?.timeInMillis), formatTime(sunriseSunset[0]?.timeInMillis), formatTime(sunriseSunset[1]?.timeInMillis), formatTime(civilTwilights[1]?.timeInMillis), formatTime(nauticalTwilights[1]?.timeInMillis), formatTime(astronomicalTwilights[1]?.timeInMillis), String.format(formatUpdatedAt, formatTime(it.time)) ) }.asLiveData() private val formatUpdatedAt = app.getString(R.string.location_updated_at) private fun formatDate(epochMillis: Long?): String? = epochMillis?.let { dateTimeFormatter.getFormattedDate(Instant.ofEpochMilli(it)) } private fun formatTime(epochMillis: Long?): String? = epochMillis?.let { dateTimeFormatter.getFormattedTime(Instant.ofEpochMilli(it)) } data class SunState( val date: String?, val astronomicalDawn: String?, val nauticalDawn: String?, val civilDawn: String?, val sunrise: String?, val sunset: String?, val civilDusk: String?, val nauticalDusk: String?, val astronomicalDusk: String?, val updatedAt: String? ) companion object { private const val LOCATION_UPDATE_INTERVAL_MS = 60_000L private const val LOCATION_UPDATE_PRIORITY = LocationRequest.PRIORITY_LOW_POWER } }
mit
ad79066523f7f565434d06079fd26f0f
38.504348
96
0.691105
4.883871
false
false
false
false
BenWoodworth/FastCraft
fastcraft-bukkit/bukkit-1.15/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/recipe/FcCraftingRecipe_Bukkit_1_15.kt
1
2601
package net.benwoodworth.fastcraft.bukkit.recipe import net.benwoodworth.fastcraft.platform.player.FcPlayer import net.benwoodworth.fastcraft.platform.recipe.FcCraftingRecipe import net.benwoodworth.fastcraft.platform.recipe.FcIngredient import net.benwoodworth.fastcraft.platform.world.FcItem import net.benwoodworth.fastcraft.platform.world.FcItemStack import org.bukkit.Server import org.bukkit.inventory.ComplexRecipe import org.bukkit.inventory.Recipe import javax.inject.Inject import javax.inject.Singleton open class FcCraftingRecipe_Bukkit_1_15( recipe: Recipe, server: Server, preparedRecipeFactory: FcCraftingRecipePrepared_Bukkit.Factory, fcItemStackFactory: FcItemStack.Factory, inventoryViewFactory: CraftingInventoryViewFactory, fcPlayerOperations: FcPlayer.Operations, fcItemOperations: FcItem.Operations, fcItemStackOperations: FcItemStack.Operations, ) : FcCraftingRecipe_Bukkit_1_13( recipe = recipe, server = server, preparedRecipeFactory = preparedRecipeFactory, fcItemStackFactory = fcItemStackFactory, craftingInventoryViewFactory = inventoryViewFactory, fcPlayerOperations = fcPlayerOperations, fcItemOperations = fcItemOperations, fcItemStackOperations = fcItemStackOperations, ) { override fun loadIngredients(): List<FcIngredient> { return when (recipe) { is ComplexRecipe -> emptyList() else -> super.loadIngredients() } } @Singleton class Factory @Inject constructor( private val server: Server, private val fcCraftingRecipePreparedFactory: FcCraftingRecipePrepared_Bukkit.Factory, private val fcItemStackFactory: FcItemStack.Factory, private val craftingInventoryViewFactory: CraftingInventoryViewFactory, private val fcPlayerOperations: FcPlayer.Operations, private val fcItemOperations: FcItem.Operations, private val fcItemStackOperations: FcItemStack.Operations, ) : FcCraftingRecipe_Bukkit.Factory { override fun create(recipe: Recipe): FcCraftingRecipe { return FcCraftingRecipe_Bukkit_1_15( recipe = recipe, server = server, preparedRecipeFactory = fcCraftingRecipePreparedFactory, fcItemStackFactory = fcItemStackFactory, inventoryViewFactory = craftingInventoryViewFactory, fcPlayerOperations = fcPlayerOperations, fcItemOperations = fcItemOperations, fcItemStackOperations = fcItemStackOperations, ) } } }
gpl-3.0
8d200dccf660c2a8b343cee84501d666
40.285714
93
0.737024
5.407484
false
false
false
false
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/source/online/HttpSource.kt
1
12303
package eu.kanade.tachiyomi.source.online import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.network.newCallWithProgress import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.source.model.* import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import rx.Observable import uy.kohesive.injekt.injectLazy import java.net.URI import java.net.URISyntaxException import java.security.MessageDigest /** * A simple implementation for sources from a website. */ abstract class HttpSource : CatalogueSource { /** * Network service. */ protected val network: NetworkHelper by injectLazy() // /** // * Preferences that a source may need. // */ // val preferences: SharedPreferences by lazy { // Injekt.get<Application>().getSharedPreferences("source_$id", Context.MODE_PRIVATE) // } /** * Base url of the website without the trailing slash, like: http://mysite.com */ abstract val baseUrl: String /** * Version id used to generate the source id. If the site completely changes and urls are * incompatible, you may increase this value and it'll be considered as a new source. */ open val versionId = 1 /** * Id of the source. By default it uses a generated id using the first 16 characters (64 bits) * of the MD5 of the string: sourcename/language/versionId * Note the generated id sets the sign bit to 0. */ override val id by lazy { val key = "${name.toLowerCase()}/$lang/$versionId" val bytes = MessageDigest.getInstance("MD5").digest(key.toByteArray()) (0..7).map { bytes[it].toLong() and 0xff shl 8 * (7 - it) }.reduce(Long::or) and Long.MAX_VALUE } /** * Headers used for requests. */ val headers: Headers by lazy { headersBuilder().build() } /** * Default network client for doing requests. */ open val client: OkHttpClient get() = network.client /** * Headers builder for requests. Implementations can override this method for custom headers. */ protected open fun headersBuilder() = Headers.Builder().apply { add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)") } /** * Visible name of the source. */ override fun toString() = "$name (${lang.toUpperCase()})" /** * Returns an observable containing a page with a list of manga. Normally it's not needed to * override this method. * * @param page the page number to retrieve. */ override fun fetchPopularManga(page: Int): Observable<MangasPage> { return client.newCall(popularMangaRequest(page)) .asObservableSuccess() .map { response -> popularMangaParse(response) } } /** * Returns the request for the popular manga given the page. * * @param page the page number to retrieve. */ protected abstract fun popularMangaRequest(page: Int): Request /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ protected abstract fun popularMangaParse(response: Response): MangasPage /** * Returns an observable containing a page with a list of manga. Normally it's not needed to * override this method. * * @param page the page number to retrieve. * @param query the search query. * @param filters the list of filters to apply. */ override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return client.newCall(searchMangaRequest(page, query, filters)) .asObservableSuccess() .map { response -> searchMangaParse(response) } } /** * Returns the request for the search manga given the page. * * @param page the page number to retrieve. * @param query the search query. * @param filters the list of filters to apply. */ protected abstract fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ protected abstract fun searchMangaParse(response: Response): MangasPage /** * Returns an observable containing a page with a list of latest manga updates. * * @param page the page number to retrieve. */ override fun fetchLatestUpdates(page: Int): Observable<MangasPage> { return client.newCall(latestUpdatesRequest(page)) .asObservableSuccess() .map { response -> latestUpdatesParse(response) } } /** * Returns the request for latest manga given the page. * * @param page the page number to retrieve. */ protected abstract fun latestUpdatesRequest(page: Int): Request /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ protected abstract fun latestUpdatesParse(response: Response): MangasPage /** * Returns an observable with the updated details for a manga. Normally it's not needed to * override this method. * * @param manga the manga to be updated. */ override fun fetchMangaDetails(manga: SManga): Observable<SManga> { return client.newCall(mangaDetailsRequest(manga)) .asObservableSuccess() .map { response -> mangaDetailsParse(response).apply { initialized = true } } } /** * Returns the request for the details of a manga. Override only if it's needed to change the * url, send different headers or request method like POST. * * @param manga the manga to be updated. */ open fun mangaDetailsRequest(manga: SManga): Request { return GET(baseUrl + manga.url, headers) } /** * Parses the response from the site and returns the details of a manga. * * @param response the response from the site. */ protected abstract fun mangaDetailsParse(response: Response): SManga /** * Returns an observable with the updated chapter list for a manga. Normally it's not needed to * override this method. If a manga is licensed an empty chapter list observable is returned * * @param manga the manga to look for chapters. */ override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> { if (manga.status != SManga.LICENSED) { return client.newCall(chapterListRequest(manga)) .asObservableSuccess() .map { response -> chapterListParse(response) } } else { return Observable.error(Exception("Licensed - No chapters to show")) } } /** * Returns the request for updating the chapter list. Override only if it's needed to override * the url, send different headers or request method like POST. * * @param manga the manga to look for chapters. */ protected open fun chapterListRequest(manga: SManga): Request { return GET(baseUrl + manga.url, headers) } /** * Parses the response from the site and returns a list of chapters. * * @param response the response from the site. */ protected abstract fun chapterListParse(response: Response): List<SChapter> /** * Returns an observable with the page list for a chapter. * * @param chapter the chapter whose page list has to be fetched. */ override fun fetchPageList(chapter: SChapter): Observable<List<Page>> { return client.newCall(pageListRequest(chapter)) .asObservableSuccess() .map { response -> pageListParse(response) } } /** * Returns the request for getting the page list. Override only if it's needed to override the * url, send different headers or request method like POST. * * @param chapter the chapter whose page list has to be fetched. */ protected open fun pageListRequest(chapter: SChapter): Request { return GET(baseUrl + chapter.url, headers) } /** * Parses the response from the site and returns a list of pages. * * @param response the response from the site. */ protected abstract fun pageListParse(response: Response): List<Page> /** * Returns an observable with the page containing the source url of the image. If there's any * error, it will return null instead of throwing an exception. * * @param page the page whose source image has to be fetched. */ open fun fetchImageUrl(page: Page): Observable<String> { return client.newCall(imageUrlRequest(page)) .asObservableSuccess() .map { imageUrlParse(it) } } /** * Returns the request for getting the url to the source image. Override only if it's needed to * override the url, send different headers or request method like POST. * * @param page the chapter whose page list has to be fetched */ protected open fun imageUrlRequest(page: Page): Request { return GET(page.url, headers) } /** * Parses the response from the site and returns the absolute url to the source image. * * @param response the response from the site. */ protected abstract fun imageUrlParse(response: Response): String /** * Returns an observable with the response of the source image. * * @param page the page whose source image has to be downloaded. */ fun fetchImage(page: Page): Observable<Response> { return client.newCallWithProgress(imageRequest(page), page) .asObservableSuccess() } /** * Returns the request for getting the source image. Override only if it's needed to override * the url, send different headers or request method like POST. * * @param page the chapter whose page list has to be fetched */ protected open fun imageRequest(page: Page): Request { return GET(page.imageUrl!!, headers) } /** * Assigns the url of the chapter without the scheme and domain. It saves some redundancy from * database and the urls could still work after a domain change. * * @param url the full url to the chapter. */ fun SChapter.setUrlWithoutDomain(url: String) { this.url = getUrlWithoutDomain(url) } /** * Assigns the url of the manga without the scheme and domain. It saves some redundancy from * database and the urls could still work after a domain change. * * @param url the full url to the manga. */ fun SManga.setUrlWithoutDomain(url: String) { this.url = getUrlWithoutDomain(url) } /** * Returns the url of the given string without the scheme and domain. * * @param orig the full url. */ private fun getUrlWithoutDomain(orig: String): String { try { val uri = URI(orig) var out = uri.path if (uri.query != null) out += "?" + uri.query if (uri.fragment != null) out += "#" + uri.fragment return out } catch (e: URISyntaxException) { return orig } } /** * Called before inserting a new chapter into database. Use it if you need to override chapter * fields, like the title or the chapter number. Do not change anything to [manga]. * * @param chapter the chapter to be added. * @param manga the manga of the chapter. */ open fun prepareNewChapter(chapter: SChapter, manga: SManga) { } /** * Returns the list of filters for the source. */ override fun getFilterList() = FilterList() }
apache-2.0
db3c62c0e913a7952d81ae1470f36d36
32.614754
106
0.632935
4.783437
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/discovery/SettingsItem.kt
2
2809
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments.discovery import android.view.View import android.widget.Switch import android.widget.TextView import androidx.annotation.StringRes import androidx.core.view.isVisible import butterknife.BindView import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import im.vector.R import im.vector.ui.epoxy.BaseEpoxyHolder import im.vector.ui.themes.ThemeUtils import im.vector.ui.util.setTextOrHide @EpoxyModelClass(layout = R.layout.item_settings_simple_item) abstract class SettingsItem : EpoxyModelWithHolder<SettingsItem.Holder>() { @EpoxyAttribute var title: String? = null @EpoxyAttribute @StringRes var titleResId: Int? = null @EpoxyAttribute @StringRes var descriptionResId: Int? = null @EpoxyAttribute var description: CharSequence? = null @EpoxyAttribute var itemClickListener: View.OnClickListener? = null override fun bind(holder: Holder) { if (titleResId != null) { holder.titleText.setText(titleResId!!) } else { holder.titleText.setTextOrHide(title) } if (descriptionResId != null) { holder.descriptionText.setText(descriptionResId!!) } else { holder.descriptionText.setTextOrHide(description) } //If there is only a description, use primary color // holder.descriptionText.setTextColor( // if (holder.titleText.text.isNullOrBlank()) { // ThemeUtils.getColor(holder.main.context, android.R.attr.textColorPrimary) // } else { // ThemeUtils.getColor(holder.main.context, android.R.attr.textColorSecondary) // } // ) holder.switchButton.isVisible = false holder.main.setOnClickListener(itemClickListener) } class Holder : BaseEpoxyHolder() { @BindView(R.id.settings_item_title) lateinit var titleText: TextView @BindView(R.id.settings_item_description) lateinit var descriptionText: TextView @BindView(R.id.settings_item_switch) lateinit var switchButton: Switch } }
apache-2.0
a74ad84c7b263ffe48631fe7c237ce2c
29.879121
97
0.694197
4.47293
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/writer/DaoWriter.kt
1
25269
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.writer import androidx.room.ext.L import androidx.room.ext.N import androidx.room.ext.RoomTypeNames import androidx.room.ext.SupportDbTypeNames import androidx.room.ext.T import androidx.room.ext.typeName import androidx.room.parser.QueryType import androidx.room.processor.OnConflictProcessor import androidx.room.solver.CodeGenScope import androidx.room.vo.Dao import androidx.room.vo.Entity import androidx.room.vo.InsertionMethod import androidx.room.vo.QueryMethod import androidx.room.vo.RawQueryMethod import androidx.room.vo.ShortcutMethod import androidx.room.vo.TransactionMethod import com.google.auto.common.MoreTypes import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.FieldSpec import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import me.eugeniomarletti.kotlin.metadata.shadow.load.java.JvmAbi import stripNonJava import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.ElementKind import javax.lang.model.element.ExecutableElement import javax.lang.model.element.Modifier.FINAL import javax.lang.model.element.Modifier.PRIVATE import javax.lang.model.element.Modifier.PUBLIC import javax.lang.model.type.DeclaredType import javax.lang.model.type.TypeKind /** * Creates the implementation for a class annotated with Dao. */ class DaoWriter(val dao: Dao, val processingEnv: ProcessingEnvironment) : ClassWriter(dao.typeName) { private val declaredDao = MoreTypes.asDeclared(dao.element.asType()) companion object { // TODO nothing prevents this from conflicting, we should fix. val dbField: FieldSpec = FieldSpec .builder(RoomTypeNames.ROOM_DB, "__db", PRIVATE, FINAL) .build() private fun typeNameToFieldName(typeName: TypeName?): String { if (typeName is ClassName) { return typeName.simpleName() } else { return typeName.toString().replace('.', '_').stripNonJava() } } } override fun createTypeSpecBuilder(): TypeSpec.Builder { val builder = TypeSpec.classBuilder(dao.implTypeName) /** * if delete / update query method wants to return modified rows, we need prepared query. * in that case, if args are dynamic, we cannot re-use the query, if not, we should re-use * it. this requires more work but creates good performance. */ val groupedDeleteUpdate = dao.queryMethods .filter { it.query.type == QueryType.DELETE || it.query.type == QueryType.UPDATE } .groupBy { it.parameters.any { it.queryParamAdapter?.isMultiple ?: true } } // delete queries that can be prepared ahead of time val preparedDeleteOrUpdateQueries = groupedDeleteUpdate[false] ?: emptyList() // delete queries that must be rebuild every single time val oneOffDeleteOrUpdateQueries = groupedDeleteUpdate[true] ?: emptyList() val shortcutMethods = createInsertionMethods() + createDeletionMethods() + createUpdateMethods() + createTransactionMethods() + createPreparedDeleteOrUpdateQueries(preparedDeleteOrUpdateQueries) builder.apply { addModifiers(PUBLIC) if (dao.element.kind == ElementKind.INTERFACE) { addSuperinterface(dao.typeName) } else { superclass(dao.typeName) } addField(dbField) val dbParam = ParameterSpec .builder(dao.constructorParamType ?: dbField.type, dbField.name).build() addMethod(createConstructor(dbParam, shortcutMethods, dao.constructorParamType != null)) shortcutMethods.forEach { addMethod(it.methodImpl) } dao.queryMethods.filter { it.query.type == QueryType.SELECT }.forEach { method -> addMethod(createSelectMethod(method)) } oneOffDeleteOrUpdateQueries.forEach { addMethod(createDeleteOrUpdateQueryMethod(it)) } dao.rawQueryMethods.forEach { addMethod(createRawQueryMethod(it)) } } return builder } private fun createPreparedDeleteOrUpdateQueries( preparedDeleteQueries: List<QueryMethod>): List<PreparedStmtQuery> { return preparedDeleteQueries.map { method -> val fieldSpec = getOrCreateField(PreparedStatementField(method)) val queryWriter = QueryWriter(method) val fieldImpl = PreparedStatementWriter(queryWriter) .createAnonymous(this@DaoWriter, dbField) val methodBody = createPreparedDeleteQueryMethodBody(method, fieldSpec, queryWriter) PreparedStmtQuery(mapOf(PreparedStmtQuery.NO_PARAM_FIELD to (fieldSpec to fieldImpl)), methodBody) } } private fun createPreparedDeleteQueryMethodBody( method: QueryMethod, preparedStmtField: FieldSpec, queryWriter: QueryWriter ): MethodSpec { val scope = CodeGenScope(this) val methodBuilder = overrideWithoutAnnotations(method.element, declaredDao).apply { val stmtName = scope.getTmpVar("_stmt") addStatement("final $T $L = $N.acquire()", SupportDbTypeNames.SQLITE_STMT, stmtName, preparedStmtField) addStatement("$N.beginTransaction()", dbField) beginControlFlow("try").apply { val bindScope = scope.fork() queryWriter.bindArgs(stmtName, emptyList(), bindScope) addCode(bindScope.builder().build()) if (method.returnsValue) { val resultVar = scope.getTmpVar("_result") addStatement("final $L $L = $L.executeUpdateDelete()", method.returnType.typeName(), resultVar, stmtName) addStatement("$N.setTransactionSuccessful()", dbField) addStatement("return $L", resultVar) } else { addStatement("$L.executeUpdateDelete()", stmtName) addStatement("$N.setTransactionSuccessful()", dbField) } } nextControlFlow("finally").apply { addStatement("$N.endTransaction()", dbField) addStatement("$N.release($L)", preparedStmtField, stmtName) } endControlFlow() } return methodBuilder.build() } private fun createTransactionMethods(): List<PreparedStmtQuery> { return dao.transactionMethods.map { PreparedStmtQuery(emptyMap(), createTransactionMethodBody(it)) } } private fun createTransactionMethodBody(method: TransactionMethod): MethodSpec { val scope = CodeGenScope(this) val methodBuilder = overrideWithoutAnnotations(method.element, declaredDao).apply { addStatement("$N.beginTransaction()", dbField) beginControlFlow("try").apply { val returnsValue = method.element.returnType.kind != TypeKind.VOID val resultVar = if (returnsValue) { scope.getTmpVar("_result") } else { null } addDelegateToSuperStatement(method.element, method.callType, resultVar) addStatement("$N.setTransactionSuccessful()", dbField) if (returnsValue) { addStatement("return $N", resultVar) } } nextControlFlow("finally").apply { addStatement("$N.endTransaction()", dbField) } endControlFlow() } return methodBuilder.build() } private fun MethodSpec.Builder.addDelegateToSuperStatement( element: ExecutableElement, callType: TransactionMethod.CallType, result: String?) { val params: MutableList<Any> = mutableListOf() val format = buildString { if (result != null) { append("$T $L = ") params.add(element.returnType) params.add(result) } when (callType) { TransactionMethod.CallType.CONCRETE -> { append("super.$N(") params.add(element.simpleName) } TransactionMethod.CallType.DEFAULT_JAVA8 -> { append("$N.super.$N(") params.add(element.enclosingElement.simpleName) params.add(element.simpleName) } TransactionMethod.CallType.DEFAULT_KOTLIN -> { append("$N.$N.$N(this, ") params.add(element.enclosingElement.simpleName) params.add(JvmAbi.DEFAULT_IMPLS_CLASS_NAME) params.add(element.simpleName) } } var first = true element.parameters.forEach { if (first) { first = false } else { append(", ") } append(L) params.add(it.simpleName) } append(")") } addStatement(format, *params.toTypedArray()) } private fun createConstructor( dbParam: ParameterSpec, shortcutMethods: List<PreparedStmtQuery>, callSuper: Boolean): MethodSpec { return MethodSpec.constructorBuilder().apply { addParameter(dbParam) addModifiers(PUBLIC) if (callSuper) { addStatement("super($N)", dbParam) } addStatement("this.$N = $N", dbField, dbParam) shortcutMethods.filterNot { it.fields.isEmpty() }.map { it.fields.values }.flatten().groupBy { it.first.name }.map { it.value.first() }.forEach { addStatement("this.$N = $L", it.first, it.second) } }.build() } private fun createSelectMethod(method: QueryMethod): MethodSpec { return overrideWithoutAnnotations(method.element, declaredDao).apply { addCode(createQueryMethodBody(method)) }.build() } private fun createRawQueryMethod(method: RawQueryMethod): MethodSpec { return overrideWithoutAnnotations(method.element, declaredDao).apply { val scope = CodeGenScope(this@DaoWriter) val roomSQLiteQueryVar: String val queryParam = method.runtimeQueryParam val shouldReleaseQuery: Boolean when { queryParam?.isString() == true -> { roomSQLiteQueryVar = scope.getTmpVar("_statement") shouldReleaseQuery = true addStatement("$T $L = $T.acquire($L, 0)", RoomTypeNames.ROOM_SQL_QUERY, roomSQLiteQueryVar, RoomTypeNames.ROOM_SQL_QUERY, queryParam.paramName) } queryParam?.isSupportQuery() == true -> { shouldReleaseQuery = false roomSQLiteQueryVar = scope.getTmpVar("_internalQuery") // move it to a final variable so that the generated code can use it inside // callback blocks in java 7 addStatement("final $T $L = $N", queryParam.type, roomSQLiteQueryVar, queryParam.paramName) } else -> { // try to generate compiling code. we would've already reported this error roomSQLiteQueryVar = scope.getTmpVar("_statement") shouldReleaseQuery = false addStatement("$T $L = $T.acquire($L, 0)", RoomTypeNames.ROOM_SQL_QUERY, roomSQLiteQueryVar, RoomTypeNames.ROOM_SQL_QUERY, "missing query parameter") } } if (method.returnsValue) { // don't generate code because it will create 1 more error. The original error is // already reported by the processor. method.queryResultBinder.convertAndReturn( roomSQLiteQueryVar = roomSQLiteQueryVar, canReleaseQuery = shouldReleaseQuery, dbField = dbField, inTransaction = method.inTransaction, scope = scope) } addCode(scope.builder().build()) }.build() } private fun createDeleteOrUpdateQueryMethod(method: QueryMethod): MethodSpec { return overrideWithoutAnnotations(method.element, declaredDao).apply { addCode(createDeleteOrUpdateQueryMethodBody(method)) }.build() } /** * Groups all insertion methods based on the insert statement they will use then creates all * field specs, EntityInsertionAdapterWriter and actual insert methods. */ private fun createInsertionMethods(): List<PreparedStmtQuery> { return dao.insertionMethods .map { insertionMethod -> val onConflict = OnConflictProcessor.onConflictText(insertionMethod.onConflict) val entities = insertionMethod.entities val fields = entities.mapValues { val spec = getOrCreateField(InsertionMethodField(it.value, onConflict)) val impl = EntityInsertionAdapterWriter(it.value, onConflict) .createAnonymous(this@DaoWriter, dbField.name) spec to impl } val methodImpl = overrideWithoutAnnotations(insertionMethod.element, declaredDao).apply { addCode(createInsertionMethodBody(insertionMethod, fields)) }.build() PreparedStmtQuery(fields, methodImpl) } } private fun createInsertionMethodBody( method: InsertionMethod, insertionAdapters: Map<String, Pair<FieldSpec, TypeSpec>> ): CodeBlock { val insertionType = method.insertionType if (insertionAdapters.isEmpty() || insertionType == null) { return CodeBlock.builder().build() } val scope = CodeGenScope(this) return scope.builder().apply { // TODO assert thread // TODO collect results addStatement("$N.beginTransaction()", dbField) val needsReturnType = insertionType != InsertionMethod.Type.INSERT_VOID val resultVar = if (needsReturnType) { scope.getTmpVar("_result") } else { null } beginControlFlow("try").apply { method.parameters.forEach { param -> val insertionAdapter = insertionAdapters[param.name]?.first if (needsReturnType) { // if it has more than 1 parameter, we would've already printed the error // so we don't care about re-declaring the variable here addStatement("$T $L = $N.$L($L)", insertionType.returnTypeName, resultVar, insertionAdapter, insertionType.methodName, param.name) } else { addStatement("$N.$L($L)", insertionAdapter, insertionType.methodName, param.name) } } addStatement("$N.setTransactionSuccessful()", dbField) if (needsReturnType) { addStatement("return $L", resultVar) } } nextControlFlow("finally").apply { addStatement("$N.endTransaction()", dbField) } endControlFlow() }.build() } /** * Creates EntityUpdateAdapter for each deletion method. */ private fun createDeletionMethods(): List<PreparedStmtQuery> { return createShortcutMethods(dao.deletionMethods, "deletion", { _, entity -> EntityDeletionAdapterWriter(entity) .createAnonymous(this@DaoWriter, dbField.name) }) } /** * Creates EntityUpdateAdapter for each @Update method. */ private fun createUpdateMethods(): List<PreparedStmtQuery> { return createShortcutMethods(dao.updateMethods, "update", { update, entity -> val onConflict = OnConflictProcessor.onConflictText(update.onConflictStrategy) EntityUpdateAdapterWriter(entity, onConflict) .createAnonymous(this@DaoWriter, dbField.name) }) } private fun <T : ShortcutMethod> createShortcutMethods( methods: List<T>, methodPrefix: String, implCallback: (T, Entity) -> TypeSpec ): List<PreparedStmtQuery> { return methods.mapNotNull { method -> val entities = method.entities if (entities.isEmpty()) { null } else { val fields = entities.mapValues { val spec = getOrCreateField(DeleteOrUpdateAdapterField(it.value, methodPrefix)) val impl = implCallback(method, it.value) spec to impl } val methodSpec = overrideWithoutAnnotations(method.element, declaredDao).apply { addCode(createDeleteOrUpdateMethodBody(method, fields)) }.build() PreparedStmtQuery(fields, methodSpec) } } } private fun createDeleteOrUpdateMethodBody( method: ShortcutMethod, adapters: Map<String, Pair<FieldSpec, TypeSpec>> ): CodeBlock { if (adapters.isEmpty()) { return CodeBlock.builder().build() } val scope = CodeGenScope(this) val resultVar = if (method.returnCount) { scope.getTmpVar("_total") } else { null } return scope.builder().apply { if (resultVar != null) { addStatement("$T $L = 0", TypeName.INT, resultVar) } addStatement("$N.beginTransaction()", dbField) beginControlFlow("try").apply { method.parameters.forEach { param -> val adapter = adapters[param.name]?.first addStatement("$L$N.$L($L)", if (resultVar == null) "" else "$resultVar +=", adapter, param.handleMethodName(), param.name) } addStatement("$N.setTransactionSuccessful()", dbField) if (resultVar != null) { addStatement("return $L", resultVar) } } nextControlFlow("finally").apply { addStatement("$N.endTransaction()", dbField) } endControlFlow() }.build() } /** * @Query with delete action */ private fun createDeleteOrUpdateQueryMethodBody(method: QueryMethod): CodeBlock { val queryWriter = QueryWriter(method) val scope = CodeGenScope(this) val sqlVar = scope.getTmpVar("_sql") val stmtVar = scope.getTmpVar("_stmt") val listSizeArgs = queryWriter.prepareQuery(sqlVar, scope) scope.builder().apply { addStatement("$T $L = $N.compileStatement($L)", SupportDbTypeNames.SQLITE_STMT, stmtVar, dbField, sqlVar) queryWriter.bindArgs(stmtVar, listSizeArgs, scope) addStatement("$N.beginTransaction()", dbField) beginControlFlow("try").apply { if (method.returnsValue) { val resultVar = scope.getTmpVar("_result") addStatement("final $L $L = $L.executeUpdateDelete()", method.returnType.typeName(), resultVar, stmtVar) addStatement("$N.setTransactionSuccessful()", dbField) addStatement("return $L", resultVar) } else { addStatement("$L.executeUpdateDelete()", stmtVar) addStatement("$N.setTransactionSuccessful()", dbField) } } nextControlFlow("finally").apply { addStatement("$N.endTransaction()", dbField) } endControlFlow() } return scope.builder().build() } private fun createQueryMethodBody(method: QueryMethod): CodeBlock { val queryWriter = QueryWriter(method) val scope = CodeGenScope(this) val sqlVar = scope.getTmpVar("_sql") val roomSQLiteQueryVar = scope.getTmpVar("_statement") queryWriter.prepareReadAndBind(sqlVar, roomSQLiteQueryVar, scope) method.queryResultBinder.convertAndReturn( roomSQLiteQueryVar = roomSQLiteQueryVar, canReleaseQuery = true, dbField = dbField, inTransaction = method.inTransaction, scope = scope) return scope.builder().build() } private fun overrideWithoutAnnotations( elm: ExecutableElement, owner: DeclaredType): MethodSpec.Builder { val baseSpec = MethodSpec.overriding(elm, owner, processingEnv.typeUtils).build() return MethodSpec.methodBuilder(baseSpec.name).apply { addAnnotation(Override::class.java) addModifiers(baseSpec.modifiers) addParameters(baseSpec.parameters) varargs(baseSpec.varargs) returns(baseSpec.returnType) } } /** * Represents a query statement prepared in Dao implementation. * * @param fields This map holds all the member fields necessary for this query. The key is the * corresponding parameter name in the defining query method. The value is a pair from the field * declaration to definition. * @param methodImpl The body of the query method implementation. */ data class PreparedStmtQuery( val fields: Map<String, Pair<FieldSpec, TypeSpec>>, val methodImpl: MethodSpec) { companion object { // The key to be used in `fields` where the method requires a field that is not // associated with any of its parameters const val NO_PARAM_FIELD = "-" } } private class InsertionMethodField(val entity: Entity, val onConflictText: String) : SharedFieldSpec( "insertionAdapterOf${Companion.typeNameToFieldName(entity.typeName)}", RoomTypeNames.INSERTION_ADAPTER) { override fun getUniqueKey(): String { return "${entity.typeName} $onConflictText" } override fun prepare(writer: ClassWriter, builder: FieldSpec.Builder) { builder.addModifiers(FINAL, PRIVATE) } } class DeleteOrUpdateAdapterField(val entity: Entity, val methodPrefix: String) : SharedFieldSpec( "${methodPrefix}AdapterOf${Companion.typeNameToFieldName(entity.typeName)}", RoomTypeNames.DELETE_OR_UPDATE_ADAPTER) { override fun prepare(writer: ClassWriter, builder: FieldSpec.Builder) { builder.addModifiers(PRIVATE, FINAL) } override fun getUniqueKey(): String { return entity.typeName.toString() + methodPrefix } } class PreparedStatementField(val method: QueryMethod) : SharedFieldSpec( "preparedStmtOf${method.name.capitalize()}", RoomTypeNames.SHARED_SQLITE_STMT) { override fun prepare(writer: ClassWriter, builder: FieldSpec.Builder) { builder.addModifiers(PRIVATE, FINAL) } override fun getUniqueKey(): String { return method.query.original } } }
apache-2.0
f88902953ca49499fec2e5545ca8d015
40.766942
100
0.581978
5.383255
false
false
false
false
kvnxiao/meirei
meirei-core/src/main/kotlin/com/github/kvnxiao/discord/meirei/command/database/CommandRegistryImpl.kt
1
8393
/* * 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.command.database import com.github.kvnxiao.discord.meirei.Meirei import com.github.kvnxiao.discord.meirei.command.CommandDefaults import com.github.kvnxiao.discord.meirei.command.CommandPackage import com.github.kvnxiao.discord.meirei.command.CommandProperties import com.github.kvnxiao.discord.meirei.command.DiscordCommand import com.github.kvnxiao.discord.meirei.permission.PermissionProperties import com.github.kvnxiao.discord.meirei.utility.CommandAlias import com.github.kvnxiao.discord.meirei.utility.CommandId class CommandRegistryImpl : CommandRegistry() { // Map for command executors private val idExecutorMap: MutableMap<CommandId, DiscordCommand> = mutableMapOf() private val aliasIdMap: MutableMap<CommandAlias, CommandId> = mutableMapOf() // Map for command properties private val idPropertiesMap: MutableMap<CommandId, CommandProperties> = mutableMapOf() // Map for permission properties private val idPermissionsMap: MutableMap<CommandId, PermissionProperties> = mutableMapOf() // Disabled commands private val disabledCommands: MutableSet<CommandId> = mutableSetOf() private val parentIdSubCommandsMap: MutableMap<CommandId, SubCommandRegistry> = mutableMapOf() override fun addCommand(command: DiscordCommand, commandProperties: CommandProperties, permissionProperties: PermissionProperties): Boolean { // Check for prefix + alias clash and unique id clashes if (!validateAliases(commandProperties.prefix, commandProperties.aliases)) { Meirei.LOGGER.warn { "Could not register command '$command' with prefix '${commandProperties.prefix}' due to it clashing with existing aliases." } return false } else if (idExecutorMap.containsKey(commandProperties.id)) { Meirei.LOGGER.warn { "Could not register command '$command' with prefix '${commandProperties.prefix}' due to the unique id already existing in the registry." } return false } // TODO: custom prefix validation // Insert command into alias->id map commandProperties.aliases.forEach { aliasIdMap[commandProperties.prefix + it] = commandProperties.id } // Insert command into id->executor map idExecutorMap[commandProperties.id] = command // Insert properties into id->prop map idPropertiesMap[commandProperties.id] = commandProperties idPermissionsMap[commandProperties.id] = permissionProperties Meirei.LOGGER.debug { "Registered command '${command.id}': prefix '${commandProperties.prefix}', aliases '${commandProperties.aliases}'" } return true } override fun deleteCommand(id: CommandId): Boolean { // Remove from aliases map val properties = idPropertiesMap[id] ?: return false properties.aliases.forEach { aliasIdMap.remove(properties.prefix + it) } // Remove from properties maps idPropertiesMap.remove(id) idPermissionsMap.remove(id) // Remove from executor map idExecutorMap.remove(id) return true } override fun addSubCommand(subCommand: DiscordCommand, commandProperties: CommandProperties, permissionProperties: PermissionProperties, parentId: CommandId): Boolean { // Fix commandProperties if it is missing parent-id link val properties = if (commandProperties.parentId == CommandDefaults.PARENT_ID) { CommandProperties( commandProperties.id, commandProperties.aliases, commandProperties.prefix, commandProperties.description, commandProperties.usage, commandProperties.execWithSubCommands, commandProperties.isDisabled, parentId ) } else { commandProperties } // Update sub-command registry val subCommandRegistry = parentIdSubCommandsMap.getOrPut(parentId, { SubCommandRegistryImpl(subCommand.id) }) val success = subCommandRegistry.addSubCommand(properties, parentId) return if (success) { // Add sub-command to main registry idExecutorMap[properties.id] = subCommand idPropertiesMap[properties.id] = properties idPermissionsMap[properties.id] = permissionProperties true } else { parentIdSubCommandsMap.remove(parentId) false } } override fun removeSubCommand(subCommandId: CommandId): Boolean { val subCommandProperties = idPropertiesMap[subCommandId] ?: return false if (subCommandProperties.parentId == CommandDefaults.PARENT_ID) return false val subCommandRegistry = parentIdSubCommandsMap[subCommandProperties.parentId] ?: return false val success = subCommandRegistry.removeSubCommand(subCommandProperties) if (success) { // Remove sub-command info from main registry idExecutorMap.remove(subCommandId) idPropertiesMap.remove(subCommandId) idPropertiesMap.remove(subCommandId) if (subCommandRegistry.getAllSubCommandIds().isEmpty()) { parentIdSubCommandsMap.remove(subCommandProperties.parentId) } return true } return false } override fun getCommandByAlias(alias: CommandAlias): DiscordCommand? { val id = aliasIdMap[alias] return if (id != null) idExecutorMap[id] else null } override fun getCommandById(id: CommandId): DiscordCommand? { return idExecutorMap[id] } override fun getPropertiesById(id: CommandId): CommandProperties? { return idPropertiesMap[id] } override fun getPermissionsById(id: CommandId): PermissionProperties? { return idPermissionsMap[id] } override fun getAllCommands(sortById: Boolean): List<CommandPackage> { return if (sortById) { idExecutorMap.values .filter { idPropertiesMap[it.id]!!.parentId == CommandDefaults.PARENT_ID } .map { CommandPackage(it, idPropertiesMap[it.id]!!, idPermissionsMap[it.id]!!) } .sortedBy { it.command.id } .toList() } else { idExecutorMap.values .filter { idPropertiesMap[it.id]!!.parentId == CommandDefaults.PARENT_ID } .map { CommandPackage(it, idPropertiesMap[it.id]!!, idPermissionsMap[it.id]!!) } .toList() } } override fun getAllCommandAliases(sorted: Boolean): List<String> { return if (sorted) aliasIdMap.keys.sorted().toList() else aliasIdMap.keys.toList() } override fun getSubCommandRegistry(parentId: String): SubCommandRegistry? { return parentIdSubCommandsMap[parentId] } override fun getSubCommandByAlias(alias: CommandAlias, parentId: CommandId): DiscordCommand? { val subCommandRegistry = getSubCommandRegistry(parentId) val subCommandId = subCommandRegistry?.getSubCommandIdByAlias(alias) return if (subCommandId != null) { getCommandById(subCommandId) } else { null } } override fun enableCommand(id: CommandId) { disabledCommands.remove(id) } override fun disableCommand(id: CommandId) { disabledCommands.add(id) } override fun hasSubCommands(parentId: String): Boolean { return parentIdSubCommandsMap[parentId]?.containsCommands() ?: false } private fun validateAliases(prefix: String, aliases: Set<String>): Boolean { return aliases.none { aliasIdMap.containsKey(prefix + it) } } }
apache-2.0
3a46e80b4a72838b19ed336b56001399
40.549505
172
0.682116
4.934156
false
false
false
false
oversecio/oversec_crypto
crypto/src/main/java/io/oversec/one/crypto/ui/EncryptionInfoActivity.kt
1
6538
package io.oversec.one.crypto.ui import android.app.Activity import android.app.ActivityOptions import android.content.Context import android.content.Intent import android.content.IntentSender import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import io.oversec.one.common.CoreContract import io.oversec.one.crypto.* import kotlinx.android.synthetic.main.activity_encryption_info.* import roboguice.util.Ln class EncryptionInfoActivity : AppCompatActivity() { private var mTdr: BaseDecryptResult? = null private var mOrigText: String? = null private lateinit var mFragment: AbstractTextEncryptionInfoFragment private lateinit var mEncryptionHandler: AbstractCryptoHandler override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //make sure to clear any pending decrypt tasks in the background, as they might interfere with pending intents generated by the user in the UI thread of this activity CryptoHandlerFacade.getInstance(this).clearDecryptQueue() setContentView(R.layout.activity_encryption_info) mOrigText = intent.getStringExtra(EXTRA_ENCRYPTED_TEXT) val mPackageName = intent.getStringExtra(EXTRA_PACKAGENAME) val aEncryptionHandler = CryptoHandlerFacade.getInstance(this).getCryptoHandler(mOrigText!!) if (aEncryptionHandler == null) { finish() return } aEncryptionHandler.let { mEncryptionHandler = it; mFragment = it.getTextEncryptionInfoFragment(mPackageName) } mFragment.setArgs(mPackageName) val manager = fragmentManager val transaction = manager.beginTransaction() transaction.replace(R.id.encryptionInfoFragment_container, mFragment, "Foo") transaction.commit() setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) } override fun onResumeFragments() { update(null) super.onResumeFragments() } fun update(actionIntent: Intent?) { if (actionIntent == null && mTdr != null) { return } var uix: UserInteractionRequiredException? = null try { mTdr = CryptoHandlerFacade.getInstance(this).decryptWithLock(mOrigText!!, actionIntent) } catch (e: UserInteractionRequiredException) { //we might be dealing with a external key, so try to use cached info first val atdr = CoreContract.instance!!.getFromEncryptionCache(mOrigText!!) if (atdr != null) { mTdr = atdr } else { uix = e } } mFragment.setData(this, mOrigText!!, mTdr, uix, mEncryptionHandler) } fun update(decryptResult: BaseDecryptResult) { mTdr = decryptResult mFragment.setData(this, mOrigText!!, decryptResult, null, mEncryptionHandler) } override fun onCreateOptionsMenu(menu: Menu): Boolean { return mFragment.onCreateOptionsMenu(this, menu) } override fun onPrepareOptionsMenu(menu: Menu): Boolean { mFragment.onPrepareOptionsMenu(menu) return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { finish() setupExitTransition() } else { mFragment.onOptionsItemSelected(this, item) } return super.onOptionsItemSelected(item) } override fun onBackPressed() { super.onBackPressed() setupExitTransition() } private fun setupExitTransition() { overridePendingTransition(0, R.anim.activity_out) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_CODE_DECRYPT) { if (resultCode == Activity.RESULT_OK) { //try to decrypt again val nodeOrigText = intent.getStringExtra(EXTRA_ENCRYPTED_TEXT) try { val dr = CryptoHandlerFacade.getInstance(this).decryptWithLock(nodeOrigText, data) CoreContract.instance!!.putInEncryptionCache(nodeOrigText, dr!!) update(dr) } catch (e: UserInteractionRequiredException) { try { startIntentSenderForResult( e.pendingIntent.intentSender, REQUEST_CODE_DECRYPT, null, 0, 0, 0 ) } catch (e1: IntentSender.SendIntentException) { // and now?? } } } else { Ln.w("user cancelled pendingintent activity") } } else if (requestCode == REQUEST_CODE_DOWNLOAD_MISSING_KEYS) { if (resultCode == Activity.RESULT_OK) { update(data) } else { Ln.w("user cancelled pendingintent activity") } } else if (requestCode == REQUEST_CODE_SHOW_SIGNATURE_KEY) { //nothing to be done } } companion object { private const val EXTRA_ENCRYPTED_TEXT = "enc_text" private const val EXTRA_PACKAGENAME = "packagename" const val REQUEST_CODE_DECRYPT = 5001 const val REQUEST_CODE_DOWNLOAD_MISSING_KEYS = 5002 const val REQUEST_CODE_SHOW_SIGNATURE_KEY = 5003 fun show(ctx: Context, packagename: String, encryptedText: String, source: View?) { val i = Intent() i.setClass(ctx, EncryptionInfoActivity::class.java) i.putExtra(EXTRA_ENCRYPTED_TEXT, encryptedText) i.putExtra(EXTRA_PACKAGENAME, packagename) i.flags = (Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) val opts = source?.let { ActivityOptions.makeScaleUpAnimation(it, 0, 0, 0, 0) } if (opts != null) { ctx.startActivity(i, opts.toBundle()) } else { ctx.startActivity(i) } } } }
gpl-3.0
ae735364eb4c012b371a9a87b06407f4
33.410526
174
0.609972
4.893713
false
false
false
false
misty000/kotlinfx
kotlinfx-core/src/main/kotlin/kotlinfx/builders/Transform.kt
2
1593
// http://docs.oracle.com/javase/8/javafx/api/javafx/scene/transform/package-summary.html package kotlinfx.builders // TODO: Affine-Scale public fun Shear( f: javafx.scene.transform.Shear.() -> Unit = {}): javafx.scene.transform.Shear { val x = javafx.scene.transform.Shear() x.f() return x } public fun Shear( x: Double, y: Double, f: javafx.scene.transform.Shear.() -> Unit = {}): javafx.scene.transform.Shear { val z = javafx.scene.transform.Shear(x, y) z.f() return z } public fun Shear( x: Double, y: Double, pivotX: Double, pivotY: Double, f: javafx.scene.transform.Shear.() -> Unit = {}): javafx.scene.transform.Shear { val z = javafx.scene.transform.Shear(x, y, pivotX, pivotY) z.f() return z } // For abstract javafx.scene.transform.Transform a builder does not make sense. // For javafx.scene.transform.TransformChangedEvent a builder does not make sense. public fun Translate( f: javafx.scene.transform.Translate.() -> Unit = {}): javafx.scene.transform.Translate { val x = javafx.scene.transform.Translate() x.f() return x } public fun Translate( x: Double, y: Double, f: javafx.scene.transform.Translate.() -> Unit = {}): javafx.scene.transform.Translate { val z = javafx.scene.transform.Translate(x, y) z.f() return z } public fun Translate( x: Double, y: Double, z: Double, f: javafx.scene.transform.Translate.() -> Unit = {}): javafx.scene.transform.Translate { val w = javafx.scene.transform.Translate(x, y, z) w.f() return w }
mit
5d2a97b06bd630ac0cf3019bdea3dfc2
23.136364
90
0.652228
3.31185
false
false
false
false
google/private-compute-libraries
javatests/com/google/android/libraries/pcc/chronicle/codegen/processor/TestUtils.kt
1
1928
/* * Copyright 2022 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.android.libraries.pcc.chronicle.codegen.processor import com.google.android.libraries.pcc.chronicle.storage.datacache.ManagedDataCache /** * Do a field-by-field comparison of two [ManagedDataCache] objects. We don't override equals(), * since this is only needed for testing. */ fun ManagedDataCache<*>.configEquals(other: Any?): Boolean { if (this === other) return true if (other !is ManagedDataCache<*>) return false val entityClassField = ManagedDataCache::class.java.getDeclaredField("entityClass") entityClassField.isAccessible = true if (entityClassField.get(this) != entityClassField.get(other)) return false val cacheField = ManagedDataCache::class.java.getDeclaredField("cache") cacheField.isAccessible = true if (cacheField.get(this) != cacheField.get(other)) return false val maxSizeField = ManagedDataCache::class.java.getDeclaredField("maxSize") maxSizeField.isAccessible = true if (maxSizeField.getInt(this) != maxSizeField.getInt(other)) return false val ttlField = ManagedDataCache::class.java.getDeclaredField("ttl") ttlField.isAccessible = true if (ttlField.get(this) != ttlField.get(other)) return false if (dataTypeDescriptor != other.dataTypeDescriptor) return false if (managementStrategy != other.managementStrategy) return false return true }
apache-2.0
2bbdf4d87ebac32d71504040cbfb9146
38.346939
96
0.760373
4.246696
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/TaskContainerExtensionsTest.kt
4
8061
package org.gradle.kotlin.dsl import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.inOrder import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import org.gradle.api.Action import org.gradle.api.DefaultTask import org.gradle.api.Task import org.gradle.api.reflect.TypeOf import org.gradle.api.tasks.Delete import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class TaskContainerExtensionsTest { @Test fun `can create tasks with injected constructor arguments`() { val task = mock<DefaultTask>() val tasks = mock<TaskContainer> { on { create("my", DefaultTask::class.java, "foo", "bar") } doReturn task } tasks.create<DefaultTask>("my", "foo", "bar") verify(tasks).create("my", DefaultTask::class.java, "foo", "bar") } @Test fun `can register tasks with injected constructor arguments`() { val taskProvider = mock<TaskProvider<Task>>() val tasks = mock<TaskContainer> { on { register("my", Task::class.java, "foo", "bar") } doReturn taskProvider } tasks.register<Task>("my", "foo", "bar") verify(tasks).register("my", Task::class.java, "foo", "bar") } @Test fun `val task by registering`() { val taskProvider = mock<TaskProvider<Task>>() val tasks = mock<TaskContainer> { on { register("clean") } doReturn taskProvider } tasks { val clean by registering inOrder(tasks, taskProvider) { verify(tasks).register("clean") verifyNoMoreInteractions() } assertInferredTypeOf( clean, typeOf<TaskProvider<Task>>() ) } } @Test fun `val task by registering { }`() { val taskProvider = mock<TaskProvider<Task>>() val tasks = mock<TaskContainer> { on { register(eq("clean"), any<Action<Task>>()) } doReturn taskProvider } tasks { val clean by registering { assertInferredTypeOf( this, typeOf<Task>() ) } inOrder(tasks, taskProvider) { verify(tasks).register(eq("clean"), any<Action<Task>>()) verifyNoMoreInteractions() } assertInferredTypeOf( clean, typeOf<TaskProvider<Task>>() ) } } @Test fun `val task by registering(type)`() { val taskProvider = mockTaskProviderFor(mock<Delete>()) val tasks = mock<TaskContainer> { on { register("clean", Delete::class.java) } doReturn taskProvider } tasks { val clean by registering(Delete::class) inOrder(tasks, taskProvider) { verify(tasks).register("clean", Delete::class.java) verifyNoMoreInteractions() } assertInferredTypeOf( clean, typeOf<TaskProvider<Delete>>() ) } } @Test fun `val task by registering(type) { }`() { val taskProvider = mockTaskProviderFor(mock<Delete>()) val tasks = mock<TaskContainer> { onRegisterWithAction("clean", Delete::class, taskProvider) } tasks { val clean by registering(Delete::class) { assertInferredTypeOf( this, typeOf<Delete>() ) } inOrder(tasks) { verify(tasks).register(eq("clean"), eq(Delete::class.java), any<Action<Delete>>()) verifyNoMoreInteractions() } assertInferredTypeOf( clean, typeOf<TaskProvider<Delete>>() ) } } @Test fun `val task by existing { }`() { // given: val taskProvider = mockTaskProviderFor(mock<Task>()) val tasks = mock<TaskContainer> { on { named("clean") } doReturn taskProvider } // then: tasks { // invoke syntax val clean by existing { assertInferredTypeOf( this, typeOf<Task>() ) } inOrder(container, taskProvider) { verify(container).named("clean") verify(taskProvider).configure(any<Action<Task>>()) verifyNoMoreInteractions() } assertInferredTypeOf( clean, typeOf<TaskProvider<Task>>() ) } tasks.apply { // regular syntax val clean by existing { } assertInferredTypeOf( clean, typeOf<TaskProvider<Task>>() ) } } @Test fun `val task by existing(type)`() { // given: val task = mock<Delete>() val taskProvider = mockTaskProviderFor(task) val tasks = mock<TaskContainer> { on { named("clean", Delete::class.java) } doReturn taskProvider } // then: tasks { // invoke syntax val clean by existing(Delete::class) inOrder(container, taskProvider) { verify(container).named("clean", Delete::class.java) verifyNoMoreInteractions() } assertInferredTypeOf( clean, typeOf<TaskProvider<Delete>>() ) } tasks.apply { // regular syntax val clean by existing(Delete::class) assertInferredTypeOf( clean, typeOf<TaskProvider<Delete>>() ) } } @Test fun `task accessors can be made available via existing delegate provider`() { // given: val task = mock<Delete>() val taskProvider = mockTaskProviderFor(task) val tasks = mock<TaskContainer> { @Suppress("unchecked_cast") on { named("clean") }.thenReturn(taskProvider as TaskProvider<Task>) on { named("clean", Delete::class.java) }.thenReturn(taskProvider) } // when: tasks { assertInferredTypeOf(this, typeOf<TaskContainerScope>()) val clean by existing assertInferredTypeOf(clean, typeOf<TaskProvider<Task>>()) clean { // configure assertInferredTypeOf(this, typeOf<Task>()) } existing.clean { // configure assertInferredTypeOf(this, typeOf<Delete>()) } } // then: inOrder(tasks, taskProvider, task) { verify(tasks, times(1)).named("clean") verify(taskProvider, times(1)).configure(any()) verify(tasks, times(1)).named("clean", Delete::class.java) verify(taskProvider, times(1)).configure(any()) verifyNoMoreInteractions() } } // Hypothetical task accessor private val ExistingDomainObjectDelegateProvider<out TaskContainer>.clean: TaskProvider<Delete> get() = delegateProvider.named<Delete>("clean") } internal fun <T : Task> mockTaskProviderFor(task: T): TaskProvider<T> = mock { on { get() } doReturn task on { configure(any()) } doAnswer { it.getArgument<Action<T>>(0).execute(task) } } internal inline fun <reified T> assertInferredTypeOf(@Suppress("unused_parameter") value: T, expectedType: TypeOf<T>) { assertThat(typeOf<T>(), equalTo(expectedType)) }
apache-2.0
a11f170691731a2421fcd4a30e74ec38
26.233108
110
0.543605
4.909257
false
false
false
false
kamgurgul/cpu-info
app/src/main/java/com/kgurgul/cpuinfo/domain/Interactor.kt
1
1565
package com.kgurgul.cpuinfo.domain import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext interface Interactor { val dispatcher: CoroutineDispatcher } abstract class ImmutableInteractor<P : Any, T> : Interactor { protected abstract fun createObservable(params: P): Flow<T> fun observe(params: P): Flow<T> = createObservable(params).flowOn(dispatcher) } abstract class MutableInteractor<P : Any, T> : Interactor { private val sharedFlow = MutableSharedFlow<P>(replay = 1) operator fun invoke(params: P) = sharedFlow.tryEmit(params) protected abstract fun createObservable(params: P): Flow<T> fun observe(): Flow<T> = sharedFlow .flatMapLatest { createObservable(it).flowOn(dispatcher) } } abstract class ResultInteractor<in P, R> : Interactor { suspend operator fun invoke(params: P): R { return withContext(dispatcher) { doWork(params) } } protected abstract suspend fun doWork(params: P): R } fun <T> ImmutableInteractor<Unit, T>.observe() = observe(Unit) operator fun <T> MutableInteractor<Unit, T>.invoke() = invoke(Unit) fun <I : MutableInteractor<P, T>, P, T> CoroutineScope.launchObserve( interactor: I, f: suspend (Flow<T>) -> Unit ) = launch(interactor.dispatcher) { f(interactor.observe()) }
apache-2.0
d99ec8de8acab9159597610986e0bc84
29.096154
81
0.739936
4.107612
false
false
false
false
VerifAPS/verifaps-lib
geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/apps/api.kt
1
792
package edu.kit.iti.formal.automation.testtables.apps import com.github.ajalt.clikt.core.CliktCommand /** * * @author Alexander Weigl * @version 1 (14.12.18) */ object Api { @JvmStatic fun main(args: Array<String>) { ApiApp().main(args) } } class ApiApp : CliktCommand(name = "ttapi") { val apps = HashMap<String, CliktCommand>() val reader = System.`in`.bufferedReader() val writer = System.`out`.bufferedWriter() override fun run() { do { val line= reader.readLine().split("[ \t]") val cmd = line[0] val args = line.drop(1) when (line[0]) { "cliFormat" -> PrinterApp().main(args) "gtt" -> GetetaApp().main(args) } } while (true) } }
gpl-3.0
7d28f0634f2918e9975d0e6ca9ecbf5e
22.294118
54
0.551768
3.64977
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/series/HighSeriesOf19Statistic.kt
1
956
package ca.josephroque.bowlingcompanion.statistics.impl.series import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator /** * Copyright (C) 2018 Joseph Roque * * Highest series of 19 games. */ class HighSeriesOf19Statistic(value: Int = 0) : HighSeriesStatistic(value) { // MARK: Overrides override val seriesSize = 19 override val titleId = Id override val id = Id.toLong() // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::HighSeriesOf19Statistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_high_series_of_19 } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(value = p.readInt()) }
mit
0c41f8868f8343ab5b5ce342932f7c1c
25.555556
76
0.687238
4.267857
false
false
false
false
Fondesa/RecyclerViewDivider
recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/BaseDividerItemDecoration.kt
1
8345
/* * Copyright (c) 2020 Giorgio Antonioli * * 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.fondesa.recyclerviewdivider import android.graphics.Canvas import android.graphics.Rect import android.view.View import androidx.annotation.VisibleForTesting import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.markItemDecorationsDirty /** * Base implementation of [RecyclerView.ItemDecoration] which provides some utilities methods. * It also provides different implementations of [getItemOffsets] and [onDraw]. * * @param asSpace true if the divider should behave as a space. */ public abstract class BaseDividerItemDecoration( @VisibleForTesting internal val asSpace: Boolean ) : RecyclerView.ItemDecoration() { private val attachStateListenerHolders = mutableMapOf<RecyclerView, View.OnAttachStateChangeListener>() private val observerHolders = mutableMapOf<RecyclerView.Adapter<*>, RecyclerView.AdapterDataObserver>() /** * Adds this decoration to the given [RecyclerView]. * If this decoration was already added to the given [RecyclerView], it will be removed first. * * @param recyclerView the [RecyclerView] which will add this [RecyclerView.ItemDecoration]. */ public fun addTo(recyclerView: RecyclerView) { removeFrom(recyclerView) recyclerView.addItemDecoration(this) } /** * Removes this decoration from the given [RecyclerView]. * * @param recyclerView the [RecyclerView] which will remove this [RecyclerView.ItemDecoration]. */ public fun removeFrom(recyclerView: RecyclerView) { recyclerView.removeItemDecoration(this) } /** * Variation of [RecyclerView.ItemDecoration.getItemOffsets] which validates the [RecyclerView] before being notified. * * @param layoutManager the [RecyclerView.LayoutManager] attached to the [RecyclerView]. * @param outRect the [Rect] on which the offsets should be set. * @param itemView the [View] of the cell which needs to get its offsets. * @param itemCount the number of items in the adapter attached to the [RecyclerView]. * @param itemIndex the index of the cell which needs to get its offsets. * @see [RecyclerView.ItemDecoration.getItemOffsets]. */ protected abstract fun getItemOffsets( layoutManager: RecyclerView.LayoutManager, outRect: Rect, itemView: View, itemCount: Int, itemIndex: Int ) /** * Variation of [RecyclerView.ItemDecoration.onDraw] which validates the [RecyclerView] before being notified. * This method will be invoked only if the divider shouldn't behave as a space since, if it's a space, it shouldn't draw anything. * * @param canvas the [Canvas] on which the divider should be drawn. * @param recyclerView the [RecyclerView] which has added this decoration. * @param layoutManager the [RecyclerView.LayoutManager] attached to the [RecyclerView]. * @param itemCount the number of items in the adapter attached to the [RecyclerView]. * @see [RecyclerView.ItemDecoration.onDraw]. */ protected abstract fun onDraw(canvas: Canvas, recyclerView: RecyclerView, layoutManager: RecyclerView.LayoutManager, itemCount: Int) /** * Callback invoked when the the adapter's data changes. * Specifically, this callback is invoked every time a method of [RecyclerView.AdapterDataObserver] is invoked. */ protected open fun onDataChanged() { // In this way, getItemOffsets() will be executed also on the previous items. // Do not call invalidateItemDecorations() since we don't need requestLayout(). attachStateListenerHolders.keys.forEach { recyclerView -> recyclerView.markItemDecorationsDirty() } } final override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { parent.setupAttachStateListener() // Avoids to call super.getItemOffsets to avoid to pre-compute the layout position of the item. // To avoid to depend on the implementations of this class, set the offsets to zero by default. outRect.setEmpty() val adapter = parent.adapter ?: return adapter.setupDataObserver() val itemCount = adapter.itemCount if (itemCount == 0) return val layoutManager = parent.layoutManager ?: return val itemIndex = parent.getChildAdapterPositionOrNull(view, itemCount) ?: return getItemOffsets(layoutManager = layoutManager, outRect = outRect, itemView = view, itemCount = itemCount, itemIndex = itemIndex) } final override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { super.onDraw(c, parent, state) parent.setupAttachStateListener() // The divider shouldn't be drawn if it's configured as a space. if (asSpace) return val adapter = parent.adapter ?: return adapter.setupDataObserver() val itemCount = adapter.itemCount if (itemCount == 0) return val layoutManager = parent.layoutManager ?: return onDraw(canvas = c, recyclerView = parent, layoutManager = layoutManager, itemCount = itemCount) } @Suppress("DEPRECATION") final override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) { super.getItemOffsets(outRect, itemPosition, parent) } @Suppress("DEPRECATION") final override fun onDraw(c: Canvas, parent: RecyclerView) { super.onDraw(c, parent) } private fun RecyclerView.setupAttachStateListener() { // If the listener is already attached, we shouldn't add a new listener. if (this in attachStateListenerHolders) return val listener = OnRecyclerViewDetachedFromWindow(::destroy) attachStateListenerHolders[this] = listener addOnAttachStateChangeListener(listener) } private fun RecyclerView.Adapter<*>.setupDataObserver() { // If the observer is already attached, we shouldn't add a new listener. if (this in observerHolders) return clearObserverHolder() val observer = DataObserver(::onDataChanged) observerHolders[this] = observer registerAdapterDataObserver(observer) } private fun clearAttachStateListenerHolders() { attachStateListenerHolders.forEach { (recyclerView, listener) -> recyclerView.removeOnAttachStateChangeListener(listener) } attachStateListenerHolders.clear() } private fun clearObserverHolder() { observerHolders.forEach { (adapter, observer) -> adapter.unregisterAdapterDataObserver(observer) } observerHolders.clear() } private fun destroy() { clearObserverHolder() clearAttachStateListenerHolders() } private class DataObserver(private val onDataChanged: () -> Unit) : RecyclerView.AdapterDataObserver() { override fun onChanged() = onDataChanged() override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) = onDataChanged() override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) = onDataChanged() override fun onItemRangeInserted(positionStart: Int, itemCount: Int) = onDataChanged() override fun onItemRangeChanged(positionStart: Int, itemCount: Int) = onDataChanged() override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) = onDataChanged() } private class OnRecyclerViewDetachedFromWindow(private val onDetach: () -> Unit) : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) = Unit override fun onViewDetachedFromWindow(v: View) = onDetach() } }
apache-2.0
7615b84cafa81bf018fa17f780af91d6
43.865591
136
0.712043
5.163985
false
false
false
false
pratikbutani/AppIntro
appintro/src/main/java/com/github/paolorotolo/appintro/internal/viewpager/ViewPagerTransformer.kt
2
3684
package com.github.paolorotolo.appintro.internal.viewpager import android.view.View import androidx.viewpager.widget.ViewPager private const val MIN_SCALE_DEPTH = 0.75f private const val MIN_SCALE_ZOOM = 0.85f private const val MIN_ALPHA_ZOOM = 0.5f private const val SCALE_FACTOR_SLIDE = 0.85f private const val MIN_ALPHA_SLIDE = 0.35f private const val FLOW_ROTATION_ANGLE = -30f internal class ViewPagerTransformer( private val transformType: TransformType ) : ViewPager.PageTransformer { override fun transformPage(page: View, position: Float) { when (transformType) { TransformType.FLOW -> { page.rotationY = position * FLOW_ROTATION_ANGLE } TransformType.SLIDE_OVER -> transformSlideOver(position, page) TransformType.DEPTH -> transformDepth(position, page) TransformType.ZOOM -> transformZoom(position, page) TransformType.FADE -> transformFade(position, page) } } private fun transformFade(position: Float, page: View) { if (position <= -1.0f || position >= 1.0f) { page.translationX = page.width.toFloat() page.alpha = 0.0f page.isClickable = false } else if (position == 0.0f) { page.translationX = 0.0f page.alpha = 1.0f page.isClickable = true } else { // position is between -1.0F & 0.0F OR 0.0F & 1.0F page.translationX = page.width * -position page.alpha = 1.0f - Math.abs(position) } } private fun transformZoom(position: Float, page: View) { if (position >= -1 && position <= 1) { page.scaleXY = Math.max(MIN_SCALE_ZOOM, 1 - Math.abs(position)) page.alpha = MIN_ALPHA_ZOOM + (page.scaleXY - MIN_SCALE_ZOOM) / (1 - MIN_SCALE_ZOOM) * (1 - MIN_ALPHA_ZOOM) val vMargin = page.height * (1 - page.scaleXY) / 2 val hMargin = page.width * (1 - page.scaleXY) / 2 if (position < 0) { page.translationX = hMargin - vMargin / 2 } else { page.translationX = -hMargin + vMargin / 2 } } else { page.transformDefaults() } } private fun transformDepth(position: Float, page: View) { if (position > 0 && position < 1) { // moving to the right page.alpha = 1 - position page.scaleXY = MIN_SCALE_DEPTH + (1 - MIN_SCALE_DEPTH) * (1 - Math.abs(position)) page.translationX = page.width * -position } else { page.transformDefaults() } } private fun transformSlideOver(position: Float, page: View) { if (position < 0 && position > -1) { // this is the page to the left page.scaleXY = Math.abs(Math.abs(position) - 1) * (1.0f - SCALE_FACTOR_SLIDE) + SCALE_FACTOR_SLIDE page.alpha = Math.max(MIN_ALPHA_SLIDE, 1 - Math.abs(position)) val pageWidth = page.width val translateValue = position * -pageWidth if (translateValue > -pageWidth) { page.translationX = translateValue } else { page.translationX = 0f } } else { page.transformDefaults() } } } enum class TransformType { FLOW, DEPTH, ZOOM, SLIDE_OVER, FADE } private fun View.transformDefaults() { this.alpha = 1f this.scaleXY = 1f this.translationX = 0f } private var View.scaleXY: Float get() = this.scaleX set(value) { this.scaleX = value this.scaleY = value }
apache-2.0
83299b914c40722131d652526484f3fe
32.189189
110
0.572204
3.89018
false
false
false
false
LorittaBot/Loritta
web/spicy-morenitta/src/main/kotlin/jsheaders/jquery.kt
1
55741
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS") import org.w3c.dom.* import org.w3c.dom.events.Event import org.w3c.xhr.XMLHttpRequest import kotlin.js.* external interface JQueryAjaxSettings { var accepts: Any? get() = definedExternally; set(value) = definedExternally var async: Boolean? get() = definedExternally; set(value) = definedExternally val beforeSend: ((jqXHR: JQueryXHR, settings: JQueryAjaxSettings) -> Any)? get() = definedExternally var cache: Boolean? get() = definedExternally; set(value) = definedExternally val complete: ((jqXHR: JQueryXHR, textStatus: String) -> Any)? get() = definedExternally var contents: Json? get() = definedExternally; set(value) = definedExternally var contentType: Any? get() = definedExternally; set(value) = definedExternally var context: Any? get() = definedExternally; set(value) = definedExternally var converters: Json? get() = definedExternally; set(value) = definedExternally var crossDomain: Boolean? get() = definedExternally; set(value) = definedExternally var data: Any? get() = definedExternally; set(value) = definedExternally val dataFilter: ((data: Any, ty: Any) -> Any)? get() = definedExternally var dataType: String? get() = definedExternally; set(value) = definedExternally val error: ((jqXHR: JQueryXHR, textStatus: String, errorThrown: String) -> Any)? get() = definedExternally var global: Boolean? get() = definedExternally; set(value) = definedExternally var headers: Json? get() = definedExternally; set(value) = definedExternally var ifModified: Boolean? get() = definedExternally; set(value) = definedExternally var isLocal: Boolean? get() = definedExternally; set(value) = definedExternally var jsonp: Any? get() = definedExternally; set(value) = definedExternally var jsonpCallback: Any? get() = definedExternally; set(value) = definedExternally var method: String? get() = definedExternally; set(value) = definedExternally var mimeType: String? get() = definedExternally; set(value) = definedExternally var password: String? get() = definedExternally; set(value) = definedExternally var processData: Boolean? get() = definedExternally; set(value) = definedExternally var scriptCharset: String? get() = definedExternally; set(value) = definedExternally var statusCode: Json? get() = definedExternally; set(value) = definedExternally val success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Any)? get() = definedExternally var timeout: Number? get() = definedExternally; set(value) = definedExternally var traditional: Boolean? get() = definedExternally; set(value) = definedExternally var type: String? get() = definedExternally; set(value) = definedExternally var url: String? get() = definedExternally; set(value) = definedExternally var username: String? get() = definedExternally; set(value) = definedExternally var xhr: Any? get() = definedExternally; set(value) = definedExternally var xhrFields: Json? get() = definedExternally; set(value) = definedExternally } external interface JQueryXHR : XMLHttpRequest, JQueryPromise<Any> { override fun overrideMimeType(mimeType: String): Any fun abort(statusText: String? = definedExternally /* null */) fun <R> then(doneCallback: (data: Any, textStatus: String, jqXHR: JQueryXHR) -> dynamic /* R | JQueryPromise<R> */, failCallback: ((jqXHR: JQueryXHR, textStatus: String, errorThrown: Any) -> Unit)? = definedExternally /* null */): JQueryPromise<R> var responseJSON: Any? get() = definedExternally; set(value) = definedExternally fun error(xhr: JQueryXHR, textStatus: String, errorThrown: String) } external interface JQueryCallback { fun add(callbacks: Function<*>): JQueryCallback fun add(callbacks: Array<Function<*>>): JQueryCallback fun disable(): JQueryCallback fun disabled(): Boolean fun empty(): JQueryCallback fun fire(vararg arguments: Any): JQueryCallback fun fired(): Boolean fun fireWith(context: Any? = definedExternally /* null */, args: Array<Any>? = definedExternally /* null */): JQueryCallback fun has(callback: Function<*>): Boolean fun lock(): JQueryCallback fun locked(): Boolean fun remove(callbacks: Function<*>): JQueryCallback fun remove(callbacks: Array<Function<*>>): JQueryCallback } external interface JQueryGenericPromise<T> { fun <U> then(doneFilter: (value: T? /*= null*/, values: Any) -> dynamic /* U | JQueryPromise<U> */, failFilter: ((reasons: Any) -> Any)? = definedExternally /* null */, progressFilter: ((progression: Any) -> Any)? = definedExternally /* null */): JQueryPromise<U> fun then(doneFilter: (value: T? /*= null*/, values: Any) -> Unit, failFilter: ((reasons: Any) -> Any)? = definedExternally /* null */, progressFilter: ((progression: Any) -> Any)? = definedExternally /* null */): JQueryPromise<Unit> } external interface JQueryPromiseCallback<T> { @nativeInvoke operator fun invoke(value: T? = definedExternally /* null */, vararg args: Any) } external interface JQueryPromiseOperator<T, U> { @nativeInvoke operator fun invoke(callback1: JQueryPromiseCallback<T>, vararg callbacksN: JQueryPromiseCallback<Any>): JQueryPromise<U> @nativeInvoke operator fun invoke(callback1: JQueryPromiseCallback<T>, vararg callbacksN: Array<JQueryPromiseCallback<Any>>): JQueryPromise<U> @nativeInvoke operator fun invoke(callback1: Array<JQueryPromiseCallback<T>>, vararg callbacksN: JQueryPromiseCallback<Any>): JQueryPromise<U> @nativeInvoke operator fun invoke(callback1: Array<JQueryPromiseCallback<T>>, vararg callbacksN: Array<JQueryPromiseCallback<Any>>): JQueryPromise<U> } external interface JQueryPromise<T> : JQueryGenericPromise<T> { fun state(): String fun always(alwaysCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg alwaysCallbackN: JQueryPromiseCallback<Any>): JQueryPromise<T> fun always(alwaysCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg alwaysCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryPromise<T> fun always(alwaysCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg alwaysCallbackN: JQueryPromiseCallback<Any>): JQueryPromise<T> fun always(alwaysCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg alwaysCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryPromise<T> fun done(doneCallback1: JQueryPromiseCallback<T>? = definedExternally /* null */, vararg doneCallbackN: JQueryPromiseCallback<T>): JQueryPromise<T> fun done(doneCallback1: JQueryPromiseCallback<T>? = definedExternally /* null */, vararg doneCallbackN: Array<JQueryPromiseCallback<T>>): JQueryPromise<T> fun done(doneCallback1: Array<JQueryPromiseCallback<T>>? = definedExternally /* null */, vararg doneCallbackN: JQueryPromiseCallback<T>): JQueryPromise<T> fun done(doneCallback1: Array<JQueryPromiseCallback<T>>? = definedExternally /* null */, vararg doneCallbackN: Array<JQueryPromiseCallback<T>>): JQueryPromise<T> fun fail(failCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg failCallbackN: JQueryPromiseCallback<Any>): JQueryPromise<T> fun fail(failCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg failCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryPromise<T> fun fail(failCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg failCallbackN: JQueryPromiseCallback<Any>): JQueryPromise<T> fun fail(failCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg failCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryPromise<T> fun progress(progressCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg progressCallbackN: JQueryPromiseCallback<Any>): JQueryPromise<T> fun progress(progressCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg progressCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryPromise<T> fun progress(progressCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg progressCallbackN: JQueryPromiseCallback<Any>): JQueryPromise<T> fun progress(progressCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg progressCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryPromise<T> fun pipe(doneFilter: ((x: Any) -> Any)? = definedExternally /* null */, failFilter: ((x: Any) -> Any)? = definedExternally /* null */, progressFilter: ((x: Any) -> Any)? = definedExternally /* null */): JQueryPromise<Any> fun promise(target: Any? = definedExternally /* null */): JQueryPromise<T> } external interface JQueryDeferred<T> : JQueryGenericPromise<T> { fun state(): String fun always(alwaysCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg alwaysCallbackN: JQueryPromiseCallback<Any>): JQueryDeferred<T> fun always(alwaysCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg alwaysCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryDeferred<T> fun always(alwaysCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg alwaysCallbackN: JQueryPromiseCallback<Any>): JQueryDeferred<T> fun always(alwaysCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg alwaysCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryDeferred<T> fun done(doneCallback1: JQueryPromiseCallback<T>? = definedExternally /* null */, vararg doneCallbackN: JQueryPromiseCallback<T>): JQueryDeferred<T> fun done(doneCallback1: JQueryPromiseCallback<T>? = definedExternally /* null */, vararg doneCallbackN: Array<JQueryPromiseCallback<T>>): JQueryDeferred<T> fun done(doneCallback1: Array<JQueryPromiseCallback<T>>? = definedExternally /* null */, vararg doneCallbackN: JQueryPromiseCallback<T>): JQueryDeferred<T> fun done(doneCallback1: Array<JQueryPromiseCallback<T>>? = definedExternally /* null */, vararg doneCallbackN: Array<JQueryPromiseCallback<T>>): JQueryDeferred<T> fun fail(failCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg failCallbackN: JQueryPromiseCallback<Any>): JQueryDeferred<T> fun fail(failCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg failCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryDeferred<T> fun fail(failCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg failCallbackN: JQueryPromiseCallback<Any>): JQueryDeferred<T> fun fail(failCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg failCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryDeferred<T> fun progress(progressCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg progressCallbackN: JQueryPromiseCallback<Any>): JQueryDeferred<T> fun progress(progressCallback1: JQueryPromiseCallback<Any>? = definedExternally /* null */, vararg progressCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryDeferred<T> fun progress(progressCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg progressCallbackN: JQueryPromiseCallback<Any>): JQueryDeferred<T> fun progress(progressCallback1: Array<JQueryPromiseCallback<Any>>? = definedExternally /* null */, vararg progressCallbackN: Array<JQueryPromiseCallback<Any>>): JQueryDeferred<T> fun notify(value: Any? = definedExternally /* null */, vararg args: Any): JQueryDeferred<T> fun notifyWith(context: Any, args: Array<Any>? = definedExternally /* null */): JQueryDeferred<T> fun reject(value: Any? = definedExternally /* null */, vararg args: Any): JQueryDeferred<T> fun rejectWith(context: Any, args: Array<Any>? = definedExternally /* null */): JQueryDeferred<T> fun resolve(value: T? = definedExternally /* null */, vararg args: Any): JQueryDeferred<T> fun resolveWith(context: Any, args: Array<T>? = definedExternally /* null */): JQueryDeferred<T> fun promise(target: Any? = definedExternally /* null */): JQueryPromise<T> fun pipe(doneFilter: ((x: Any) -> Any)? = definedExternally /* null */, failFilter: ((x: Any) -> Any)? = definedExternally /* null */, progressFilter: ((x: Any) -> Any)? = definedExternally /* null */): JQueryPromise<Any> } external interface BaseJQueryEventObject : Event { override var currentTarget: Element var data: Any var delegateTarget: Element fun isDefaultPrevented(): Boolean fun isImmediatePropagationStopped(): Boolean fun isPropagationStopped(): Boolean var namespace: String var originalEvent: Event override fun preventDefault(): Any var relatedTarget: Element var result: Any override fun stopImmediatePropagation() override fun stopPropagation() override var target: Element var pageX: Number var pageY: Number var which: Number var metaKey: Boolean } external interface JQueryInputEventObject : BaseJQueryEventObject { var altKey: Boolean var ctrlKey: Boolean override var metaKey: Boolean var shiftKey: Boolean } external interface JQueryMouseEventObject : JQueryInputEventObject { var button: Number var clientX: Number var clientY: Number var offsetX: Number var offsetY: Number override var pageX: Number override var pageY: Number var screenX: Number var screenY: Number } external interface JQueryKeyEventObject : JQueryInputEventObject { var char: Any var charCode: Number var key: Any var keyCode: Number } external interface JQueryEventObject : BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject external interface JQuerySupport { var ajax: Boolean? get() = definedExternally; set(value) = definedExternally var boxModel: Boolean? get() = definedExternally; set(value) = definedExternally var changeBubbles: Boolean? get() = definedExternally; set(value) = definedExternally var checkClone: Boolean? get() = definedExternally; set(value) = definedExternally var checkOn: Boolean? get() = definedExternally; set(value) = definedExternally var cors: Boolean? get() = definedExternally; set(value) = definedExternally var cssFloat: Boolean? get() = definedExternally; set(value) = definedExternally var hrefNormalized: Boolean? get() = definedExternally; set(value) = definedExternally var htmlSerialize: Boolean? get() = definedExternally; set(value) = definedExternally var leadingWhitespace: Boolean? get() = definedExternally; set(value) = definedExternally var noCloneChecked: Boolean? get() = definedExternally; set(value) = definedExternally var noCloneEvent: Boolean? get() = definedExternally; set(value) = definedExternally var opacity: Boolean? get() = definedExternally; set(value) = definedExternally var optDisabled: Boolean? get() = definedExternally; set(value) = definedExternally var optSelected: Boolean? get() = definedExternally; set(value) = definedExternally val scriptEval: (() -> Boolean)? get() = definedExternally var style: Boolean? get() = definedExternally; set(value) = definedExternally var submitBubbles: Boolean? get() = definedExternally; set(value) = definedExternally var tbody: Boolean? get() = definedExternally; set(value) = definedExternally } external interface JQueryParam { @nativeInvoke operator fun invoke(obj: Any): String @nativeInvoke operator fun invoke(obj: Any, traditional: Boolean): String } external interface JQueryEventConstructor { @nativeInvoke operator fun invoke(name: String, eventProperties: Any? = definedExternally /* null */): JQueryEventObject } external interface JQueryCoordinates { var left: Number var top: Number } external interface cssPropertySetter { @nativeInvoke operator fun invoke(index: Number, value: String? = definedExternally /* null */): dynamic /* String | Number */ } external interface JQueryCssProperties { @nativeGetter operator fun get(propertyName: String): dynamic /* String | Number | cssPropertySetter */ @nativeSetter operator fun set(propertyName: String, value: String) @nativeSetter operator fun set(propertyName: String, value: Number) @nativeSetter operator fun set(propertyName: String, value: cssPropertySetter) } external interface JQuerySerializeArrayElement { var name: String var value: String } external interface JQueryAnimationOptions { var duration: Any? get() = definedExternally; set(value) = definedExternally var easing: String? get() = definedExternally; set(value) = definedExternally var complete: Function<*>? get() = definedExternally; set(value) = definedExternally var step: ((now: Number, tween: Any) -> Any)? get() = definedExternally; set(value) = definedExternally var progress: ((animation: JQueryPromise<Any>, progress: Number, remainingMs: Number) -> Any)? get() = definedExternally; set(value) = definedExternally var start: ((animation: JQueryPromise<Any>) -> Any)? get() = definedExternally; set(value) = definedExternally var done: ((animation: JQueryPromise<Any>, jumpedToEnd: Boolean) -> Any)? get() = definedExternally; set(value) = definedExternally var fail: ((animation: JQueryPromise<Any>, jumpedToEnd: Boolean) -> Any)? get() = definedExternally; set(value) = definedExternally var always: ((animation: JQueryPromise<Any>, jumpedToEnd: Boolean) -> Any)? get() = definedExternally; set(value) = definedExternally var queue: Any? get() = definedExternally; set(value) = definedExternally var specialEasing: Any? get() = definedExternally; set(value) = definedExternally } external interface JQueryEasingFunction { @nativeInvoke operator fun invoke(percent: Number): Number } external interface JQueryEasingFunctions { @nativeGetter operator fun get(name: String): JQueryEasingFunction? @nativeSetter operator fun set(name: String, value: JQueryEasingFunction) var linear: JQueryEasingFunction var swing: JQueryEasingFunction } external interface `T$0` { var slow: Number var fast: Number } external interface `T$1` { var tick: () -> Unit var interval: Number var stop: () -> Unit var speeds: `T$0` var off: Boolean var step: Any } external interface JQueryStatic { fun ajax(settings: JQueryAjaxSettings): JQueryXHR fun ajax(url: String, settings: JQueryAjaxSettings? = definedExternally /* null */): JQueryXHR fun ajaxPrefilter(dataTypes: String, handler: (opts: Any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) -> Any) fun ajaxPrefilter(handler: (opts: Any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) -> Any) fun ajaxTransport(dataType: String, handler: (opts: Any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) -> Any) var ajaxSettings: JQueryAjaxSettings fun ajaxSetup(options: JQueryAjaxSettings) fun get(url: String, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Unit)? = definedExternally /* null */, dataType: String? = definedExternally /* null */): JQueryXHR fun get(url: String, data: Any? = definedExternally /* null */, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Unit)? = definedExternally /* null */, dataType: String? = definedExternally /* null */): JQueryXHR fun get(url: String, data: String? = definedExternally /* null */, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Unit)? = definedExternally /* null */, dataType: String? = definedExternally /* null */): JQueryXHR fun get(settings: JQueryAjaxSettings): JQueryXHR fun getJSON(url: String, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Unit)? = definedExternally /* null */): JQueryXHR fun getJSON(url: String, data: Any? = definedExternally /* null */, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Unit)? = definedExternally /* null */): JQueryXHR fun getJSON(url: String, data: String? = definedExternally /* null */, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Unit)? = definedExternally /* null */): JQueryXHR fun getScript(url: String, success: ((script: String, textStatus: String, jqXHR: JQueryXHR) -> Any)? = definedExternally /* null */): JQueryXHR var param: JQueryParam fun post(url: String, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Any)? = definedExternally /* null */, dataType: String? = definedExternally /* null */): JQueryXHR fun post(url: String, data: Any? = definedExternally /* null */, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Any)? = definedExternally /* null */, dataType: String? = definedExternally /* null */): JQueryXHR fun post(url: String, data: String? = definedExternally /* null */, success: ((data: Any, textStatus: String, jqXHR: JQueryXHR) -> Any)? = definedExternally /* null */, dataType: String? = definedExternally /* null */): JQueryXHR fun post(settings: JQueryAjaxSettings): JQueryXHR fun Callbacks(flags: String? = definedExternally /* null */): JQueryCallback fun holdReady(hold: Boolean) @nativeInvoke operator fun invoke(selector: String, context: Element? = definedExternally /* null */): JQuery @nativeInvoke operator fun invoke(selector: String, context: JQuery? = definedExternally /* null */): JQuery @nativeInvoke operator fun invoke(element: Element): JQuery @nativeInvoke operator fun invoke(elementArray: Array<Element>): JQuery @nativeInvoke operator fun invoke(callback: (jQueryAlias: JQueryStatic? /*= null*/) -> Any): JQuery @nativeInvoke operator fun invoke(`object`: Any): JQuery @nativeInvoke operator fun invoke(`object`: JQuery): JQuery @nativeInvoke operator fun invoke(): JQuery @nativeInvoke operator fun invoke(html: String, ownerDocument: Document? = definedExternally /* null */): JQuery @nativeInvoke operator fun invoke(html: String, attributes: Any): JQuery fun noConflict(removeAll: Boolean? = definedExternally /* null */): JQueryStatic fun <T> `when`(vararg deferreds: T): JQueryPromise<T> fun <T> `when`(vararg deferreds: JQueryPromise<T>): JQueryPromise<T> var cssHooks: Json var cssNumber: Any fun <T> data(element: Element, key: String, value: T): T fun data(element: Element, key: String): Any fun data(element: Element): Any fun dequeue(element: Element, queueName: String? = definedExternally /* null */) fun hasData(element: Element): Boolean fun queue(element: Element, queueName: String? = definedExternally /* null */): Array<Any> fun queue(element: Element, queueName: String, newQueue: Array<Function<*>>): JQuery fun queue(element: Element, queueName: String, callback: Function<*>): JQuery fun removeData(element: Element, name: String? = definedExternally /* null */): JQuery fun <T> Deferred(beforeStart: ((deferred: JQueryDeferred<T>) -> Any)? = definedExternally /* null */): JQueryDeferred<T> var easing: JQueryEasingFunctions var fx: `T$1` fun proxy(func: (args: Any) -> Any, context: Any, vararg additionalArguments: Any): Any fun proxy(context: Any, name: String, vararg additionalArguments: Any): Any var Event: JQueryEventConstructor fun error(message: Any): JQuery var expr: Any var fn: JQuery var isReady: Boolean var support: JQuerySupport fun contains(container: Element, contained: Element): Boolean fun <T> each(collection: Array<T>, callback: (indexInArray: Number, valueOfElement: T) -> dynamic /* Boolean | Unit */): Array<T> fun <T : Any> each(collection: T, callback: (keyInObject: String, valueOfElement: Any) -> dynamic /* Boolean | Unit */): T fun extend(target: Any, object1: Any? = definedExternally /* null */, vararg objectN: Any): Any fun extend(deep: Boolean, target: Any, object1: Any? = definedExternally /* null */, vararg objectN: Any): Any fun globalEval(code: String): Any fun <T> grep(array: Array<T>, func: (elementOfArray: T? /*= null*/, indexInArray: Number? /*= null*/) -> Boolean, invert: Boolean? = definedExternally /* null */): Array<T> fun <T> inArray(value: T, array: Array<T>, fromIndex: Number? = definedExternally /* null */): Number fun isArray(obj: Any): Boolean fun isEmptyObject(obj: Any): Boolean fun isFunction(obj: Any): Boolean fun isNumeric(value: Any): Boolean fun isPlainObject(obj: Any): Boolean fun isWindow(obj: Any): Boolean fun isXMLDoc(node: Node): Boolean fun makeArray(obj: Any): Array<Any> fun <T, U> map(array: Array<T>, callback: (elementOfArray: T? /*= null*/, indexInArray: Number? /*= null*/) -> U): Array<U> fun map(arrayOrObject: Any, callback: (value: Any? /*= null*/, indexOrKey: Any? /*= null*/) -> Any): Any fun <T> merge(first: Array<T>, second: Array<T>): Array<T> fun noop(): Any fun now(): Number fun parseJSON(json: String): Any fun parseXML(data: String): XMLDocument fun trim(str: String): String fun type(obj: Any): dynamic /* Any /* "array" */ | Any /* "boolean" */ | Any /* "date" */ | Any /* "error" */ | Any /* "function" */ | Any /* "null" */ | Any /* "number" */ | Any /* "object" */ | Any /* "regexp" */ | Any /* "string" */ | Any /* "symbol" */ | Any /* "undefined" */ */ fun <T : Element> unique(array: Array<T>): Array<T> fun parseHTML(data: String, context: HTMLElement? = definedExternally /* null */, keepScripts: Boolean? = definedExternally /* null */): Array<Any> fun parseHTML(data: String, context: Document? = definedExternally /* null */, keepScripts: Boolean? = definedExternally /* null */): Array<Any> } external interface `T$2` { @nativeGetter operator fun get(key: String): ((eventObject: JQueryEventObject, args: Any) -> Any)? @nativeSetter operator fun set(key: String, value: (eventObject: JQueryEventObject, args: Any) -> Any) } external interface `T$3` { @nativeGetter operator fun get(key: String): ((eventObject: JQueryEventObject, args: Any) -> Any)? @nativeSetter operator fun set(key: String, value: (eventObject: JQueryEventObject, args: Any) -> Any) } external interface `T$4` { @nativeGetter operator fun get(method: String): ((args: Any) -> Any)? @nativeSetter operator fun set(method: String, value: (args: Any) -> Any) } external interface JQuery { fun ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: Any) -> Any): JQuery fun ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: Any) -> Any): JQuery fun ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) -> Any): JQuery fun ajaxStart(handler: () -> Any): JQuery fun ajaxStop(handler: () -> Any): JQuery fun ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) -> Any): JQuery fun load(url: String, data: String? = definedExternally /* null */, complete: ((responseText: String, textStatus: String, XMLHttpRequest: XMLHttpRequest) -> Any)? = definedExternally /* null */): JQuery fun load(url: String, data: Any? = definedExternally /* null */, complete: ((responseText: String, textStatus: String, XMLHttpRequest: XMLHttpRequest) -> Any)? = definedExternally /* null */): JQuery fun serialize(): String fun serializeArray(): Array<JQuerySerializeArrayElement> fun addClass(className: String): JQuery fun addClass(func: (index: Number, className: String) -> String): JQuery fun addBack(selector: String? = definedExternally /* null */): JQuery fun attr(attributeName: String): String fun attr(attributeName: String, value: String?): JQuery fun attr(attributeName: String, value: Number): JQuery fun attr(attributeName: String, value: Nothing?): JQuery fun attr(attributeName: String, func: (index: Number, attr: String) -> dynamic /* String | Number */): JQuery fun attr(attributes: Any): JQuery fun hasClass(className: String): Boolean fun html(): String fun html(htmlString: String): JQuery fun html(func: (index: Number, oldhtml: String) -> String): JQuery fun prop(propertyName: String): Any fun prop(propertyName: String, value: String): JQuery fun prop(propertyName: String, value: Number): JQuery fun prop(propertyName: String, value: Boolean): JQuery fun prop(properties: Any): JQuery fun prop(propertyName: String, func: (index: Number, oldPropertyValue: Any) -> Any): JQuery fun removeAttr(attributeName: String): JQuery fun removeClass(className: String? = definedExternally /* null */): JQuery fun removeClass(func: (index: Number, className: String) -> String): JQuery fun removeProp(propertyName: String): JQuery fun toggleClass(className: String, swtch: Boolean? = definedExternally /* null */): JQuery fun toggleClass(swtch: Boolean? = definedExternally /* null */): JQuery fun toggleClass(func: (index: Number, className: String, swtch: Boolean) -> String, swtch: Boolean? = definedExternally /* null */): JQuery fun `val`(): Any fun `val`(value: String?): JQuery fun `val`(value: Array<String>): JQuery fun `val`(value: Number): JQuery fun `val`(func: (index: Number, value: String) -> String): JQuery fun css(propertyName: String): String fun css(propertyNames: Array<String>): Any fun css(propertyName: String, value: String): JQuery fun css(propertyName: String, value: Number): JQuery fun css(propertyName: String, value: (index: Number, value: String) -> dynamic /* String | Number */): JQuery fun css(properties: JQueryCssProperties): JQuery fun height(): Number fun height(value: Number): JQuery fun height(value: String): JQuery fun height(func: (index: Number, height: Number) -> dynamic /* Number | String */): JQuery fun innerHeight(): Number fun innerHeight(value: Number): JQuery fun innerHeight(value: String): JQuery fun innerWidth(): Number fun innerWidth(value: Number): JQuery fun innerWidth(value: String): JQuery fun offset(): JQueryCoordinates fun offset(coordinates: JQueryCoordinates): JQuery fun offset(func: (index: Number, coords: JQueryCoordinates) -> JQueryCoordinates): JQuery fun outerHeight(includeMargin: Boolean? = definedExternally /* null */): Number fun outerHeight(value: Number): JQuery fun outerHeight(value: String): JQuery fun outerWidth(includeMargin: Boolean? = definedExternally /* null */): Number fun outerWidth(value: Number): JQuery fun outerWidth(value: String): JQuery fun position(): JQueryCoordinates fun scrollLeft(): Number fun scrollLeft(value: Number): JQuery fun scrollTop(): Number fun scrollTop(value: Number): JQuery fun width(): Number fun width(value: Number): JQuery fun width(value: String): JQuery fun width(func: (index: Number, width: Number) -> dynamic /* Number | String */): JQuery fun clearQueue(queueName: String? = definedExternally /* null */): JQuery fun data(key: String, value: Any): JQuery fun data(key: String): Any fun data(obj: Json): JQuery fun data(): Any fun dequeue(queueName: String? = definedExternally /* null */): JQuery fun removeData(name: String): JQuery fun removeData(list: Array<String>): JQuery fun removeData(): JQuery fun promise(type: String? = definedExternally /* null */, target: Any? = definedExternally /* null */): JQueryPromise<Any> fun animate(properties: Any, duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun animate(properties: Any, duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun animate(properties: Any, duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun animate(properties: Any, duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun animate(properties: Any, options: JQueryAnimationOptions): JQuery fun delay(duration: Number, queueName: String? = definedExternally /* null */): JQuery fun fadeIn(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeIn(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeIn(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeIn(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeIn(options: JQueryAnimationOptions): JQuery fun fadeOut(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeOut(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeOut(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeOut(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeOut(options: JQueryAnimationOptions): JQuery fun fadeTo(duration: String, opacity: Number, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeTo(duration: Number, opacity: Number, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeTo(duration: String, opacity: Number, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeTo(duration: Number, opacity: Number, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeToggle(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeToggle(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeToggle(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeToggle(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun fadeToggle(options: JQueryAnimationOptions): JQuery fun finish(queue: String? = definedExternally /* null */): JQuery fun hide(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun hide(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun hide(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun hide(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun hide(options: JQueryAnimationOptions): JQuery fun show(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun show(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun show(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun show(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun show(options: JQueryAnimationOptions): JQuery fun slideDown(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideDown(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideDown(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideDown(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideDown(options: JQueryAnimationOptions): JQuery fun slideToggle(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideToggle(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideToggle(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideToggle(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideToggle(options: JQueryAnimationOptions): JQuery fun slideUp(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideUp(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideUp(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideUp(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun slideUp(options: JQueryAnimationOptions): JQuery fun stop(clearQueue: Boolean? = definedExternally /* null */, jumpToEnd: Boolean? = definedExternally /* null */): JQuery fun stop(queue: String? = definedExternally /* null */, clearQueue: Boolean? = definedExternally /* null */, jumpToEnd: Boolean? = definedExternally /* null */): JQuery fun toggle(duration: Number? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun toggle(duration: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun toggle(duration: Number? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun toggle(duration: String? = definedExternally /* null */, easing: String? = definedExternally /* null */, complete: Function<*>? = definedExternally /* null */): JQuery fun toggle(options: JQueryAnimationOptions): JQuery fun toggle(showOrHide: Boolean): JQuery fun bind(eventType: String, eventData: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun bind(eventType: String, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun bind(eventType: String, eventData: Any, preventBubble: Boolean): JQuery fun bind(eventType: String, preventBubble: Boolean): JQuery fun bind(events: Any): JQuery fun blur(): JQuery fun blur(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun blur(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun change(): JQuery fun change(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun change(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun click(): JQuery fun click(handler: (eventObject: JQueryEventObject) -> Unit): JQuery fun click(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun contextmenu(): JQuery fun contextmenu(handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun contextmenu(eventData: Any, handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun dblclick(): JQuery fun dblclick(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun dblclick(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun delegate(selector: Any, eventType: String, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun delegate(selector: Any, eventType: String, eventData: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun focus(): JQuery fun focus(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun focus(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun focusin(): JQuery fun focusin(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun focusin(eventData: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun focusout(): JQuery fun focusout(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun focusout(eventData: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun hover(handlerIn: (eventObject: JQueryEventObject) -> Any, handlerOut: (eventObject: JQueryEventObject) -> Any): JQuery fun hover(handlerInOut: (eventObject: JQueryEventObject) -> Any): JQuery fun keydown(): JQuery fun keydown(handler: (eventObject: JQueryKeyEventObject) -> Any): JQuery fun keydown(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryKeyEventObject) -> Any)? = definedExternally /* null */): JQuery fun keypress(): JQuery fun keypress(handler: (eventObject: JQueryKeyEventObject) -> Any): JQuery fun keypress(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryKeyEventObject) -> Any)? = definedExternally /* null */): JQuery fun keyup(): JQuery fun keyup(handler: (eventObject: JQueryKeyEventObject) -> Any): JQuery fun keyup(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryKeyEventObject) -> Any)? = definedExternally /* null */): JQuery fun load(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun load(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun mousedown(): JQuery fun mousedown(handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mousedown(eventData: Any, handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseenter(): JQuery fun mouseenter(handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseenter(eventData: Any, handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseleave(): JQuery fun mouseleave(handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseleave(eventData: Any, handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mousemove(): JQuery fun mousemove(handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mousemove(eventData: Any, handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseout(): JQuery fun mouseout(handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseout(eventData: Any, handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseover(): JQuery fun mouseover(handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseover(eventData: Any, handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseup(): JQuery fun mouseup(handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun mouseup(eventData: Any, handler: (eventObject: JQueryMouseEventObject) -> Any): JQuery fun off(): JQuery fun off(events: String, selector: String? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun off(events: String, handler: (eventObject: JQueryEventObject, args: Any) -> Any): JQuery fun off(events: String, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun off(events: Json, selector: String? = definedExternally /* null */): JQuery fun on(events: String, handler: (eventObject: JQueryEventObject, args: Any) -> Unit): JQuery fun on(events: String, data: Any, handler: (eventObject: JQueryEventObject, args: Any) -> Any): JQuery fun on(events: String, selector: String, handler: (eventObject: JQueryEventObject, eventData: Any) -> Any): JQuery fun on(events: String, selector: String, data: Any, handler: (eventObject: JQueryEventObject, eventData: Any) -> Any): JQuery fun on(events: `T$2`, selector: String? = definedExternally /* null */, data: Any? = definedExternally /* null */): JQuery fun on(events: `T$3`, data: Any? = definedExternally /* null */): JQuery fun one(events: String, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun one(events: String, data: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun one(events: String, selector: String, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun one(events: String, selector: String, data: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun one(events: Json, selector: String? = definedExternally /* null */, data: Any? = definedExternally /* null */): JQuery fun one(events: Json, data: Any? = definedExternally /* null */): JQuery fun ready(handler: (jQueryAlias: JQueryStatic? /*= null*/) -> Any): JQuery fun resize(): JQuery fun resize(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun resize(eventData: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun scroll(): JQuery fun scroll(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun scroll(eventData: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun select(): JQuery fun select(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun select(eventData: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun submit(): JQuery fun submit(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun submit(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun trigger(eventType: String, extraParameters: Array<Any>? = definedExternally /* null */): JQuery fun trigger(eventType: String, extraParameters: Any? = definedExternally /* null */): JQuery fun trigger(event: JQueryEventObject, extraParameters: Array<Any>? = definedExternally /* null */): JQuery fun trigger(event: JQueryEventObject, extraParameters: Any? = definedExternally /* null */): JQuery fun triggerHandler(eventType: String, vararg extraParameters: Any): Any fun triggerHandler(event: JQueryEventObject, vararg extraParameters: Any): Any fun unbind(eventType: String? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun unbind(eventType: String, fls: Boolean): JQuery fun unbind(evt: Any): JQuery fun undelegate(): JQuery fun undelegate(selector: String, eventType: String, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery fun undelegate(selector: String, events: Any): JQuery fun undelegate(namespace: String): JQuery fun unload(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun unload(eventData: Any? = definedExternally /* null */, handler: ((eventObject: JQueryEventObject) -> Any)? = definedExternally /* null */): JQuery var context: Element var jquery: String fun error(handler: (eventObject: JQueryEventObject) -> Any): JQuery fun error(eventData: Any, handler: (eventObject: JQueryEventObject) -> Any): JQuery fun pushStack(elements: Array<Any>): JQuery fun pushStack(elements: Array<Any>, name: String, arguments: Array<Any>): JQuery fun after(content1: JQuery, vararg content2: Any): JQuery fun after(content1: Array<Any>, vararg content2: Any): JQuery fun after(content1: Element, vararg content2: Any): JQuery fun after(content1: DocumentFragment, vararg content2: Any): JQuery fun after(content1: Text, vararg content2: Any): JQuery fun after(content1: String, vararg content2: Any): JQuery fun after(func: (index: Number, html: String) -> dynamic /* String | Element | JQuery */): JQuery fun append(content1: JQuery, vararg content2: Any): JQuery fun append(content1: Array<Any>, vararg content2: Any): JQuery fun append(content1: Element, vararg content2: Any): JQuery fun append(content1: DocumentFragment, vararg content2: Any): JQuery fun append(content1: Text, vararg content2: Any): JQuery fun append(content1: String, vararg content2: Any): JQuery fun append(func: (index: Number, html: String) -> dynamic /* String | Element | JQuery */): JQuery fun appendTo(target: JQuery): JQuery fun appendTo(target: Array<Any>): JQuery fun appendTo(target: Element): JQuery fun appendTo(target: String): JQuery fun before(content1: JQuery, vararg content2: Any): JQuery fun before(content1: Array<Any>, vararg content2: Any): JQuery fun before(content1: Element, vararg content2: Any): JQuery fun before(content1: DocumentFragment, vararg content2: Any): JQuery fun before(content1: Text, vararg content2: Any): JQuery fun before(content1: String, vararg content2: Any): JQuery fun before(func: (index: Number, html: String) -> dynamic /* String | Element | JQuery */): JQuery fun clone(withDataAndEvents: Boolean? = definedExternally /* null */, deepWithDataAndEvents: Boolean? = definedExternally /* null */): JQuery fun detach(selector: String? = definedExternally /* null */): JQuery fun empty(): JQuery fun insertAfter(target: JQuery): JQuery fun insertAfter(target: Array<Any>): JQuery fun insertAfter(target: Element): JQuery fun insertAfter(target: Text): JQuery fun insertAfter(target: String): JQuery fun insertBefore(target: JQuery): JQuery fun insertBefore(target: Array<Any>): JQuery fun insertBefore(target: Element): JQuery fun insertBefore(target: Text): JQuery fun insertBefore(target: String): JQuery fun prepend(content1: JQuery, vararg content2: Any): JQuery fun prepend(content1: Array<Any>, vararg content2: Any): JQuery fun prepend(content1: Element, vararg content2: Any): JQuery fun prepend(content1: DocumentFragment, vararg content2: Any): JQuery fun prepend(content1: Text, vararg content2: Any): JQuery fun prepend(content1: String, vararg content2: Any): JQuery fun prepend(func: (index: Number, html: String) -> dynamic /* String | Element | JQuery */): JQuery fun prependTo(target: JQuery): JQuery fun prependTo(target: Array<Any>): JQuery fun prependTo(target: Element): JQuery fun prependTo(target: String): JQuery fun remove(selector: String? = definedExternally /* null */): JQuery fun replaceAll(target: JQuery): JQuery fun replaceAll(target: Array<Any>): JQuery fun replaceAll(target: Element): JQuery fun replaceAll(target: String): JQuery fun replaceWith(newContent: JQuery): JQuery fun replaceWith(newContent: Array<Any>): JQuery fun replaceWith(newContent: Element): JQuery fun replaceWith(newContent: Text): JQuery fun replaceWith(newContent: String): JQuery fun replaceWith(func: () -> dynamic /* Element | JQuery */): JQuery fun text(): String fun text(text: String): JQuery fun text(text: Number): JQuery fun text(text: Boolean): JQuery fun text(func: (index: Number, text: String) -> String): JQuery fun toArray(): Array<HTMLElement> fun unwrap(): JQuery fun wrap(wrappingElement: JQuery): JQuery fun wrap(wrappingElement: Element): JQuery fun wrap(wrappingElement: String): JQuery fun wrap(func: (index: Number) -> dynamic /* String | JQuery */): JQuery fun wrapAll(wrappingElement: JQuery): JQuery fun wrapAll(wrappingElement: Element): JQuery fun wrapAll(wrappingElement: String): JQuery fun wrapAll(func: (index: Number) -> String): JQuery fun wrapInner(wrappingElement: JQuery): JQuery fun wrapInner(wrappingElement: Element): JQuery fun wrapInner(wrappingElement: String): JQuery fun wrapInner(func: (index: Number) -> String): JQuery fun each(func: (index: Number, elem: Element) -> dynamic /* Boolean | Unit */): JQuery fun get(index: Number): HTMLElement fun get(): Array<HTMLElement> fun index(): Number fun index(selector: String): Number fun index(selector: JQuery): Number fun index(selector: Element): Number var length: Number var selector: String @nativeGetter operator fun get(index: Number): HTMLElement? @nativeSetter operator fun set(index: Number, value: HTMLElement) fun add(selector: String, context: Element? = definedExternally /* null */): JQuery fun add(vararg elements: Element): JQuery fun add(html: String): JQuery fun add(obj: JQuery): JQuery fun children(selector: String? = definedExternally /* null */): JQuery fun closest(selector: String): JQuery fun closest(selector: String, context: Element? = definedExternally /* null */): JQuery fun closest(obj: JQuery): JQuery fun closest(element: Element): JQuery fun closest(selectors: Any, context: Element? = definedExternally /* null */): Array<Any> fun contents(): JQuery fun end(): JQuery fun eq(index: Number): JQuery fun filter(selector: String): JQuery fun filter(func: (index: Number, element: Element) -> Boolean): JQuery fun filter(element: Element): JQuery fun filter(obj: JQuery): JQuery fun find(selector: String): JQuery fun find(element: Element): JQuery fun find(obj: JQuery): JQuery fun first(): JQuery fun has(selector: String): JQuery fun has(contained: Element): JQuery fun `is`(selector: String): Boolean fun `is`(func: (index: Number, element: Element) -> Boolean): Boolean fun `is`(obj: JQuery): Boolean fun `is`(elements: Any): Boolean fun last(): JQuery fun map(callback: (index: Number, domElement: Element) -> Any): JQuery fun next(selector: String? = definedExternally /* null */): JQuery fun nextAll(selector: String? = definedExternally /* null */): JQuery fun nextUntil(selector: String? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun nextUntil(element: Element? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun nextUntil(obj: JQuery? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun not(selector: String): JQuery fun not(func: (index: Number, element: Element) -> Boolean): JQuery fun not(elements: Element): JQuery fun not(elements: Array<Element>): JQuery fun not(obj: JQuery): JQuery fun offsetParent(): JQuery fun parent(selector: String? = definedExternally /* null */): JQuery fun parents(selector: String? = definedExternally /* null */): JQuery fun parentsUntil(selector: String? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun parentsUntil(element: Element? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun parentsUntil(obj: JQuery? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun prev(selector: String? = definedExternally /* null */): JQuery fun prevAll(selector: String? = definedExternally /* null */): JQuery fun prevUntil(selector: String? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun prevUntil(element: Element? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun prevUntil(obj: JQuery? = definedExternally /* null */, filter: String? = definedExternally /* null */): JQuery fun siblings(selector: String? = definedExternally /* null */): JQuery fun slice(start: Number, end: Number? = definedExternally /* null */): JQuery fun queue(queueName: String? = definedExternally /* null */): Array<Any> fun queue(newQueue: Array<Function<*>>): JQuery fun queue(callback: Function<*>): JQuery fun queue(queueName: String, newQueue: Array<Function<*>>): JQuery fun queue(queueName: String, callback: Function<*>): JQuery fun extend(`object`: `T$4`): JQuery } external var jQuery: JQueryStatic = definedExternally @JsModule("jquery") external val `$`: JQueryStatic = definedExternally
agpl-3.0
d3bc162466a49181da52d4239e7a0361
64.732311
284
0.738702
4.072253
false
false
false
false
darakeon/dfm
android/Lib/src/main/kotlin/com/darakeon/dfm/lib/api/Retrofit.kt
1
1124
package com.darakeon.dfm.lib.api import android.content.Context import com.google.gson.Gson import com.google.gson.GsonBuilder import okhttp3.Dispatcher import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object Retrofit { fun build( context: Context, dispatcher: Dispatcher, interceptor: (Interceptor.Chain) -> Response ): Retrofit { return build { val client = OkHttpClient.Builder() .dispatcher(dispatcher) .addInterceptor(interceptor) .build() it.baseUrl( MainInfo.getSiteUrl(context) ).client(client) } } fun build(url: String): Retrofit { return build { it.baseUrl(url) } } private fun build(config: (Retrofit.Builder) -> Unit): Retrofit { val builder = Retrofit.Builder() config(builder) val gson: Gson = GsonBuilder() .setLenient() .create() builder.addConverterFactory( GsonConverterFactory.create(gson) ) val name = "javax.net.ssl.trustStore" val value = "NONE" System.setProperty(name, value) return builder.build() } }
gpl-3.0
fdda633a9231809ebef81c829b38e586
19.814815
66
0.726868
3.534591
false
false
false
false
pronghorn-tech/server
src/test/kotlin/tech/pronghorn/http/HttpRequestParseTests.kt
1
3722
/* * Copyright 2017 Pronghorn Technology 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 tech.pronghorn.http import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.RepeatedTest import org.mockito.Mockito.mock import tech.pronghorn.http.protocol.parseHttpRequest import tech.pronghorn.server.HttpServerConnection import tech.pronghorn.test.PronghornTest import tech.pronghorn.test.lightRepeatCount import java.nio.ByteBuffer class HttpRequestParseTests : PronghornTest() { val validRequestLines = arrayOf( "GET /plaintext HTTP/1.1", "Host: server", "User-Agent: Mozilla/5.0", "Cookie: uid=12345678901234567890", "Accept: text/html", "Accept-Language: en-US,en", "Connection: keep-alive" ) val mockConnection = mock(HttpServerConnection::class.java) fun convertRequestLinesToBytes(lines: Array<String>): ByteArray { return lines.joinToString("\r\n").plus("\r\n\r\n").toByteArray(Charsets.US_ASCII) } fun writeRequestLinesToBuffer(lines: Array<String>): ByteBuffer { val bytes = convertRequestLinesToBytes(lines) val buffer = ByteBuffer.allocate(bytes.size) buffer.put(bytes) buffer.flip() return buffer } /* * Tests parsing a full request in all potential partial pieces. * Purpose: Ensure parsing doesn't throw exceptions when parsing incomplete messages. */ @RepeatedTest(lightRepeatCount) fun progressiveParsing() { var x = 0 var validResponses = 0 val validRequestBytes = convertRequestLinesToBytes(validRequestLines) while (x <= validRequestBytes.size) { val buffer = ByteBuffer.allocate(x) buffer.put(validRequestBytes, 0, x) buffer.flip() val parsed = parseHttpRequest(buffer, mockConnection) if (parsed is HttpRequest) { assertEquals(6, parsed.headers.size) validResponses += 1 } x += 1 } assertEquals(1, validResponses) } /* * Tests parsing with an invalid request method * Purpose: Ensure the proper error type is returned in this case. */ @RepeatedTest(lightRepeatCount) fun parseInvalidMethodError() { val invalidMethodLines = validRequestLines.copyOf() invalidMethodLines[0] = invalidMethodLines[0].replace("GET", "WRONG") val buffer = writeRequestLinesToBuffer(invalidMethodLines) val parsed = parseHttpRequest(buffer, mockConnection) assertEquals(InvalidMethodParseError, parsed) } /* * Tests parsing with an invalid http version * Purpose: Ensure the proper error type is returned in this case. */ @RepeatedTest(lightRepeatCount) fun parseInvalidVersionError() { val invalidMethodLines = validRequestLines.copyOf() invalidMethodLines[0] = invalidMethodLines[0].replace("HTTP/1.1", "HTTP/3") val buffer = writeRequestLinesToBuffer(invalidMethodLines) val parsed = parseHttpRequest(buffer, mockConnection) assertEquals(InvalidVersionParseError, parsed) } }
apache-2.0
82e35f55e25e44ccd53bdc8727fc85d5
34.447619
89
0.680279
4.452153
false
true
false
false
simonorono/pradera_baja
farmacia/src/main/kotlin/pb/farmacia/controller/Main.kt
1
2630
/* * Copyright 2016 SimΓ³n OroΓ±o * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pb.farmacia.controller import javafx.event.ActionEvent import javafx.fxml.FXML import javafx.scene.control.TableView import javafx.scene.control.TextField import pb.farmacia.data.Articulo import pb.farmacia.data.DB import pb.farmacia.data.reporte import pb.farmacia.window.Eventos import pb.farmacia.window.FormArticulo @Suppress("unused", "UNUSED_PARAMETER") class Main { @FXML lateinit private var busqueda: TextField @FXML lateinit private var tabla: TableView<Articulo> private fun buscar(): List<Articulo> { var result = DB.getArticulos() if (busqueda.length > 0) { result = result.filter { it.descripcion.contains(busqueda.text) } } return result } private fun update() { tabla.items.clear(); tabla.items.addAll(buscar()) } @FXML private fun initialize() = update() @FXML private fun buscarOnAction(event: ActionEvent) = update() @FXML private fun restablecerOnAction(event: ActionEvent) { busqueda.text = "" update() } @FXML private fun agregarOnAction(event: ActionEvent) { val form = FormArticulo() form.showAndWait() update() } @FXML private fun editarOnAction(event: ActionEvent) { tabla.selectionModel.selectedItem?.let { val form = FormArticulo(it) form.showAndWait() update() } } @FXML private fun eliminarOnAction(event: ActionEvent) { tabla.selectionModel.selectedItem?.let { DB.deleteArticulo(it) update() } } @FXML private fun historialOnAction(event: ActionEvent) { tabla.selectionModel.selectedItem?.let { val hist = Eventos(it) hist.showAndWait() } update() } @FXML private fun reporteOnAction(event: ActionEvent) { val articulos = DB.getArticulos() if (articulos.size > 0) { reporte(articulos) } } }
apache-2.0
ddf954b4799c97dbd0d52db3e09e96fd
25.019802
77
0.647641
3.881832
false
false
false
false
cliffano/swaggy-jenkins
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/PipelineBranchesitempullRequestlinks.kt
1
884
package org.openapitools.model import java.util.Objects import com.fasterxml.jackson.annotation.JsonProperty import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import javax.validation.Valid import io.swagger.v3.oas.annotations.media.Schema /** * * @param self * @param propertyClass */ data class PipelineBranchesitempullRequestlinks( @Schema(example = "null", description = "") @field:JsonProperty("self") val self: kotlin.String? = null, @Schema(example = "null", description = "") @field:JsonProperty("_class") val propertyClass: kotlin.String? = null ) { }
mit
e59595473a5aad85e48cd8280c1baaac
27.516129
74
0.785068
4.189573
false
false
false
false
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/shared/promises/extensions/LoopedInPromise.kt
2
3846
package com.lasthopesoftware.bluewater.shared.promises.extensions import android.content.Context import android.os.Handler import com.namehillsoftware.handoff.Messenger import com.namehillsoftware.handoff.promises.MessengerOperator import com.namehillsoftware.handoff.promises.Promise import com.namehillsoftware.handoff.promises.queued.MessageWriter import com.namehillsoftware.handoff.promises.queued.PreparedMessengerOperator import com.namehillsoftware.handoff.promises.queued.cancellation.CancellableMessageWriter import com.namehillsoftware.handoff.promises.queued.cancellation.CancellablePreparedMessengerOperator import com.namehillsoftware.handoff.promises.response.ImmediateResponse import com.namehillsoftware.handoff.promises.response.PromisedResponse import org.joda.time.Duration open class LoopedInPromise<Result> : Promise<Result> { constructor(task: MessageWriter<Result>, context: Context) : this(task, Handler(context.mainLooper)) constructor(task: MessageWriter<Result>, handler: Handler) : super(Executors.LoopedInResponse<Result>(PreparedMessengerOperator<Result>(task), handler)) constructor(task: MessageWriter<Result>, context: Context, delay: Duration) : this(task, Handler(context.mainLooper), delay) constructor(task: MessageWriter<Result>, handler: Handler, delay: Duration) : super(Executors.DelayedLoopedInPromise<Result>(PreparedMessengerOperator<Result>(task), handler, delay)) constructor(task: CancellableMessageWriter<Result>, handler: Handler) : super(Executors.LoopedInResponse<Result>(CancellablePreparedMessengerOperator<Result>(task), handler)) constructor(task: MessengerOperator<Result>, handler: Handler) : super(Executors.LoopedInResponse<Result>(task, handler)) private class Executors { class LoopedInResponse<Result>(private val task: MessengerOperator<Result>, private val handler: Handler) : MessengerOperator<Result>, Runnable { private lateinit var resultMessenger: Messenger<Result> override fun send(resultMessenger: Messenger<Result>) { this.resultMessenger = resultMessenger if (handler.looper.thread === Thread.currentThread()) run() else handler.post(this) } override fun run() { try { task.send(resultMessenger) } catch (err: Throwable) { resultMessenger.sendRejection(err) } } } class DelayedLoopedInPromise<Result>(private val task: MessengerOperator<Result>, private val handler: Handler, private val delay: Duration) : MessengerOperator<Result>, Runnable { private lateinit var resultMessenger: Messenger<Result> override fun send(resultMessenger: Messenger<Result>) { this.resultMessenger = resultMessenger handler.postDelayed(this, delay.millis) } override fun run() { try { task.send(resultMessenger) } catch (err: Throwable) { resultMessenger.sendRejection(err) } } } } private class OneParameterExecutors { class ReducingFunction<TResult, TNewResult>(private val callable: ImmediateResponse<TResult, TNewResult>, private val handler: Handler) : PromisedResponse<TResult, TNewResult>, MessageWriter<TNewResult> { private var result: TResult? = null override fun prepareMessage(): TNewResult = callable.respond(result) override fun promiseResponse(result: TResult): Promise<TNewResult> { this.result = result return LoopedInPromise(this, handler) } } } companion object { @JvmStatic fun <TResult, TNewResult> response(task: ImmediateResponse<TResult, TNewResult>, context: Context): PromisedResponse<TResult, TNewResult> { return response(task, Handler(context.mainLooper)) } @JvmStatic fun <TResult, TNewResult> response(task: ImmediateResponse<TResult, TNewResult>, handler: Handler): PromisedResponse<TResult, TNewResult> { return OneParameterExecutors.ReducingFunction(task, handler) } } }
lgpl-3.0
e914c29a67fe0cee7ef9d3fdaedb9b4e
38.649485
182
0.783931
4.095847
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/multiblocks/structures/MultiblockBigCombustionChamber.kt
2
5005
package com.cout970.magneticraft.features.multiblocks.structures import com.cout970.magneticraft.misc.vector.plus import com.cout970.magneticraft.misc.vector.rotateBox import com.cout970.magneticraft.misc.vector.times import com.cout970.magneticraft.misc.vector.vec3Of import com.cout970.magneticraft.systems.multiblocks.* import com.cout970.magneticraft.systems.tilerenderers.PIXEL import net.minecraft.init.Blocks import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.util.text.ITextComponent import com.cout970.magneticraft.features.multiblocks.Blocks as Multiblocks object MultiblockBigCombustionChamber : Multiblock() { override val name: String = "big_combustion_chamber" override val size: BlockPos = BlockPos(3, 2, 4) override val scheme: List<Multiblock.MultiblockLayer> override val center: BlockPos = BlockPos(1, 0, 0) init { val A = IgnoreBlockComponent val C = corrugatedIronBlock() val B = ofBlock(Blocks.BRICK_BLOCK) val M = mainBlockOf(controllerBlock) scheme = Multiblock.yLayers( Multiblock.zLayers( listOf(B, B, B), // y = 1 listOf(B, B, B), listOf(B, B, B), listOf(A, C, A)), Multiblock.zLayers( listOf(B, M, B), // y = 0 listOf(B, B, B), listOf(B, B, B), listOf(A, C, A)) ) } override fun getControllerBlock() = Multiblocks.bigCombustionChamber override fun getGlobalCollisionBoxes(): List<AxisAlignedBB> = hitboxes val hitboxes = listOf( Vec3d(-16.000, 30.000, -16.000) * PIXEL to Vec3d(32.000, 32.000, 32.000) * PIXEL, Vec3d(24.000, 2.000, 24.000) * PIXEL to Vec3d(32.000, 30.000, 32.000) * PIXEL, Vec3d(-16.000, 3.000, 3.000) * PIXEL to Vec3d(-15.000, 13.000, 13.000) * PIXEL, Vec3d(12.000, 2.000, 29.000) * PIXEL to Vec3d(14.000, 12.000, 31.000) * PIXEL, Vec3d(-8.000, 14.000, 29.000) * PIXEL to Vec3d(24.000, 16.000, 32.000) * PIXEL, Vec3d(-8.000, 12.000, 29.000) * PIXEL to Vec3d(-5.000, 13.000, 31.000) * PIXEL, Vec3d(-8.000, 13.000, 29.000) * PIXEL to Vec3d(-4.000, 14.000, 31.000) * PIXEL, Vec3d(1.000, 12.000, 29.000) * PIXEL to Vec3d(5.000, 13.000, 31.000) * PIXEL, Vec3d(0.000, 13.000, 29.000) * PIXEL to Vec3d(6.000, 14.000, 31.000) * PIXEL, Vec3d(11.000, 12.000, 29.000) * PIXEL to Vec3d(15.000, 13.000, 31.000) * PIXEL, Vec3d(10.000, 13.000, 29.000) * PIXEL to Vec3d(16.000, 14.000, 31.000) * PIXEL, Vec3d(20.000, 13.000, 29.000) * PIXEL to Vec3d(24.000, 14.000, 31.000) * PIXEL, Vec3d(21.000, 12.000, 29.000) * PIXEL to Vec3d(24.000, 13.000, 31.000) * PIXEL, Vec3d(-8.000, 1.000, 29.000) * PIXEL to Vec3d(24.000, 16.000, 29.000) * PIXEL, Vec3d(24.000, 2.000, -16.000) * PIXEL to Vec3d(32.000, 30.000, -8.000) * PIXEL, Vec3d(-16.000, 2.000, 24.000) * PIXEL to Vec3d(-8.000, 30.000, 32.000) * PIXEL, Vec3d(-16.000, 2.000, -16.000) * PIXEL to Vec3d(-8.000, 30.000, -8.000) * PIXEL, Vec3d(30.000, 2.000, -8.000) * PIXEL to Vec3d(31.000, 30.000, 8.000) * PIXEL, Vec3d(30.000, 2.000, 8.000) * PIXEL to Vec3d(31.000, 30.000, 24.000) * PIXEL, Vec3d(-15.000, 2.000, -8.000) * PIXEL to Vec3d(-14.000, 30.000, 8.000) * PIXEL, Vec3d(-15.000, 2.000, 8.000) * PIXEL to Vec3d(-14.000, 30.000, 24.000) * PIXEL, Vec3d(8.000, 2.000, -15.000) * PIXEL to Vec3d(24.000, 30.000, -14.000) * PIXEL, Vec3d(-8.000, 2.000, -15.000) * PIXEL to Vec3d(8.000, 30.000, -14.000) * PIXEL, Vec3d(-8.000, 16.000, 30.000) * PIXEL to Vec3d(8.000, 31.000, 31.000) * PIXEL, Vec3d(8.000, 16.000, 30.000) * PIXEL to Vec3d(24.000, 31.000, 31.000) * PIXEL, Vec3d(31.000, 3.000, 3.000) * PIXEL to Vec3d(32.000, 13.000, 13.000) * PIXEL, Vec3d(22.000, 2.000, 29.000) * PIXEL to Vec3d(24.000, 12.000, 31.000) * PIXEL, Vec3d(2.000, 2.000, 29.000) * PIXEL to Vec3d(4.000, 12.000, 31.000) * PIXEL, Vec3d(-8.000, 2.000, 29.000) * PIXEL to Vec3d(-6.000, 12.000, 31.000) * PIXEL, Vec3d(-16.000, 0.000, -16.000) * PIXEL to Vec3d(32.000, 2.000, 32.000) * PIXEL, Vec3d(1.000, 0.000, -32.000) * PIXEL to Vec3d(15.000, 2.000, -16.000) * PIXEL, Vec3d(4.000, 16.000, -28.000) * PIXEL to Vec3d(12.000, 30.000, -20.000) * PIXEL, Vec3d(1.000, 0.000, -32.000) * PIXEL to Vec3d(15.000, 2.000, -16.000) * PIXEL, Vec3d(2.000, 2.000, -31.000) * PIXEL to Vec3d(14.000, 16.000, -16.000) * PIXEL, Vec3d(1.000, 2.000, -16.000) * PIXEL to Vec3d(15.000, 17.000, -15.000) * PIXEL ).map { EnumFacing.SOUTH.rotateBox(vec3Of(0.5), it) + vec3Of(0, 0, 1) } override fun checkExtraRequirements(data: MutableList<BlockData>, context: MultiblockContext): List<ITextComponent> = emptyList() }
gpl-2.0
c730cde01fa2a765f49b08eeb289f805
55.247191
133
0.618382
2.672184
false
false
false
false
EyeSeeTea/QAApp
app/src/main/java/org/eyeseetea/malariacare/presentation/presenters/OrgUnitProgramFilterPresenter.kt
1
6008
package org.eyeseetea.malariacare.presentation.presenters import org.eyeseetea.malariacare.domain.entity.OrgUnit import org.eyeseetea.malariacare.domain.entity.Program import org.eyeseetea.malariacare.domain.usecase.GetOrgUnitsUseCase import org.eyeseetea.malariacare.domain.usecase.GetProgramsUseCase import org.eyeseetea.malariacare.presentation.boundary.Executor class OrgUnitProgramFilterPresenter( private val executor: Executor, private val getOrgUnitsUseCase: GetOrgUnitsUseCase, private val getProgramsUseCase: GetProgramsUseCase ) { internal var view: View? = null private var programs: List<Program> = listOf() private var orgUnits: List<OrgUnit> = listOf() private var programsNames: MutableList<String> = mutableListOf() private var orgUnitsNames: MutableList<String> = mutableListOf() private var exclusiveFilter: Boolean = false private lateinit var allOrgUnitText: String private lateinit var allProgramsText: String private lateinit var selectedProgramName: String private lateinit var selectedOrgUnitName: String lateinit var selectedUidProgram: String lateinit var selectedUidOrgUnit: String fun attachView(view: View, allOrgUnitText: String, allProgramsText: String) { this.view = view this.allOrgUnitText = allOrgUnitText this.allProgramsText = allProgramsText loadMetadata() } fun onProgramSelected(programName: String) { if (selectedProgramName != programName) { changeSelectedProgram(programName) if (exclusiveFilter && programName != allProgramsText) { unSelectOrgUnit() } notifyProgramFilterChange() } } fun onOrgUnitSelected(orgUnitName: String) { if (selectedOrgUnitName != orgUnitName) { changeSelectedOrgUnit(orgUnitName) if (exclusiveFilter && orgUnitName != allOrgUnitText) { unSelectProgram() } notifyOrgUnitFilterChange() } } fun setExclusiveFilter(exclusiveFilter: Boolean) { this.exclusiveFilter = exclusiveFilter } fun changeSelectedFilters(programUidFilter: String, orgUnitUidFilter: String) { val programToSelect = programs.firstOrNull { program -> program.uid == programUidFilter } val orgUnitToSelect = orgUnits.firstOrNull { orgUnit -> orgUnit.uid == orgUnitUidFilter } val programNameToSelect = programToSelect?.name ?: allProgramsText val orgUnitNameToSelect = orgUnitToSelect?.name ?: allOrgUnitText onProgramSelected(programNameToSelect) if (exclusiveFilter && programNameToSelect != allProgramsText) { unSelectOrgUnit() notifyOrgUnitFilterChange() } else { onOrgUnitSelected(orgUnitNameToSelect) } notifySelectOrgUnit() notifySelectProgram() } private fun loadMetadata() = executor.asyncExecute { loadOrgUnits() loadPrograms() } private fun loadOrgUnits() { orgUnits = getOrgUnitsUseCase.execute() orgUnitsNames = orgUnits.map { orgUnit -> orgUnit.name } as MutableList<String> changeSelectedOrgUnit(allOrgUnitText) orgUnitsNames.add(0, selectedOrgUnitName) showOrgUnits() } private fun loadPrograms() { programs = getProgramsUseCase.execute() programsNames = programs.map { program -> program.name } as MutableList<String> changeSelectedProgram(allProgramsText) programsNames.add(0, selectedProgramName) showPrograms() } private fun changeSelectedProgram(programName: String) { selectedProgramName = programName if (selectedProgramName == allProgramsText) { selectedUidProgram = "" } else { selectedUidProgram = programs.first { program -> program.name == selectedProgramName }.uid } } private fun changeSelectedOrgUnit(orgUnitName: String) { selectedOrgUnitName = orgUnitName if (selectedOrgUnitName == allOrgUnitText) { selectedUidOrgUnit = "" } else { selectedUidOrgUnit = orgUnits.first { orgUnit -> orgUnit.name == selectedOrgUnitName }.uid } } private fun showOrgUnits() = executor.uiExecute { view?.showOrgUnits(orgUnitsNames as List<String>) } private fun showPrograms() = executor.uiExecute { view?.showPrograms(programsNames as List<String>) } private fun notifyProgramFilterChange() = executor.uiExecute { view?.notifyProgramFilterChange(selectedUidProgram) } private fun notifyOrgUnitFilterChange() = executor.uiExecute { view?.notifyOrgUnitFilterChange(selectedUidOrgUnit) } private fun unSelectOrgUnit() = executor.uiExecute { changeSelectedOrgUnit(allOrgUnitText) view?.unSelectOrgUnitFilter() } private fun unSelectProgram() = executor.uiExecute { changeSelectedProgram(allProgramsText) view?.unSelectProgramFilter() } private fun notifySelectOrgUnit() = executor.uiExecute { val indexToSelect = orgUnitsNames.indexOf(selectedOrgUnitName) view?.selectOrgUnitFilter(indexToSelect) } private fun notifySelectProgram() = executor.uiExecute { val indexToSelect = programsNames.indexOf(selectedProgramName) view?.selectProgramFilter(indexToSelect) } interface View { fun showPrograms(programs: List<@JvmSuppressWildcards String>) fun showOrgUnits(orgUnits: List<@JvmSuppressWildcards String>) fun notifyProgramFilterChange(programFilter: String) fun notifyOrgUnitFilterChange(orgUnitFilter: String) fun unSelectOrgUnitFilter() fun unSelectProgramFilter() fun selectOrgUnitFilter(indexToSelect: Int) fun selectProgramFilter(indexToSelect: Int) } }
gpl-3.0
b4c9a5b620c7775489988865855c7509
30.129534
87
0.685419
4.896496
false
false
false
false
robinverduijn/gradle
subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/codecs/TransformationNodeCodecs.kt
1
3885
/* * Copyright 2019 the original author or authors. * * 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.gradle.instantexecution.serialization.codecs import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvableArtifact import org.gradle.api.internal.artifacts.transform.ArtifactTransformListener import org.gradle.api.internal.artifacts.transform.ExecutionGraphDependenciesResolver import org.gradle.api.internal.artifacts.transform.TransformationNode import org.gradle.api.internal.artifacts.transform.TransformationStep import org.gradle.instantexecution.serialization.Codec import org.gradle.instantexecution.serialization.ReadContext import org.gradle.instantexecution.serialization.WriteContext import org.gradle.instantexecution.serialization.decodePreservingIdentity import org.gradle.instantexecution.serialization.encodePreservingIdentityOf import org.gradle.internal.operations.BuildOperationExecutor internal abstract class AbstractTransformationNodeCodec<T : TransformationNode> : Codec<T> { override suspend fun WriteContext.encode(value: T) { encodePreservingIdentityOf(sharedIdentities, value) { doEncode(value) } } override suspend fun ReadContext.decode(): T { return decodePreservingIdentity(sharedIdentities) { id -> val node = doDecode() sharedIdentities.putInstance(id, node) node } } protected abstract suspend fun WriteContext.doEncode(value: T) protected abstract suspend fun ReadContext.doDecode(): T } internal class InitialTransformationNodeCodec( private val buildOperationExecutor: BuildOperationExecutor, private val transformListener: ArtifactTransformListener ) : AbstractTransformationNodeCodec<TransformationNode.InitialTransformationNode>() { override suspend fun WriteContext.doEncode(value: TransformationNode.InitialTransformationNode) { write(value.transformationStep) write(value.dependenciesResolver) write(value.artifact) } override suspend fun ReadContext.doDecode(): TransformationNode.InitialTransformationNode { val transformationStep = read() as TransformationStep val resolver = read() as ExecutionGraphDependenciesResolver val artifact = read() as ResolvableArtifact return TransformationNode.initial(transformationStep, artifact, resolver, buildOperationExecutor, transformListener) } } internal class ChainedTransformationNodeCodec( private val buildOperationExecutor: BuildOperationExecutor, private val transformListener: ArtifactTransformListener ) : AbstractTransformationNodeCodec<TransformationNode.ChainedTransformationNode>() { override suspend fun WriteContext.doEncode(value: TransformationNode.ChainedTransformationNode) { write(value.transformationStep) write(value.dependenciesResolver) write(value.previousTransformationNode) } override suspend fun ReadContext.doDecode(): TransformationNode.ChainedTransformationNode { val transformationStep = read() as TransformationStep val resolver = read() as ExecutionGraphDependenciesResolver val previousStep = read() as TransformationNode return TransformationNode.chained(transformationStep, previousStep, resolver, buildOperationExecutor, transformListener) } }
apache-2.0
66a4d33a8602bc91722a009f3efc73bb
41.692308
128
0.786358
5.111842
false
false
false
false
wireapp/wire-android
app/src/main/java/com/waz/zclient/audio/AudioService.kt
1
10915
package com.waz.zclient.audio import android.annotation.TargetApi import android.content.Context import android.media.* import android.os.Build import io.reactivex.Observable import java.io.* import java.nio.ByteBuffer import java.nio.ByteOrder.LITTLE_ENDIAN interface AudioService { companion object { const val LogTag = "AudioService" data class RecordingProgress(val maxAmplitude: Int) object Pcm { const val sampleRate = 44100 const val inputChannel = AudioFormat.CHANNEL_IN_MONO const val outputChannel = AudioFormat.CHANNEL_OUT_MONO const val sampleFormat = AudioFormat.ENCODING_PCM_16BIT const val readBufferSize = 1 shl 11 val recorderBufferSize = Math.max(1 shl 16, AudioRecord.getMinBufferSize(sampleRate, inputChannel, sampleFormat)) fun durationInMillisFromByteCount(byteCount: Long): Long = durationFromInMillisFromSampleCount(byteCount / Short.SIZE_BYTES) fun durationFromInMillisFromSampleCount(sampleCount: Long): Long = sampleCount * 1000L / sampleRate } } /** * Returns Observable which will emmit one element when audio focus is granted and * fail when audio focus will be lost. */ fun withAudioFocus(streamType: Int = AudioManager.STREAM_MUSIC, durationHint: Int = AudioManager.AUDIOFOCUS_GAIN): Observable<Unit> /** * Returns Observable which is responsible for audio recording. Audio recording starts when * somebody subscribes to it and stops on unsubscribe. * We record PCM directly instead of using MediaRecorder, because our voice filter code only * supports .pcm and .wav files */ fun recordPcmAudio(pcmFile: File, onFinish: () -> Unit = {}): Observable<RecordingProgress> fun preparePcmAudioTrack(pcmFile: File): AudioTrack fun recodePcmToM4A(pcmFile: File, m4aFile: File) fun recordM4AAudio(m4aFile: File, onFinish: (File) -> Unit = {}): Observable<RecordingProgress> } class AudioServiceImpl(private val context: Context): AudioService { override fun withAudioFocus(streamType: Int, durationHint: Int): Observable<Unit> = Observable.create { emitter -> val manager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager val listener = AudioManager.OnAudioFocusChangeListener { when (it) { AudioManager.AUDIOFOCUS_LOSS or AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> emitter.onError(RuntimeException("Audio focus lost. Current: $it.")) else -> {} } } emitter.setCancellable { manager.abandonAudioFocus(listener) } when (manager.requestAudioFocus(listener, streamType, durationHint)) { AudioManager.AUDIOFOCUS_REQUEST_GRANTED -> emitter.onNext(Unit) AudioManager.AUDIOFOCUS_REQUEST_FAILED -> emitter.onError(RuntimeException("Audio focus request failed.")) } } override fun recordPcmAudio(pcmFile: File, onFinish: () -> Unit): Observable<AudioService.Companion.RecordingProgress> = Observable.create { emitter -> var fos: FileOutputStream? = null val recorder = AudioRecord( MediaRecorder.AudioSource.MIC, AudioService.Companion.Pcm.sampleRate, AudioService.Companion.Pcm.inputChannel, AudioService.Companion.Pcm.sampleFormat, AudioService.Companion.Pcm.recorderBufferSize ) val readBuffer = ShortArray(AudioService.Companion.Pcm.readBufferSize) recorder.startRecording() Thread(Runnable { try { fos = FileOutputStream(pcmFile) var shortsRead = recorder.read(readBuffer, 0, AudioService.Companion.Pcm.readBufferSize) while (shortsRead > 0 && !emitter.isDisposed) { val bytes = ByteBuffer.allocateDirect(shortsRead * Short.SIZE_BYTES).order(LITTLE_ENDIAN) val shorts = bytes.asShortBuffer().put(readBuffer, 0, shortsRead) shorts.flip() var maxAmplitude = 0 while (shorts.hasRemaining()) { val elem = shorts.get() if (Math.abs(elem.toInt()) > Math.abs(maxAmplitude)) maxAmplitude = elem.toInt() } fos?.channel?.write(bytes) emitter.onNext(AudioService.Companion.RecordingProgress(maxAmplitude)) shortsRead = recorder.read(readBuffer, 0, AudioService.Companion.Pcm.readBufferSize) } } catch (ex: Exception) { try { recorder.release() fos?.flush() fos?.close() } catch (ex: Exception) { } emitter.onError(RuntimeException("Error while pcm audio recording.", ex)) } }).start() emitter.setCancellable { try { recorder.stop() recorder.release() fos?.flush() fos?.close() onFinish() } catch (ex: Exception) { } } } override fun preparePcmAudioTrack(pcmFile: File): AudioTrack { val track = AudioTrack( AudioManager.STREAM_MUSIC, AudioService.Companion.Pcm.sampleRate, AudioService.Companion.Pcm.outputChannel, AudioService.Companion.Pcm.sampleFormat, AudioService.Companion.Pcm.readBufferSize, AudioTrack.MODE_STREAM) Thread(Runnable { val playerBuffer = ByteArray(AudioService.Companion.Pcm.readBufferSize) val fis = FileInputStream(pcmFile) var readCount = fis.read(playerBuffer) while (readCount != -1) { track.write(playerBuffer, 0, readCount) readCount = fis.read(playerBuffer) } }).start() return track } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) @Throws(IOException::class) override fun recodePcmToM4A(pcmFile: File, m4aFile: File) { val codecTimeout = 5000 val compressedAudioMime = "audio/mp4a-latm" val channelCount = 1 val targetBitrate = 128000 val sampleRate = AudioService.Companion.Pcm.sampleRate var mediaFormat = MediaFormat.createAudioFormat(compressedAudioMime, sampleRate, channelCount) mediaFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC) mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, targetBitrate) val mediaCodec = MediaCodec.createEncoderByType(compressedAudioMime) mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) mediaCodec.start() val codecInputBuffers = mediaCodec.inputBuffers val codecOutputBuffers = mediaCodec.outputBuffers val bufferInfo = MediaCodec.BufferInfo() val mediaMuxer = MediaMuxer(m4aFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) var totalBytesRead = 0 var presentationTimeUs = 0.0 val tempBuffer = ByteArray(2 * sampleRate) var hasMoreData = true var stop = false var audioTrackId = 0 var outputBufferIndex: Int val inputStream = FileInputStream(pcmFile) while (!stop) { var inputBufferIndex = 0 var currentBatchRead = 0 while (inputBufferIndex != -1 && hasMoreData && currentBatchRead <= 50 * sampleRate) { inputBufferIndex = mediaCodec.dequeueInputBuffer(codecTimeout.toLong()) if (inputBufferIndex >= 0) { val buffer = codecInputBuffers[inputBufferIndex] buffer.clear() val bytesRead = inputStream.read(tempBuffer, 0, buffer.limit()) if (bytesRead == -1) { mediaCodec.queueInputBuffer(inputBufferIndex, 0, 0, presentationTimeUs.toLong(), 0) hasMoreData = false stop = true } else { totalBytesRead += bytesRead currentBatchRead += bytesRead buffer.put(tempBuffer, 0, bytesRead) mediaCodec.queueInputBuffer(inputBufferIndex, 0, bytesRead, presentationTimeUs.toLong(), 0) presentationTimeUs = (1000000L * (totalBytesRead / 2) / sampleRate).toDouble() } } } outputBufferIndex = 0 while (outputBufferIndex != MediaCodec.INFO_TRY_AGAIN_LATER) { outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, codecTimeout.toLong()) if (outputBufferIndex >= 0) { val encodedData = codecOutputBuffers[outputBufferIndex] encodedData.position(bufferInfo.offset) encodedData.limit(bufferInfo.offset + bufferInfo.size) if (bufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0 && bufferInfo.size != 0) { mediaCodec.releaseOutputBuffer(outputBufferIndex, false) } else { mediaMuxer.writeSampleData(audioTrackId, codecOutputBuffers[outputBufferIndex], bufferInfo) mediaCodec.releaseOutputBuffer(outputBufferIndex, false) } } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { mediaFormat = mediaCodec.outputFormat audioTrackId = mediaMuxer.addTrack(mediaFormat) mediaMuxer.start() } } } inputStream.close() mediaCodec.stop() mediaCodec.release() mediaMuxer.stop() mediaMuxer.release() } override fun recordM4AAudio(m4aFile: File, onFinish: (File) -> Unit): Observable<AudioService.Companion.RecordingProgress> { val pcmFile = File(m4aFile.parent, "${m4aFile.nameWithoutExtension}_${System.currentTimeMillis()}.pcm") if (pcmFile.exists()) pcmFile.delete() pcmFile.createNewFile() try { return recordPcmAudio(pcmFile) { recodePcmToM4A(pcmFile, m4aFile) onFinish(m4aFile) } } finally { pcmFile.delete() } } }
gpl-3.0
2e9bd9f3fc40b836d32e3eace6de4e12
41.972441
128
0.592213
5.112412
false
false
false
false
fluttercommunity/plus_plugins
packages/sensors_plus/sensors_plus/android/src/main/kotlin/dev/fluttercommunity/plus/sensors/SensorsPlugin.kt
1
3465
package dev.fluttercommunity.plus.sensors import android.content.Context import android.hardware.Sensor import android.hardware.SensorManager import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.EventChannel /** SensorsPlugin */ class SensorsPlugin : FlutterPlugin { private lateinit var accelerometerChannel: EventChannel private lateinit var userAccelChannel: EventChannel private lateinit var gyroscopeChannel: EventChannel private lateinit var magnetometerChannel: EventChannel private lateinit var accelerationStreamHandler: StreamHandlerImpl private lateinit var linearAccelerationStreamHandler: StreamHandlerImpl private lateinit var gyroScopeStreamHandler: StreamHandlerImpl private lateinit var magnetometerStreamHandler: StreamHandlerImpl override fun onAttachedToEngine(binding: FlutterPluginBinding) { setupEventChannels(binding.applicationContext, binding.binaryMessenger) } override fun onDetachedFromEngine(binding: FlutterPluginBinding) { teardownEventChannels() } private fun setupEventChannels(context: Context, messenger: BinaryMessenger) { val sensorsManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager accelerometerChannel = EventChannel(messenger, ACCELEROMETER_CHANNEL_NAME) accelerationStreamHandler = StreamHandlerImpl( sensorsManager, Sensor.TYPE_ACCELEROMETER ) accelerometerChannel.setStreamHandler(accelerationStreamHandler) userAccelChannel = EventChannel(messenger, USER_ACCELEROMETER_CHANNEL_NAME) linearAccelerationStreamHandler = StreamHandlerImpl( sensorsManager, Sensor.TYPE_LINEAR_ACCELERATION ) userAccelChannel.setStreamHandler(linearAccelerationStreamHandler) gyroscopeChannel = EventChannel(messenger, GYROSCOPE_CHANNEL_NAME) gyroScopeStreamHandler = StreamHandlerImpl( sensorsManager, Sensor.TYPE_GYROSCOPE ) gyroscopeChannel.setStreamHandler(gyroScopeStreamHandler) magnetometerChannel = EventChannel(messenger, MAGNETOMETER_CHANNEL_NAME) magnetometerStreamHandler = StreamHandlerImpl( sensorsManager, Sensor.TYPE_MAGNETIC_FIELD ) magnetometerChannel.setStreamHandler(magnetometerStreamHandler) } private fun teardownEventChannels() { accelerometerChannel.setStreamHandler(null) userAccelChannel.setStreamHandler(null) gyroscopeChannel.setStreamHandler(null) magnetometerChannel.setStreamHandler(null) accelerationStreamHandler.onCancel(null) linearAccelerationStreamHandler.onCancel(null) gyroScopeStreamHandler.onCancel(null) magnetometerStreamHandler.onCancel(null) } companion object { private const val ACCELEROMETER_CHANNEL_NAME = "dev.fluttercommunity.plus/sensors/accelerometer" private const val GYROSCOPE_CHANNEL_NAME = "dev.fluttercommunity.plus/sensors/gyroscope" private const val USER_ACCELEROMETER_CHANNEL_NAME = "dev.fluttercommunity.plus/sensors/user_accel" private const val MAGNETOMETER_CHANNEL_NAME = "dev.fluttercommunity.plus/sensors/magnetometer" } }
bsd-3-clause
8a2fa97a989cf7c01b615cc7d8f44e4e
41.777778
106
0.755844
5.148588
false
false
false
false
nestlabs/connectedhomeip
src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/setuppayloadscanner/CHIPDeviceDetailsFragment.kt
2
4289
/* * Copyright (c) 2020 Project CHIP Authors * 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.chip.chiptool.setuppayloadscanner import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import com.google.chip.chiptool.R import com.google.chip.chiptool.util.FragmentUtil import kotlinx.android.synthetic.main.chip_device_info_fragment.view.discoveryCapabilitiesTv import kotlinx.android.synthetic.main.chip_device_info_fragment.view.discriminatorTv import kotlinx.android.synthetic.main.chip_device_info_fragment.view.productIdTv import kotlinx.android.synthetic.main.chip_device_info_fragment.view.setupCodeTv import kotlinx.android.synthetic.main.chip_device_info_fragment.view.vendorIdTv import kotlinx.android.synthetic.main.chip_device_info_fragment.view.vendorTagsContainer import kotlinx.android.synthetic.main.chip_device_info_fragment.view.vendorTagsLabelTv import kotlinx.android.synthetic.main.chip_device_info_fragment.view.versionTv import kotlinx.android.synthetic.main.chip_device_info_fragment.view.commissioningFlowTv import kotlinx.android.synthetic.main.chip_device_info_fragment.view.customFlowBtn /** Show the [CHIPDeviceInfo]. */ class CHIPDeviceDetailsFragment : Fragment() { private lateinit var deviceInfo: CHIPDeviceInfo override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { deviceInfo = checkNotNull(requireArguments().getParcelable(ARG_DEVICE_INFO)) return inflater.inflate(R.layout.chip_device_info_fragment, container, false).apply { versionTv.text = "${deviceInfo.version}" vendorIdTv.text = "${deviceInfo.vendorId}" productIdTv.text = "${deviceInfo.productId}" setupCodeTv.text = "${deviceInfo.setupPinCode}" discriminatorTv.text = "${deviceInfo.discriminator}" discoveryCapabilitiesTv.text = requireContext().getString( R.string.chip_device_info_discovery_capabilities_text, deviceInfo.discoveryCapabilities ) if (deviceInfo.optionalQrCodeInfoMap.isEmpty()) { vendorTagsLabelTv.visibility = View.GONE vendorTagsContainer.visibility = View.GONE } else { vendorTagsLabelTv.visibility = View.VISIBLE vendorTagsContainer.visibility = View.VISIBLE deviceInfo.optionalQrCodeInfoMap.forEach { (_, qrCodeInfo) -> val tv = inflater.inflate(R.layout.barcode_vendor_tag, null, false) as TextView val info = "${qrCodeInfo.tag}. ${qrCodeInfo.data}, ${qrCodeInfo.intDataValue}" tv.text = info vendorTagsContainer.addView(tv) } } commissioningFlowTv.text = "${deviceInfo.commissioningFlow}" // commissioningFlow = 2 (Custom), read device info from Ledger if (deviceInfo.commissioningFlow == 2) { customFlowBtn.visibility = View.VISIBLE customFlowBtn.setOnClickListener { FragmentUtil.getHost(this@CHIPDeviceDetailsFragment, Callback::class.java) ?.handleReadFromLedgerClicked(deviceInfo) } } } } /** Interface for notifying the host. */ interface Callback { /** Notifies listener of Read Device Info from Ledger button click. */ fun handleReadFromLedgerClicked(deviceInfo: CHIPDeviceInfo) } companion object { private const val ARG_DEVICE_INFO = "device_info" @JvmStatic fun newInstance(deviceInfo: CHIPDeviceInfo): CHIPDeviceDetailsFragment { return CHIPDeviceDetailsFragment().apply { arguments = Bundle(1).apply { putParcelable(ARG_DEVICE_INFO, deviceInfo) } } } } }
apache-2.0
0b2ad844492deaa78ef5bec8360bd4b7
38.712963
92
0.738867
4.221457
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/ui/preferences/components/AccentColorPreference.kt
1
1407
package app.lawnchair.ui.preferences.components import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import app.lawnchair.preferences.getAdapter import app.lawnchair.preferences2.preferenceManager2 import app.lawnchair.theme.color.ColorOption import app.lawnchair.ui.preferences.components.colorpreference.ColorPreference import com.android.launcher3.R val staticColors = listOf( ColorOption.CustomColor(0xFFF32020), ColorOption.CustomColor(0xFFF20D69), ColorOption.CustomColor(0xFF7452FF), ColorOption.CustomColor(0xFF2C41C9), ColorOption.LawnchairBlue, ColorOption.CustomColor(0xFF00BAD6), ColorOption.CustomColor(0xFF00A399), ColorOption.CustomColor(0xFF47B84F), ColorOption.CustomColor(0xFFFFBB00), ColorOption.CustomColor(0xFFFF9800), ColorOption.CustomColor(0xFF7C5445), ColorOption.CustomColor(0xFF67818E) ).map(ColorOption::colorPreferenceEntry) val dynamicColors = listOf(ColorOption.SystemAccent, ColorOption.WallpaperPrimary) .filter(ColorOption::isSupported) .map(ColorOption::colorPreferenceEntry) @Composable fun AccentColorPreference() { val adapter = preferenceManager2().accentColor.getAdapter() ColorPreference( adapter = adapter, label = stringResource(id = R.string.accent_color), dynamicEntries = dynamicColors, staticEntries = staticColors, ) }
gpl-3.0
700756d95f26b6de8f72f7daca6a3183
35.076923
82
0.789623
3.844262
false
false
false
false
droibit/chopsticks
sample/src/main/java/com/github/droibit/chopstick/sample/view/ViewListActivity.kt
1
1386
package com.github.droibit.chopstick.sample.view import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.ArrayAdapter import android.widget.ListView import androidx.appcompat.app.AppCompatActivity import com.github.droibit.chopstick.sample.R import com.github.droibit.chopstick.view.bindView class ViewListActivity : AppCompatActivity() { companion object { private const val BIND_VIEW_ACTIVITY = 0 private const val BIND_VIEW_FRAGMENT_ACTIVITY = 1 @JvmStatic fun makeIntent(context: Context) = Intent(context, ViewListActivity::class.java) } private val listView: ListView by bindView(android.R.id.list) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list) listView.adapter = ArrayAdapter.createFromResource( this, R.array.view_list_items, android.R.layout.simple_list_item_1 ) listView.setOnItemClickListener { _, _, i, _ -> launchActivity(position = i) } } private fun launchActivity(position: Int) { when (position) { BIND_VIEW_ACTIVITY -> startActivity(BindViewActivity.makeIntent(this)) BIND_VIEW_FRAGMENT_ACTIVITY -> startActivity(BindViewFragmentActivity.makeIntent(this)) } } }
apache-2.0
7098e6364176a2780a8441bdc26067fe
32
99
0.7114
4.470968
false
false
false
false
bachhuberdesign/deck-builder-gwent
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/deckselect/DeckSelectController.kt
1
3603
package com.bachhuberdesign.deckbuildergwent.features.deckselect import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bachhuberdesign.deckbuildergwent.MainActivity import com.bachhuberdesign.deckbuildergwent.R import com.bachhuberdesign.deckbuildergwent.features.deckbuild.Deck import com.bachhuberdesign.deckbuildergwent.features.deckbuild.DeckbuildController import com.bachhuberdesign.deckbuildergwent.features.shared.exception.CardException import com.bachhuberdesign.deckbuildergwent.inject.module.ActivityModule import com.bachhuberdesign.deckbuildergwent.util.DeckDrawerItem import com.bachhuberdesign.deckbuildergwent.util.inflate import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter import kotlinx.android.synthetic.main.controller_deck_select.view.* import javax.inject.Inject /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ class DeckSelectController : Controller(), DeckSelectMvpContract { companion object { @JvmStatic val TAG: String = DeckSelectController::class.java.name } @Inject lateinit var presenter: DeckSelectPresenter var recyclerView: RecyclerView? = null var adapter: FastItemAdapter<DeckDrawerItem>? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = container.inflate(R.layout.controller_deck_select) activity?.title = "Deck List" (activity as MainActivity).persistedComponent .activitySubcomponent(ActivityModule(activity!!)) .inject(this) initRecyclerView(view) return view } override fun onAttach(view: View) { super.onAttach(view) presenter.attach(this) presenter.loadDeckList() } override fun onDetach(view: View) { super.onDetach(view) presenter.detach() } private fun initRecyclerView(v: View) { adapter = FastItemAdapter() adapter!!.withOnClickListener({ view, adapter, item, position -> if (item.deckId == 0) { CardException("Deck ID not set") } else { router.pushController(RouterTransaction.with(DeckbuildController(item.deckId)) .tag(DeckbuildController.TAG) .pushChangeHandler(FadeChangeHandler()) .popChangeHandler(FadeChangeHandler())) } true }) val layoutManager = LinearLayoutManager(activity) recyclerView = v.recycler_view recyclerView?.setHasFixedSize(true) recyclerView?.layoutManager = layoutManager recyclerView?.adapter = adapter } override fun onDecksLoaded(decks: List<Deck>) { decks.forEach { deck -> val item = DeckDrawerItem() .withDeckName(deck.name) .withDeckId(deck.id) .withBackgroundUrl("file:///android_asset/slim/${deck.leader?.iconUrl}") .withBackgroundColor(R.color.primary_dark) adapter?.add(item) } adapter?.notifyDataSetChanged() } override fun onNoDecksAvailable() { Log.d(TAG, "onNoDecksAvailable()") // TODO: Show UI for no available decks } }
apache-2.0
0ac9da7a36c5039092037c4cd23416c4
32.37037
94
0.691368
5.018106
false
false
false
false
MyDogTom/detekt
detekt-rules/src/test/resources/cases/FinalClass.kt
1
1408
package cases // should report 9 for protected = internal @Suppress("unused") class FinalClass : BaseClass { private val i = 0 protected var i1 = 0 // positive case protected constructor(i1: Int) : super() { // positive case this.i1 = i1 } // should not report protected = private visibility protected override val abstractProp = 0 // should not report protected = private visibility protected override fun abstractFunction() { } protected fun function() { } // positive case protected inner class InnerClass1 { // positive case protected val i = 0 // positive case } inner class InnerClass2 { protected val i = 0 // positive case } protected object InnerObject // positive case protected companion object { // positive case protected class A { // positive case protected var x = 0 // positive case } } } @Suppress("unused") abstract class BaseClass { protected abstract val abstractProp: Int protected abstract fun abstractFunction() protected object InnerObject protected companion object { protected class A { protected var x = 0 // positive case } } } @Suppress("unused") open class OpenClass { inner class InnerClass { protected val i = 0 // positive case } } @Suppress("unused") sealed class SealedClass { protected fun a() {} } @Suppress("unused") class FinalClassWithProtectedConstructor protected constructor() // positive case
apache-2.0
12cbd37ffa89893481524a8f95a8b8ad
17.773333
81
0.715199
3.966197
false
false
false
false
weibaohui/korm
src/main/kotlin/com/sdibt/korm/core/callbacks/CallBackUpdate.kt
1
3824
/* * 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 com.sdibt.korm.core.callbacks import com.sdibt.korm.core.db.DataSourceType import com.sdibt.korm.core.db.KormSqlSession import com.sdibt.korm.core.entity.EntityFieldsCache import java.time.LocalDateTime class CallBackUpdate(db: KormSqlSession) { val defaultCallBack = DefaultCallBack.instance.getCallBack(db) fun init() { defaultCallBack.update().reg("beforeUpdate") { beforeUpdateCallback(it) } defaultCallBack.update().reg("updateDateTime") { updateDateTimeCallback(it) } defaultCallBack.update().reg("updateOperator") { updateOperatorCallback(it) } defaultCallBack.update().reg("update") { updateCallback(it) } defaultCallBack.update().reg("sqlProcess") { CallBackCommon().sqlProcess(it) } defaultCallBack.update().reg("setDataSource") { CallBackCommon().setDataSoure(it) } defaultCallBack.update().reg("exec") { execCallback(it) } defaultCallBack.update().reg("afterUpdate") { afterUpdateCallback(it) } } fun beforeUpdateCallback(scope: Scope): Scope { var scope = scope if (!scope.hasError) { scope = scope.callMethod("beforeSave") } if (!scope.hasError) { scope = scope.callMethod("beforeUpdate") } return scope } fun afterUpdateCallback(scope: Scope): Scope { var scope = scope if (!scope.hasError) { scope = scope.callMethod("afterUpdate") } if (!scope.hasError) { scope = scope.callMethod("afterSave") } return scope } fun updateOperatorCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.entity == null) return scope val item = EntityFieldsCache.item(scope.entity!!) item.updatedBy?.apply { scope.sqlParam.put("${item.updatedBy}", scope.callMethodGetOperator("getOperator")) } return scope } fun updateDateTimeCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.entity == null) return scope val item = EntityFieldsCache.item(scope.entity!!) item.updatedAt?.apply { scope.sqlParam.put("${item.updatedAt}", LocalDateTime.now()) } return scope } fun updateCallback(scope: Scope): Scope { when (scope.actionType) { ActionType.Entity -> return scope.updateEntity() ActionType.ObjectQL -> return scope.updateOQL() } } fun execCallback(scope: Scope): Scope { if (scope.db.Error == null) { val (rowsAffected, generatedKeys) = scope.db.executeUpdate( scope.sqlString, scope.sqlParam, dsName = scope.dsName, dsType = DataSourceType.WRITE ) scope.rowsAffected = rowsAffected scope.generatedKeys = generatedKeys scope.result = rowsAffected } return scope } }
apache-2.0
2941b0bc7a7a2204b7eaffcb42ae91f3
32.54386
95
0.643567
4.520095
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/authorization/listeners/PermissionMapListener.kt
1
2624
package com.openlattice.authorization.listeners import com.google.common.eventbus.EventBus import com.hazelcast.core.EntryEvent import com.hazelcast.map.listener.EntryAddedListener import com.hazelcast.map.listener.EntryRemovedListener import com.hazelcast.map.listener.EntryUpdatedListener import com.openlattice.assembler.events.MaterializePermissionChangeEvent import com.openlattice.authorization.AceKey import com.openlattice.authorization.AceValue import com.openlattice.authorization.Permission import com.openlattice.authorization.PrincipalType import com.openlattice.authorization.securable.SecurableObjectType /** * Handles internal permission change events. This class sits far below of authorization layer, so should not be * responsible for handling audit related events. * @author Matthew Tamayo-Rios &lt;[email protected]&gt; */ class PermissionMapListener(private val eventBus: EventBus) : EntryAddedListener<AceKey, AceValue>, EntryRemovedListener<AceKey, AceValue>, EntryUpdatedListener<AceKey, AceValue> { override fun entryAdded(event: EntryEvent<AceKey, AceValue>) { if (isMaterializationEvent(event)) { postMaterializationEvent(event) } } override fun entryRemoved(event: EntryEvent<AceKey, AceValue>) { if (isMaterializationEvent(event)) { postMaterializationEvent(event) } } override fun entryUpdated(event: EntryEvent<AceKey, AceValue>) { if (isMaterializationEvent(event)) { postMaterializationEvent(event) } } private fun postMaterializationEvent(event: EntryEvent<AceKey, AceValue>) { eventBus.post( MaterializePermissionChangeEvent( event.key.principal, setOf(event.key.aclKey.first()), event.value.securableObjectType ) ) } private fun isMaterializationEvent(event: EntryEvent<AceKey, AceValue>): Boolean { return event.value.contains(Permission.MATERIALIZE) && event.key.principal.type == PrincipalType.ORGANIZATION && (event.value.securableObjectType == SecurableObjectType.EntitySet || event.value.securableObjectType == SecurableObjectType.PropertyTypeInEntitySet) } override fun equals(other: Any?): Boolean { return other != null && other is PermissionMapListener } override fun hashCode(): Int { return eventBus.hashCode() } }
gpl-3.0
f82e0bb22af1803179149c9ec3190c01
38.179104
164
0.684451
4.979127
false
false
false
false
tkiapril/Weisseliste
src/main/kotlin/kotlin/sql/BatchInsertQuery.kt
1
2773
package kotlin.sql import java.util.* class BatchInsertQuery(val table: Table, val _ignore: Boolean = false) { val data = ArrayList<LinkedHashMap<Column<*>, Any?>>() fun addBatch() { data.add(LinkedHashMap()) } operator fun <T> set(column: Column<T>, value: T) { val values = data.last() if (values.containsKey(column)) { error("$column is already initialized") } values.put(column, column.columnType.valueToDB(value)) } fun execute(session: Session): List<Int> { if (data.isEmpty()) return emptyList() val generatedKeys = ArrayList<Int>() val (auto, columns) = table.columns.partition { it.columnType.autoinc } val ignore = if (_ignore) "IGNORE" else "" var sql = StringBuilder("INSERT $ignore INTO ${session.identity(table)}") sql.append(" (") sql.append((columns.map{ session.identity(it) }).joinToString(", ")) sql.append(") ") sql.append("VALUES ") val paramsPlaceholder = columns.map{ "?" }.joinToString(", ", prefix = "(", postfix = "),") sql.append(paramsPlaceholder.repeat(data.size).removeSuffix(",")) try { val sqlText = sql.toString() session.execBatch { val stmt = session.prepareStatement(sqlText, auto.map{session.identity(it)}) val args = arrayListOf<Pair<ColumnType, Any?>>() for ((i, d) in data.withIndex()) { columns.mapTo(args) {it.columnType to (d[it] ?: it.defaultValue)} stmt.fillParameters(columns, d, i) } log(sqlText, args) val count = stmt.executeUpdate() assert(count == data.size) { "Number of results don't match number of entries in batch" } if (auto.isNotEmpty()) { val rs = stmt.generatedKeys!! while (rs.next()) { generatedKeys.add(rs.getInt(1)) } if (generatedKeys.size == 1 && count > 1) { // H2 only returns one last generated keys... var id = generatedKeys.first() while (generatedKeys.size < count) { id -= 1 generatedKeys.add(0, id) } } assert(generatedKeys.isEmpty() || generatedKeys.size == count) { "Number of autoincs doesn't match number of batch entries" } } } } catch (e: Exception) { println("BAD SQL: $sql") throw e } return generatedKeys } }
agpl-3.0
635bc3d2fd57a26ae57a8d5e284d8c7f
32.011905
145
0.507393
4.740171
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/CardBrowserMySearchesDialog.kt
1
5586
//noinspection MissingCopyrightHeader #8659 package com.ichi2.anki.dialogs import android.annotation.SuppressLint import android.app.Dialog import android.os.Bundle import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.input.input import com.afollestad.materialdialogs.list.customListAdapter import com.afollestad.materialdialogs.list.getRecyclerView import com.ichi2.anki.R import com.ichi2.anki.analytics.AnalyticsDialogFragment import com.ichi2.ui.ButtonItemAdapter import com.ichi2.utils.BundleUtils.getSerializableWithCast import timber.log.Timber // TODO: Add different classes for the two different dialogs class CardBrowserMySearchesDialog : AnalyticsDialogFragment() { private var buttonItemAdapter: ButtonItemAdapter? = null private var savedFilters: HashMap<String, String>? = null private var savedFilterKeys: ArrayList<String>? = null interface MySearchesDialogListener { fun onSelection(searchName: String?) fun onRemoveSearch(searchName: String?) fun onSaveSearch(searchName: String?, searchTerms: String?) } @SuppressLint("CheckResult") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { super.onCreate(savedInstanceState) val dialog = MaterialDialog(requireActivity()) val type = requireArguments().getInt("type") if (type == CARD_BROWSER_MY_SEARCHES_TYPE_LIST) { savedFilters = requireArguments().getSerializableWithCast<HashMap<String, String>>("savedFilters") savedFilters?.let { savedFilterKeys = ArrayList(it.keys) } buttonItemAdapter = ButtonItemAdapter( savedFilterKeys!!, itemCallback = { searchName -> Timber.d("item clicked: %s", searchName) mySearchesDialogListener!!.onSelection(searchName) dialog.dismiss() }, buttonCallback = { searchName -> Timber.d("button clicked: %s", searchName) removeSearch(searchName) } ).apply { notifyAdapterDataSetChanged() // so the values are sorted. dialog.title(text = resources.getString(R.string.card_browser_list_my_searches_title)) .customListAdapter(this, null) } } else if (type == CARD_BROWSER_MY_SEARCHES_TYPE_SAVE) { val currentSearchTerms = requireArguments().getString("currentSearchTerms") dialog.title(text = getString(R.string.card_browser_list_my_searches_save)) .positiveButton(android.R.string.ok) .negativeButton(R.string.dialog_cancel) .input(hintRes = R.string.card_browser_list_my_searches_new_name) { _: MaterialDialog?, text: CharSequence -> Timber.d("Saving search with title/terms: %s/%s", text, currentSearchTerms) mySearchesDialogListener!!.onSaveSearch(text.toString(), currentSearchTerms) } } runCatching { dialog.getRecyclerView() }.onSuccess { recyclerView -> val layoutManager = recyclerView.layoutManager as LinearLayoutManager val dividerItemDecoration = DividerItemDecoration(recyclerView.context, layoutManager.orientation) val scale = resources.displayMetrics.density val dpAsPixels = (5 * scale + 0.5f).toInt() dialog.view.setPadding(dpAsPixels, 0, dpAsPixels, dpAsPixels) recyclerView.addItemDecoration(dividerItemDecoration) } return dialog } private fun removeSearch(searchName: String) { MaterialDialog(requireActivity()).show { message(text = resources.getString(R.string.card_browser_list_my_searches_remove_content, searchName)) positiveButton(android.R.string.ok) { mySearchesDialogListener!!.onRemoveSearch(searchName) savedFilters!!.remove(searchName) savedFilterKeys!!.remove(searchName) buttonItemAdapter!!.apply { remove(searchName) notifyAdapterDataSetChanged() } dialog?.dismiss() // Dismiss the root dialog if (savedFilters!!.isEmpty()) { dialog!!.dismiss() } } negativeButton(R.string.dialog_cancel) } } companion object { const val CARD_BROWSER_MY_SEARCHES_TYPE_LIST = 0 // list searches dialog const val CARD_BROWSER_MY_SEARCHES_TYPE_SAVE = 1 // save searches dialog private var mySearchesDialogListener: MySearchesDialogListener? = null fun newInstance( savedFilters: HashMap<String, String>?, mySearchesDialogListener: MySearchesDialogListener?, currentSearchTerms: String?, type: Int ): CardBrowserMySearchesDialog { this.mySearchesDialogListener = mySearchesDialogListener val cardBrowserMySearchesDialog = CardBrowserMySearchesDialog() val args = Bundle() args.putSerializable("savedFilters", savedFilters) args.putInt("type", type) args.putString("currentSearchTerms", currentSearchTerms) cardBrowserMySearchesDialog.arguments = args return cardBrowserMySearchesDialog } } }
gpl-3.0
e425ddf5eb1f9f4330a974a77688e0cd
44.786885
125
0.652166
5.177016
false
false
false
false
pdvrieze/ProcessManager
java-common/src/jvmMain/kotlin/net/devrieze/util/Tripple.kt
1
2326
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ /* * Created on Oct 9, 2004 * */ package net.devrieze.util /** * This class implements a tupple as is commonly used in many code snippets. * Such functionality could be implemented using * * @param S The type of the first element. * @param T The type of the second element. * @param U The type of the third element. * @see net.devrieze.util.Tupple * * @author Paul de Vrieze * @version 1.0 $Revision$ * * @constructor Create a tripple with the specified elements. * * @property elem1 The first element * @property elem2 The second element * @property elem3 The third element * */ class Tripple<S, T, U>( var elem1: S, var elem2: T, var elem3: U) { fun copy(elem1: S = this.elem1, elem2: T = this.elem2, elem3: U = this.elem3) = Tripple(elem1, elem2, elem3) override fun toString(): String { return "($elem1, $elem2, $elem3)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Tripple<*, *, *> if (elem1 != other.elem1) return false if (elem2 != other.elem2) return false if (elem3 != other.elem3) return false return true } override fun hashCode(): Int { var result = elem1?.hashCode() ?: 0 result = 31 * result + (elem2?.hashCode() ?: 0) result = 31 * result + (elem3?.hashCode() ?: 0) return result } companion object { fun <X, Y, Z> tripple(elem1: X, elem2: Y, elem3: Z): Tripple<X, Y, Z> { return Tripple(elem1, elem2, elem3) } } }
lgpl-3.0
71a29b05ac85cb2f2c50bd396dace4e9
27.716049
112
0.641015
3.703822
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/entities/PersonStatsEntity.kt
1
2179
package com.boardgamegeek.entities import android.content.Context import com.boardgamegeek.extensions.PlayStats.LOG_PLAY_STATS_ACCESSORIES import com.boardgamegeek.extensions.PlayStats.LOG_PLAY_STATS_EXPANSIONS import com.boardgamegeek.extensions.get import com.boardgamegeek.extensions.preferences class PersonStatsEntity( val averageRating: Double, val whitmoreScore: Int, val whitmoreScoreWithExpansions: Int, val playCount: Int, val hIndex: HIndexEntity ) { companion object { fun fromLinkedCollection(collection: List<BriefGameEntity>, context: Context): PersonStatsEntity { val baseGameCollection = collection.filter { it.subtype == "boardgame" } val averageRating = (baseGameCollection.sumOf { it.personalRating }) / baseGameCollection.filter { it.personalRating > 0.0 }.size val whitmoreScore = baseGameCollection .filter { it.personalRating > 6.5 } .sumOf { it.personalRating * 2.0 - 13.0 } .toInt() val whitmoreScoreWithExpansions = collection .filter { it.subtype != "boardgameaccessory" } .filter { it.personalRating > 6.5 } .sumOf { it.personalRating * 2.0 - 13.0 } .toInt() val playCount = baseGameCollection.sumOf { it.playCount } // TODO handle expansions val prefs = context.preferences() val exp = prefs[LOG_PLAY_STATS_EXPANSIONS, false] ?: false val acc = prefs[LOG_PLAY_STATS_ACCESSORIES, false] ?: false val hIndexList = when { exp && acc -> collection acc -> collection.filter { it.subtype != "boardgameexpansion" } acc -> collection.filter { it.subtype != "boardgameaccessory" } else -> baseGameCollection } .distinctBy { it.gameId } .map { it.playCount } val hIndex = HIndexEntity.fromList(hIndexList) return PersonStatsEntity(averageRating, whitmoreScore, whitmoreScoreWithExpansions, playCount, hIndex) } } }
gpl-3.0
525f4ebb98b7785e696456f6decd2985
40.113208
114
0.621386
4.456033
false
false
false
false
Kotlin/kotlinx.serialization
core/commonMain/src/kotlinx/serialization/internal/Platform.common.kt
1
6602
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:OptIn(ExperimentalSerializationApi::class) package kotlinx.serialization.internal import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlin.native.concurrent.* import kotlin.reflect.* internal object InternalHexConverter { private const val hexCode = "0123456789ABCDEF" fun parseHexBinary(s: String): ByteArray { val len = s.length require(len % 2 == 0) { "HexBinary string must be even length" } val bytes = ByteArray(len / 2) var i = 0 while (i < len) { val h = hexToInt(s[i]) val l = hexToInt(s[i + 1]) require(!(h == -1 || l == -1)) { "Invalid hex chars: ${s[i]}${s[i+1]}" } bytes[i / 2] = ((h shl 4) + l).toByte() i += 2 } return bytes } private fun hexToInt(ch: Char): Int = when (ch) { in '0'..'9' -> ch - '0' in 'A'..'F' -> ch - 'A' + 10 in 'a'..'f' -> ch - 'a' + 10 else -> -1 } fun printHexBinary(data: ByteArray, lowerCase: Boolean = false): String { val r = StringBuilder(data.size * 2) for (b in data) { r.append(hexCode[b.toInt() shr 4 and 0xF]) r.append(hexCode[b.toInt() and 0xF]) } return if (lowerCase) r.toString().lowercase() else r.toString() } fun toHexString(n: Int): String { val arr = ByteArray(4) for (i in 0 until 4) { arr[i] = (n shr (24 - i * 8)).toByte() } return printHexBinary(arr, true).trimStart('0').takeIf { it.isNotEmpty() } ?: "0" } } @OptIn(ExperimentalSerializationApi::class) internal fun SerialDescriptor.cachedSerialNames(): Set<String> { if (this is CachedNames) return serialNames val result = HashSet<String>(elementsCount) for (i in 0 until elementsCount) { result += getElementName(i) } return result } @SharedImmutable private val EMPTY_DESCRIPTOR_ARRAY: Array<SerialDescriptor> = arrayOf() /** * Same as [toTypedArray], but uses special empty array constant, if [this] * is null or empty. */ internal fun List<SerialDescriptor>?.compactArray(): Array<SerialDescriptor> = takeUnless { it.isNullOrEmpty() }?.toTypedArray() ?: EMPTY_DESCRIPTOR_ARRAY @Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE") @PublishedApi internal inline fun <T> KSerializer<*>.cast(): KSerializer<T> = this as KSerializer<T> @Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE") @PublishedApi internal inline fun <T> SerializationStrategy<*>.cast(): SerializationStrategy<T> = this as SerializationStrategy<T> @Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE") @PublishedApi internal inline fun <T> DeserializationStrategy<*>.cast(): DeserializationStrategy<T> = this as DeserializationStrategy<T> internal fun KClass<*>.serializerNotRegistered(): Nothing { throw SerializationException( "Serializer for class '${simpleName}' is not found.\n" + "Mark the class as @Serializable or provide the serializer explicitly." ) } internal expect fun KClass<*>.platformSpecificSerializerNotRegistered(): Nothing @Suppress("UNCHECKED_CAST") internal fun KType.kclass() = when (val t = classifier) { is KClass<*> -> t is KTypeParameter -> { error("Captured type paramerer $t from generic non-reified function. " + "Such functionality cannot be supported as $t is erased, either specify serializer explicitly or make " + "calling function inline with reified $t") } else -> error("Only KClass supported as classifier, got $t") } as KClass<Any> /** * Constructs KSerializer<D<T0, T1, ...>> by given KSerializer<T0>, KSerializer<T1>, ... * via reflection (on JVM) or compiler+plugin intrinsic `SerializerFactory` (on Native) */ internal expect fun <T : Any> KClass<T>.constructSerializerForGivenTypeArgs(vararg args: KSerializer<Any?>): KSerializer<T>? /** * Checks whether given KType and its corresponding KClass represent a reference array */ internal expect fun isReferenceArray(rootClass: KClass<Any>): Boolean /** * Array.get that checks indices on JS */ internal expect fun <T> Array<T>.getChecked(index: Int): T /** * Array.get that checks indices on JS */ internal expect fun BooleanArray.getChecked(index: Int): Boolean internal expect fun <T : Any> KClass<T>.compiledSerializerImpl(): KSerializer<T>? /** * Create serializers cache for non-parametrized and non-contextual serializers. * The activity and type of cache is determined for a specific platform and a specific environment. */ internal expect fun <T> createCache(factory: (KClass<*>) -> KSerializer<T>?): SerializerCache<T> /** * Create serializers cache for parametrized and non-contextual serializers. Parameters also non-contextual. * The activity and type of cache is determined for a specific platform and a specific environment. */ internal expect fun <T> createParametrizedCache(factory: (KClass<Any>, List<KType>) -> KSerializer<T>?): ParametrizedSerializerCache<T> internal expect fun <T : Any, E : T?> ArrayList<E>.toNativeArrayImpl(eClass: KClass<T>): Array<E> /** * Checks whether the receiver is an instance of a given kclass. * * This check is a replacement for [KClass.isInstance] because on JVM it requires kotlin-reflect.jar in classpath (see KT-14720). * * On JS and Native, this function delegates to aforementioned [KClass.isInstance] since it is supported there out-of-the-box; * on JVM, it falls back to `java.lang.Class.isInstance`, which causes difference when applied to function types with big arity. */ internal expect fun Any.isInstanceOf(kclass: KClass<*>): Boolean internal inline fun <T, K> Iterable<T>.elementsHashCodeBy(selector: (T) -> K): Int { return fold(1) { hash, element -> 31 * hash + selector(element).hashCode() } } /** * Cache class for non-parametrized and non-contextual serializers. */ internal interface SerializerCache<T> { /** * Returns cached serializer or `null` if serializer not found. */ fun get(key: KClass<Any>): KSerializer<T>? } /** * Cache class for parametrized and non-contextual serializers. */ internal interface ParametrizedSerializerCache<T> { /** * Returns successful result with cached serializer or `null` if root serializer not found. * If no serializer was found for the parameters, then result contains an exception. */ fun get(key: KClass<Any>, types: List<KType> = emptyList()): Result<KSerializer<T>?> }
apache-2.0
7d7e495517c702e02a2d43539ad98bfe
35.677778
135
0.679643
4.015815
false
false
false
false
Kotlin/kotlinx.serialization
core/commonMain/src/kotlinx/serialization/modules/SerializersModule.kt
1
10296
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.modules import kotlinx.serialization.* import kotlinx.serialization.internal.* import kotlin.js.* import kotlin.jvm.* import kotlin.native.concurrent.* import kotlin.reflect.* /** * [SerializersModule] is a collection of serializers used by [ContextualSerializer] and [PolymorphicSerializer] * to override or provide serializers at the runtime, whereas at the compile-time they provided by the serialization plugin. * It can be considered as a map where serializers can be found using their statically known KClasses. * * To enable runtime serializers resolution, one of the special annotations must be used on target types * ([Polymorphic] or [Contextual]), and a serial module with serializers should be used during construction of [SerialFormat]. * * Serializers module can be built with `SerializersModule {}` builder function. * Empty module can be obtained with `EmptySerializersModule()` factory function. * * @see Contextual * @see Polymorphic */ public sealed class SerializersModule { @ExperimentalSerializationApi @Deprecated( "Deprecated in favor of overload with default parameter", ReplaceWith("getContextual(kclass)"), DeprecationLevel.HIDDEN ) // Was experimental since 1.0.0, HIDDEN in 1.2.0 in a backwards-compatible manner public fun <T : Any> getContextual(kclass: KClass<T>): KSerializer<T>? = getContextual(kclass, emptyList()) /** * Returns a contextual serializer associated with a given [kClass]. * If given class has generic parameters and module has provider for [kClass], * [typeArgumentsSerializers] are used to create serializer. * This method is used in context-sensitive operations on a property marked with [Contextual] by a [ContextualSerializer]. * * @see SerializersModuleBuilder.contextual */ @ExperimentalSerializationApi public abstract fun <T : Any> getContextual( kClass: KClass<T>, typeArgumentsSerializers: List<KSerializer<*>> = emptyList() ): KSerializer<T>? /** * Returns a polymorphic serializer registered for a class of the given [value] in the scope of [baseClass]. */ @ExperimentalSerializationApi public abstract fun <T : Any> getPolymorphic(baseClass: KClass<in T>, value: T): SerializationStrategy<T>? /** * Returns a polymorphic deserializer registered for a [serializedClassName] in the scope of [baseClass] * or default value constructed from [serializedClassName] if a default serializer provider was registered. */ @ExperimentalSerializationApi public abstract fun <T : Any> getPolymorphic(baseClass: KClass<in T>, serializedClassName: String?): DeserializationStrategy<out T>? /** * Copies contents of this module to the given [collector]. */ @ExperimentalSerializationApi public abstract fun dumpTo(collector: SerializersModuleCollector) } /** * A [SerializersModule] which is empty and always returns `null`. */ @SharedImmutable @Deprecated("Deprecated in the favour of 'EmptySerializersModule()'", level = DeprecationLevel.WARNING, replaceWith = ReplaceWith("EmptySerializersModule()")) @JsName("EmptySerializersModuleLegacyJs") // Compatibility with JS public val EmptySerializersModule: SerializersModule = SerialModuleImpl(emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap()) /** * Returns a combination of two serial modules * * If serializer for some class presents in both modules, a [SerializerAlreadyRegisteredException] is thrown. * To overwrite serializers, use [SerializersModule.overwriteWith] function. */ public operator fun SerializersModule.plus(other: SerializersModule): SerializersModule = SerializersModule { include(this@plus) include(other) } /** * Returns a combination of two serial modules * * If serializer for some class presents in both modules, result module * will contain serializer from [other] module. */ @OptIn(ExperimentalSerializationApi::class) public infix fun SerializersModule.overwriteWith(other: SerializersModule): SerializersModule = SerializersModule { include(this@overwriteWith) other.dumpTo(object : SerializersModuleCollector { override fun <T : Any> contextual(kClass: KClass<T>, serializer: KSerializer<T>) { registerSerializer(kClass, ContextualProvider.Argless(serializer), allowOverwrite = true) } override fun <T : Any> contextual( kClass: KClass<T>, provider: (serializers: List<KSerializer<*>>) -> KSerializer<*> ) { registerSerializer(kClass, ContextualProvider.WithTypeArguments(provider), allowOverwrite = true) } override fun <Base : Any, Sub : Base> polymorphic( baseClass: KClass<Base>, actualClass: KClass<Sub>, actualSerializer: KSerializer<Sub> ) { registerPolymorphicSerializer(baseClass, actualClass, actualSerializer, allowOverwrite = true) } override fun <Base : Any> polymorphicDefaultSerializer( baseClass: KClass<Base>, defaultSerializerProvider: (value: Base) -> SerializationStrategy<Base>? ) { registerDefaultPolymorphicSerializer(baseClass, defaultSerializerProvider, allowOverwrite = true) } override fun <Base : Any> polymorphicDefaultDeserializer( baseClass: KClass<Base>, defaultDeserializerProvider: (className: String?) -> DeserializationStrategy<out Base>? ) { registerDefaultPolymorphicDeserializer(baseClass, defaultDeserializerProvider, allowOverwrite = true) } }) } // Implementation details below /** * A default implementation of [SerializersModule] * which uses hash maps to store serializers associated with KClasses. */ @Suppress("UNCHECKED_CAST") @OptIn(ExperimentalSerializationApi::class) internal class SerialModuleImpl( private val class2ContextualFactory: Map<KClass<*>, ContextualProvider>, @JvmField val polyBase2Serializers: Map<KClass<*>, Map<KClass<*>, KSerializer<*>>>, private val polyBase2DefaultSerializerProvider: Map<KClass<*>, PolymorphicSerializerProvider<*>>, private val polyBase2NamedSerializers: Map<KClass<*>, Map<String, KSerializer<*>>>, private val polyBase2DefaultDeserializerProvider: Map<KClass<*>, PolymorphicDeserializerProvider<*>> ) : SerializersModule() { override fun <T : Any> getPolymorphic(baseClass: KClass<in T>, value: T): SerializationStrategy<T>? { if (!value.isInstanceOf(baseClass)) return null // Registered val registered = polyBase2Serializers[baseClass]?.get(value::class) as? SerializationStrategy<T> if (registered != null) return registered // Default return (polyBase2DefaultSerializerProvider[baseClass] as? PolymorphicSerializerProvider<T>)?.invoke(value) } override fun <T : Any> getPolymorphic(baseClass: KClass<in T>, serializedClassName: String?): DeserializationStrategy<out T>? { // Registered val registered = polyBase2NamedSerializers[baseClass]?.get(serializedClassName) as? KSerializer<out T> if (registered != null) return registered // Default return (polyBase2DefaultDeserializerProvider[baseClass] as? PolymorphicDeserializerProvider<T>)?.invoke(serializedClassName) } override fun <T : Any> getContextual(kClass: KClass<T>, typeArgumentsSerializers: List<KSerializer<*>>): KSerializer<T>? { return (class2ContextualFactory[kClass]?.invoke(typeArgumentsSerializers)) as? KSerializer<T>? } override fun dumpTo(collector: SerializersModuleCollector) { class2ContextualFactory.forEach { (kclass, serial) -> when (serial) { is ContextualProvider.Argless -> collector.contextual( kclass as KClass<Any>, serial.serializer as KSerializer<Any> ) is ContextualProvider.WithTypeArguments -> collector.contextual(kclass, serial.provider) } } polyBase2Serializers.forEach { (baseClass, classMap) -> classMap.forEach { (actualClass, serializer) -> collector.polymorphic( baseClass as KClass<Any>, actualClass as KClass<Any>, serializer.cast() ) } } polyBase2DefaultSerializerProvider.forEach { (baseClass, provider) -> collector.polymorphicDefaultSerializer(baseClass as KClass<Any>, provider as (PolymorphicSerializerProvider<Any>)) } polyBase2DefaultDeserializerProvider.forEach { (baseClass, provider) -> collector.polymorphicDefaultDeserializer(baseClass as KClass<Any>, provider as (PolymorphicDeserializerProvider<out Any>)) } } } internal typealias PolymorphicDeserializerProvider<Base> = (className: String?) -> DeserializationStrategy<out Base>? internal typealias PolymorphicSerializerProvider<Base> = (value: Base) -> SerializationStrategy<Base>? /** This class is needed to support re-registering the same static (argless) serializers: * * ``` * val m1 = serializersModuleOf(A::class, A.serializer()) * val m2 = serializersModuleOf(A::class, A.serializer()) * val aggregate = m1 + m2 // should not throw * ``` */ internal sealed class ContextualProvider { abstract operator fun invoke(typeArgumentsSerializers: List<KSerializer<*>>): KSerializer<*> class Argless(val serializer: KSerializer<*>) : ContextualProvider() { override fun invoke(typeArgumentsSerializers: List<KSerializer<*>>): KSerializer<*> = serializer override fun equals(other: Any?): Boolean = other is Argless && other.serializer == this.serializer override fun hashCode(): Int = serializer.hashCode() } class WithTypeArguments(val provider: (typeArgumentsSerializers: List<KSerializer<*>>) -> KSerializer<*>) : ContextualProvider() { override fun invoke(typeArgumentsSerializers: List<KSerializer<*>>): KSerializer<*> = provider(typeArgumentsSerializers) } }
apache-2.0
a917607cc3803e3e666f48a08b44c958
42.812766
136
0.706682
5.094508
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/reporting/deploy/postgres/readers/ReportingSetReader.kt
1
5416
// Copyright 2022 The Cross-Media Measurement Authors // // 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.wfanet.measurement.reporting.deploy.postgres.readers import com.google.gson.JsonObject import com.google.gson.JsonParser import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.flow import org.wfanet.measurement.common.db.r2dbc.DatabaseClient import org.wfanet.measurement.common.db.r2dbc.ReadContext import org.wfanet.measurement.common.db.r2dbc.ResultRow import org.wfanet.measurement.common.db.r2dbc.boundStatement import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.common.identity.InternalId import org.wfanet.measurement.internal.reporting.ReportingSet import org.wfanet.measurement.internal.reporting.ReportingSet.EventGroupKey import org.wfanet.measurement.internal.reporting.ReportingSetKt import org.wfanet.measurement.internal.reporting.StreamReportingSetsRequest import org.wfanet.measurement.internal.reporting.reportingSet import org.wfanet.measurement.reporting.service.internal.ReportingInternalException import org.wfanet.measurement.reporting.service.internal.ReportingSetNotFoundException class ReportingSetReader { data class Result( val measurementConsumerReferenceId: String, val reportingSetId: InternalId, var reportingSet: ReportingSet ) private val baseSql: String = """ SELECT MeasurementConsumerReferenceId, ReportingSetId, ExternalReportingSetId, Filter, DisplayName, ( SELECT ARRAY( SELECT json_build_object( 'measurementConsumerReferenceId', MeasurementConsumerReferenceId, 'dataProviderReferenceId', DataProviderReferenceId, 'eventGroupReferenceId', EventGroupReferenceId ) FROM ReportingSetEventGroups WHERE ReportingSetEventGroups.MeasurementConsumerReferenceId = ReportingSets.MeasurementConsumerReferenceId AND ReportingSetEventGroups.ReportingSetId = ReportingSets.ReportingSetId ) ) AS EventGroups FROM ReportingSets """ fun translate(row: ResultRow): Result = Result(row["MeasurementConsumerReferenceId"], row["ReportingSetId"], buildReportingSet(row)) /** * Reads a Reporting Set using external ID. * * Throws a subclass of [ReportingInternalException]. * @throws [ReportingSetNotFoundException] Reporting Set not found. */ suspend fun readReportingSetByExternalId( readContext: ReadContext, measurementConsumerReferenceId: String, externalReportingSetId: ExternalId ): Result { val statement = boundStatement( baseSql + """ WHERE MeasurementConsumerReferenceId = $1 AND ExternalReportingSetId = $2 """ ) { bind("$1", measurementConsumerReferenceId) bind("$2", externalReportingSetId) } return readContext.executeQuery(statement).consume(::translate).firstOrNull() ?: throw ReportingSetNotFoundException() } fun listReportingSets( client: DatabaseClient, filter: StreamReportingSetsRequest.Filter, limit: Int = 0 ): Flow<Result> { val statement = boundStatement( baseSql + """ WHERE MeasurementConsumerReferenceId = $1 AND ExternalReportingSetId > $2 ORDER BY ExternalReportingSetId ASC LIMIT $3 """ ) { bind("$1", filter.measurementConsumerReferenceId) bind("$2", filter.externalReportingSetIdAfter) if (limit > 0) { bind("$3", limit) } else { bind("$3", 50) } } return flow { val readContext = client.readTransaction() try { emitAll(readContext.executeQuery(statement).consume(::translate)) } finally { readContext.close() } } } private fun buildReportingSet(row: ResultRow): ReportingSet { return reportingSet { measurementConsumerReferenceId = row["MeasurementConsumerReferenceId"] externalReportingSetId = row["ExternalReportingSetId"] filter = row["Filter"] displayName = row["DisplayName"] val eventGroupsArr = row.get<Array<String>>("EventGroups") eventGroupsArr.forEach { eventGroupKeys += buildEventGroupKey(JsonParser.parseString(it).asJsonObject) } } } private fun buildEventGroupKey(eventGroup: JsonObject): EventGroupKey { return ReportingSetKt.eventGroupKey { measurementConsumerReferenceId = eventGroup.getAsJsonPrimitive("measurementConsumerReferenceId").asString dataProviderReferenceId = eventGroup.getAsJsonPrimitive("dataProviderReferenceId").asString eventGroupReferenceId = eventGroup.getAsJsonPrimitive("eventGroupReferenceId").asString } } }
apache-2.0
5fbd73a4d8a860338d01ba5c391bc3e6
34.168831
117
0.722489
4.982521
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/run/bibtex/BibtexSettingsEditor.kt
1
6065
package nl.hannahsten.texifyidea.run.bibtex import com.intellij.execution.configuration.EnvironmentVariablesComponent import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileTypeDescriptor import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.* import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.RawCommandLineEditor import com.intellij.ui.SeparatorComponent import nl.hannahsten.texifyidea.run.compiler.BibliographyCompiler import java.awt.event.ItemEvent import javax.swing.JCheckBox import javax.swing.JComponent import javax.swing.JPanel /** * @author Sten Wessel */ class BibtexSettingsEditor(private val project: Project) : SettingsEditor<BibtexRunConfiguration>() { private lateinit var panel: JPanel private lateinit var compiler: LabeledComponent<ComboBox<BibliographyCompiler>> private lateinit var enableCompilerPath: JCheckBox private lateinit var compilerPath: TextFieldWithBrowseButton private lateinit var compilerArguments: LabeledComponent<RawCommandLineEditor> private lateinit var environmentVariables: EnvironmentVariablesComponent private lateinit var mainFile: LabeledComponent<TextFieldWithBrowseButton> /** Keep track of the the working directory for bibtex, i.e., where bibtex should find the files it needs. * Is automatically set based on the LaTeX run config when created. */ private lateinit var bibWorkingDir: LabeledComponent<TextFieldWithBrowseButton> override fun createEditor(): JComponent { createUIComponents() return panel } override fun resetEditorFrom(runConfig: BibtexRunConfiguration) { compiler.component.selectedItem = runConfig.compiler compilerPath.text = runConfig.compilerPath ?: "" compilerArguments.component.text = runConfig.compilerArguments ?: "" environmentVariables.envData = runConfig.environmentVariables enableCompilerPath.isSelected = runConfig.compilerPath != null mainFile.component.text = runConfig.mainFile?.path ?: "" bibWorkingDir.component.text = runConfig.bibWorkingDir?.path ?: "" } override fun applyEditorTo(runConfig: BibtexRunConfiguration) { runConfig.compiler = compiler.component.selectedItem as BibliographyCompiler? runConfig.compilerPath = if (enableCompilerPath.isSelected) compilerPath.text else null runConfig.compilerArguments = compilerArguments.component.text runConfig.environmentVariables = environmentVariables.envData runConfig.mainFile = LocalFileSystem.getInstance().findFileByPath(mainFile.component.text) runConfig.bibWorkingDir = LocalFileSystem.getInstance().findFileByPath(bibWorkingDir.component.text) } private fun createUIComponents() { panel = JPanel().apply { layout = VerticalFlowLayout(VerticalFlowLayout.TOP) // Compiler val compilerField = ComboBox(BibliographyCompiler.values()) compiler = LabeledComponent.create(compilerField, "Compiler") add(compiler) // Custom compiler path compilerPath = TextFieldWithBrowseButton().apply { addBrowseFolderListener( TextBrowseFolderListener( FileChooserDescriptor(true, false, false, false, false, false) .withFileFilter { file -> file.nameWithoutExtension == (compiler.component.selectedItem as BibliographyCompiler?)?.executableName } .withTitle("Choose ${compiler.component.selectedItem} executable") ) ) isEnabled = false addPropertyChangeListener("enabled") { e -> if (!(e.newValue as Boolean)) { this.text = "" } } } enableCompilerPath = JCheckBox("Select custom compiler executable path (required on Mac OS X)").apply { addItemListener { e -> compilerPath.isEnabled = e.stateChange == ItemEvent.SELECTED } } add(enableCompilerPath) add(compilerPath) // Custom compiler arguments val argumentsTitle = "Custom compiler arguments" val argumentsField = RawCommandLineEditor() compilerArguments = LabeledComponent.create(argumentsField, argumentsTitle) add(compilerArguments) environmentVariables = EnvironmentVariablesComponent() add(environmentVariables) add(SeparatorComponent()) // Main file val mainFileField = TextFieldWithBrowseButton().apply { addBrowseFolderListener( TextBrowseFolderListener( FileTypeDescriptor("Choose the main .tex file", ".tex") .withRoots(*ProjectRootManager.getInstance(project).contentRootsFromAllModules) ) ) } mainFile = LabeledComponent.create(mainFileField, "Main file that includes bibliography") add(mainFile) // Working directory val workingDirField = TextFieldWithBrowseButton() workingDirField.addBrowseFolderListener( TextBrowseFolderListener( FileChooserDescriptor(false, true, false, false, false, false) .withTitle("Choose the BibTeX working directory") .withRoots( *ProjectRootManager.getInstance(project) .contentRootsFromAllModules ) ) ) bibWorkingDir = LabeledComponent.create(workingDirField, "Working directory for bibtex") add(bibWorkingDir) } } }
mit
7bbf270bc11595b0be03d9e0ef1f91b5
44.261194
159
0.664963
6.089357
false
true
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/completion/BibtexKeyProvider.kt
1
3745
package nl.hannahsten.texifyidea.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.PsiFile import com.intellij.util.PlatformIcons import com.intellij.util.ProcessingContext import com.intellij.util.containers.ContainerUtil import nl.hannahsten.texifyidea.TexifyIcons import nl.hannahsten.texifyidea.completion.handlers.TokenTypeInsertHandler import nl.hannahsten.texifyidea.lang.* import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.psi.BibtexEntry import nl.hannahsten.texifyidea.psi.BibtexKey import nl.hannahsten.texifyidea.util.* /** * @author Hannah Schellekens */ object BibtexKeyProvider : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val psiElement = parameters.position val entry = psiElement.parentOfType(BibtexEntry::class) ?: return val token = entry.tokenType() ?: return val entryType = BibtexDefaultEntryType[token] ?: return val optional: Set<BibtexEntryField> = entryType.optional.toSet() val required: Set<BibtexEntryField> = entryType.required.toSet() // Removed already present items. val allFields: Set<BibtexEntryField> = entryType.allFields().toSet() val userDefined: Set<BibtexEntryField> = findUserDefinedKeys(entry.containingFile, allFields) val keys = entry.keyNames() val fields = (allFields + userDefined).toMutableSet() fields.removeIf { it.fieldName in keys } // Add lookup elements. result.addAllElements( ContainerUtil.map2List(fields) { val (message, icon) = when (it) { in required -> " required" and TexifyIcons.KEY_REQUIRED in optional -> " optional" and PlatformIcons.PROTECTED_ICON in userDefined -> " custom" and TexifyIcons.KEY_USER_DEFINED else -> "" and PlatformIcons.PROTECTED_ICON } LookupElementBuilder.create(it, it.fieldName) .withPresentableText(it.fieldName) .bold() .withTypeText(message, true) .withIcon(icon) .withTailText(packageName(it), true) .withInsertHandler(TokenTypeInsertHandler) } ) } /** * Scans the given file for fields that are defined by the user. * * @param file * The file to scan. * @param allFields * All fields that are already in the autocomplete. * @return A list containing all user defined keys. */ private fun findUserDefinedKeys(file: PsiFile, allFields: Collection<BibtexEntryField>): Set<BibtexEntryField> { val result = HashSet<BibtexEntryField>() val presentFieldSet: MutableSet<String> = allFields.map { it.fieldName } .toMutableSet() for (key in file.childrenOfType(BibtexKey::class)) { val name = key.text if (name !in presentFieldSet) { presentFieldSet.add(name) result.add(SimpleBibtexEntryField(name, "User defined string.")) } } return result } private fun packageName(dependend: Dependend): String { return when (val dependency = dependend.dependency) { LatexPackage.DEFAULT -> "" else -> " (${dependency.name})" } } }
mit
3a13b12ce001568d06be7ae8eb5fd250
40.164835
124
0.662216
5.053981
false
false
false
false
V2Ray-Android/Actinium
app/src/main/kotlin/com/v2ray/actinium/util/ConfigManager.kt
1
1291
package com.v2ray.actinium.util import android.content.Context import com.v2ray.actinium.ActiniumApplication import com.v2ray.actinium.defaultDPreference import java.io.File object ConfigManager { const val PREF_CURR_CONFIG = "pref_curr_config" private lateinit var app: ActiniumApplication val configFileDir by lazy { File(app.filesDir, "configs") } val configs: Array<out String> get() = configFileDir.list() fun inject(app: ActiniumApplication) { this.app = app if (app.firstRun) { if (!configFileDir.exists() || !configFileDir.isDirectory) configFileDir.mkdirs() // TODO: The official server has been suspended AssetsUtil.copyAsset(app.assets, "conf_default.json", File(configFileDir, "default").absolutePath) } } fun getConfigFileByName(name: String) = File(configFileDir, name) fun delConfigFileByName(name: String) = getConfigFileByName(name).delete() fun delConfigFilesByName(names: Collection<String>) = names.forEach { delConfigFileByName(it) } } val Context.currConfigFile: File get() = File(ConfigManager.configFileDir, currConfigName) val Context.currConfigName: String get() = defaultDPreference.getPrefString(ConfigManager.PREF_CURR_CONFIG, "default")
gpl-3.0
a6ce3c93975041ce4e0018761f7cdaea
33
118
0.721921
4.124601
false
true
false
false
k0kubun/github-ranking
worker/src/main/kotlin/com/github/k0kubun/gitstar_ranking/db/PaginatedOrganizations.kt
2
1101
package com.github.k0kubun.gitstar_ranking.db import com.github.k0kubun.gitstar_ranking.core.Organization import com.github.k0kubun.gitstar_ranking.core.StarsCursor import org.jooq.DSLContext private const val PAGE_SIZE = 5000 // This class does cursor-based-pagination for organizations order by stargazers_count DESC. class PaginatedOrganizations(private val database: DSLContext) { private var lastMinStars: Long? = null private var lastMinId: Long? = null fun nextOrgs(): List<Organization> { val orgs: List<Organization> = if (lastMinId != null && lastMinStars != null) { OrganizationQuery(database).orderByStarsDesc( limit = PAGE_SIZE, after = StarsCursor(id = lastMinId!!, stars = lastMinStars!!) ) } else { OrganizationQuery(database).orderByStarsDesc(limit = PAGE_SIZE) } if (orgs.isEmpty()) { return orgs } val lastOrg = orgs[orgs.size - 1] lastMinStars = lastOrg.stargazersCount lastMinId = lastOrg.id return orgs } }
mit
7ff6b3b53a2f6a9a1063053c1f743e2c
34.516129
92
0.658492
4.20229
false
false
false
false
if710/if710.github.io
2019-08-16/RecyclerView/app/src/main/java/br/ufpe/cin/android/recyclerview/ListViewActivity.kt
1
1642
package br.ufpe.cin.android.recyclerview import android.app.Activity import android.os.Bundle import android.widget.ArrayAdapter import android.widget.TextView import android.widget.Toast import kotlinx.android.synthetic.main.activity_listview.* import java.util.* class ListViewActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_listview) //k -> v //Map<Integer, String> mapa = new... //mapa.put(0,"alguma string); val opcoes = hashMapOf( 0 to Constants.lista, 1 to Constants.listaLonga, 2 to Constants.palavrasSimilares ) btn_Troca.setOnClickListener { val i = Random().nextInt(opcoes.size) val opcao = opcoes[i] if (opcao != null) { val adapter = ArrayAdapter<String>( //this, applicationContext, android.R.layout.simple_list_item_1, opcao ) //listaElementos.setAdapter(adapter) listaElementos.adapter = adapter } } listaElementos.setOnItemClickListener { parent, view, posicao, _ -> val texto = parent.adapter.getItem(posicao) val txt = (view as TextView).text Toast.makeText( this, //texto.toString(), txt, Toast.LENGTH_SHORT ).show() } } }
mit
2aa70daf20210c76f8345225a43f4b3c
27.807018
59
0.537759
4.625352
false
false
false
false
AlbRoehm/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/NumberAbbreviator.kt
1
917
package com.habitrpg.android.habitica.helpers import android.content.Context import com.habitrpg.android.habitica.R import java.math.RoundingMode import java.text.DecimalFormat object NumberAbbreviator { fun abbreviate(context: Context, number: Double): String { var usedNumber = number var counter = 0 while (usedNumber >= 1000) { counter++ usedNumber /= 1000 } val formatter = DecimalFormat("###.##" + abbreviationForCounter(context, counter)) formatter.roundingMode = RoundingMode.FLOOR return formatter.format(usedNumber) } private fun abbreviationForCounter(context: Context, counter: Int): String = when (counter) { 1 -> context.getString(R.string.thousand_abbrev) 2 -> context.getString(R.string.million_abbrev) 3 -> context.getString(R.string.billion_abbrev) else -> "" } }
gpl-3.0
384a76ba4290e40c71821859c9b61d14
28.580645
97
0.665213
4.38756
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/fragments/points/GivePointsFrag.kt
1
5798
package com.duopoints.android.fragments.points import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentStatePagerAdapter import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.duopoints.android.R import com.duopoints.android.fragments.base.BasePresenterFrag import com.duopoints.android.fragments.points.models.GivePointsCompleteData import com.duopoints.android.fragments.points.models.GivePointsEventDetails import com.duopoints.android.fragments.points.steps.details.GivePointsDetailsFrag import com.duopoints.android.fragments.points.steps.media.GivePointsMediaFrag import com.duopoints.android.fragments.points.steps.summary.GivePointsSummaryFrag import com.duopoints.android.fragments.points.steps.what.GivePointsWhatFrag import com.duopoints.android.rest.models.points.PointType import com.duopoints.android.rest.models.points.PointTypeCategory import com.duopoints.android.ui.animations.Animations import kotlinx.android.synthetic.main.frag_points_layout.* class GivePointsFrag : BasePresenterFrag<GivePointsPresenter>(), GivePointsListener { override fun createPresenter(): GivePointsPresenter { return GivePointsPresenter(this) } override fun getEnterAnimation(): Int { return R.anim.enter_from_up } override fun getExitAnimation(): Int { return R.anim.exit_to_up } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return createAndBindView(R.layout.frag_points_layout, inflater, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) givingPointsPager.offscreenPageLimit = 4 givingPointsPager.adapter = ViewPagerAdapter(this) givingPointsStepsIndicator.setViewPager(givingPointsPager, 3) // Reloads on cart update (until opposite Lifecycle event) presenter.observeCartUpdates() } override fun onResume() { super.onResume() mainActivity.lockDrawers() // Locks the drawers, to prevent too many touch events. } override fun onPause() { super.onPause() mainActivity.unlockDrawers() } private inner class ViewPagerAdapter internal constructor(givePointsFrag: GivePointsFrag) : FragmentStatePagerAdapter(givePointsFrag.fragmentManager) { internal var fragments: MutableList<Fragment> = mutableListOf() init { fragments.add(GivePointsWhatFrag.newInstance(givePointsFrag)) fragments.add(GivePointsMediaFrag.newInstance(givePointsFrag)) fragments.add(GivePointsDetailsFrag.newInstance(givePointsFrag)) } override fun getItem(position: Int): Fragment { return fragments[position] } override fun getCount(): Int { return fragments.size } internal fun addCompleted(fragment: Fragment) { fragments.add(fragment) this.notifyDataSetChanged() } } /******************** * CLASS FUNCTIONS ********************/ fun eventReady(data: GivePointsCompleteData) { actionButton.text = "Ready to give Points" // actionButton.setBackgroundResource(R.attr.colorAccentGreen) actionButton.setOnClickListener { givingPointsPager.adapter?.let { // Add the summary screen (givingPointsPager.adapter as ViewPagerAdapter).addCompleted(GivePointsSummaryFrag.newInstance(data)) // Go to the summary screen givingPointsPager.setCurrentItem(3, true) // Disable moving back to any other fragment. givingPointsPager.setPagingEnabled(false) // Collapse the ActionButton Animations.collapseVertically(actionButton) } } } fun cartEmpty() { actionButton.text = "No Points" actionButton.setBackgroundResource(R.color.colorAccent) actionButton.setOnClickListener { givingPointsPager.currentItem = 0 } } fun mediaNull() { actionButton.text = "No Media" actionButton.setBackgroundResource(R.color.colorAccent) actionButton.setOnClickListener { givingPointsPager.currentItem = 1 // Show the Media list // Ask about no Media selected AlertDialog.Builder(context) .setTitle("No Media") .setMessage("You have not added any media to this event. Are you sure?") .setNegativeButton("Cancel", null) .setPositiveButton("Yes") { _, _ -> presenter.mediaUpdated(emptyList()) } .show() } } fun detailsEmpty() { actionButton.text = "Details Missing" actionButton.setBackgroundResource(R.color.colorAccent) actionButton.setOnClickListener { givingPointsPager.currentItem = 2 } } /************************************** * LISTENER - From Viewpager fragments **************************************/ override fun pointUpdated(selectedCategory: PointTypeCategory?, pointType: PointType) { presenter.pointUpdated(selectedCategory, pointType) } override fun mediaUpdated(mediaUris: List<Uri>?) { presenter.mediaUpdated(mediaUris) } override fun eventDetailsUpdated(eventDetails: GivePointsEventDetails?) { presenter.eventDetailsUpdated(eventDetails) } companion object { @JvmStatic fun newInstance(): GivePointsFrag { return GivePointsFrag() } } }
gpl-3.0
6c5ba232929fd7432887a481a655ed13
34.576687
155
0.67851
4.989673
false
false
false
false
B515/Schedule
app/src/main/kotlin/xyz/b515/schedule/util/CourseParser.kt
1
2519
package xyz.b515.schedule.util import com.jrummyapps.android.colorpicker.ColorPickerDialog import org.jsoup.Jsoup import xyz.b515.schedule.db.CourseManager import xyz.b515.schedule.entity.Course import xyz.b515.schedule.entity.Spacetime import java.util.* object CourseParser { private val weekdayTimePattern = "周(.)第(.+)θŠ‚\\{第(\\d+)-(\\d+)周\\}".toRegex() fun parse(text: String, manager: CourseManager) { val names = ArrayList<String>() val document = Jsoup.parse(text) val courses = document.getElementById("Table1").getElementsByTag("td") for (td in courses) { if ("周" !in td.text()) continue for (nodes in td.textNodes().map { it.text() }.chunked(4)) { val name = nodes[0] val course: Course if (name !in names) { names.add(name) course = Course() course.name = name course.teacher = nodes[2] val color = ColorPickerDialog.MATERIAL_COLORS[Random().nextInt(18)] course.color = ColorHelper.shadeColor(color, 0.33) manager.insertCourse(course) } else { course = manager.getCourse(name) } val spacetime = Spacetime() spacetime.course = course val m = weekdayTimePattern.find(nodes[1]) m?.let { val values = m.groupValues val weeks = values[2].split(",") with(spacetime) { weekday = translateWeekday(values[1]) startTime = weeks.first().toInt() endTime = weeks.last().toInt() startWeek = values[3].toInt() endWeek = values[4].toInt() location = nodes[3] oddWeek = "单周" in nodes[1] evenWeek = "εŒε‘¨" in nodes[1] } } manager.insertSpacetime(spacetime) } } } private fun translateWeekday(s: String) = when (s) { "δΈ€" -> Calendar.MONDAY "二" -> Calendar.TUESDAY "δΈ‰" -> Calendar.WEDNESDAY "ε››" -> Calendar.THURSDAY "δΊ”" -> Calendar.FRIDAY "ε…­" -> Calendar.SATURDAY "ζ—₯" -> Calendar.SUNDAY else -> 0 } }
apache-2.0
8f9a3f65778adad77bc4e4647383f9d9
32.133333
87
0.491348
4.559633
false
false
false
false
DSolyom/ViolinDS
ViolinDS/app/src/main/java/ds/violin/v1/app/violin/LocationViolin.kt
1
10857
/* Copyright 2016 DΓ‘niel SΓ³lyom 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 ds.violin.v1.app.violin import android.Manifest import android.app.Activity import android.content.Context import android.content.IntentSender import android.content.pm.PackageManager import android.location.Location import android.location.LocationManager import android.os.Bundle import android.provider.Settings import com.google.android.gms.common.ConnectionResult import com.google.android.gms.location.* import ds.violin.v1.Global import ds.violin.v1.util.common.Debug interface LocationViolin : LocationListener { companion object { const val CHECK_SETTINGS_CODE = 8345 const val ASK_PERMISSION_LOCATION = "DS_Ask_LocationViolin_Ask_Perimission_" const val TAG_I_STATE = "__location_violin_" } /** @see [LocationRequest] */ val locationUpdateInterval: Long /** @see [LocationRequest] */ val locationFastestUpdateInterval: Long /** @see [LocationRequest] */ val locationPriority: Int /** * required user permissions for location - choose one or more from: * [Manifest.permission.ACCESS_COARSE_LOCATION], * [Manifest.permission.ACCESS_FINE_LOCATION] */ val requiredLocationPermissions: Array<String> /** = null, last known location - or [currentLocation] if that is set */ var lastKnownLocation: Location? /** = null, current location or null if no location has been found */ var currentLocation: Location? /** = ArrayList(), #Private */ var locationRequests: MutableList<LocationRequest> /** should look for location - should call [initLocationChecking] when setting after the first time */ var locationCheckEnabled: Boolean /** = false, #Private */ var checkedLocationSettings: Boolean /** = false, #Private */ var locationRequestsStarted: Boolean /** = true, #Private */ var locationDisabledNotified: Boolean /** * call before [GoogleApiViolin.onCreate] */ fun onCreate(savedInstanceState: Bundle?) { (this as GoogleApiViolin).requiredApis.add(LocationServices.API) checkedLocationSettings = Global.preferences.getBoolean(TAG_I_STATE + "checked_settings", checkedLocationSettings) } /** * save [checkedLocationSettings] - call this in [onLocationSettingsDisabled] if locations are not * that important and one failed question was enough */ fun saveCheckedLocationSettings() { Global.preferences.edit(). putBoolean(TAG_I_STATE + "checked_settings", checkedLocationSettings).apply() } fun onResume() { if (locationCheckEnabled && (this as GoogleApiViolin).googleApiClient?.isConnected ?: false) { // check location settings knowing that either it is either already working or // already checked and no further message to the user will be showing initLocationChecking() } } fun onPause() { if (locationCheckEnabled && (this as GoogleApiViolin).googleApiClient?.isConnected ?: false) { stopLocationRequests() } } fun onGoogleApiConnected(connectionHint: Bundle?) { lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation( (this as GoogleApiViolin).googleApiClient) initLocationChecking() } fun onGoogleApiConnectionFailed(result: ConnectionResult) { onLocationSettingsDisabled() // TODO: sure? } fun initLocationChecking() { if (locationCheckEnabled) { if (locationRequests.isEmpty()) { addLocationRequests() } if (!locationRequests.isEmpty()) { startLocationRequests() } } else { stopLocationRequests() } } fun addLocationRequests() { locationRequests.add(createDefaultLocationRequest()) } /** * check if getting location is enabled on the device - start resolution when required */ fun checkLocationSettings() { if (checkedLocationSettings) { return } val locationSettingsRequest = LocationSettingsRequest.Builder() .addAllLocationRequests(locationRequests) .build() val result = LocationServices.SettingsApi. checkLocationSettings((this as GoogleApiViolin).googleApiClient, locationSettingsRequest) result.setResultCallback { result -> val status = result.status when (status.statusCode) { LocationSettingsStatusCodes.SUCCESS -> { // make sure we ask for settings again if it was turned off checkedLocationSettings = false /** */ startLocationRequests() } LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> if (checkedLocationSettings) { if (!locationDisabledNotified) { onLocationSettingsDisabled() } } else { try { status.startResolutionForResult( (this@LocationViolin as PlayingViolin).violinActivity as Activity, CHECK_SETTINGS_CODE) checkedLocationSettings = true } catch (e: IntentSender.SendIntentException) { } } LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> if (!locationDisabledNotified) { onLocationSettingsDisabled() } } } } fun createDefaultLocationRequest(): LocationRequest { val locationRequest = LocationRequest(); locationRequest.interval = locationUpdateInterval; locationRequest.fastestInterval = locationFastestUpdateInterval; locationRequest.priority = locationPriority; return locationRequest } fun onActivityResult(requestCode: Int, resultCode: Int, result: Any?) { if (requestCode == CHECK_SETTINGS_CODE) { // need to check manually if location settings are now enabled because resultCode could always be 0 on some devices var lm = ((this as PlayingViolin).violinActivity as Context).getSystemService(Context.LOCATION_SERVICE) as LocationManager var good = false for (permission in requiredLocationPermissions) { good = good or when (permission) { Manifest.permission.ACCESS_COARSE_LOCATION -> lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) Manifest.permission.ACCESS_FINE_LOCATION -> lm.isProviderEnabled(LocationManager.GPS_PROVIDER) else -> false } if (good) { startLocationRequests() break } } if (!good) { onLocationSettingsDisabled() } } } fun startLocationRequests() { try { if (!locationRequestsStarted) { for (request in locationRequests) { LocationServices.FusedLocationApi.requestLocationUpdates( (this as GoogleApiViolin).googleApiClient, request, this) } locationRequestsStarted = true checkLocationSettings() } } catch(e: SecurityException) { if (!checkedLocationSettings) { (this as PlayingViolin). askUserForPermission(ASK_PERMISSION_LOCATION, requiredLocationPermissions) { permissions, grantResults -> val success = grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED if (success) { startLocationRequests() } else { onLocationSettingsDisabled() } } } } } fun stopLocationRequests() { locationRequestsStarted = false LocationServices.FusedLocationApi.removeLocationUpdates( (this as GoogleApiViolin).googleApiClient, this) } /** * override to act when location settings are still disabled or permissions are still not given after asking for them * * if location's are not required you can set [checkedLocationSettings] to true and call [saveCheckedLocationSettings] * not to check for permission again * * !note: always call this (super) to set [locationDisabledNotified] */ fun onLocationSettingsDisabled() { locationDisabledNotified = true Debug.logD("LocationViolin", "Location settings disabled") } override fun onLocationChanged(location: Location?) { lastKnownLocation = location currentLocation = location } fun restoreInstanceState(savedInstanceState: Bundle) { lastKnownLocation = savedInstanceState.getParcelable(TAG_I_STATE + "lastknownlocation_") currentLocation = savedInstanceState.getParcelable(TAG_I_STATE + "currentlocation_") locationCheckEnabled = savedInstanceState.getSerializable(TAG_I_STATE + "locationcheckenabled_") as Boolean checkedLocationSettings = savedInstanceState.getSerializable(TAG_I_STATE + "checkedlocationsettings_") as Boolean locationDisabledNotified = savedInstanceState.getSerializable(TAG_I_STATE + "locationdisablednotified_") as Boolean } fun saveInstanceState(outState: Bundle) { outState.putParcelable(TAG_I_STATE + "lastknownlocation_", lastKnownLocation) outState.putParcelable(TAG_I_STATE + "currentlocation_", currentLocation) outState.putSerializable(TAG_I_STATE + "locationcheckenabled_", locationCheckEnabled) outState.putSerializable(TAG_I_STATE + "checkedlocationsettings_", checkedLocationSettings) outState.putSerializable(TAG_I_STATE + "locationdisablednotified_", locationDisabledNotified) } }
apache-2.0
5f6217fbcdf0fcbd87c25924ea3c1147
38.620438
134
0.629664
5.529801
false
false
false
false
cout970/ComputerMod
src/main/kotlin/com/cout970/computer/util/vector/Vec3d.kt
1
1193
package com.cout970.computer.util.vector import net.minecraft.util.math.Vec3d /** * Created by cout970 on 14/05/2016. */ // constructors fun Vec3d(): Vec3d = net.minecraft.util.math.Vec3d(0.0, 0.0, 0.0) fun Vec3d(x: Float, y: Float, z: Float): Vec3d = net.minecraft.util.math.Vec3d(x.toDouble(), y.toDouble(), z.toDouble()) fun Vec3d(x: Int, y: Int, z: Int): Vec3d = net.minecraft.util.math.Vec3d(x.toDouble(), y.toDouble(), z.toDouble()) // getters fun Vec3d.getX(): Double = xCoord.toDouble() fun Vec3d.getY(): Double = yCoord.toDouble() fun Vec3d.getZ(): Double = zCoord.toDouble() fun Vec3d.getXf(): Float = xCoord.toFloat() fun Vec3d.getYf(): Float = yCoord.toFloat() fun Vec3d.getZf(): Float = zCoord.toFloat() fun Vec3d.getXi(): Int = xCoord.toInt() fun Vec3d.getYi(): Int = yCoord.toInt() fun Vec3d.getZi(): Int = zCoord.toInt() // setters fun Vec3d.setX(xCoord: Double) = Vec3d(xCoord, yCoord, zCoord) fun Vec3d.setY(yCoord: Double) = Vec3d(xCoord, yCoord, zCoord) fun Vec3d.setZ(zCoord: Double) = Vec3d(xCoord, yCoord, zCoord) // utilities fun Vec3d.xy() = Vec2d(xCoord, yCoord) fun Vec3d.yz() = Vec2d(yCoord, zCoord) fun Vec3d.xz() = Vec2d(xCoord, zCoord)
gpl-3.0
97e940446c39c13de0d34c43139f8c2d
21.961538
120
0.689858
2.490605
false
false
false
false
demmonic/KInject
src/main/java/info/demmonic/kinject/CallTransformer.kt
1
1782
package info.demmonic.kinject import org.objectweb.asm.Opcodes import org.objectweb.asm.tree.MethodInsnNode /** * @author Demmonic */ class CallTransformer : Transformer { var methodClassName: String? = "" var methodName: String? = "" var methodDesc: String? = "" var injectIdx: Int = -1 var toClassName: String? = "" var toMethodName: String? = "" var toMethodDesc: String? = "" constructor() { } constructor(methodClassName: String?, methodName: String?, methodDesc: String?, injectIdx: Int, toClassName: String?, toMethodName: String?, toMethodDesc: String?) { this.methodClassName = methodClassName this.methodName = methodName this.methodDesc = methodDesc this.injectIdx = injectIdx this.toClassName = toClassName this.toMethodName = toMethodName this.toMethodDesc = toMethodDesc } override fun transform(cl: NodeClassLoader) { val methodParent = cl.raw.values.findLast { n -> n.name.equals(methodClassName) } ?: throw IllegalArgumentException("Unable to find method node with name $methodClassName") val method = methodParent.typedMethods.findLast { f -> f.name.equals(methodName) && f.desc.equals(methodDesc) } ?: throw IllegalArgumentException("Unable to find method with the name $methodName and the desc $methodDesc") val arr = method.instructions.toArray() for (ins in arr) { if (ins.opcode == Opcodes.RETURN) { method.instructions.insertBefore(ins, MethodInsnNode(Opcodes.INVOKESTATIC, toClassName, toMethodName, toMethodDesc, false)) } } } }
mit
a596d33a245a0d7e1f1c6a98c1c73c77
32.018519
139
0.628507
4.652742
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/ToolPane_Impl.kt
1
7355
/* 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.application.Platform import javafx.geometry.Side import javafx.scene.layout.BorderPane import uk.co.nickthecoder.paratask.ParaTaskApp import uk.co.nickthecoder.paratask.Tool import uk.co.nickthecoder.paratask.gui.MyTab import uk.co.nickthecoder.paratask.gui.MyTabPane import uk.co.nickthecoder.paratask.table.filter.Filtered class ToolPane_Impl(override val tool: Tool) : ToolPane, BorderPane() { override val tabPane = MyTabPane<MinorTab>() override var parametersPane: ToolParametersPane = ToolParametersPane_Impl(tool) override lateinit var halfTab: HalfTab override val parametersTab = ParametersTab(parametersPane) val header: HeaderOrFooter? = tool.createHeader() val footer: HeaderOrFooter? = tool.createFooter() var filterTab: FilterTab? = null init { center = tabPane tabPane.side = Side.BOTTOM parametersTab.canClose = false tabPane.add(parametersTab) // Add the filter tab, if the tool has a filter if (tool is Filtered) { val filters = tool.rowFilters if (filters.isNotEmpty()) { filterTab = FilterTab(tool, filters) tabPane.add(filterTab!!) } } tabPane.selectionModel.selectedItemProperty().addListener { _, oldTab, newTab -> onTabChanged(oldTab, newTab) } } /** * Called when the MAJOR tab has changed, and is used to ensure focus on the currently selected MINOR tab. */ override fun selected() { val tab = tabPane.selectionModel.selectedItem if (tab is MinorTab) { Platform.runLater { tab.focus() } } } fun onTabChanged(oldTab: MyTab?, newTab: MyTab?) { if (oldTab is MinorTab) { oldTab.deselected() } if (newTab is MinorTab) { newTab.selected() } top = if (newTab is ResultsTab) header else null bottom = if (newTab is ResultsTab) footer else null } override fun resultsTool(): Tool { val tab = tabPane.selectionModel.selectedItem if (tab is ResultsTab) { return tab.results.tool } else { return tool } } private fun removeOldResults(oldResultsList: List<Results>): Int { var index = 0 // This is Order n squared, but n is small, so I won't bother optimising it! for (oldResults in oldResultsList) { val oldIndex = removeResults(oldResults) if (oldIndex >= 0) { index = oldIndex } } return index } private fun removeResults(results: Results): Int { for ((i, tab) in tabPane.tabs.withIndex()) { if (tab is ResultsTab && tab.results === results) { tabPane.remove(tab) return i } } return -1 } override fun replaceResults(resultsList: List<Results>, oldResultsList: List<Results>) { removeOldResults(oldResultsList) parametersTab.styleClass.remove("separated") if (resultsList.isNotEmpty()) { parametersTab.styleClass.add("separated") } resultsList.forEach { results -> addResults(results) } // Select the first tab, unless another tab selected itself while being added. if (parametersTab.isSelected || filterTab?.isSelected == true) { tabPane.selectionModel.select(0) } } override fun addResults(results: Results): ResultsTab { tabPane.tabs.forEachIndexed { index, tab -> if (tab !is ResultsTab) { return addResults(results, index) } } return addResults(results, 0) } override fun addResults(results: Results, index: Int): ResultsTab { val resultsTab = ResultsTab(results) resultsTab.canClose = results.canClose tabPane.add(index, resultsTab) results.attached(resultsTab, this) return resultsTab } private var attached: Boolean = false override fun isAttached(): Boolean { return attached } override fun attached(halfTab: HalfTab) { this.halfTab = halfTab ParaTaskApp.logAttach("ToolPane.attaching") parametersPane.attached(this) filterTab?.parametersPane?.attached(this) tool.attached(this) ParaTaskApp.logAttach("ToolPane.attached") attached = true } override fun detaching() { attached = false ParaTaskApp.logAttach("ToolPane detaching") parametersPane.detaching() filterTab?.parametersPane?.detaching() tool.detaching() parametersPane.detaching() removeOldResults(tool.resultsList) header?.detatching() ParaTaskApp.logAttach("ToolPane detached") } override fun nextTab() { if (tabPane.tabs.isNotEmpty()) { var index = tabPane.selectionModel.selectedIndex + 1 if (index >= tabPane.tabs.size) index = 0 tabPane.selectionModel.clearAndSelect(index) } } override fun prevTab() { if (tabPane.tabs.isNotEmpty()) { var index = tabPane.selectionModel.selectedIndex - 1 if (index < 0) index = tabPane.tabs.size - 1 tabPane.selectionModel.clearAndSelect(index) } } override fun selectTab(index: Int) { if (index >= 0 && index < tabPane.tabs.size) { tabPane.selectionModel.clearAndSelect(index) } } override fun focusHeader() { if (header != null) { ParaTaskApp.logFocus("ToolPane_Implt focusHeader. header.focus()") header.focus() } else { val results = currentResults() if (results is ResultsWithHeader) { ParaTaskApp.logFocus("ToolPane_Implt focusHeader. results.headerRows.focus()") results.headerRows.focus() } } } override fun focusResults() { if (skipFocus) { println("ToolPane_Impl Skipped focus") } else { val tab = tabPane.selectionModel.selectedItem if (tab is MinorTab) { ParaTaskApp.logFocus("ToolPane_Implt focusResults. tab.focus()") tab.focus() } } } override var skipFocus: Boolean = false override fun currentResults(): Results? { val tab = tabPane.selectedTab if (tab is ResultsTab) { return tab.results } return null } }
gpl-3.0
229b80223217166a57431b5307bc62f6
28.302789
119
0.616315
4.490232
false
false
false
false
rsiebert/TVHClient
data/src/main/java/org/tvheadend/data/dao/RecordingDao.kt
1
6145
package org.tvheadend.data.dao import androidx.lifecycle.LiveData import androidx.room.* import org.tvheadend.data.entity.RecordingEntity @Dao internal interface RecordingDao { @get:Query("SELECT COUNT (*) FROM recordings AS rec " + " WHERE (rec.error IS NULL AND rec.state = 'completed') " + " AND rec.connection_id IN (SELECT id FROM connections WHERE active = 1)") val completedRecordingCount: LiveData<Int> @get:Query("SELECT COUNT (*) FROM recordings AS rec " + " WHERE (rec.error IS NULL AND (rec.state = 'recording' OR rec.state = 'scheduled')) " + " AND rec.connection_id IN (SELECT id FROM connections WHERE active = 1)") val scheduledRecordingCount: LiveData<Int> @get:Query("SELECT COUNT (*) FROM recordings AS rec " + " WHERE (rec.error IS NULL AND (rec.state = 'recording')) " + " AND rec.connection_id IN (SELECT id FROM connections WHERE active = 1)") val runningRecordingCount: LiveData<Int> @get:Query("SELECT COUNT (*) FROM recordings AS rec " + " WHERE ((rec.error IS NOT NULL AND (rec.state='missed' OR rec.state='invalid')) " + " OR (rec.error IS NULL AND rec.state='missed') " + " OR (rec.error='Aborted by user' AND rec.state='completed')) " + " AND rec.connection_id IN (SELECT id FROM connections WHERE active = 1)") val failedRecordingCount: LiveData<Int> @get:Query("SELECT COUNT (*) FROM recordings AS rec " + " WHERE (rec.error = 'File missing' AND rec.state = 'completed') " + " AND rec.connection_id IN (SELECT id FROM connections WHERE active = 1)") val removedRecordingCount: LiveData<Int> @get:Query("SELECT COUNT (*) FROM recordings AS rec " + " WHERE $CONNECTION_IS_ACTIVE") val itemCountSync: Int @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " ORDER BY rec.start DESC") fun loadRecordings(): LiveData<List<RecordingEntity>> @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND rec.error IS NULL AND rec.state = 'completed' " + ORDER_BY) fun loadCompletedRecordings(sortOrder: Int): LiveData<List<RecordingEntity>> @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND rec.error IS NULL AND (rec.state = 'recording' OR rec.state = 'scheduled')" + " AND rec.duplicate = 0 " + " ORDER BY rec.start ASC") fun loadUniqueScheduledRecordings(): LiveData<List<RecordingEntity>> @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND rec.error IS NULL AND (rec.state = 'recording' OR rec.state = 'scheduled')" + " ORDER BY rec.start ASC") fun loadScheduledRecordings(): LiveData<List<RecordingEntity>> @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND (rec.error IS NOT NULL AND (rec.state='missed' OR rec.state='invalid')) " + " OR (rec.error IS NULL AND rec.state='missed') " + " OR (rec.error='Aborted by user' AND rec.state='completed')" + " ORDER BY rec.start DESC") fun loadFailedRecordings(): LiveData<List<RecordingEntity>> @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND rec.error = 'File missing' AND rec.state = 'completed'" + " ORDER BY rec.start DESC") fun loadRemovedRecordings(): LiveData<List<RecordingEntity>> @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND rec.id = :id") fun loadRecordingById(id: Int): LiveData<RecordingEntity> @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND rec.id = :id") fun loadRecordingByIdSync(id: Int): RecordingEntity? @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND rec.channel_id = :channelId") fun loadRecordingsByChannelId(channelId: Int): LiveData<List<RecordingEntity>> @Transaction @Query(RECORDING_BASE_QUERY + " WHERE $CONNECTION_IS_ACTIVE" + " AND rec.event_id = :id") fun loadRecordingByEventIdSync(id: Int): RecordingEntity? @Transaction @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(recording: RecordingEntity) @Transaction @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(recordings: List<RecordingEntity>) @Update fun update(recording: RecordingEntity) @Delete fun delete(recording: RecordingEntity) @Delete fun delete(recordings: List<RecordingEntity>) @Query("DELETE FROM recordings " + " WHERE connection_id IN (SELECT id FROM connections WHERE active = 1) " + " AND id = :id") fun deleteById(id: Int) @Query("DELETE FROM recordings") fun deleteAll() companion object { const val RECORDING_BASE_QUERY = "SELECT DISTINCT rec.*, " + "c.name AS channel_name, " + "c.icon AS channel_icon " + "FROM recordings AS rec " + "LEFT JOIN channels AS c ON c.id = rec.channel_id " const val ORDER_BY = " ORDER BY " + "CASE :sortOrder WHEN 0 THEN rec.start END ASC," + "CASE :sortOrder WHEN 1 THEN rec.start END DESC," + "CASE :sortOrder WHEN 2 THEN rec.title END ASC," + "CASE :sortOrder WHEN 3 THEN rec.title END DESC," + "CASE :sortOrder WHEN 4 THEN rec.content_type END ASC," + "CASE :sortOrder WHEN 5 THEN rec.content_type END DESC," + "CASE :sortOrder WHEN 6 THEN rec.duration END ASC," + "CASE :sortOrder WHEN 7 THEN rec.duration END DESC" const val CONNECTION_IS_ACTIVE = " rec.connection_id IN (SELECT id FROM connections WHERE active = 1) " } }
gpl-3.0
4312e5595214b7e2b87b244116290209
38.902597
111
0.614809
4.149223
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLRootQueryLabels.kt
1
1707
package net.nemerosa.ontrack.graphql.schema import graphql.Scalars.GraphQLString import graphql.schema.GraphQLFieldDefinition import net.nemerosa.ontrack.graphql.support.listType import net.nemerosa.ontrack.model.labels.LabelManagementService import org.springframework.stereotype.Component /** * Gets the list of labels */ @Component class GQLRootQueryLabels( private val label: GQLTypeLabel, private val labelManagementService: LabelManagementService ) : GQLRootQuery { override fun getFieldDefinition(): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name("labels") .description("List of all labels") .type(listType(label.typeRef)) .argument { it.name("category") .description("Category to look for") .type(GraphQLString) } .argument { it.name("name") .description("Name to look for") .type(GraphQLString) } .dataFetcher { environment -> val category: String? = environment.getArgument("category") val name: String? = environment.getArgument("name") if (category != null || name != null) { labelManagementService.findLabels(category, name) } else { labelManagementService.labels } } .build() }
mit
a104bb576701002fe7d52b359c9807a5
39.666667
83
0.521383
6.345725
false
false
false
false
LarsKrogJensen/graphql-kotlin
src/main/kotlin/graphql/execution/ExecutionContextBuilder.kt
1
2745
package graphql.execution import graphql.Assert.assertNotNull import graphql.GraphQLException import graphql.execution.instrumentation.Instrumentation import graphql.language.Document import graphql.language.FragmentDefinition import graphql.language.OperationDefinition import graphql.schema.GraphQLSchema import java.util.* class ExecutionContextBuilder(private val valuesResolver: ValuesResolver, private val instrumentation: Instrumentation) { private var executionId: ExecutionId? = null fun executionId(executionId: ExecutionId): ExecutionContextBuilder { this.executionId = executionId return this } fun build(graphQLSchema: GraphQLSchema, queryStrategy: IExecutionStrategy, mutationStrategy: IExecutionStrategy, subscriptionStrategy: IExecutionStrategy, root: Any, document: Document, operationName: String?, args: Map<String, Any>): ExecutionContext { // preconditions assertNotNull(executionId, "You must provide a query identifier") val fragmentsByName = LinkedHashMap<String, FragmentDefinition>() val operationsByName = LinkedHashMap<String?, OperationDefinition>() for (definition in document.definitions) { if (definition is OperationDefinition) { //definition.name?.let { operationsByName.put(it, definition) } operationsByName.put(definition.name, definition) } if (definition is FragmentDefinition) { val fragmentDefinition = definition fragmentsByName.put(fragmentDefinition.name, fragmentDefinition) } } if (operationName == null && operationsByName.size > 1) { throw GraphQLException("missing operation name") } val operation: OperationDefinition? if (operationName == null || operationName.isEmpty()) { operation = operationsByName.values.iterator().next() } else { operation = operationsByName[operationName] } if (operation == null) { throw GraphQLException("Missing operation by name '" + operationName + "'") } val variableValues = valuesResolver.getVariableValues(graphQLSchema, operation.variableDefinitions, args) return ExecutionContext( instrumentation, executionId!!, graphQLSchema, queryStrategy, mutationStrategy, subscriptionStrategy, fragmentsByName, operation, variableValues, root) } }
mit
417b91dd6653f60aeafa77c78434e766
36.60274
113
0.636794
5.967391
false
false
false
false
KyuBlade/kotlin-discord-bot
src/main/kotlin/com/omega/discord/bot/permission/GuildPermissions.kt
1
4795
package com.omega.discord.bot.permission import com.omega.discord.bot.database.DatabaseFactory import sx.blah.discord.handle.obj.IGuild import sx.blah.discord.handle.obj.IUser class GuildPermissions(val guild: IGuild, groups: List<Group> = listOf(), users: List<User> = listOf()) { private val userMap: MutableMap<IUser, User> = hashMapOf() private val groupMap: MutableMap<String, Group> = hashMapOf() private val defaultGroup: Group init { // First init if (groups.isEmpty()) { defaultGroup = Group(guild = guild, name = "default", permissions = hashSetOf( Permission.COMMAND_INVITE, Permission.COMMAND_SKIP, Permission.COMMAND_QUEUE ) ) groupMap["default"] = defaultGroup DatabaseFactory.groupDAO.insert(defaultGroup) } else { groups.forEach { groupMap[it.name] = it } users.forEach { userMap[it.user] = it } defaultGroup = groupMap["default"]!! } } /** * Change a permission for a user * @param user the user to set permission for * @param permission the permission to change * @param override the permission override to set for this permission */ fun set(user: IUser, permission: Permission, override: PermissionOverride) = getUserPermissions(user).set(permission, override) /** * Get permissions of a user. * @param user user to get permissions for */ fun get(user: IUser): User = getUserPermissions(user) /** * Add permissions to a group. * @param groupName name of the group * @param permission permission to add * @return the group if permission has been added, null if the group was not found */ fun add(groupName: String, permission: Permission): Group? { val group: Group? = getGroupPermissions(groupName) group?.add(permission) return group } /** * Add permissions to a group. * @param groupName name of the group * @param permission permission to remove * @return the group if permission has been added, null if the group was not found */ fun remove(groupName: String, permission: Permission): Group? { val group: Group? = getGroupPermissions(groupName) group?.remove(permission) return group } /** * Get permissions of a group. * @param groupName group to get permissions for */ fun get(groupName: String): Group? = getGroupPermissions(groupName) /** * Add a group. * @param name name of the new group * @return the created group, null if it already exists */ fun addGroup(name: String): Group? { return if (name !in groupMap) { val group = Group(guild = guild, name = name) groupMap[name] = group group } else { null } } /** * Remove a group. * @param name name of the group to remove * @return the removed group, null if it doesn't exists */ fun removeGroup(name: String): Group? { return if (name in groupMap) { groupMap.remove(name) } else { null } } /** * Get the list of groups. */ fun getGroups(): Collection<Group> = groupMap.values /** * Set the group of a user. * @param user user to set group to * @param name the group to set * @return the user if the group has been set, null if the group was not found */ fun setGroup(user: IUser, name: String): User? { val group: Group? = getGroupPermissions(name) return if (group != null) { val userPerm = getUserPermissions(user) userPerm.group = group userPerm } else { null } } /** * Check if the user have the permission. * @param user user to check * @param permission permission to check */ fun hasPermission(user: IUser, permission: Permission): Boolean = getUserPermissions(user).has(permission) private fun getUserPermissions(user: IUser): User { var userPerms = userMap[user] if (userPerms == null) { userPerms = User(guild = guild, group = defaultGroup, user = user) userMap[user] = userPerms DatabaseFactory.userDAO.insert(userPerms) } return userPerms } /** * Get a group. * @param name the group name to get * @return the group associated with this name or null if not found */ private fun getGroupPermissions(name: String): Group? = groupMap[name] }
gpl-3.0
6a03b31f6c1dc7c0261c27ea68054906
27.891566
105
0.591449
4.510818
false
false
false
false
ivan-osipov/Clabo
src/main/kotlin/com/github/ivan_osipov/clabo/api/model/Update.kt
1
1094
package com.github.ivan_osipov.clabo.api.model import com.github.ivan_osipov.clabo.api.model.inline_mode.InlineQuery import com.google.gson.annotations.SerializedName /** * @see <a href="https://core.telegram.org/bots/api#update">docs</a> */ class Update: Identifiable() { @SerializedName("update_id") override lateinit var id: String @SerializedName("message") var message: Message? = null @SerializedName("edited_message") var editedMessage: Message? = null @SerializedName("channel_post") var channelPost: Message? = null @SerializedName("edited_channel_post") var editedChannelPost: Message? = null @SerializedName("inline_query") var inlineQuery: InlineQuery? = null @SerializedName("chosen_inline_result") var chosenInlineResult: ChosenInlineResult? = null @SerializedName("callback_query") var callbackQuery: CallbackQuery? = null @SerializedName("shipping_query") var shippingQuery: ShippingQuery? = null @SerializedName("pre_checkout_query") var preCheckoutQuery: PreCheckoutQuery? = null }
apache-2.0
4ebb0ca184f023264e6837a58f75e1d9
25.707317
69
0.718464
4.08209
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/connection/main/State01SendingProtocolVersion.kt
1
722
package org.pixelndice.table.pixelclient.connection.main import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.App import org.pixelndice.table.pixelprotocol.Protobuf private val logger = LogManager.getLogger(State01SendingProtocolVersion::class.java) class State01SendingProtocolVersion : State { override fun process(ctx: Context) { logger.info("Sending protocol version: ${App.version}") val packet = Protobuf.Packet.newBuilder() val pversion = Protobuf.Version.newBuilder() pversion.version = App.version packet.version = pversion.build() ctx.packet = packet.build() ctx.state = State02WaitingProtocolVersion() } }
bsd-2-clause
bb81705b11da04f0602557ab0a385cbc
25.740741
84
0.732687
4.375758
false
false
false
false
rmnn/compiler
src/main/kotlin/ru/dageev/compiler/domain/node/expression/Parameter.kt
1
873
package ru.dageev.compiler.domain.node.expression import ru.dageev.compiler.bytecodegeneration.expression.ExpressionGenerator import ru.dageev.compiler.bytecodegeneration.statement.StatementGenerator import ru.dageev.compiler.domain.type.Type /** * Created by dageev * on 15-May-16. */ class Parameter(val name: String, type: Type) : Expression(type) { override fun accept(generator: StatementGenerator) { generator.generate(this) } override fun accept(generator: ExpressionGenerator) { generator.generate(this) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Parameter if (name != other.name) return false return true } override fun hashCode(): Int { return name.hashCode() } }
apache-2.0
46206511fedadb7f783975c7716a3063
24.705882
75
0.687285
4.343284
false
false
false
false
deeplearning4j/deeplearning4j
platform-tests/src/test/kotlin/org/eclipse/deeplearning4j/frameworkimport/frameworkimport/tensorflow/TestTensorflowUtils.kt
1
240481
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.tensorflow import org.eclipse.deeplearning4j.frameworkimport.frameworkimport.tensorflow.GraphInput import org.nd4j.linalg.api.ops.impl.transforms.floating.RSqrt import org.nd4j.linalg.factory.Nd4j import org.nd4j.samediff.frameworkimport.tensorflow.definitions.registry import org.nd4j.shade.protobuf.ByteString import org.nd4j.tensorflow.conversion.graphrunner.GraphRunner import org.tensorflow.framework.* import java.nio.charset.Charset fun graphForOp(nd4jOpName: String,inputFrameworkOpName: String): List<GraphInput> { val tensorflowOpDef = registry().lookupInputFrameworkOpDef(inputFrameworkOpName) when (nd4jOpName) { "check_numerics" -> { val tensor = NodeDef { name = "tensor" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("tensor") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("message",AttrValue { s = ByteString.copyFrom("test message".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(tensor) Node(opNode) } val xVal = Nd4j.create(floatArrayOf(1.0f,2.0f,3.0f)) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("tensor" to xVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("tensor"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "gruCell" -> { val x = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val hPrev = NodeDef { name = "h_prev" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val wRu = NodeDef { name = "w_ru" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val wC = NodeDef { name = "w_c" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val bRu = NodeDef { name = "b_ru" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val bc = NodeDef { name = "b_c" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("x") Input("h_prev") Input("w_ru") Input("w_c") Input("b_ru") Input("b_c") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val r = NodeDef { name = "r" Input("output:0") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val u = NodeDef { name = "u" Input("output:1") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val c = NodeDef { name = "c" Input("output:2") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val h = NodeDef { name = "h" Input("output:3") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(x) Node(hPrev) Node(wRu) Node(wC) Node(bRu) Node(bc) Node(opNode) Node(r) Node(u) Node(c) Node(h) } val xVal = Nd4j.linspace(1,20,20).reshape(2,10) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val hPrevVal = Nd4j.linspace(1,8,8).reshape(2,4) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wRuVal = Nd4j.linspace(1,112,112).reshape(14,8) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wcVal = Nd4j.linspace(1,56,56).reshape(14,4) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val bRuVal = Nd4j.linspace(1,8,8).reshape(8) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val bcVal = Nd4j.linspace(1,4,4).reshape(4) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("x" to xVal,"h_prev" to hPrevVal,"w_ru" to wRuVal,"w_c" to wcVal,"b_ru" to bRuVal,"b_c" to bcVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("x","h_prev","w_ru","w_c","b_ru","b_c"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "lstmBlockCell" -> { val x = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val csPrev = NodeDef { name = "cs_prev" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val hPrev = NodeDef { name = "h_prev" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val w = NodeDef { name = "w" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val wci = NodeDef { name = "wci" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val wcf = NodeDef { name = "wcf" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val wco = NodeDef { name = "wco" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val bias = NodeDef { name = "b" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("x") Input("cs_prev") Input("h_prev") Input("w") Input("wci") Input("wcf") Input("wco") Input("b") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("forget_bias",AttrValue { f = 2.0f }) Attribute("use_peephole",AttrValue { b = false }) } val i = NodeDef { name = "i" Input("output:0") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val cs = NodeDef { name = "cs" Input("output:1") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val f = NodeDef { name = "f" Input("output:2") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val o = NodeDef { name = "o" Input("output:3") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val ci = NodeDef { name = "ci" Input("output:4") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val h = NodeDef { name = "h" Input("output:5") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(x) Node(csPrev) Node(hPrev) Node(w) Node(wci) Node(wcf) Node(wco) Node(bias) Node(opNode) Node(i) Node(cs) Node(f) Node(o) Node(ci) Node(h) } val xVal = Nd4j.linspace(1,5,5).reshape(1,5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val csPrevVal = Nd4j.linspace(1,3,3).reshape(1,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val hPrevVal = Nd4j.linspace(1,3,3).reshape(1,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wVal = Nd4j.linspace(1,96,96).reshape(8,12) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wciVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wcfVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wcoVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val bVal = Nd4j.zeros(12) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("x" to xVal,"cs_prev" to csPrevVal,"h_prev" to hPrevVal,"w" to wVal,"wci" to wciVal,"wcf" to wcfVal,"wco" to wcoVal,"b" to bVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("x","cs_prev","h_prev","w","wci","wcf","wco","b"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "lstmBlock" -> { if(inputFrameworkOpName == "BlockLSTM") { val seqLenMax = NodeDef { name = "seq_len_max" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val x = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val csPrev = NodeDef { name = "cs_prev" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val hPrev = NodeDef { name = "h_prev" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val w = NodeDef { name = "w" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val wci = NodeDef { name = "wci" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val wcf = NodeDef { name = "wcf" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val wco = NodeDef { name = "wco" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val bias = NodeDef { name = "b" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("seq_len_max") Input("x") Input("cs_prev") Input("h_prev") Input("w") Input("wci") Input("wcf") Input("wco") Input("b") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) Attribute("forget_bias", AttrValue { f = 2.0f }) Attribute("forget_bias", AttrValue { f = 3.0f }) Attribute("use_peephole", AttrValue { b = false }) } val i = NodeDef { name = "i" Input("output:0") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val cs = NodeDef { name = "cs" Input("output:1") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val f = NodeDef { name = "f" Input("output:2") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val o = NodeDef { name = "o" Input("output:3") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val ci = NodeDef { name = "ci" Input("output:4") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val h = NodeDef { name = "h" Input("output:5") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(seqLenMax) Node(x) Node(csPrev) Node(hPrev) Node(w) Node(wci) Node(wcf) Node(wco) Node(bias) Node(opNode) Node(i) Node(cs) Node(f) Node(o) Node(ci) Node(h) } val seqLenVal = Nd4j.scalar(5.0) .castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val xVal = Nd4j.linspace(1,20,20).reshape(5,1,4) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val csPrevVal = Nd4j.linspace(1,3,3).reshape(1,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val hPrevVal = Nd4j.linspace(1,3,3).reshape(1,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wVal = Nd4j.linspace(1,84,84).reshape(7,12) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wciVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wcfVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wcoVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val bVal = Nd4j.zeros(12) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("seq_len_max" to seqLenVal,"x" to xVal,"cs_prev" to csPrevVal,"h_prev" to hPrevVal,"w" to wVal,"wci" to wciVal,"wcf" to wcfVal,"wco" to wcoVal,"b" to bVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("seq_len_max","x","cs_prev","h_prev","w","wci","wcf","wco","b"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } else { //BlockLSTMV2 val seqLenMax = NodeDef { name = "seq_len_max" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val x = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val csPrev = NodeDef { name = "cs_prev" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val hPrev = NodeDef { name = "h_prev" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val w = NodeDef { name = "w" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val wci = NodeDef { name = "wci" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val wcf = NodeDef { name = "wcf" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val wco = NodeDef { name = "wco" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val bias = NodeDef { name = "b" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("seq_len_max") Input("x") Input("cs_prev") Input("h_prev") Input("w") Input("wci") Input("wcf") Input("wco") Input("b") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) Attribute("use_peephole", AttrValue { b = false }) } val i = NodeDef { name = "i" Input("output:0") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val cs = NodeDef { name = "cs" Input("output:1") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val f = NodeDef { name = "f" Input("output:2") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val o = NodeDef { name = "o" Input("output:3") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val ci = NodeDef { name = "ci" Input("output:4") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val h = NodeDef { name = "h" Input("output:5") op = "Identity" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(seqLenMax) Node(x) Node(csPrev) Node(hPrev) Node(w) Node(wci) Node(wcf) Node(wco) Node(bias) Node(opNode) Node(i) Node(cs) Node(f) Node(o) Node(ci) Node(h) } val seqLenVal = Nd4j.scalar(5.0) .castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val xVal = Nd4j.linspace(1,20,20).reshape(5,1,4) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val csPrevVal = Nd4j.linspace(1,3,3).reshape(1,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val hPrevVal = Nd4j.linspace(1,3,3).reshape(1,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wVal = Nd4j.linspace(1,84,84).reshape(7,12) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wciVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wcfVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val wcoVal = Nd4j.linspace(1,3,3).reshape(3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val bVal = Nd4j.zeros(12) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("seq_len_max" to seqLenVal,"x" to xVal,"cs_prev" to csPrevVal,"h_prev" to hPrevVal,"w" to wVal,"wci" to wciVal,"wcf" to wcfVal,"wco" to wcoVal,"b" to bVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("seq_len_max","x","cs_prev","h_prev","w","wci","wcf","wco","b"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } "adjust_hue","adjust_saturation" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val delta = NodeDef { name = "delta" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("delta") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(input) Node(delta) Node(opNode) } val xVal = Nd4j.zeros(3,3,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val deltaVal = Nd4j.scalar(0.5).castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("input" to xVal,"delta" to deltaVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","delta"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "adjust_contrast_v2" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val delta = NodeDef { name = "contrast_factor" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("contrast_factor") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(input) Node(delta) Node(opNode) } val xVal = Nd4j.zeros(3,3,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val deltaVal = Nd4j.scalar(0.5).castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("input" to xVal,"contrast_factor" to deltaVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","contrast_factor"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "rgb_to_hsv" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(input) Node(opNode) } val xVal = Nd4j.zeros(3,3,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("input" to xVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "reverse_sequence" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val seqLengths = NodeDef { name = "seq_lengths" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("seq_lengths") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) Attribute("Tlen",AttrValue { type = DataType.DT_INT32 }) Attribute("seq_dim",AttrValue { i = 2 }) Attribute("batch_dim",AttrValue { i = 1 }) } val graphDef = GraphDef { Node(input) Node(seqLengths) Node(opNode) } val xVal = Nd4j.linspace(1,60,60).reshape(3,4,5) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val yVal = Nd4j.create(floatArrayOf(4f,4f,4f,4f)) .reshape(4) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to xVal,"seq_lengths" to yVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","seq_lengths"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "resize_nearest_neighbor" -> { val images = NodeDef { name = "images" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val size = NodeDef { name = "size" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("images") Input("size") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(images) Node(size) Node(opNode) } val xVal = Nd4j.linspace(1,36,36).reshape(1,3,3,4) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val yVal = Nd4j.create(floatArrayOf(6f,6f)) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("images" to xVal,"size" to yVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("images","size"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "resize_bilinear" -> { val images = NodeDef { name = "images" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val size = NodeDef { name = "size" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("images") Input("size") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(images) Node(size) Node(opNode) } val xVal = Nd4j.linspace(1,36,36).reshape(1,3,3,4) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val yVal = Nd4j.create(floatArrayOf(6f,6f)) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("images" to xVal,"size" to yVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("images","size"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "resize_bicubic" -> { val images = NodeDef { name = "images" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val size = NodeDef { name = "size" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("images") Input("size") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(images) Node(size) Node(opNode) } val xVal = Nd4j.linspace(1,36,36).reshape(1,3,3,4) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val yVal = Nd4j.create(floatArrayOf(6f,6f)) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("images" to xVal,"size" to yVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("images","size"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "resize_area" -> { val images = NodeDef { name = "images" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val size = NodeDef { name = "size" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("images") Input("size") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(images) Node(size) Node(opNode) } val xVal = Nd4j.linspace(1,36,36).reshape(1,3,3,4) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val yVal = Nd4j.create(floatArrayOf(6f,6f)) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("images" to xVal,"size" to yVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("images","size"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "mirror_pad" -> { val mirrorPadRet = ArrayList<GraphInput>() listOf("REFLECT","SYMMETRIC").forEach { mode -> val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val paddings = NodeDef { name = "paddings" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("paddings") op = tensorflowOpDef.name name = "output" Attribute("mode", AttrValue { s = ByteString.copyFrom(mode.toByteArray(Charset.defaultCharset())) }) Attribute("Tpaddings", AttrValue { type = DataType.DT_INT32 }) Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(input) Node(paddings) Node(opNode) } val xVal = Nd4j.linspace(1,5,5).reshape(5) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val yVal = Nd4j.create(floatArrayOf(1f,1f)) .reshape(1,2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to xVal,"paddings" to yVal) mirrorPadRet.add( GraphInput( graphDef = graphDef, inputNames = listOf("input","paddings"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } return mirrorPadRet } "listdiff" -> { val x = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val y = NodeDef { name = "y" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("x") Input("y") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(x) Node(y) Node(opNode) } val xVal = Nd4j.linspace(1,4,4).reshape(4) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val yVal = Nd4j.create(floatArrayOf(3f,1f)) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("x" to xVal,"y" to yVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("x","y"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "histogram_fixed_width" -> { val values = NodeDef { name = "values" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val valueRange = NodeDef { name = "value_range" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val nBins = NodeDef { name = "nbins" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("values") Input("value_range") Input("nbins") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(values) Node(valueRange) Node(nBins) Node(opNode) } val valuesVal = Nd4j.ones(2,3) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val valueRangeVal = Nd4j.create(floatArrayOf(0f,5f)) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val nbinsVal = Nd4j.scalar(5f) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("values" to valuesVal,"value_range" to valueRangeVal,"nbins" to nbinsVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("values","value_range","nbins"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "extract_image_patches" -> { val images = NodeDef { name = "images" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} val opNode = NodeDef { Input("images") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("ksizes",AttrValue { ListInts(listOf(1,1,1,1)) }) Attribute("strides",AttrValue { ListInts(listOf(1,1,1,1)) }) Attribute("rates",AttrValue { ListInts(listOf(1,1,1,1)) }) Attribute("padding",AttrValue { s = ByteString.copyFrom("SAME".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(images) Node(opNode) } //1,2,5,4 //3,2,2,2 val imagesVal = Nd4j.ones(2,4,4,4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("images" to imagesVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("images"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "crop_and_resize" -> { val images = NodeDef { name = "images" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val boxes = NodeDef { name = "boxes" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val boxesI = NodeDef { name = "boxesI" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val cropSize = NodeDef { name = "cropSize" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("images") Input("boxes") Input("boxesI") Input("cropSize") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(images) Node(boxes) Node(boxesI) Node(cropSize) Node(opNode) } val imagesVal = Nd4j.create(floatArrayOf(1f,2f,3f,4f)) .reshape(1,2,2,1) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val boxesVal = Nd4j.create(floatArrayOf(0f,0f,1f,1f)) .reshape(1,4) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val boxesIVal = Nd4j.create(floatArrayOf(0f)) .reshape(1) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val cropSizeVal = Nd4j.create(floatArrayOf(1f,1f)) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("images" to imagesVal,"boxes" to boxesVal,"boxesI" to boxesIVal,"cropSize" to cropSizeVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("images","boxes","boxesI","cropSize"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "broadcastgradientargs" -> { val s0 = NodeDef { name = "s0" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val s1 = NodeDef { name = "s1" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("s0") Input("s1") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(s0) Node(s1) Node(opNode) } val s0Val = Nd4j.create(floatArrayOf(2f,2f,2f)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val s1Val = Nd4j.create(floatArrayOf(2f,1f,2f)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("s0" to s0Val,"s1" to s1Val) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("s0","s1"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "broadcast_dynamic_shape" -> { val s0 = NodeDef { name = "s0" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val s1 = NodeDef { name = "s1" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("s0") Input("s1") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(s0) Node(s1) Node(opNode) } val s0Val = Nd4j.create(floatArrayOf(2f,2f,2f)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val s1Val = Nd4j.create(floatArrayOf(2f,1f,2f)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("s0" to s0Val,"s1" to s1Val) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("s0","s1"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "lrn" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("depth_radius",AttrValue { i = 5 }) Attribute("bias",AttrValue { f = 1f }) Attribute("alpha",AttrValue { f = 0.5f }) Attribute("beta",AttrValue { f = 0.5f }) } val graphDef = GraphDef { Node(input) Node(opNode) } //1,2,5,4 //3,2,2,2 //1, 1,2,2,1, 1,2,2,1 val inputVal = Nd4j.linspace(1,16,16).reshape(2,2,2,2) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("input" to inputVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "fused_batch_norm" -> { val x = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val scale = NodeDef { name = "scale" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val offset = NodeDef { name = "offset" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val mean = NodeDef { name = "mean" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val variance = NodeDef { name = "variance" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val epsilon = 0.0001f println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("x") Input("scale") Input("offset") Input("mean") Input("variance") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("is_training",AttrValue { b = false }) Attribute("data_format",AttrValue { s = ByteString.copyFrom("NHWC".toByteArray(Charset.defaultCharset())) }) Attribute("epsilon",AttrValue { f = epsilon }) } val y = NodeDef { name = "y" Input("output:0") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val batchMean = NodeDef { name = "batch_mean" Input("output:1") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val batchVariance = NodeDef { name = "batch_variance" Input("output:2") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(x) Node(scale) Node(mean) Node(offset) Node(variance) Node(opNode) Node(y) Node(batchMean) Node(batchVariance) } val xVal = Nd4j.ones(2,2,2,2) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val scaleVal = Nd4j.zeros(2).addi(0.5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val offsetVal = Nd4j.zeros(2).addi(2).castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) // xAffected *= (*variance + epsilon).transform(transform::RSqrt) * (*scale) + (*offset); val testResult = Nd4j.ones(8,2).muli(Nd4j.exec(RSqrt(Nd4j.scalar(epsilon)))).muli(scaleVal).addi(offsetVal) val meanVal = Nd4j.zeros(2) val varianceVal = Nd4j.zeros(2) val otherResult = xVal.sub(meanVal).div(varianceVal.add(epsilon)).mul(scaleVal).add(offsetVal) // (batch - self.moving_mean) / (self.moving_var + epsilon) * gamma + beta. val inputs = mapOf("x" to xVal,"scale" to scaleVal,"mean" to meanVal,"offset" to offsetVal,"variance" to varianceVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("x","scale","offset","mean","variance"), outputNames = listOf("y","batch_mean","batch_variance"), inputArrays = inputs, dynamicArrays = inputs ) ) } "conv3dnew" -> { // int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; // int paddingMode = 1; // 1-SAME, 0-VALID; //int dataFormat = 1; // 1-NDHWC, 0-NCDHW //2,3,4,3,4 //2,3,2,4,3 //auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); //auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); //, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, 1, dataFormat} val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val filter = NodeDef { name = "filter" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} //, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, 1, dataFormat} val opNode = NodeDef { Input("input") Input("filter") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("strides",AttrValue { ListInts(listOf(1,1,1,1,1)) }) Attribute("padding",AttrValue { s = ByteString.copyFrom("SAME".toByteArray(Charset.defaultCharset())) }) Attribute("data_format",AttrValue { s = ByteString.copyFrom("NDHWC".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(input) Node(filter) Node(opNode) } //1,2,5,4 //3,2,2,2 val inputVal = Nd4j.ones(2,3,4,3,4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val filterVal = Nd4j.ones(2,3,2,4,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal,"filter" to filterVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","filter"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "avgpool3dnew","maxpool3dnew" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("ksize",AttrValue { ListInts(listOf(1,1,1,1,1)) }) Attribute("strides",AttrValue { ListInts(listOf(1,1,1,1,1)) }) Attribute("padding",AttrValue { s = ByteString.copyFrom("SAME".toByteArray(Charset.defaultCharset())) }) Attribute("data_format",AttrValue { s = ByteString.copyFrom("NDHWC".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(input) Node(opNode) } //2,3,3,43 val inputVal = Nd4j.ones(2,3,3,4,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("input" to inputVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "draw_bounding_boxes" -> { val images = NodeDef { name = "images" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val boxes = NodeDef { name = "boxes" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val colors = NodeDef { name = "colors" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("images") Input("boxes") Input("colors") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(images) Node(boxes) Node(colors) Node(opNode) } val imagesVal = Nd4j.linspace(1,120,120).reshape(2,4,5,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val boxesVal = Nd4j.linspace(1,16,16).reshape(2,2,4) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val colorVal = Nd4j.create(floatArrayOf(201f, 202f, 203f, 127f, 128f, 129f)).reshape(2,3) val inputs = mapOf("images" to imagesVal,"boxes" to boxesVal,"colors" to colorVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("images","boxes","colors"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "create" -> { val shape = NodeDef { name = "shape" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("shape") op = tensorflowOpDef.name name = "output" Attribute("init",AttrValue { b = true }) Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(shape) Node(opNode) } val shapeVal = Nd4j.create(doubleArrayOf(1.0,2.0)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("shape" to shapeVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("shape"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "select" -> { val condition = NodeDef { name = "condition" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val t = NodeDef { name = "t" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val e = NodeDef { name = "e" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("condition") Input("t") Input("e") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(condition) Node(t) Node(e) Node(opNode) } val conditionVal = Nd4j.create(booleanArrayOf(true,false,false)) .castTo(org.nd4j.linalg.api.buffer.DataType.BOOL) val tVal = Nd4j.linspace(1,9,9).reshape(3,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val eVal = Nd4j.create(doubleArrayOf(9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0)) .reshape(3,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("condition" to conditionVal,"t" to tVal,"e" to eVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("condition","t","e"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "compare_and_bitpack" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val threshold = NodeDef { name = "threshold" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("threshold") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(input) Node(threshold) Node(opNode) } val inputVal = Nd4j.create(floatArrayOf(-12f, -11f, -10f, -9f, -8f, -7f, -6f, -5f, -4f, -3f, -2f, -1f, 0f, 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 11f)).reshape(2,3,4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val thresholdVal = Nd4j.scalar(2.0) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal,"threshold" to thresholdVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","threshold"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "strided_slice" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val begin = NodeDef { name = "begin" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val end = NodeDef { name = "end" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val strides = NodeDef { name = "strides" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("begin") Input("end") Input("strides") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Index",AttrValue { type = DataType.DT_INT32 }) Attribute("shrink_axis_mask",AttrValue { i = 1 }) } val graphDef = GraphDef { Node(input) Node(begin) Node(end) Node(strides) Node(opNode) } val inputVal = Nd4j.linspace(1,10,10).reshape(5,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val beginVal = Nd4j.create(doubleArrayOf(0.0)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val endVal = Nd4j.create(doubleArrayOf(1.0)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val strideVal = Nd4j.create(doubleArrayOf(1.0)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to inputVal,"begin" to beginVal, "end" to endVal,"strides" to strideVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","begin","end","strides"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "bincount" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val size = NodeDef { name = "size" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val weights = NodeDef { name = "weights" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("size") Input("weights") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(input) Node(size) Node(weights) Node(opNode) } val inputVal = Nd4j.create(doubleArrayOf(1.0, 2.0, 0.0, 1.0, 2.0, 2.0, 1.0, 2.0)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val sizeVal = Nd4j.create(doubleArrayOf(3.0)) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val weightVal = Nd4j.create(doubleArrayOf(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal,"size" to sizeVal, "weights" to weightVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","size","weights"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "broadcast_to" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val shape = NodeDef { name = "shape" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("shape") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tidx",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(input) Node(shape) Node(opNode) } val inputVal = Nd4j.create(doubleArrayOf(2.0)) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val shapeVal = Nd4j.zeros(2).addi(4) .castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"shape" to shapeVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","shape"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "condition" -> { val condition = NodeDef { name = "condition" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val t = NodeDef { name = "t" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val e = NodeDef { name = "e" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("condition") Input("t") Input("e") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(condition) Node(t) Node(e) Node(opNode) } val conditionVal = Nd4j.create(booleanArrayOf(true,true,false,false)).reshape(2,2) .castTo(org.nd4j.linalg.api.buffer.DataType.BOOL) val tVal = Nd4j.linspace(1,4,4).reshape(2,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val eVal = Nd4j.linspace(1,4,4).reshape(2,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("condition" to conditionVal,"t" to tVal,"e" to eVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("condition","t","e"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "biasadd" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val bias = NodeDef { name = "bias" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("bias") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(input) Node(bias) Node(opNode) } val inputVal = Nd4j.linspace(1,2 * 3 * 3 * 2,2 * 3 * 3 * 2).reshape(2,3,3,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val biasVal = Nd4j.linspace(1,2,2).reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal,"bias" to biasVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","bias"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "dilation2d" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val filter = NodeDef { name = "filter" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} val opNode = NodeDef { Input("input") Input("filter") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("strides",AttrValue { ListInts(listOf(1,1,1,1)) }) Attribute("rates",AttrValue { ListInts(listOf(1,1,1,1)) }) Attribute("padding",AttrValue { s = ByteString.copyFrom("SAME".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(input) Node(filter) Node(opNode) } //1,2,5,4 //3,2,2,2 //1, 1,2,2,1, 1,2,2,1 val inputVal = Nd4j.linspace(1,2 * 6 * 6 * 3,2 * 6 * 6 * 3).reshape(2,6,6,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val filterVal = Nd4j.linspace(1,3 * 2 * 3,3 * 2 * 3).reshape(3,2,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal,"filter" to filterVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","filter"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "depthwise_conv2d" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val filter = NodeDef { name = "filter" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} val opNode = NodeDef { Input("input") Input("filter") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("strides",AttrValue { ListInts(listOf(1,1,1,1)) }) Attribute("padding",AttrValue { s = ByteString.copyFrom("SAME".toByteArray(Charset.defaultCharset())) }) Attribute("data_format",AttrValue { s = ByteString.copyFrom("NHWC".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(input) Node(filter) Node(opNode) } //1,2,5,4 //3,2,2,2 val inputVal = Nd4j.ones(2,4,3,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val filterVal = Nd4j.ones(3,2,2,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal,"filter" to filterVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","filter"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "conv2d" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val filter = NodeDef { name = "filter" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} val opNode = NodeDef { Input("input") Input("filter") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("strides",AttrValue { ListInts(listOf(1,1,1,1)) }) Attribute("padding",AttrValue { s = ByteString.copyFrom("SAME".toByteArray(Charset.defaultCharset())) }) Attribute("data_format",AttrValue { s = ByteString.copyFrom("NHWC".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(input) Node(filter) Node(opNode) } //1,2,5,4 //3,2,2,2 val inputVal = Nd4j.ones(1,4,1,1) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val filterVal = Nd4j.ones(1,1,1,4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal,"filter" to filterVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","filter"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "avgpool2d","maxpool2d" -> { if(tensorflowOpDef.name == "AvgPool" || tensorflowOpDef.name == "MaxPool") { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) Attribute("ksize", AttrValue { ListInts(listOf(1, 1, 1, 1)) }) Attribute("strides", AttrValue { ListInts(listOf(1, 1, 1, 1)) }) Attribute("padding", AttrValue { s = ByteString.copyFrom("SAME".toByteArray(Charset.defaultCharset())) }) Attribute("data_format", AttrValue { s = ByteString.copyFrom("NHWC".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(input) Node(opNode) } val inputVal = Nd4j.ones(2,4,4,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } else { //MaxPoolV2 val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val ksize = NodeDef { name = "ksize" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val stride = NodeDef { name = "stride" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") // {2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1} val opNode = NodeDef { Input("input") Input("ksize") Input("stride") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) Attribute("padding", AttrValue { s = ByteString.copyFrom("SAME".toByteArray(Charset.defaultCharset())) }) Attribute("data_format", AttrValue { s = ByteString.copyFrom("NHWC".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(input) Node(ksize) Node(stride) Node(opNode) } val inputVal = Nd4j.ones(2,4,4,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val ksizeVal = Nd4j.create(floatArrayOf(1.0f,2.0f,2.0f,1.0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val strideVal = Nd4j.create(floatArrayOf(1.0f,2.0f,2.0f,1.0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to inputVal,"ksize" to ksizeVal,"stride" to strideVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("input","ksize","stride"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } "space_to_batch" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val paddings = NodeDef { name = "paddings" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("paddings") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tpaddings",AttrValue { type = DataType.DT_INT64 }) Attribute("block_size",AttrValue { i = 2 }) } val graphDef = GraphDef { Node(input) Node(paddings) Node(opNode) } val inputVal = Nd4j.linspace(1,12,12).reshape(1,2,2,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val paddingsVal = Nd4j.zeros(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"paddings" to paddingsVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","paddings"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "batch_to_space_nd" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val blockShape = NodeDef { name = "block_shape" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("shape",AttrValue { shape = TensorShapeProto { Dims(listOf(3)) } }) } val crops = NodeDef { name = "crops" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("block_shape") Input("crops") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tblock_shape",AttrValue { type = DataType.DT_INT32 }) Attribute("Tcrops",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(input) Node(blockShape) Node(crops) Node(opNode) } val tVal = Nd4j.linspace(1,24,24).reshape(8,1,1,1,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val blockShapeVal = Nd4j.zeros(3).addi(2).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val cropsVal = Nd4j.zeros(3,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to tVal,"block_shape" to blockShapeVal,"crops" to cropsVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","block_shape","crops"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "space_to_batch_nd" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val blockShape = NodeDef { name = "block_shape" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("shape",AttrValue { shape = TensorShapeProto { Dims(listOf(3)) } }) } val paddings = NodeDef { name = "paddings" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("block_shape") Input("paddings") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tblock_shape",AttrValue { type = DataType.DT_INT32 }) Attribute("Tpaddings",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(input) Node(blockShape) Node(paddings) Node(opNode) } val tVal = Nd4j.linspace(1,48,48).reshape(2,2,4,3,1) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val blockShapeVal = Nd4j.create(floatArrayOf(2.0f,2.0f,3f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val paddingsVal = Nd4j.create(floatArrayOf(0f,0f,0f,2f,2f,1f)).reshape(3,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to tVal,"block_shape" to blockShapeVal,"paddings" to paddingsVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","block_shape","paddings"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "batch_to_space" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val crops = NodeDef { name = "crops" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("crops") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tidx",AttrValue { type = DataType.DT_INT64 }) Attribute("block_size",AttrValue { i = 2 }) } val graphDef = GraphDef { Node(input) Node(crops) Node(opNode) } val tVal = Nd4j.linspace(1,12,12).reshape(4,1,1,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val cropsVal = Nd4j.zeros(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to tVal,"crops" to cropsVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","crops"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "slice" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val begin = NodeDef { name = "begin" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val size = NodeDef { name = "size" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("begin") Input("size") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Index",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(input) Node(begin) Node(size) Node(opNode) } val tVal = Nd4j.linspace(1,12,12).reshape(3,4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val beginVal = Nd4j.create(doubleArrayOf(0.0,1.0)).reshape(2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val sizeVal = Nd4j.create(doubleArrayOf(0.0,1.0)).reshape(2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to tVal,"begin" to beginVal,"size" to sizeVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","begin","size"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "ClipByValue" -> { val t = NodeDef { name = "t" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val clipValueMin = NodeDef { name = "clip_value_min" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val clipValueMax = NodeDef { name = "clip_value_max" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("t") Input("clip_value_min") Input("clip_value_max") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(t) Node(clipValueMin) Node(clipValueMax) Node(opNode) } val tVal = Nd4j.linspace(1,12,12).reshape(3,4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val clipValueMinVal = Nd4j.scalar(0.0).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val clipValueMaxVal = Nd4j.scalar(1.0).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("t" to tVal,"clip_value_min" to clipValueMinVal,"clip_value_max" to clipValueMaxVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("t","clip_value_min","clip_value_max"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "squeeze" -> { val value = NodeDef { name = "value" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("value") op = tensorflowOpDef.name name = "output" Attribute("squeeze_dims",AttrValue { ListInts(listOf(2)) }) Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(value) Node(opNode) } val valuesVal = Nd4j.linspace(1,12,12).reshape(3,4,1) .castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("value" to valuesVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("value"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "identity_n" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val input2 = NodeDef { name = "input2" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("input2") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { ListDataType(listOf(DataType.DT_INT64,DataType.DT_INT64)) }) } val out0 = NodeDef { name = "out0" Input("output:0") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val out1 = NodeDef { name = "out1" Input("output:1") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(input) Node(input2) Node(opNode) Node(out0) Node(out1) } val inputVal = Nd4j.linspace(1,4,4) .reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"input2" to inputVal.dup()) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","input2"), outputNames = listOf("out0","out1"), inputArrays = inputs, dynamicArrays = inputs ) ) } "shapes_of" -> { val input1 = NodeDef { name = "input1" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val input2 = NodeDef { name = "input2" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val opNode = NodeDef { Input("input1") Input("input2") op = tensorflowOpDef.name name = "output" Attribute("N",AttrValue { i = 2 }) Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("out_type",AttrValue { type = DataType.DT_INT64 }) } val out0 = NodeDef { name = "out0" Input("output:0") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val out1 = NodeDef { name = "out1" Input("output:1") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(input1) Node(input2) Node(opNode) Node(out0) Node(out1) } val input1Val = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val input2Val = Nd4j.linspace(1,6,6).reshape(2,3).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input1" to input1Val,"input2" to input2Val) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input1","input2"), outputNames = listOf("out0","out1"), inputArrays = inputs, dynamicArrays = inputs ) ) } "dynamic_stitch" -> { val indices1 = NodeDef { name = "indices" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val indices2 = NodeDef { name = "indices2" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val data0 = NodeDef { name = "data0" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val data1 = NodeDef { name = "data1" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("indices") Input("indices2") Input("data0") Input("data1") op = tensorflowOpDef.name name = "output" Attribute("N",AttrValue { i = 2 }) Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(indices1) Node(indices2) Node(data0) Node(data1) Node(opNode) } val testGraph = GraphRunner.builder().graphBytes(graphDef.toByteArray()).build() val indicesVal = Nd4j.create(floatArrayOf(1.0f,3.0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val indices2Val = Nd4j.create(floatArrayOf(5.0f,0.0f,2.0f,4.0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val dataVal = Nd4j.create(floatArrayOf(-1f,-1f)).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val data2Val = Nd4j.create(floatArrayOf(0.1f,5.2f,4.3f,7.4f)).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("indices" to indicesVal,"indices2" to indices2Val,"data0" to dataVal,"data1" to data2Val) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("indices","indices2","data0","data1"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "dynamic_partition" -> { val data = NodeDef { name = "data" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val partitions = NodeDef { name = "partitions" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("data") Input("partitions") op = tensorflowOpDef.name name = "output" Attribute("num_partitions",AttrValue { i = 2 }) Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val out0 = NodeDef { name = "out0" Input("output:0") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val out1 = NodeDef { name = "out1" Input("output:1") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(data) Node(partitions) Node(opNode) Node(out0) Node(out1) } val testGraph = GraphRunner.builder().graphBytes(graphDef.toByteArray()).build() val partitionsVal = Nd4j.create(floatArrayOf(0f,0f,1f,1f,0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val dataVal = Nd4j.create(floatArrayOf(10f, 20f, 30f, 40f, 50f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("data" to dataVal,"partitions" to partitionsVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("data","partitions"), outputNames = listOf("out0","out1"), inputArrays = inputs, dynamicArrays = inputs ) ) } "split_v" -> { val splitDim = NodeDef { name = "split_dim" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val sizeSplits = NodeDef { name = "size_splits" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val value = NodeDef { name = "value" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("value") Input("size_splits") Input("split_dim") op = tensorflowOpDef.name name = "output" Attribute("num_split",AttrValue { i = 2 }) Attribute("Tlen",AttrValue { type = DataType.DT_INT64 }) Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val out0 = NodeDef { name = "out0" Input("output:0") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val out1 = NodeDef { name = "out1" Input("output:1") op = "Identity" Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(value) Node(sizeSplits) Node(splitDim) Node(opNode) Node(out0) Node(out1) } val splitDimVal = Nd4j.scalar(-2.0).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val sizeSplitsVal = Nd4j.create(floatArrayOf(5f,3f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val valuesVal = Nd4j.linspace(1,56,56) .reshape(8,7).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("split_dim" to splitDimVal,"value" to valuesVal,"size_splits" to sizeSplitsVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("value","size_splits","split_dim"), outputNames = listOf("out0","out1"), inputArrays = inputs, dynamicArrays = inputs ) ) } "split" -> { val splitDim = NodeDef { name = "split_dim" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val value = NodeDef { name = "value" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("split_dim") Input("value") op = tensorflowOpDef.name name = "output" Attribute("num_split",AttrValue { i = 2 }) Attribute("T",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(splitDim) Node(value) Node(opNode) } val concatDimVal = Nd4j.scalar(0.0).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val valuesVal = Nd4j.create(floatArrayOf(0f,1f,0f,1f)) .reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("split_dim" to concatDimVal,"value" to valuesVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("split_dim","value"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "matmul" -> { val mmulInput = ArrayList<GraphInput>() listOf(false,true).forEach { transA -> listOf(false,true).forEach { transB -> val a = NodeDef { name = "a" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val bNode = NodeDef { name = "b" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("a") Input("b") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(a) Node(bNode) Node(opNode) } val aVal = Nd4j.linspace(1,4,4).reshape(2,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val bVal = Nd4j.create(floatArrayOf(0f,1f,0f,1f)) .reshape(2,2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("a" to aVal,"b" to bVal) mmulInput.add( GraphInput( graphDef =graphDef, inputNames = listOf("a","b"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } return mmulInput } "range" -> { val start = NodeDef { name = "start" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val limit = NodeDef { name = "limit" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val delta = NodeDef { name = "delta" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("start") Input("limit") Input("delta") op = tensorflowOpDef.name name = "output" Attribute("Tidx", AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(start) Node(limit) Node(delta) Node(opNode) } val startVal = Nd4j.scalar(1) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val limitVal = Nd4j.scalar(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val deltaVal = Nd4j.scalar(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("start" to startVal, "limit" to limitVal, "delta" to deltaVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("start", "limit", "delta"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "lin_space" -> { val start = NodeDef { name = "start" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val stop = NodeDef { name = "stop" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val num = NodeDef { name = "num" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("start") Input("stop") Input("num") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tidx", AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(start) Node(stop) Node(num) Node(opNode) } val startVal = Nd4j.scalar(1) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val limitVal = Nd4j.scalar(1).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val deltaVal = Nd4j.scalar(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("start" to startVal,"stop" to limitVal, "num" to deltaVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("start", "stop","num"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = mapOf("limit" to limitVal) ) ) } "gather","gather_nd" -> { if(tensorflowOpDef.name != "GatherV2") { val params = NodeDef { name = "params" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val indices = NodeDef { name = "indices" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("params") Input("indices") op = tensorflowOpDef.name name = "output" Attribute("Tparams",AttrValue { type = DataType.DT_INT64 }) Attribute("Tindices",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(params) Node(indices) Node(opNode) } val paramsVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val indicesVal = Nd4j.create(floatArrayOf(0f,1f,0f,1f)) .reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("params" to paramsVal,"indices" to indicesVal.dup()) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("params","indices"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } else { val params = NodeDef { name = "params" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val indices = NodeDef { name = "indices" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val axis = NodeDef { name = "axis" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("params") Input("indices") Input("axis") op = tensorflowOpDef.name name = "output" Attribute("Tparams",AttrValue { type = DataType.DT_INT64 }) Attribute("Tindices",AttrValue { type = DataType.DT_INT64 }) Attribute("Taxis",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(params) Node(indices) Node(axis) Node(opNode) } val paramsVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val indicesVal = Nd4j.create(floatArrayOf(0f,1f,0f,1f)) .reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val axisVal = Nd4j.scalar(0).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("params" to paramsVal,"indices" to indicesVal.dup(),"axis" to axisVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("params","indices","axis"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } "stack" -> { val concat1 = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val concat2 = NodeDef { name = "input2" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("input2") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("N",AttrValue { i = 2 }) Attribute("axis",AttrValue { i = 0 }) } val graphDef = GraphDef { Node(concat1) Node(concat2) Node(opNode) } val inputVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"input2" to inputVal.dup()) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","input2"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "unstack" -> { val concat1 = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("num",AttrValue { i = 2 }) Attribute("axis",AttrValue { i = 0 }) } val graphDef = GraphDef { Node(concat1) Node(opNode) } val inputVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "mergesum" -> { val concat1 = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val concat2 = NodeDef { name = "input2" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("input2") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("N",AttrValue { i = 2 }) } val graphDef = GraphDef { Node(concat1) Node(concat2) Node(opNode) } val inputVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"input2" to inputVal.dup()) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","input2"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "merge" -> { val concat1 = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val concat2 = NodeDef { name = "input2" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("input2") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("N",AttrValue { i = 2 }) } val graphDef = GraphDef { Node(concat1) Node(concat2) Node(opNode) } val inputVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"input2" to inputVal.dup()) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","input2"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "mergeadd" -> { val concat1 = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val concat2 = NodeDef { name = "input2" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("input2") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("N",AttrValue { i = 2 }) Attribute("shape",AttrValue { shape = TensorShapeProto { Dims(listOf(4,2)) } }) } val graphDef = GraphDef { Node(concat1) Node(concat2) Node(opNode) } val inputVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"input2" to inputVal.dup()) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","input2"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "concat" -> { if(inputFrameworkOpName == "Concat") { val concatDim = NodeDef { name = "concat_dim" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("value",AttrValue { tensor = TensorProto { dtype = DataType.DT_INT32 Int32Data(listOf(0)) Shape(listOf()) } }) } val concat1 = NodeDef { name = "input" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT64 }) } val concat2 = NodeDef { name = "input2" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("concat_dim") Input("input") Input("input2") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_INT64 }) Attribute("N", AttrValue { i = 2 }) } val graphDef = GraphDef { Node(concatDim) Node(concat1) Node(concat2) Node(opNode) } val inputVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"input2" to inputVal.dup()) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","input2"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } else { //ConcatV2 val concatDim = NodeDef { name = "concat_dim" op = "Const" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) Attribute("value",AttrValue { tensor = TensorProto { dtype = DataType.DT_INT32 Int32Data(listOf(0)) Shape(listOf()) } }) } val concat1 = NodeDef { name = "input" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT64 }) } val concat2 = NodeDef { name = "input2" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") Input("input2") Input("concat_dim") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_INT64 }) Attribute("N", AttrValue { i = 2 }) } val graphDef = GraphDef { Node(concat1) Node(concat2) Node(concatDim) Node(opNode) } val inputVal = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal,"input2" to inputVal.dup()) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","input2"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } "shape_of" -> { val tensorNode = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("out_type",AttrValue { type = DataType.DT_INT64 }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val inputVal = Nd4j.create(floatArrayOf(1.0f,0.0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to inputVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "toggle_bits","invert_permutation" -> { val tensorNode = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } println("Running test import process for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val inputVal = Nd4j.create(floatArrayOf(1.0f,0.0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to inputVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "reverse" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val axis = NodeDef { name = "axis" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("input") Input("axis") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("Tidx",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(input) Node(axis) Node(opNode) } val inputVal = Nd4j.zeros(2,2).addi(0.5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val axisVal = Nd4j.zeros(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to inputVal,"axis" to axisVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","axis"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "roll" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val shift = NodeDef { name = "shift" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val axis = NodeDef { name = "axis" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("input") Input("shift") Input("axis") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("Tshift",AttrValue { type = DataType.DT_INT32 }) Attribute("Taxis",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(input) Node(shift) Node(axis) Node(opNode) } val inputVal = Nd4j.zeros(2,2).addi(0.5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val shiftVal = Nd4j.zeros(2).addi(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val axisVal = Nd4j.zeros(2).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to inputVal,"shift" to shiftVal,"axis" to axisVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","shift","axis"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "tile" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val multiples = NodeDef { name = "multiples" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("input") Input("multiples") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("Tmultiples",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(input) Node(multiples) Node(opNode) } val inputVal = Nd4j.zeros(2,2).addi(0.5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val multiplesVal = Nd4j.zeros(2).addi(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to inputVal,"multiples" to multiplesVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input","multiples"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "leakyrelu" -> { val a = NodeDef { name = "a" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val opNode = NodeDef { Input("a") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) Attribute("alpha",AttrValue { f = 0.1f }) } val graphDef = GraphDef { Node(a) Node(opNode) } val aVal = Nd4j.zeros(2,2).addi(0.5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("a" to aVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("a"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "betainc" -> { val a = NodeDef { name = "a" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val b = NodeDef { name = "b" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val x = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val opNode = NodeDef { Input("a") Input("b") Input("x") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(a) Node(b) Node(x) Node(opNode) } val aVal = Nd4j.zeros(2,2).addi(0.5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val bVal = Nd4j.zeros(2,2).addi(0.5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val xVal = Nd4j.zeros(2,2).addi(0.5) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("a" to aVal,"b" to bVal,"x" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("a","b","x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "top_k" -> { if(tensorflowOpDef.name == "TopK") { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) Attribute("k", AttrValue { i = 2 }) } val graphDef = GraphDef { Node(input) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("input" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } else { //TopKV2 val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val k = NodeDef { name = "k" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("value",AttrValue { tensor = TensorProto { Int32Data(listOf(2)) dtype = DataType.DT_INT32 } }) } val opNode = NodeDef { Input("input") Input("k") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(input) Node(k) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("input" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } "enter" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) Attribute("is_constant",AttrValue { b = false }) Attribute("frame_name",AttrValue { s = ByteString.copyFrom("hello".toByteArray(Charset.defaultCharset())) }) } val graphDef = GraphDef { Node(input) Node(opNode) } val xVal = Nd4j.linspace(1, 6, 6) .reshape(2, 3) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "Assert" -> { val condition = NodeDef { name = "condition" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val input = NodeDef { name = "input" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) Attribute("value",AttrValue { tensor = TensorProto { FloatData(listOf(0.0f)) dtype = DataType.DT_FLOAT } }) } val opNode = NodeDef { Input("condition") Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { ListDataType(listOf(DataType.DT_FLOAT)) }) } val graphDef = GraphDef { Node(condition) Node(input) Node(opNode) } val xVal = Nd4j.create(listOf(true,true,true,true).toBooleanArray()) val inputs = mapOf("condition" to xVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("condition"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "bitcast" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("type",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(input) Node(opNode) } val xVal = Nd4j.zeros(2,3) .castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("input" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "exit" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(input) Node(opNode) } val xVal = Nd4j.linspace(1, 6, 6) .reshape(2, 3) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "expand_dims" -> { val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val n = NodeDef { name = "dimension" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("value",AttrValue { tensor = TensorProto { Int32Data(listOf(0)) dtype = DataType.DT_INT32 } }) } val opNode = NodeDef { Input("input") Input("dimension") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(input) Node(n) Node(opNode) } val xVal = Nd4j.linspace(1, 6, 6) .reshape(2, 3) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "non_max_suppression","non_max_suppression_v3" -> { if(inputFrameworkOpName == "NonMaxSuppression") { val overlaps = NodeDef { name = "overlaps" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val scores = NodeDef { name = "scores" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val maxOutputSize = NodeDef { name = "maxOutputSize" op = "Const" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) Attribute("value", AttrValue { tensor = TensorProto { Int32Data(listOf(1)) dtype = DataType.DT_INT32 } }) } val opNode = NodeDef { Input("overlaps") Input("scores") Input("maxOutputSize") op = tensorflowOpDef.name name = "output" Attribute("iou_threshold", AttrValue { f = 0.5f }) } val graphDef = GraphDef { Node(overlaps) Node(scores) Node(maxOutputSize) Node(opNode) } val overlapsVal = Nd4j.create(arrayOf( floatArrayOf(0f,0f,1f,1f), floatArrayOf(0f,0.1f,1f,1.1f), floatArrayOf(0f,-0.1f,1f,0.9f), floatArrayOf(0f,10f,1f,11f) )).castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val scoresVal = Nd4j.create(listOf(0.9f,0.75f,0.6f,0.95f).toFloatArray()) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("overlaps" to overlapsVal,"scores" to scoresVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("overlaps","scores"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } else if(inputFrameworkOpName == "NonMaxSuppressionV2") { val overlaps = NodeDef { name = "overlaps" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val scores = NodeDef { name = "scores" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val maxOutputSize = NodeDef { name = "maxOutputSize" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("value",AttrValue { tensor = TensorProto { Int32Data(listOf(1)) dtype = DataType.DT_INT32 } }) } val iouThreshold = NodeDef { name = "iouThreshold" op = "Const" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) Attribute("value", AttrValue { tensor = TensorProto { FloatData(listOf(0.5f)) dtype = DataType.DT_FLOAT } }) } val opNode = NodeDef { Input("overlaps") Input("scores") Input("maxOutputSize") Input("iouThreshold") op = tensorflowOpDef.name name = "output" } val graphDef = GraphDef { Node(overlaps) Node(scores) Node(iouThreshold) Node(maxOutputSize) Node(opNode) } val overlapsVal = Nd4j.create(arrayOf( floatArrayOf(0f,0f,1f,1f), floatArrayOf(0f,0.1f,1f,1.1f), floatArrayOf(0f,-0.1f,1f,0.9f), floatArrayOf(0f,10f,1f,11f) )).castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val scoresVal = Nd4j.create(listOf(0.9f,0.75f,0.6f,0.95f).toFloatArray()) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("overlaps" to overlapsVal,"scores" to scoresVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("overlaps","scores"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } else { //V3 and later val overlaps = NodeDef { name = "overlaps" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val scores = NodeDef { name = "scores" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val maxOutputSize = NodeDef { name = "maxOutputSize" op = "Const" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) Attribute("value", AttrValue { tensor = TensorProto { Int32Data(listOf(1)) dtype = DataType.DT_INT32 } }) } val overlapThreshold = NodeDef { name = "iouThreshold" op = "Const" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) Attribute("value", AttrValue { tensor = TensorProto { FloatData(listOf(0.5f)) dtype = DataType.DT_FLOAT } }) } val scoreThreshold = NodeDef { name = "scoreThreshold" op = "Const" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) Attribute("value", AttrValue { tensor = TensorProto { FloatData(listOf(0.5f)) dtype = DataType.DT_FLOAT } }) } val opNode = NodeDef { Input("overlaps") Input("scores") Input("maxOutputSize") Input("iouThreshold") Input("scoreThreshold") op = tensorflowOpDef.name name = "output" } val graphDef = GraphDef { Node(overlaps) Node(scores) Node(scoreThreshold) Node(overlapThreshold) Node(maxOutputSize) Node(opNode) } val overlapsVal = Nd4j.create(arrayOf( floatArrayOf(0f,0f,1f,1f), floatArrayOf(0f,0.1f,1f,1.1f), floatArrayOf(0f,-0.1f,1f,0.9f), floatArrayOf(0f,10f,1f,11f) )).castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val scoresVal = Nd4j.create(listOf(0.9f,0.75f,0.6f,0.95f).toFloatArray()) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("overlaps" to overlapsVal,"scores" to scoresVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("overlaps","scores"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } "non_max_suppression_overlaps" -> { val overlaps = NodeDef { name = "overlaps" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val scores = NodeDef { name = "scores" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val maxOutputSize = NodeDef { name = "maxOutputSize" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("value",AttrValue { tensor = TensorProto { Int32Data(listOf(1)) dtype = DataType.DT_INT32 } }) } val overlapThreshold = NodeDef { name = "overlapThreshold" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) Attribute("value",AttrValue { tensor = TensorProto { FloatData(listOf(2.0f)) dtype = DataType.DT_FLOAT } }) } val scoreThreshold = NodeDef { name = "scoreThreshold" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) Attribute("value",AttrValue { tensor = TensorProto { FloatData(listOf(0.5f)) dtype = DataType.DT_FLOAT } }) } val opNode = NodeDef { Input("overlaps") Input("scores") Input("maxOutputSize") Input("overlapThreshold") Input("scoreThreshold") op = tensorflowOpDef.name name = "output" } val graphDef = GraphDef { Node(overlaps) Node(scores) Node(scoreThreshold) Node(overlapThreshold) Node(maxOutputSize) Node(opNode) } val overlapsVal = Nd4j.create(arrayOf( floatArrayOf(0f,0f,1f,1f), floatArrayOf(0f,0.1f,1f,1.1f), floatArrayOf(0f,-0.1f,1f,0.9f), floatArrayOf(0f,10f,1f,11f) )).castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val scoresVal = Nd4j.create(listOf(0.9f,0.75f,0.6f,0.95f).toFloatArray()) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("overlaps" to overlapsVal,"scores" to scoresVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("overlaps","scores"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "nth_element" -> { val ret = ArrayList<GraphInput>() listOf(true,false).forEach { reverse -> val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val n = NodeDef { name = "n" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("value",AttrValue { tensor = TensorProto { Int32Data(listOf(2)) dtype = DataType.DT_INT32 } }) } val opNode = NodeDef { Input("input") Input("n") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_INT32 }) Attribute("reverse", AttrValue { type = DataType.DT_BOOL b = reverse }) } val graphDef = GraphDef { Node(input) Node(n) Node(opNode) } val xVal = Nd4j.linspace(1, 6, 6) .reshape(2, 3) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("input" to xVal) ret.add( GraphInput( graphDef =graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } return ret } "cholesky" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val xVal = Nd4j.create(floatArrayOf(4f,12f,-16f, 12f ,37f,-43f, -16f, -43f, 98f)) .reshape(3,3) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "matrix_diag_part" -> { val retSolve = ArrayList<GraphInput>() val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("input") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(input) Node(opNode) } val inputVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal) retSolve.add( GraphInput( graphDef = graphDef, inputNames = listOf("input"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) return retSolve } "matrix_set_diag","matrix_diag_part" -> { val retSolve = ArrayList<GraphInput>() val input = NodeDef { name = "input" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val diagonal = NodeDef { name = "diagonal" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("input") Input("diagonal") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(input) Node(diagonal) Node(opNode) } val inputVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val diagonalVal = Nd4j.zeros(2).addi(1) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("input" to inputVal,"diagonal" to diagonalVal) retSolve.add( GraphInput( graphDef = graphDef, inputNames = listOf("input","diagonal"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) return retSolve } "solve","triangular_solve" -> { val retSolve = ArrayList<GraphInput>() listOf(false,true).forEach { useAdjoint -> val a = NodeDef { name = "a" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val bNode = NodeDef { name = "b" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("a") Input("b") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) Attribute("adjoint", AttrValue { b = useAdjoint }) } val graphDef = GraphDef { Node(a) Node(bNode) Node(opNode) } val aVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val bVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("a" to aVal,"b" to bVal) retSolve.add( GraphInput( graphDef = graphDef, inputNames = listOf("a","b"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } return retSolve } "matrix_determinant","log_matrix_determinant" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val finalResult = NodeDef { Input("output:1") op = "Identity" name = "finalResult" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } if(nd4jOpName == "log_matrix_determinant") { val graphDef = GraphDef { Node(tensorNode) Node(opNode) Node(finalResult) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef = graphDef, inputNames = listOf("x"), outputNames = listOf("finalResult"), inputArrays = inputs, dynamicArrays = inputs ) ) } else { val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } "lu" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "matrix_inverse" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "in_top_k" -> { if(tensorflowOpDef.name == "InTopK") { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val predictions = NodeDef { name = "predictions" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("x") Input("predictions") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_INT32 }) Attribute("k", AttrValue { i = 2 }) } val graphDef = GraphDef { Node(tensorNode) Node(predictions) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val predictionsArr = Nd4j.linspace(1, 2, 2) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("x" to xVal,"predictions" to predictionsArr) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("x","predictions"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } else { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_FLOAT }) } val predictions = NodeDef { name = "predictions" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val k = NodeDef { name = "k" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("value", AttrValue { tensor = TensorProto { Int32Data(listOf(2)) dtype = DataType.DT_INT32 } }) } val opNode = NodeDef { Input("x") Input("predictions") Input("k") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(predictions) Node(k) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val predictionsArr = Nd4j.linspace(1, 2, 2) .reshape(2) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("x" to xVal,"predictions" to predictionsArr) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("x","predictions"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } "onehot" -> { val indices = NodeDef { name = "indices" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val depth = NodeDef { name = "depth" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute("value",AttrValue { tensor = TensorProto { dtype = DataType.DT_INT32 Int32Data(listOf(1)) } }) } val onValue = NodeDef { name = "on" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) Attribute("value",AttrValue { tensor = TensorProto { dtype = DataType.DT_INT64 Int64Data(listOf(1)) } }) } val offValue = NodeDef { name = "off" op = "Const" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) Attribute("value",AttrValue { tensor = TensorProto { dtype = DataType.DT_INT64 Int64Data(listOf(0)) } }) } val opNode = NodeDef { Input("indices") Input("depth") Input("on") Input("off") op = tensorflowOpDef.name name = "output" Attribute("TI",AttrValue { type = DataType.DT_INT64 }) Attribute("T",AttrValue { type = DataType.DT_INT64 }) Attribute("axis",AttrValue { i = 0 }) } val graphDef = GraphDef { Node(indices) Node(depth) Node(onValue) Node(offValue) Node(opNode) } val indicesVal = Nd4j.linspace(1, 4, 4) .castTo(org.nd4j.linalg.api.buffer.DataType.INT64) val inputs = mapOf("indices" to indicesVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("indices"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "cross" -> { val a = NodeDef { name = "a" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val b = NodeDef { name = "b" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val opNode = NodeDef { Input("a") Input("b") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val graphDef = GraphDef { Node(a) Node(b) Node(opNode) } val aVal = Nd4j.linspace(1, 27, 27) .reshape(3,3,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val bVal = Nd4j.linspace(1, 27, 27) .reshape(3,3,3) .castTo(org.nd4j.linalg.api.buffer.DataType.FLOAT) val inputs = mapOf("a" to aVal,"b" to bVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("a","b"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "transpose" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val tensorNode2 = NodeDef { op = "Const" name = "perm" Attribute("value",AttrValue { tensor = TensorProto { Int32Data(listOf(0,1)) Shape(listOf(2)) dtype = DataType.DT_INT32 } }) Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("x") Input("perm") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tperm",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(tensorNode2) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "relu", "relu6" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef = GraphDef { Node(tensorNode) Node(opNode) }, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "depth_to_space","space_to_depth" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) Attribute("data_format", AttrValue { s = ByteString.copyFrom("NHWC".toByteArray(Charset.defaultCharset())) }) Attribute("block_size", AttrValue { i = 2 }) } val xVal = Nd4j.linspace(1, 256, 256) .reshape(4, 4,4,4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef = GraphDef { Node(tensorNode) Node(opNode) }, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "softmax","digamma","diag","diag_part","lgamma" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef = GraphDef { Node(tensorNode) Node(opNode) }, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "cumsum","cumprod" -> { val ret = ArrayList<GraphInput>() listOf(false,true).forEach { reverse -> listOf(false,true).forEach { exclusive -> val inputNames = listOf("x") val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val dimensions = listOf(1) val tensorNode2 = NodeDef { op = "Const" name = "dimensions" Attribute("value",AttrValue { tensor = TensorProto { Int32Data(dimensions) dtype = DataType.DT_INT32 tensorShape = TensorShapeProto { Dims(listOf()) } } }) Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("x") Input("dimensions") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("exclusive",AttrValue { b = exclusive }) Attribute("reverse",AttrValue { b = reverse }) } val graphDef = GraphDef { Node(tensorNode) Node(tensorNode2) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) ret.add( GraphInput( graphDef =graphDef, inputNames = inputNames, outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } } return ret } "Assert" -> { val tensorNode = NodeDef { name = "condition" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val tensorNode2 = NodeDef { op = "Placeholder" name = "data" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running op def for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("condition") Input("data") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { ListDataType(listOf(DataType.DT_DOUBLE)) }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) Node(tensorNode2) } val inputs = mapOf("data" to Nd4j.linspace(1,4,4).castTo( org.nd4j.linalg.api.buffer.DataType.DOUBLE ),"condition" to Nd4j.ones(2).addi(1).castTo(org.nd4j.linalg.api.buffer.DataType.BOOL)) return listOf( GraphInput(graphDef = graphDef, inputNames = listOf("condition","data"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs) ) } "Where" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } println("Running op def for op ${tensorflowOpDef.name}") val opNode = NodeDef { Input("x") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val inputs = mapOf("x" to Nd4j.linspace(1,4,4).castTo( org.nd4j.linalg.api.buffer.DataType.DOUBLE )) return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs) ) } "boolean_or" -> { println("Running op def for op ${tensorflowOpDef.name}") val inputNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val secondNode = NodeDef { name = "y" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val opNode = NodeDef { Input("x") Input("y") name = "and" op = tensorflowOpDef.name } val inputs = mapOf("x" to Nd4j.ones(2,2).castTo( org.nd4j.linalg.api.buffer.DataType.BOOL ), "y" to Nd4j.zeros(2,2).castTo( org.nd4j.linalg.api.buffer.DataType.BOOL )) val graphDef = GraphDef { Node(inputNode) Node(secondNode) Node(opNode) } return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x","y"), outputNames = listOf("and"), inputArrays = inputs, dynamicArrays = inputs) ) } "boolean_and" -> { println("Running op def for op ${tensorflowOpDef.name}") val inputNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val secondNode = NodeDef { name = "y" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val opNode = NodeDef { Input("x") Input("y") name = "and" op = tensorflowOpDef.name } val inputs = mapOf("x" to Nd4j.ones(2,2).castTo( org.nd4j.linalg.api.buffer.DataType.BOOL ), "y" to Nd4j.zeros(2,2).castTo( org.nd4j.linalg.api.buffer.DataType.BOOL )) val graphDef = GraphDef { Node(inputNode) Node(secondNode) Node(opNode) } return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x","y"), outputNames = listOf("and"), inputArrays = inputs, dynamicArrays = inputs) ) } "igamma","igammac" -> { println("Running op def for op ${tensorflowOpDef.name}") val a = NodeDef { name = "a" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val x = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val opNode = NodeDef { Input("a") Input("x") name = "igamma" op = tensorflowOpDef.name Attribute("T",AttrValue { type = DataType.DT_FLOAT }) } val inputs = mapOf("a" to Nd4j.ones(2,2).castTo( org.nd4j.linalg.api.buffer.DataType.FLOAT ),"x" to Nd4j.ones(2,2).castTo( org.nd4j.linalg.api.buffer.DataType.FLOAT )) val graphDef = GraphDef { Node(a) Node(x) Node(opNode) } return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("a","x"), outputNames = listOf("igamma"), inputArrays = inputs, dynamicArrays = inputs) ) } "boolean_not" -> { println("Running op def for op ${tensorflowOpDef.name}") val inputNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_BOOL }) } val opNode = NodeDef { Input("x") name = "not" op = tensorflowOpDef.name } val inputs = mapOf("x" to Nd4j.ones(2,2).castTo( org.nd4j.linalg.api.buffer.DataType.BOOL )) val graphDef = GraphDef { Node(inputNode) Node(opNode) } return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x"), outputNames = listOf("not"), inputArrays = inputs, dynamicArrays = inputs) ) } "cast" -> { println("Running op def for op ${tensorflowOpDef.name}") val inputNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_FLOAT }) } val opNode = NodeDef { Input("x") name = "output" op = tensorflowOpDef.name Attribute("SrcT",AttrValue { type = DataType.DT_FLOAT }) Attribute("DstT",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(inputNode) Node(opNode) } val inputs = mapOf("x" to Nd4j.ones(2,2).castTo( org.nd4j.linalg.api.buffer.DataType.FLOAT )) return listOf( GraphInput(graphDef = graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = emptyMap()) ) } "noop" -> { println("Running op def for op ${tensorflowOpDef.name}") val opNode = NodeDef { name = "noop" op = tensorflowOpDef.name } val graphDef = GraphDef { Node(opNode) } return listOf( GraphInput(graphDef = graphDef, inputNames = listOf(), outputNames = listOf(), inputArrays = emptyMap(), dynamicArrays = emptyMap()) ) } "While" -> { println("Running op def for op ${tensorflowOpDef.name}") val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { ListDataType(listOf(DataType.DT_DOUBLE)) }) } val opNode = NodeDef { Input("x") name = "while" op = tensorflowOpDef.name } val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val inputs = mapOf("x" to Nd4j.scalar(1.0)) return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs) ) } "unique_with_counts","unique" -> { println("Running op def for op ${tensorflowOpDef.name}") val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } if(tensorflowOpDef.name == "UniqueWithCountsV2" || tensorflowOpDef.name == "UniqueV2") { val axis = NodeDef { name = "axis" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT64 }) } val opNode = NodeDef { Input("x") Input("axis") name = "output" op = tensorflowOpDef.name Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(tensorNode) Node(axis) Node(opNode) } val inputs = mapOf("x" to Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE), "axis" to Nd4j.scalar(1).reshape(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT64)) return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x","axis"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs) ) } else { val opNode = NodeDef { Input("x") name = "output" op = tensorflowOpDef.name Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) } val inputs = mapOf("x" to Nd4j.linspace(1,4,4).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE)) return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs) ) } } "pad" -> { if(tensorflowOpDef.name == "Pad") { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val tensorNode2 = NodeDef { op = "Placeholder" name = "paddings" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("x") Input("paddings") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tpaddings", AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) Node(tensorNode2) } val inputs = mapOf("x" to Nd4j.linspace(1,4,4).castTo( org.nd4j.linalg.api.buffer.DataType.DOUBLE ),"paddings" to Nd4j.ones(1,2).addi(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT32)) return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x","paddings"),outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs) ) } else if(tensorflowOpDef.name == "PadV2"){ val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val tensorNode2 = NodeDef { op = "Placeholder" name = "paddings" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val constantValues = NodeDef { op = "Const" name = "constant_values" Attribute("value", AttrValue { tensor = TensorProto { DoubleData(listOf(1.0)) dtype = DataType.DT_DOUBLE tensorShape = TensorShapeProto { Dims(listOf()) } } }) Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") Input("paddings") Input("constant_values") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tpaddings",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) Node(constantValues) Node(tensorNode2) } val inputs = mapOf("x" to Nd4j.linspace(1,4,4).castTo( org.nd4j.linalg.api.buffer.DataType.DOUBLE ),"paddings" to Nd4j.ones(1,2).addi(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT32)) return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x","paddings"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs) ) } else { throw IllegalArgumentException("Illegal mapping for padding op $tensorflowOpDef.name") } } "reshape" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val tensorNode2 = NodeDef { op = "Placeholder" name = "shape" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("x") Input("shape") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(tensorNode) Node(opNode) Node(tensorNode2) } val inputs = mapOf("x" to Nd4j.linspace(1,4,4).castTo( org.nd4j.linalg.api.buffer.DataType.DOUBLE ),"shape" to Nd4j.ones(2).addi(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT32)) return listOf( GraphInput(graphDef = graphDef,inputNames = listOf("x","shape"),outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs) ) } "reduce_logsumexp" -> { val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") Input("dimensions") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tidx",AttrValue { type = DataType.DT_INT32 }) Attribute("exclusive",AttrValue { b = false }) } val dimensions = listOf(0) val tensorNode2 = NodeDef { op = "Const" name = "dimensions" Attribute("value",AttrValue { tensor = TensorProto { Int32Data(dimensions) dtype = DataType.DT_INT32 tensorShape = TensorShapeProto { Dims(listOf()) } } }) Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(tensorNode2) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) return listOf( GraphInput( graphDef =graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } "argmin", "argmax" -> { val ret = ArrayList<GraphInput>() listOf(true, false).forEach { keepDim -> val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype", AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") Input("dimensions") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tidx",AttrValue { type = DataType.DT_INT32 }) } val dimensions = listOf(0) val tensorNode2 = NodeDef { op = "Const" name = "dimensions" Attribute("value", AttrValue { tensor = TensorProto { Int32Data(dimensions) dtype = DataType.DT_INT32 tensorShape = TensorShapeProto { Dims(listOf()) } } }) Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(tensorNode2) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) ret.add( GraphInput( graphDef =graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } return ret } "pow" -> { val ret = ArrayList<GraphInput>() val tensorNode = NodeDef { name = "x" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val tensorNode2 = NodeDef { op = "Const" name = "y" Attribute("value",AttrValue { tensor = TensorProto { DoubleData(listOf(1.0)) dtype = DataType.DT_DOUBLE tensorShape = TensorShapeProto { Dims(listOf()) } } }) Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val opNode = NodeDef { Input("x") Input("y") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) } val graphDef = GraphDef { Node(tensorNode) Node(tensorNode2) Node(opNode) } val xVal = Nd4j.linspace(1, 4, 4) .reshape(2, 2) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val inputs = mapOf("x" to xVal) ret.add( GraphInput( graphDef =graphDef, inputNames = listOf("x"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) return ret } //scatter_div //TODO: Revisit. TF op validation seems to be different than ours. "scatter_add","scatter_sub","scatter_min","scatter_sub","scatter_min","scatter_mul","scatter_update","scatter_nd","scatter_nd_add","scatter_nd_sub","scatter_nd_update" -> { val ret = ArrayList<GraphInput>() listOf(true,false).forEach { lock -> val xRef = NodeDef { name = "shape" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val tensorNode2 = NodeDef { op = "Placeholder" name = "indices" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val updates2 = NodeDef { op = "Placeholder" name = "updates" Attribute("dtype", AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("indices") Input("updates") Input("shape") op = tensorflowOpDef.name name = "output" Attribute("T", AttrValue { type = DataType.DT_INT32 }) Attribute("Tindices", AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(xRef) Node(tensorNode2) Node(updates2) Node(opNode) } //from testScatterOpGradients. val shape = Nd4j.scalar(8).reshape(1).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val indices = Nd4j.create(floatArrayOf(4f,3f,1f,7f)).reshape(4,1) .castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val updates = Nd4j.linspace(1,4,4).reshape(4).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("shape" to shape,"updates" to updates,"indices" to indices) ret.add( GraphInput( graphDef =graphDef, inputNames = listOf("indices","updates","shape"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) } return ret } "segment_mean", "segment_min","segment_max","segment_prod","segment_sum" -> { val ret = ArrayList<GraphInput>() val tensorNode = NodeDef { name = "data" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val segmentIds = NodeDef { op = "Placeholder" name = "segment_ids" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val opNode = NodeDef { Input("data") Input("segment_ids") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tindices",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(segmentIds) Node(opNode) } val xVal = Nd4j.linspace(1, 12, 12) .reshape(3, 4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val indices = Nd4j.create(floatArrayOf(1.0f,2.0f,3.0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("data" to xVal,"segment_ids" to indices) ret.add( GraphInput( graphDef =graphDef, inputNames = listOf("data","segment_ids"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) return ret } "unsorted_segment_sum", "unsorted_segment_prod","unsorted_segment_min","unsorted_segment_max" -> { val ret = ArrayList<GraphInput>() val tensorNode = NodeDef { name = "data" op = "Placeholder" Attribute("dtype",AttrValue { type = DataType.DT_DOUBLE }) } val segmentIds = NodeDef { op = "Placeholder" name = "segment_ids" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) } val numSegmentsNode = NodeDef { op = "Const" name = "num_segments" Attribute("dtype",AttrValue { type = DataType.DT_INT32 }) Attribute(name = "value",value = AttrValue { tensor = TensorProto { Shape(listOf()) Int32Data(listOf(2)) DataType(DataType.DT_INT32) } }) } val opNode = NodeDef { Input("data") Input("segment_ids") Input("num_segments") op = tensorflowOpDef.name name = "output" Attribute("T",AttrValue { type = DataType.DT_DOUBLE }) Attribute("Tindices",AttrValue { type = DataType.DT_INT32 }) Attribute("Tnumsegments",AttrValue { type = DataType.DT_INT32 }) } val graphDef = GraphDef { Node(tensorNode) Node(segmentIds) Node(numSegmentsNode) Node(opNode) } val xVal = Nd4j.linspace(1, 12, 12) .reshape(3, 4) .castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE) val indices = Nd4j.create(floatArrayOf(0.0f,1.0f,0.0f)).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val numSegments = Nd4j.scalar(2).castTo(org.nd4j.linalg.api.buffer.DataType.INT32) val inputs = mapOf("data" to xVal,"segment_ids" to indices,"num_segments" to numSegments) ret.add( GraphInput( graphDef =graphDef, inputNames = listOf("data","segment_ids","num_segments"), outputNames = listOf("output"), inputArrays = inputs, dynamicArrays = inputs ) ) return ret } else -> { throw IllegalArgumentException("Illegal op name $inputFrameworkOpName") } } }
apache-2.0
ca58a66d3cd30976480a665df71ed0df
28.918014
190
0.402705
4.934259
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/reactnativestripesdk/StripeSdkModule.kt
2
27055
package versioned.host.exp.exponent.modules.api.components.reactnativestripesdk import android.app.Activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.AsyncTask import android.os.Parcelable import android.util.Log import androidx.activity.ComponentActivity import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.facebook.react.bridge.* import com.facebook.react.module.annotations.ReactModule import com.stripe.android.* import com.stripe.android.googlepaylauncher.GooglePayLauncher import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncher import com.stripe.android.model.* import com.stripe.android.paymentsheet.PaymentSheetResult import com.stripe.android.view.AddPaymentMethodActivityStarter import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking @ReactModule(name = StripeSdkModule.NAME) class StripeSdkModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { var cardFieldView: StripeSdkCardView? = null var cardFormView: CardFormView? = null private lateinit var localBroadcastManager: LocalBroadcastManager override fun getName(): String { return "StripeSdk" } private lateinit var stripe: Stripe private lateinit var publishableKey: String private var stripeAccountId: String? = null private var paymentSheetFragment: PaymentSheetFragment? = null private var urlScheme: String? = null private var confirmPromise: Promise? = null private var handleCardActionPromise: Promise? = null private var confirmSetupIntentPromise: Promise? = null private var confirmPaymentSheetPaymentPromise: Promise? = null private var presentPaymentSheetPromise: Promise? = null private var initPaymentSheetPromise: Promise? = null private var confirmPaymentClientSecret: String? = null private var googlePayFragment: GooglePayFragment? = null private var initGooglePayPromise: Promise? = null private var presentGooglePayPromise: Promise? = null private val mActivityEventListener = object : BaseActivityEventListener() { override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) { if (::stripe.isInitialized) { stripe.onSetupResult( requestCode, data, object : ApiResultCallback<SetupIntentResult> { override fun onSuccess(result: SetupIntentResult) { val setupIntent = result.intent when (setupIntent.status) { StripeIntent.Status.Succeeded -> { confirmSetupIntentPromise?.resolve(createResult("setupIntent", mapFromSetupIntentResult(setupIntent))) } StripeIntent.Status.Canceled -> { confirmSetupIntentPromise?.resolve(createError(ConfirmSetupIntentErrorType.Canceled.toString(), setupIntent.lastSetupError)) } StripeIntent.Status.RequiresAction -> { confirmSetupIntentPromise?.resolve(createError(ConfirmSetupIntentErrorType.Canceled.toString(), setupIntent.lastSetupError)) } else -> { val errorMessage = "unhandled error: ${setupIntent.status}" confirmSetupIntentPromise?.resolve(createError(ConfirmSetupIntentErrorType.Failed.toString(), errorMessage)) } } } override fun onError(e: Exception) { confirmSetupIntentPromise?.resolve(createError(ConfirmSetupIntentErrorType.Failed.toString(), e)) } } ) stripe.onPaymentResult( requestCode, data, object : ApiResultCallback<PaymentIntentResult> { override fun onSuccess(result: PaymentIntentResult) { val paymentIntent = result.intent when (paymentIntent.status) { StripeIntent.Status.Succeeded, StripeIntent.Status.Processing, StripeIntent.Status.RequiresCapture -> { val pi = createResult("paymentIntent", mapFromPaymentIntentResult(paymentIntent)) confirmPromise?.resolve(pi) handleCardActionPromise?.resolve(pi) } StripeIntent.Status.RequiresAction -> { if (isPaymentIntentNextActionVoucherBased(paymentIntent.nextActionType)) { val pi = createResult("paymentIntent", mapFromPaymentIntentResult(paymentIntent)) confirmPromise?.resolve(pi) handleCardActionPromise?.resolve(pi) } else { (paymentIntent.lastPaymentError)?.let { confirmPromise?.resolve(createError(ConfirmPaymentErrorType.Canceled.toString(), it)) handleCardActionPromise?.resolve(createError(NextPaymentActionErrorType.Canceled.toString(), it)) } ?: run { confirmPromise?.resolve(createError(ConfirmPaymentErrorType.Canceled.toString(), "The payment has been canceled")) handleCardActionPromise?.resolve(createError(NextPaymentActionErrorType.Canceled.toString(), "The payment has been canceled")) } } } StripeIntent.Status.RequiresPaymentMethod -> { val error = paymentIntent.lastPaymentError confirmPromise?.resolve(createError(ConfirmPaymentErrorType.Failed.toString(), error)) handleCardActionPromise?.resolve(createError(NextPaymentActionErrorType.Failed.toString(), error)) } StripeIntent.Status.RequiresConfirmation -> { val pi = createResult("paymentIntent", mapFromPaymentIntentResult(paymentIntent)) handleCardActionPromise?.resolve(pi) } StripeIntent.Status.Canceled -> { val error = paymentIntent.lastPaymentError confirmPromise?.resolve(createError(ConfirmPaymentErrorType.Canceled.toString(), error)) handleCardActionPromise?.resolve(createError(NextPaymentActionErrorType.Canceled.toString(), error)) } else -> { val errorMessage = "unhandled error: ${paymentIntent.status}" confirmPromise?.resolve(createError(ConfirmPaymentErrorType.Unknown.toString(), errorMessage)) handleCardActionPromise?.resolve(createError(NextPaymentActionErrorType.Unknown.toString(), errorMessage)) } } } override fun onError(e: Exception) { confirmPromise?.resolve(createError(ConfirmPaymentErrorType.Failed.toString(), e)) handleCardActionPromise?.resolve(createError(NextPaymentActionErrorType.Failed.toString(), e)) } } ) paymentSheetFragment?.activity?.activityResultRegistry?.dispatchResult(requestCode, resultCode, data) googlePayFragment?.activity?.activityResultRegistry?.dispatchResult(requestCode, resultCode, data) try { val result = AddPaymentMethodActivityStarter.Result.fromIntent(data) if (data?.getParcelableExtra<Parcelable>("extra_activity_result") != null) { onFpxPaymentMethodResult(result) } } catch (e: java.lang.Exception) { Log.d("Error", e.localizedMessage ?: e.toString()) } } } } init { reactContext.addActivityEventListener(mActivityEventListener) } private fun configure3dSecure(params: ReadableMap) { val stripe3dsConfigBuilder = PaymentAuthConfig.Stripe3ds2Config.Builder() if (params.hasKey("timeout")) stripe3dsConfigBuilder.setTimeout(params.getInt("timeout")) val uiCustomization = mapToUICustomization(params) PaymentAuthConfig.init( PaymentAuthConfig.Builder() .set3ds2Config( stripe3dsConfigBuilder .setUiCustomization(uiCustomization) .build() ) .build() ) } private val googlePayReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent) { if (intent.action == ON_GOOGLE_PAY_FRAGMENT_CREATED) { googlePayFragment = (currentActivity as AppCompatActivity).supportFragmentManager.findFragmentByTag("google_pay_launch_fragment") as GooglePayFragment } if (intent.action == ON_INIT_GOOGLE_PAY) { val isReady = intent.extras?.getBoolean("isReady") ?: false if (isReady) { initGooglePayPromise?.resolve(WritableNativeMap()) } else { initGooglePayPromise?.resolve(createError(GooglePayErrorType.Failed.toString(), "Google Pay is not available on this device")) } } if (intent.action == ON_GOOGLE_PAYMENT_METHOD_RESULT) { intent.extras?.getString("error")?.let { presentGooglePayPromise?.resolve(createError(GooglePayErrorType.Failed.toString(), it)) return } when (val result = intent.extras?.getParcelable<GooglePayPaymentMethodLauncher.Result>("paymentResult")) { is GooglePayPaymentMethodLauncher.Result.Completed -> { presentGooglePayPromise?.resolve(createResult("paymentMethod", mapFromPaymentMethod(result.paymentMethod))) } GooglePayPaymentMethodLauncher.Result.Canceled -> { presentGooglePayPromise?.resolve(createError(GooglePayErrorType.Failed.toString(), "Google Pay has been canceled")) } is GooglePayPaymentMethodLauncher.Result.Failed -> { presentGooglePayPromise?.resolve(createError(GooglePayErrorType.Failed.toString(), result.error)) } } } if (intent.action == ON_GOOGLE_PAY_RESULT) { intent.extras?.getString("error")?.let { presentGooglePayPromise?.resolve(createError(GooglePayErrorType.Failed.toString(), it)) return } when (val result = intent.extras?.getParcelable<GooglePayLauncher.Result>("paymentResult")) { GooglePayLauncher.Result.Completed -> { presentGooglePayPromise?.resolve(WritableNativeMap()) } GooglePayLauncher.Result.Canceled -> { presentGooglePayPromise?.resolve(createError(GooglePayErrorType.Failed.toString(), "Google Pay has been canceled")) } is GooglePayLauncher.Result.Failed -> { presentGooglePayPromise?.resolve(createError(GooglePayErrorType.Failed.toString(), result.error)) } } } } } private val mPaymentSheetReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent) { if (intent.action == ON_FRAGMENT_CREATED) { paymentSheetFragment = (currentActivity as AppCompatActivity).supportFragmentManager.findFragmentByTag("payment_sheet_launch_fragment") as PaymentSheetFragment } if (intent.action == ON_PAYMENT_RESULT_ACTION) { when (val result = intent.extras?.getParcelable<PaymentSheetResult>("paymentResult")) { is PaymentSheetResult.Canceled -> { val message = "The payment has been canceled" confirmPaymentSheetPaymentPromise?.resolve(createError(PaymentSheetErrorType.Canceled.toString(), message)) presentPaymentSheetPromise?.resolve(createError(PaymentSheetErrorType.Canceled.toString(), message)) } is PaymentSheetResult.Failed -> { confirmPaymentSheetPaymentPromise?.resolve(createError(PaymentSheetErrorType.Failed.toString(), result.error)) presentPaymentSheetPromise?.resolve(createError(PaymentSheetErrorType.Failed.toString(), result.error)) } is PaymentSheetResult.Completed -> { confirmPaymentSheetPaymentPromise?.resolve(WritableNativeMap()) presentPaymentSheetPromise?.resolve(WritableNativeMap()) } } } else if (intent.action == ON_PAYMENT_OPTION_ACTION) { val label = intent.extras?.getString("label") val image = intent.extras?.getString("image") if (label != null && image != null) { val option: WritableMap = WritableNativeMap() option.putString("label", label) option.putString("image", image) presentPaymentSheetPromise?.resolve(createResult("paymentOption", option)) } else { presentPaymentSheetPromise?.resolve(WritableNativeMap()) } presentPaymentSheetPromise = null } else if (intent.action == ON_INIT_PAYMENT_SHEET) { initPaymentSheetPromise?.resolve(WritableNativeMap()) } else if (intent.action == ON_CONFIGURE_FLOW_CONTROLLER) { val label = intent.extras?.getString("label") val image = intent.extras?.getString("image") if (label != null && image != null) { val option: WritableMap = WritableNativeMap() option.putString("label", label) option.putString("image", image) initPaymentSheetPromise?.resolve(createResult("paymentOption", option)) } else { initPaymentSheetPromise?.resolve(WritableNativeMap()) } } } } @ReactMethod fun initialise(params: ReadableMap, promise: Promise) { val publishableKey = getValOr(params, "publishableKey", null) as String val appInfo = getMapOrNull(params, "appInfo") as ReadableMap this.stripeAccountId = getValOr(params, "stripeAccountId", null) val urlScheme = getValOr(params, "urlScheme", null) val setUrlSchemeOnAndroid = getBooleanOrFalse(params, "setUrlSchemeOnAndroid") this.urlScheme = if (setUrlSchemeOnAndroid) urlScheme else null getMapOrNull(params, "threeDSecureParams")?.let { configure3dSecure(it) } this.publishableKey = publishableKey val name = getValOr(appInfo, "name", "") as String val partnerId = getValOr(appInfo, "partnerId", "") val version = getValOr(appInfo, "version", "") val url = getValOr(appInfo, "url", "") Stripe.appInfo = AppInfo.create(name, version, url, partnerId) stripe = Stripe(reactApplicationContext, publishableKey, stripeAccountId) PaymentConfiguration.init(reactApplicationContext, publishableKey, stripeAccountId) val localBroadcastManager = LocalBroadcastManager.getInstance(reactApplicationContext) localBroadcastManager.registerReceiver(mPaymentSheetReceiver, IntentFilter(ON_PAYMENT_RESULT_ACTION)) localBroadcastManager.registerReceiver(mPaymentSheetReceiver, IntentFilter(ON_PAYMENT_OPTION_ACTION)) localBroadcastManager.registerReceiver(mPaymentSheetReceiver, IntentFilter(ON_CONFIGURE_FLOW_CONTROLLER)) localBroadcastManager.registerReceiver(mPaymentSheetReceiver, IntentFilter(ON_FRAGMENT_CREATED)) localBroadcastManager.registerReceiver(mPaymentSheetReceiver, IntentFilter(ON_INIT_PAYMENT_SHEET)) localBroadcastManager.registerReceiver(googlePayReceiver, IntentFilter(ON_GOOGLE_PAY_FRAGMENT_CREATED)) localBroadcastManager.registerReceiver(googlePayReceiver, IntentFilter(ON_INIT_GOOGLE_PAY)) localBroadcastManager.registerReceiver(googlePayReceiver, IntentFilter(ON_GOOGLE_PAY_RESULT)) localBroadcastManager.registerReceiver(googlePayReceiver, IntentFilter(ON_GOOGLE_PAYMENT_METHOD_RESULT)) promise.resolve(null) } @ReactMethod fun initPaymentSheet(params: ReadableMap, promise: Promise) { val activity = currentActivity as AppCompatActivity? if (activity == null) { promise.resolve(createError("Failed", "Activity doesn't exist")) return } this.initPaymentSheetPromise = promise val fragment = PaymentSheetFragment().also { val bundle = toBundleObject(params) it.arguments = bundle } activity.supportFragmentManager.beginTransaction() .add(fragment, "payment_sheet_launch_fragment") .commit() } @ReactMethod fun presentPaymentSheet(promise: Promise) { this.presentPaymentSheetPromise = promise paymentSheetFragment?.present() } @ReactMethod fun confirmPaymentSheetPayment(promise: Promise) { this.confirmPaymentSheetPaymentPromise = promise paymentSheetFragment?.confirmPayment() } private fun payWithFpx() { AddPaymentMethodActivityStarter(currentActivity as AppCompatActivity) .startForResult( AddPaymentMethodActivityStarter.Args.Builder() .setPaymentMethodType(PaymentMethod.Type.Fpx) .build() ) } private fun onFpxPaymentMethodResult(result: AddPaymentMethodActivityStarter.Result) { when (result) { is AddPaymentMethodActivityStarter.Result.Success -> { val activity = currentActivity as ComponentActivity stripe.confirmPayment( activity, ConfirmPaymentIntentParams.createWithPaymentMethodId( result.paymentMethod.id!!, confirmPaymentClientSecret!!, ) ) } is AddPaymentMethodActivityStarter.Result.Failure -> { confirmPromise?.resolve(createError(ConfirmPaymentErrorType.Failed.toString(), result.exception)) } is AddPaymentMethodActivityStarter.Result.Canceled -> { confirmPromise?.resolve(createError(ConfirmPaymentErrorType.Canceled.toString(), "The payment has been canceled")) } } this.confirmPaymentClientSecret = null } @ReactMethod fun createPaymentMethod(data: ReadableMap, options: ReadableMap, promise: Promise) { val cardParams = (cardFieldView?.cardParams ?: cardFormView?.cardParams) ?: run { promise.resolve(createError("Failed", "Card details not complete")) return } val cardAddress = cardFieldView?.cardAddress ?: cardFormView?.cardAddress val billingDetailsParams = mapToBillingDetails(getMapOrNull(data, "billingDetails"), cardAddress) val paymentMethodCreateParams = PaymentMethodCreateParams.create(cardParams, billingDetailsParams) stripe.createPaymentMethod( paymentMethodCreateParams, callback = object : ApiResultCallback<PaymentMethod> { override fun onError(error: Exception) { promise.resolve(createError("Failed", error)) } override fun onSuccess(result: PaymentMethod) { val paymentMethodMap: WritableMap = mapFromPaymentMethod(result) promise.resolve(createResult("paymentMethod", paymentMethodMap)) } } ) } @ReactMethod fun createToken(params: ReadableMap, promise: Promise) { val type = getValOr(params, "type", null)?.let { if (it != "Card") { promise.resolve(createError(CreateTokenErrorType.Failed.toString(), "$it type is not supported yet")) return } } val address = getMapOrNull(params, "address") val cardParamsMap = (cardFieldView?.cardParams ?: cardFormView?.cardParams)?.toParamMap() ?: run { promise.resolve(createError(CreateTokenErrorType.Failed.toString(), "Card details not complete")) return } val cardAddress = cardFieldView?.cardAddress ?: cardFormView?.cardAddress val cardParams = CardParams( number = cardParamsMap["number"] as String, expMonth = cardParamsMap["exp_month"] as Int, expYear = cardParamsMap["exp_year"] as Int, cvc = cardParamsMap["cvc"] as String, address = mapToAddress(address, cardAddress), name = getValOr(params, "name", null) ) runBlocking { try { val token = stripe.createCardToken( cardParams = cardParams, stripeAccountId = stripeAccountId ) promise.resolve(createResult("token", mapFromToken(token))) } catch (e: Exception) { promise.resolve(createError(CreateTokenErrorType.Failed.toString(), e.message)) } } } @ReactMethod fun createTokenForCVCUpdate(cvc: String, promise: Promise) { stripe.createCvcUpdateToken( cvc, callback = object : ApiResultCallback<Token> { override fun onSuccess(result: Token) { val tokenId = result.id val res = WritableNativeMap() res.putString("tokenId", tokenId) promise.resolve(res) } override fun onError(error: Exception) { promise.resolve(createError("Failed", error)) } } ) } @ReactMethod fun handleCardAction(paymentIntentClientSecret: String, promise: Promise) { val activity = currentActivity as ComponentActivity if (activity != null) { handleCardActionPromise = promise stripe.handleNextActionForPayment(activity, paymentIntentClientSecret) } } private fun payWithWeChatPay(paymentIntentClientSecret: String, appId: String) { val activity = currentActivity as ComponentActivity activity.lifecycleScope.launch { stripe.createPaymentMethod(PaymentMethodCreateParams.createWeChatPay()).id?.let { paymentMethodId -> val confirmPaymentIntentParams = ConfirmPaymentIntentParams.createWithPaymentMethodId( paymentMethodId = paymentMethodId, clientSecret = paymentIntentClientSecret, paymentMethodOptions = PaymentMethodOptionsParams.WeChatPay( appId ) ) stripe.confirmPayment(activity, confirmPaymentIntentParams) } } } @ReactMethod fun confirmPayment(paymentIntentClientSecret: String, params: ReadableMap, options: ReadableMap, promise: Promise) { confirmPromise = promise confirmPaymentClientSecret = paymentIntentClientSecret val paymentMethodType = getValOr(params, "type")?.let { mapToPaymentMethodType(it) } ?: run { promise.resolve(createError(ConfirmPaymentErrorType.Failed.toString(), "You must provide paymentMethodType")) return } val testOfflineBank = getBooleanOrFalse(params, "testOfflineBank") if (paymentMethodType == PaymentMethod.Type.Fpx && !testOfflineBank) { payWithFpx() return } // if (paymentMethodType == PaymentMethod.Type.WeChatPay) { // val appId = getValOr(params, "appId") ?: run { // promise.resolve(createError("Failed", "You must provide appId")) // return // } // payWithWeChatPay(paymentIntentClientSecret, appId) // // return // } val factory = PaymentMethodCreateParamsFactory(paymentIntentClientSecret, params, cardFieldView, cardFormView) try { val activity = currentActivity as ComponentActivity val confirmParams = factory.createConfirmParams(paymentMethodType) confirmParams.shipping = mapToShippingDetails(getMapOrNull(params, "shippingDetails")) stripe.confirmPayment(activity, confirmParams) } catch (error: PaymentMethodCreateParamsException) { promise.resolve(createError(ConfirmPaymentErrorType.Failed.toString(), error)) } } @ReactMethod fun retrievePaymentIntent(clientSecret: String, promise: Promise) { AsyncTask.execute { val paymentIntent = stripe.retrievePaymentIntentSynchronous(clientSecret) paymentIntent?.let { promise.resolve(createResult("paymentIntent", mapFromPaymentIntentResult(it))) } ?: run { promise.resolve(createError(RetrievePaymentIntentErrorType.Unknown.toString(), "Failed to retrieve the PaymentIntent")) } } } @ReactMethod fun retrieveSetupIntent(clientSecret: String, promise: Promise) { AsyncTask.execute { val setupIntent = stripe.retrieveSetupIntentSynchronous(clientSecret) setupIntent?.let { promise.resolve(createResult("setupIntent", mapFromSetupIntentResult(it))) } ?: run { promise.resolve(createError(RetrieveSetupIntentErrorType.Unknown.toString(), "Failed to retrieve the SetupIntent")) } } } @ReactMethod fun confirmSetupIntent(setupIntentClientSecret: String, params: ReadableMap, options: ReadableMap, promise: Promise) { confirmSetupIntentPromise = promise val paymentMethodType = getValOr(params, "type")?.let { mapToPaymentMethodType(it) } ?: run { promise.resolve(createError(ConfirmPaymentErrorType.Failed.toString(), "You must provide paymentMethodType")) return } val factory = PaymentMethodCreateParamsFactory(setupIntentClientSecret, params, cardFieldView, cardFormView) try { val activity = currentActivity as ComponentActivity val confirmParams = factory.createSetupParams(paymentMethodType) stripe.confirmSetupIntent(activity, confirmParams) } catch (error: PaymentMethodCreateParamsException) { promise.resolve(createError(ConfirmPaymentErrorType.Failed.toString(), error)) } } @ReactMethod fun initGooglePay(params: ReadableMap, promise: Promise) { val activity = currentActivity as AppCompatActivity val fragment = GooglePayFragment().also { val bundle = toBundleObject(params) it.arguments = bundle } initGooglePayPromise = promise activity.supportFragmentManager.beginTransaction() .add(fragment, "google_pay_launch_fragment") .commit() } @ReactMethod fun presentGooglePay(params: ReadableMap, promise: Promise) { val clientSecret = getValOr(params, "clientSecret") ?: run { promise.resolve(createError(GooglePayErrorType.Failed.toString(), "you must provide clientSecret")) return } presentGooglePayPromise = promise if (getBooleanOrFalse(params, "forSetupIntent")) { val currencyCode = getValOr(params, "currencyCode") ?: run { promise.resolve(createError(GooglePayErrorType.Failed.toString(), "you must provide currencyCode")) return } googlePayFragment?.presentForSetupIntent(clientSecret, currencyCode) } else { googlePayFragment?.presentForPaymentIntent(clientSecret) } } @ReactMethod fun createGooglePayPaymentMethod(params: ReadableMap, promise: Promise) { val currencyCode = getValOr(params, "currencyCode", null) ?: run { promise.resolve(createError(GooglePayErrorType.Failed.toString(), "you must provide currencyCode")) return } val amount = getIntOrNull(params, "amount") ?: run { promise.resolve(createError(GooglePayErrorType.Failed.toString(), "you must provide amount")) return } presentGooglePayPromise = promise googlePayFragment?.createPaymentMethod(currencyCode, amount) } // / Check paymentIntent.nextAction is voucher-based payment method. // / If it's voucher-based, the paymentIntent status stays in requiresAction until the voucher is paid or expired. // / Currently only OXXO payment is voucher-based. private fun isPaymentIntentNextActionVoucherBased(nextAction: StripeIntent.NextActionType?): Boolean { nextAction?.let { return it == StripeIntent.NextActionType.DisplayOxxoDetails } return false } companion object { const val NAME = "StripeSdk" } }
bsd-3-clause
adb596c9ccfe1b4acbf2abb9cd189ecf
41.405956
167
0.696433
5.145493
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/issues/actions/OpenCommandWindowAction.kt
1
1015
package com.github.jk1.ytplugin.issues.actions import com.github.jk1.ytplugin.issues.model.Issue import com.github.jk1.ytplugin.ui.CommandDialog import com.github.jk1.ytplugin.whenActive import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import javax.swing.Icon class OpenCommandWindowAction(private val getSelectedIssue: () -> Issue?): IssueAction() { override val text = "Open Command Dialog" override val description = "Update the selected issue by applying a command" override val icon: Icon = AllIcons.Debugger.Console override val shortcut = "control shift Y" override fun actionPerformed(event: AnActionEvent) { event.whenActive { project -> val issue = getSelectedIssue.invoke() if (issue != null) { CommandDialog(project, issue).show() } } } override fun update(event: AnActionEvent) { event.presentation.isEnabled = getSelectedIssue.invoke() != null } }
apache-2.0
de5d2fa58275020cc91a4f062803b6a7
34.034483
90
0.708374
4.375
false
false
false
false
vjames19/mosby
sample-kotlin/src/main/kotlin/com/hannesdorfmann/mosby/sample/kotlin/HeroesActivity.kt
1
2750
package com.hannesdorfmann.mosby.sample.kotlin import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import com.hannesdorfmann.mosby.mvp.viewstate.lce.LceViewState import com.hannesdorfmann.mosby.mvp.viewstate.lce.MvpLceViewStateActivity import com.hannesdorfmann.mosby.mvp.viewstate.lce.data.RetainingLceViewState import com.hannesdorfmann.mosby.sample.kotlin.model.Hero public class HeroesActivity : HeroesView, MvpLceViewStateActivity<SwipeRefreshLayout, List<Hero>, HeroesView, HeroesPresenter>(), SwipeRefreshLayout.OnRefreshListener { var adapter: HeroesAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_heroes) retainInstance = true contentView.setOnRefreshListener(this) val recyclerView = findViewById(R.id.recyclerView) as RecyclerView adapter = HeroesAdapter(this, LayoutInflater.from(this)) recyclerView.adapter = adapter recyclerView.layoutManager = GridLayoutManager(this, 2) } override fun getErrorMessage(e: Throwable?, pullToRefresh: Boolean): String? { if (pullToRefresh) return "Error while loading" else return "Error while loading. Click here to retry." } override fun createPresenter(): HeroesPresenter { return HeroesPresenter() } override fun createViewState(): LceViewState<List<Hero>, HeroesView> { return RetainingLceViewState() } override fun getData(): List<Hero>? { return adapter?.items } override fun setData(data: List<Hero>?) { adapter?.items = data adapter?.notifyDataSetChanged() } override fun loadData(pullToRefresh: Boolean) { presenter.loadHeroes(pullToRefresh) } override fun onRefresh() { loadData(true) } override fun showContent() { super.showContent() contentView.isRefreshing = false } override fun showError(t: Throwable, pullToRefresh: Boolean) { super.showError(t, pullToRefresh) contentView.isRefreshing = false } override fun showLoading(pullToRefresh: Boolean) { super.showLoading(pullToRefresh) if (pullToRefresh && !contentView.isRefreshing) { contentView.post(RefreshRunnable(contentView)) } } // Don't do that in production, could lead to memory leaks class RefreshRunnable(val swipeRefreshLayout: SwipeRefreshLayout) : Runnable { override fun run() { swipeRefreshLayout.isRefreshing = true } } }
apache-2.0
34b1f240c4b1e7e98127bd26caf65a3a
31.352941
168
0.712364
4.910714
false
false
false
false
arkon/LISTEN.moe-Unofficial-Android-App
buildSrc/src/main/kotlin/Dependencies.kt
1
216
object Versions { const val KTLINT = "0.36.0" } object BuildPluginsVersion { const val AGP = "4.0.0" const val KOTLIN = "1.3.72" const val KTLINT = "9.2.1" const val VERSIONS_PLUGIN = "0.28.0" }
mit
a2bc0e00b734f142df7a00ea131fd19d
20.6
40
0.611111
2.666667
false
false
false
false
bjzhou/Coolapk
app/src/main/kotlin/bjzhou/coolapk/app/ui/adapters/ApkListAdapter.kt
1
3316
package bjzhou.coolapk.app.ui.adapters import android.app.Activity import android.content.Intent import android.support.v4.app.FragmentActivity import android.support.v7.widget.RecyclerView import android.text.Html import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RatingBar import android.widget.TextView import bjzhou.coolapk.app.R import bjzhou.coolapk.app.model.Apk import bjzhou.coolapk.app.ui.activities.AppViewActivity import com.squareup.picasso.Picasso import java.util.* /** * Created by bjzhou on 14-7-31. */ class ApkListAdapter(activity: FragmentActivity) : RecyclerView.Adapter<ApkListAdapter.ViewHolder>(), View.OnClickListener { private val mActivity: Activity = activity private var mApkList: List<Apk> = ArrayList() fun setApkList(apkList: List<Apk>) { mApkList = apkList } override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ApkListAdapter.ViewHolder { val convertView = mActivity.layoutInflater.inflate(R.layout.list_item_app, viewGroup, false) return ViewHolder(convertView) } override fun onBindViewHolder(holder: ApkListAdapter.ViewHolder, i: Int) { holder.titleView.text = mApkList[i].title if (mApkList[i].info == null) { var apk_info = "<font color=\"#ff35a1d4\">" + mApkList[i].apkversionname + "</font>" apk_info += "<font color=\"black\">, " + mApkList[i].apksize + ", </font>" if (mApkList[i].updateFlag == "new") { apk_info += "<font color=\"red\">New</font>" } else { apk_info += "<font color=\"black\">Update</font>" } mApkList[i].info = Html.fromHtml(apk_info) } holder.infoView.text = mApkList[i].info holder.downnumView.text = mApkList[i].downnum.toString() holder.logoView.tag = mApkList[i].title Picasso.with(mActivity) .load(mApkList[i].logo) .placeholder(R.drawable.ic_default_thumbnail) .into(holder.logoView) holder.ratingBar.rating = mApkList[i].score } override fun getItemId(position: Int): Long { return mApkList[position].id.toLong() } override fun getItemCount(): Int { return mApkList.size } override fun onClick(v: View) { } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { var logoView: ImageView = itemView.findViewById(R.id.list_item_icon) as ImageView var titleView: TextView = itemView.findViewById(R.id.list_item_title) as TextView var infoView: TextView = itemView.findViewById(R.id.list_item_info) as TextView var downnumView: TextView = itemView.findViewById(R.id.list_item_downnum) as TextView var ratingBar: RatingBar = itemView.findViewById(R.id.list_item_ratingStar) as RatingBar init { itemView.setOnClickListener(this) } override fun onClick(v: View) { val intent = Intent(mActivity, AppViewActivity::class.java) intent.putExtra("id", mApkList[adapterPosition].id) mActivity.startActivity(intent) } } companion object { private val TAG = "ApkListAdapter" } }
gpl-2.0
d58954bbc7f74e3520e676617254032d
35.43956
124
0.665259
4.019394
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/repository/ResourceProvider.kt
1
4691
package at.ac.tuwien.caa.docscan.repository import androidx.annotation.IntRange import at.ac.tuwien.caa.docscan.logic.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import retrofit2.Response import timber.log.Timber import java.net.HttpURLConnection suspend fun <ApiType, ResourceType> transkribusResource( forceNetwork: () -> Boolean = { false }, loadFromDisk: (suspend () -> ApiType?)? = null, apiCall: suspend () -> Response<ApiType>, persistNetworkResponse: suspend (response: ApiType) -> Unit = { }, transformToResourceType: (result: Resource<ApiType>) -> Resource<ResourceType> = { result -> @Suppress("UNCHECKED_CAST") result as Resource<ResourceType> // is assumed in default case when no transformation function is provided }, ): Resource<ResourceType> { return withContext(Dispatchers.IO) { // a network operation is retried once only if the expected error has a 401 status retryResourceRequest( maxRetries = 1, block = { val resource = fetchResource( forceNetwork, loadFromDisk, apiCall ) if (resource is Success) { persistNetworkResponse(resource.data) } transformToResourceType(resource) }, predicate = { e -> e.is401().also { if (it) Timber.d("Suspend network call is retried after http status 401") } } ) } } fun Throwable?.is401(): Boolean { return isHttpCode(HttpURLConnection.HTTP_UNAUTHORIZED) } fun Throwable?.is403(): Boolean { return isHttpCode(HttpURLConnection.HTTP_FORBIDDEN) } fun Throwable?.is404(): Boolean { return isHttpCode(HttpURLConnection.HTTP_NOT_FOUND) } private fun Throwable?.isHttpCode(httpCode: Int): Boolean { return when (val doscScanError = (this as? DocScanException)?.docScanError) { is DocScanError.TranskribusRestError.HttpError -> { return doscScanError.httpStatusCode == httpCode } else -> { false } } } /** * fetch resource from remote or disk */ private suspend fun <ApiType> fetchResource( forceNetwork: () -> Boolean, loadFromDisk: (suspend () -> ApiType?)?, apiCall: suspend () -> Response<ApiType> ): Resource<ApiType> { if (!forceNetwork.invoke()) { loadFromDisk?.invoke()?.let { return Success(it) } } return try { apiCall.invoke().convertToResource() } catch (e: Exception) { Failure( DocScanException(DocScanError.TranskribusRestError.IOError(e)) ) } } /** * Converts a retrofit [Response] into a [Resource]. */ fun <T> Response<T>.convertToResource(): Resource<T> { return if (isSuccessful) { val body = body() if (body == null || code() == HttpURLConnection.HTTP_NO_CONTENT) { // empty responses are handled as error responses Failure( DocScanException( DocScanError.TranskribusRestError.HttpError( HttpURLConnection.HTTP_NO_CONTENT, null ) ) ) } else { Success(body) } } else { Failure( DocScanException( DocScanError.TranskribusRestError.HttpError( httpStatusCode = code(), errorBody()?.string() ) ) ) } } /** * A retry function for [Resource] requests. If the predicate should not hold, the function is * not retried and the resource is returned without re-throwing the exception again. * * @param maxRetries max retry attempts for the given suspend block */ suspend fun <T> retryResourceRequest( @IntRange(from = 0) maxRetries: Int = 1, block: suspend () -> Resource<T>, predicate: suspend (cause: Throwable) -> Boolean = { true } ): Resource<T> { repeat(maxRetries) { when (val resource = block()) { is Failure -> { if (predicate(resource.exception)) { Timber.d( resource.exception, "suspend function failed - retries left: %s", maxRetries - 1 - it ) } else { return resource } } is Success -> { return resource } } } return block() // last attempt }
lgpl-3.0
3452f2e5bde223e6e4262b3f27c0ab42
29.861842
114
0.563206
4.757606
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/madara/cerisescans/src/CeriseScans.kt
1
1848
package eu.kanade.tachiyomi.extension.pt.cerisescans import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.multisrc.madara.Madara import okhttp3.OkHttpClient import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit class CeriseScans : Madara( "Cerise Scans", "https://cerisescans.com", "pt-BR", SimpleDateFormat("dd 'de' MMMMM 'de' yyyy", Locale("pt", "BR")) ) { override val client: OkHttpClient = super.client.newBuilder() .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .build() override fun popularMangaSelector() = "div.page-item-detail.manga" override val altName: String = "Nome alternativo: " // [...document.querySelectorAll('div.genres li a')] // .map(x => `Genre("${x.innerText.trim()}", "${x.href.replace(/.*-genre\/(.*)\//, '$1')}")`) // .join(',\n') override fun getGenreList(): List<Genre> = listOf( Genre("AΓ§Γ£o", "acao"), Genre("Adulto", "adulto"), Genre("ComΓ©dia", "comedia"), Genre("Doujinshi", "doujinshi"), Genre("Drama", "drama"), Genre("Ecchi", "ecchi"), Genre("Fantasia", "fantasia"), Genre("Harem", "harem"), Genre("HarΓ©m Reverso", "harem-reverso"), Genre("Hentai", "hentai"), Genre("HistΓ³rico", "historico"), Genre("Isekai", "isekai"), Genre("Josei", "josei"), Genre("Magia", "magia"), Genre("MistΓ©rio", "misterio"), Genre("Romance", "romance"), Genre("Shoujo", "shoujo"), Genre("Slice of Life", "slice-of-life"), Genre("Sobrenatural", "sobrenatural"), Genre("Soft Yaoi", "soft-yaoi"), Genre("Soft Yuri", "soft-yuri"), Genre("Yaoi", "yaoi"), Genre("Yuri", "yuri") ) }
apache-2.0
5c3fdb680da092840008d6409970f200
33.754717
101
0.59772
3.597656
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/polls/PollsService.kt
1
12043
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.polls import com.google.gson.reflect.TypeToken import com.vk.api.sdk.requests.VKRequest import com.vk.dto.common.id.UserId import com.vk.sdk.api.GsonHolder import com.vk.sdk.api.NewApiRequest import com.vk.sdk.api.base.dto.BaseBoolInt import com.vk.sdk.api.base.dto.BaseOkResponse import com.vk.sdk.api.base.dto.BaseUploadServer import com.vk.sdk.api.polls.dto.PollsBackground import com.vk.sdk.api.polls.dto.PollsCreateBackgroundId import com.vk.sdk.api.polls.dto.PollsEditBackgroundId import com.vk.sdk.api.polls.dto.PollsGetByIdNameCase import com.vk.sdk.api.polls.dto.PollsGetVotersNameCase import com.vk.sdk.api.polls.dto.PollsPoll import com.vk.sdk.api.polls.dto.PollsVoters import com.vk.sdk.api.users.dto.UsersFields import kotlin.Boolean import kotlin.Int import kotlin.String import kotlin.collections.List class PollsService { /** * Adds the current user's vote to the selected answer in the poll. * * @param pollId - Poll ID. * @param answerIds * @param ownerId - ID of the user or community that owns the poll. Use a negative value to * designate a community ID. * @param isBoard * @return [VKRequest] with [BaseBoolInt] */ fun pollsAddVote( pollId: Int, answerIds: List<Int>, ownerId: UserId? = null, isBoard: Boolean? = null ): VKRequest<BaseBoolInt> = NewApiRequest("polls.addVote") { GsonHolder.gson.fromJson(it, BaseBoolInt::class.java) } .apply { addParam("poll_id", pollId, min = 0) addParam("answer_ids", answerIds) ownerId?.let { addParam("owner_id", it) } isBoard?.let { addParam("is_board", it) } } /** * Creates polls that can be attached to the users' or communities' posts. * * @param question - question text * @param isAnonymous - '1' - anonymous poll, participants list is hidden,, '0' - public poll, * participants list is available,, Default value is '0'. * @param isMultiple * @param endDate * @param ownerId - If a poll will be added to a communty it is required to send a negative * group identifier. Current user by default. * @param appId * @param addAnswers - available answers list, for example_ " ["yes","no","maybe"]", There can * be from 1 to 10 answers. * @param photoId * @param backgroundId * @param disableUnvote * @return [VKRequest] with [PollsPoll] */ fun pollsCreate( question: String? = null, isAnonymous: Boolean? = null, isMultiple: Boolean? = null, endDate: Int? = null, ownerId: UserId? = null, appId: Int? = null, addAnswers: String? = null, photoId: Int? = null, backgroundId: PollsCreateBackgroundId? = null, disableUnvote: Boolean? = null ): VKRequest<PollsPoll> = NewApiRequest("polls.create") { GsonHolder.gson.fromJson(it, PollsPoll::class.java) } .apply { question?.let { addParam("question", it) } isAnonymous?.let { addParam("is_anonymous", it) } isMultiple?.let { addParam("is_multiple", it) } endDate?.let { addParam("end_date", it, min = 1550700000) } ownerId?.let { addParam("owner_id", it) } appId?.let { addParam("app_id", it) } addAnswers?.let { addParam("add_answers", it) } photoId?.let { addParam("photo_id", it, min = 0) } backgroundId?.let { addParam("background_id", it.value) } disableUnvote?.let { addParam("disable_unvote", it) } } /** * Deletes the current user's vote from the selected answer in the poll. * * @param pollId - Poll ID. * @param answerId - Answer ID. * @param ownerId - ID of the user or community that owns the poll. Use a negative value to * designate a community ID. * @param isBoard * @return [VKRequest] with [BaseBoolInt] */ fun pollsDeleteVote( pollId: Int, answerId: Int, ownerId: UserId? = null, isBoard: Boolean? = null ): VKRequest<BaseBoolInt> = NewApiRequest("polls.deleteVote") { GsonHolder.gson.fromJson(it, BaseBoolInt::class.java) } .apply { addParam("poll_id", pollId, min = 0) addParam("answer_id", answerId, min = 0) ownerId?.let { addParam("owner_id", it) } isBoard?.let { addParam("is_board", it) } } /** * Edits created polls * * @param pollId - edited poll's id * @param ownerId - poll owner id * @param question - new question text * @param addAnswers - answers list, for example_ , "["yes","no","maybe"]" * @param editAnswers - object containing answers that need to be edited,, key - answer id, * value - new answer text. Example_ {"382967099"_"option1", "382967103"_"option2"}" * @param deleteAnswers - list of answer ids to be deleted. For example_ "[382967099, * 382967103]" * @param endDate * @param photoId * @param backgroundId * @return [VKRequest] with [BaseOkResponse] */ fun pollsEdit( pollId: Int, ownerId: UserId? = null, question: String? = null, addAnswers: String? = null, editAnswers: String? = null, deleteAnswers: String? = null, endDate: Int? = null, photoId: Int? = null, backgroundId: PollsEditBackgroundId? = null ): VKRequest<BaseOkResponse> = NewApiRequest("polls.edit") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("poll_id", pollId, min = 0) ownerId?.let { addParam("owner_id", it) } question?.let { addParam("question", it) } addAnswers?.let { addParam("add_answers", it) } editAnswers?.let { addParam("edit_answers", it) } deleteAnswers?.let { addParam("delete_answers", it) } endDate?.let { addParam("end_date", it, min = 0) } photoId?.let { addParam("photo_id", it, min = 0) } backgroundId?.let { addParam("background_id", it.value) } } /** * @return [VKRequest] with [Unit] */ fun pollsGetBackgrounds(): VKRequest<List<PollsBackground>> = NewApiRequest("polls.getBackgrounds") { val typeToken = object: TypeToken<List<PollsBackground>>() {}.type GsonHolder.gson.fromJson<List<PollsBackground>>(it, typeToken) } /** * Returns detailed information about a poll by its ID. * * @param pollId - Poll ID. * @param ownerId - ID of the user or community that owns the poll. Use a negative value to * designate a community ID. * @param isBoard - '1' - poll is in a board, '0' - poll is on a wall. '0' by default. * @param friendsCount * @param fields * @param nameCase * @return [VKRequest] with [PollsPoll] */ fun pollsGetById( pollId: Int, ownerId: UserId? = null, isBoard: Boolean? = null, friendsCount: Int? = null, fields: List<String>? = null, nameCase: PollsGetByIdNameCase? = null ): VKRequest<PollsPoll> = NewApiRequest("polls.getById") { GsonHolder.gson.fromJson(it, PollsPoll::class.java) } .apply { addParam("poll_id", pollId, min = 0) ownerId?.let { addParam("owner_id", it) } isBoard?.let { addParam("is_board", it) } friendsCount?.let { addParam("friends_count", it, min = 0, max = 100) } fields?.let { addParam("fields", it) } nameCase?.let { addParam("name_case", it.value) } } /** * @param ownerId * @return [VKRequest] with [BaseUploadServer] */ fun pollsGetPhotoUploadServer(ownerId: UserId? = null): VKRequest<BaseUploadServer> = NewApiRequest("polls.getPhotoUploadServer") { GsonHolder.gson.fromJson(it, BaseUploadServer::class.java) } .apply { ownerId?.let { addParam("owner_id", it) } } /** * Returns a list of IDs of users who selected specific answers in the poll. * * @param pollId - Poll ID. * @param answerIds - Answer IDs. * @param ownerId - ID of the user or community that owns the poll. Use a negative value to * designate a community ID. * @param isBoard * @param friendsOnly - '1' - to return only current user's friends, '0' - to return all users * (default), * @param offset - Offset needed to return a specific subset of voters. '0' - (default) * @param count - Number of user IDs to return (if the 'friends_only' parameter is not set, * maximum '1000', otherwise '10'). '100' - (default) * @param fields - Profile fields to return. Sample values_ 'nickname', 'screen_name', 'sex', * 'bdate (birthdate)', 'city', 'country', 'timezone', 'photo', 'photo_medium', 'photo_big', * 'has_mobile', 'rate', 'contacts', 'education', 'online', 'counters'. * @param nameCase - Case for declension of user name and surname_ , 'nom' - nominative * (default) , 'gen' - genitive , 'dat' - dative , 'acc' - accusative , 'ins' - instrumental , * 'abl' - prepositional * @return [VKRequest] with [Unit] */ fun pollsGetVoters( pollId: Int, answerIds: List<Int>, ownerId: UserId? = null, isBoard: Boolean? = null, friendsOnly: Boolean? = null, offset: Int? = null, count: Int? = null, fields: List<UsersFields>? = null, nameCase: PollsGetVotersNameCase? = null ): VKRequest<List<PollsVoters>> = NewApiRequest("polls.getVoters") { val typeToken = object: TypeToken<List<PollsVoters>>() {}.type GsonHolder.gson.fromJson<List<PollsVoters>>(it, typeToken) } .apply { addParam("poll_id", pollId, min = 0) addParam("answer_ids", answerIds) ownerId?.let { addParam("owner_id", it) } isBoard?.let { addParam("is_board", it) } friendsOnly?.let { addParam("friends_only", it) } offset?.let { addParam("offset", it, min = 0) } count?.let { addParam("count", it, min = 0) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } nameCase?.let { addParam("name_case", it.value) } } /** * @param photo * @param hash * @return [VKRequest] with [PollsBackground] */ fun pollsSavePhoto(photo: String, hash: String): VKRequest<PollsBackground> = NewApiRequest("polls.savePhoto") { GsonHolder.gson.fromJson(it, PollsBackground::class.java) } .apply { addParam("photo", photo) addParam("hash", hash) } }
mit
681fd101a7945a9b106712735d6c366d
38.745875
98
0.621191
3.805055
false
false
false
false
firebase/snippets-android
mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/BarcodeScanningActivity.kt
1
2646
package com.google.firebase.example.mlkit.kotlin import androidx.appcompat.app.AppCompatActivity import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions import com.google.firebase.ml.vision.common.FirebaseVisionImage class BarcodeScanningActivity : AppCompatActivity() { private fun scanBarcodes(image: FirebaseVisionImage) { // [START set_detector_options] val options = FirebaseVisionBarcodeDetectorOptions.Builder() .setBarcodeFormats( FirebaseVisionBarcode.FORMAT_QR_CODE, FirebaseVisionBarcode.FORMAT_AZTEC) .build() // [END set_detector_options] // [START get_detector] val detector = FirebaseVision.getInstance() .visionBarcodeDetector // Or, to specify the formats to recognize: // val detector = FirebaseVision.getInstance() // .getVisionBarcodeDetector(options) // [END get_detector] // [START fml_run_detector] val result = detector.detectInImage(image) .addOnSuccessListener { barcodes -> // Task completed successfully // [START_EXCLUDE] // [START get_barcodes] for (barcode in barcodes) { val bounds = barcode.boundingBox val corners = barcode.cornerPoints val rawValue = barcode.rawValue val valueType = barcode.valueType // See API reference for complete list of supported types when (valueType) { FirebaseVisionBarcode.TYPE_WIFI -> { val ssid = barcode.wifi!!.ssid val password = barcode.wifi!!.password val type = barcode.wifi!!.encryptionType } FirebaseVisionBarcode.TYPE_URL -> { val title = barcode.url!!.title val url = barcode.url!!.url } } } // [END get_barcodes] // [END_EXCLUDE] } .addOnFailureListener { // Task failed with an exception // ... } // [END fml_run_detector] } }
apache-2.0
eb7287528e1897a6f9f3d7b13c1b4092
41
81
0.518896
5.893096
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/parking_fee/AddParkingFeeForm.kt
1
5539
package de.westnordost.streetcomplete.quests.parking_fee import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.recyclerview.widget.RecyclerView import java.util.ArrayList import javax.inject.Inject import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.quests.OtherAnswer import de.westnordost.streetcomplete.quests.opening_hours.adapter.AddOpeningHoursAdapter import de.westnordost.streetcomplete.quests.opening_hours.adapter.OpeningMonthsRow import de.westnordost.streetcomplete.util.AdapterDataChangedWatcher import de.westnordost.streetcomplete.util.Serializer import de.westnordost.streetcomplete.ktx.toObject import kotlinx.android.synthetic.main.fragment_quest_answer.* import kotlinx.android.synthetic.main.quest_buttonpanel_yes_no.* import kotlinx.android.synthetic.main.quest_fee_hours.* class AddParkingFeeForm : AbstractQuestFormAnswerFragment<FeeAnswer>() { override val contentLayoutResId = R.layout.quest_fee_hours override val buttonsResId = R.layout.quest_buttonpanel_yes_no override val otherAnswers = listOf( OtherAnswer(R.string.quest_fee_answer_hours) { isDefiningHours = true } ) private lateinit var openingHoursAdapter: AddOpeningHoursAdapter private lateinit var content: ViewGroup private var isDefiningHours: Boolean = false set(value) { field = value content.visibility = if (value) View.VISIBLE else View.GONE noButton?.visibility = if (value) View.GONE else View.VISIBLE yesButton?.visibility = if (value) View.GONE else View.VISIBLE } private var isFeeOnlyAtHours: Boolean = false @Inject internal lateinit var serializer: Serializer init { Injector.instance.applicationComponent.inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val viewData = loadOpeningHoursData(savedInstanceState) openingHoursAdapter = AddOpeningHoursAdapter(viewData, activity!!, countryInfo) openingHoursAdapter.registerAdapterDataObserver( AdapterDataChangedWatcher { checkIsFormComplete() }) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) content = view.findViewById(R.id.content) // must be read here because setting these values effects the UI isFeeOnlyAtHours = savedInstanceState?.getBoolean(IS_FEE_ONLY_AT_HOURS, true) ?: true isDefiningHours = savedInstanceState?.getBoolean(IS_DEFINING_HOURS) ?: false okButton.setOnClickListener { onClickOk() } yesButton.setOnClickListener { onClickYesNo(true) } noButton.setOnClickListener { onClickYesNo(false) } openingHoursList.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) openingHoursList.adapter = openingHoursAdapter openingHoursList.isNestedScrollingEnabled = false checkIsFormComplete() addTimesButton.setOnClickListener { openingHoursAdapter.addNewWeekdays() } val spinnerItems = listOf( getString(R.string.quest_fee_only_at_hours), getString(R.string.quest_fee_not_at_hours) ) selectFeeOnlyAtHours.adapter = ArrayAdapter(activity!!, R.layout.spinner_item_centered, spinnerItems) selectFeeOnlyAtHours.setSelection(if (isFeeOnlyAtHours) 0 else 1) selectFeeOnlyAtHours.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { isFeeOnlyAtHours = position == 0 } override fun onNothingSelected(parent: AdapterView<*>) {} } } override fun onClickOk() { val times = openingHoursAdapter.createOpeningMonths() if (!times.isEmpty()) { if(isFeeOnlyAtHours) { applyAnswer(HasFeeAtHours(times)) } else { applyAnswer(HasFeeExceptAtHours(times)) } } else { onClickYesNo(!isFeeOnlyAtHours) } } private fun onClickYesNo(answer: Boolean) { applyAnswer(if(answer) HasFee else HasNoFee) } private fun loadOpeningHoursData(savedInstanceState: Bundle?): List<OpeningMonthsRow> = if (savedInstanceState != null) { serializer.toObject<ArrayList<OpeningMonthsRow>>(savedInstanceState.getByteArray(OPENING_HOURS_DATA)!!) } else { listOf(OpeningMonthsRow()) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putByteArray(OPENING_HOURS_DATA, serializer.toBytes(ArrayList(openingHoursAdapter.monthsRows))) outState.putBoolean(IS_DEFINING_HOURS, isDefiningHours) outState.putBoolean(IS_FEE_ONLY_AT_HOURS, isFeeOnlyAtHours) } override fun isFormComplete() = isDefiningHours && !openingHoursAdapter.createOpeningMonths().joinToString(";").isEmpty() companion object { private const val OPENING_HOURS_DATA = "oh_data" private const val IS_FEE_ONLY_AT_HOURS = "oh_fee_only_at" private const val IS_DEFINING_HOURS = "oh" } }
gpl-3.0
01c78f5655bfa0c083312ad8bb797db1
39.137681
125
0.727749
4.694068
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/SparkView.kt
1
3959
package com.habitrpg.android.habitica.ui.views import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.Animation import androidx.core.content.ContextCompat import com.habitrpg.android.habitica.R import com.habitrpg.common.habitica.extensions.dpToPx import kotlin.math.min class SparkView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private var spacing: Float = 0f set(value) { field = value invalidate() } private var paint: Paint = Paint() var thickness = 3.dpToPx(context) var length = 6.dpToPx(context) var maxSpacing = 5.dpToPx(context) var animationDuration = 2500L var color: Int get() { return paint.color } set(value) { paint.color = value } init { spacing = maxSpacing.toFloat() context.theme?.obtainStyledAttributes(attrs, R.styleable.SparkView, 0, 0)?.let { thickness = it.getDimensionPixelSize(R.styleable.SparkView_thickness, 3.dpToPx(context)) length = it.getDimensionPixelSize(R.styleable.SparkView_length, 6.dpToPx(context)) maxSpacing = it.getDimensionPixelSize(R.styleable.SparkView_maxSpacing, 5.dpToPx(context)) animationDuration = it.getInt(R.styleable.SparkView_duration, 2500).toLong() color = it.getInt(R.styleable.SparkView_color, ContextCompat.getColor(context, R.color.white)) } paint.style = Paint.Style.FILL } fun startAnimating() { val anim = ObjectAnimator.ofFloat(thickness.toFloat(), maxSpacing.toFloat()) anim.addUpdateListener { spacing = it.animatedValue as Float } anim.interpolator = AccelerateDecelerateInterpolator() anim.repeatCount = Animation.INFINITE anim.repeatMode = ValueAnimator.REVERSE anim.duration = animationDuration anim.start() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) val desiredSize = (length * 2 + maxSpacing) val width = when (MeasureSpec.getMode(widthMeasureSpec)) { MeasureSpec.EXACTLY -> widthSize MeasureSpec.AT_MOST -> min(desiredSize, widthSize) else -> desiredSize } val height = when (MeasureSpec.getMode(heightMeasureSpec)) { MeasureSpec.EXACTLY -> heightSize MeasureSpec.AT_MOST -> min(desiredSize, heightSize) else -> desiredSize } setMeasuredDimension(width, height) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) val thisCanvas = canvas ?: return val centerHorizontal = width / 2f val centerVertical = height / 2f val offset = (maxSpacing - spacing) / 2 drawHorizontal(thisCanvas, offset, centerVertical) drawHorizontal(thisCanvas, width - length.toFloat() - offset, centerVertical) drawVertical(thisCanvas, centerHorizontal, offset) drawVertical(thisCanvas, centerVertical, height - length.toFloat() - offset) } private fun drawVertical(canvas: Canvas, x: Float, y: Float) { canvas.drawRoundRect(x - (thickness / 2), y, x + (thickness / 2), y + length, thickness / 2f, thickness / 2f, paint) } private fun drawHorizontal(canvas: Canvas, x: Float, y: Float) { canvas.drawRoundRect(x, y - (thickness / 2), x + length, y + (thickness / 2), thickness / 2f, thickness / 2f, paint) } }
gpl-3.0
fbefdfc01e4e91d7e3180fc98fb3de21
36.349057
124
0.669361
4.56106
false
false
false
false
GLodi/GitNav
app/src/main/java/giuliolodi/gitnav/ui/login/LoginPresenter.kt
1
4906
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.ui.login import android.content.Intent import android.net.Uri import giuliolodi.gitnav.BuildConfig import giuliolodi.gitnav.data.DataManager import giuliolodi.gitnav.ui.base.BasePresenter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import org.eclipse.egit.github.core.client.RequestException import timber.log.Timber import java.util.* import javax.inject.Inject /** * Created by giulio on 12/05/2017. */ class LoginPresenter<V: LoginContract.View> : BasePresenter<V>, LoginContract.Presenter<V> { val TAG = "LoginPresenter" private lateinit var stateSent: String @Inject constructor(mCompositeDisposable: CompositeDisposable, mDataManager: DataManager) : super(mCompositeDisposable, mDataManager) override fun subscribe() { if (!getDataManager().getToken().isEmpty()) getView().intentToEventActivity() } override fun onLoginClick(user: String, pass: String) { getCompositeDisposable().add(getDataManager().tryAuthentication(user, pass) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { getView().showLoading() } .subscribe( { getView().hideLoading() getView().showSuccess() getView().intentToEventActivity() }, { throwable -> throwable?.localizedMessage?.let { getView().showError(it) } getView().hideLoading() if ((throwable as? RequestException)?.status != 401) Timber.e(throwable) } )) } override fun getFirstStepUri(): Uri { stateSent = UUID.randomUUID().toString() return Uri.Builder().scheme("https") .authority("github.com") .appendPath("login") .appendPath("oauth") .appendPath("authorize") .appendQueryParameter("client_id", BuildConfig.GITHUB_CLIENT_ID) .appendQueryParameter("redirect_uri", "gitnav://login") .appendQueryParameter("scope", "user,repo,gist") .appendQueryParameter("state", stateSent) .build() } override fun onHandleAuthIntent(intent: Intent?) { intent?.data?.let { if (it.toString().startsWith("gitnav://login")) { getView().showLoading() val code = it.getQueryParameter("code") val stateReceived = it.getQueryParameter("state") if (stateSent == stateReceived) { requestAccessToken(code, stateReceived) } else { getView().hideLoading() getView().showError("State code received is not correct. Try again.") } } } } private fun requestAccessToken(code: String, stateReceived: String) { getCompositeDisposable().add(getDataManager().apiRequestAccessToken(BuildConfig.GITHUB_CLIENT_ID, BuildConfig.GITHUB_CLIENT_SECRET, code, "gitnav://login", stateReceived) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMapCompletable { tokenRequested -> getDataManager().downloadUserInfoFromToken(tokenRequested.token) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } .subscribe( { getView().hideLoading() getView().showSuccess() getView().intentToEventActivity() }, { throwable -> throwable?.localizedMessage?.let { getView().showError(it) } getView().hideLoading() Timber.e(throwable) } )) } }
apache-2.0
bc0d5fd74bca41a90d7bc8013e691bc4
39.213115
178
0.573176
5.606857
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/DirtyArrows.kt
1
4807
package nl.sugcube.dirtyarrows import nl.sugcube.dirtyarrows.bow.AutoActivation import nl.sugcube.dirtyarrows.bow.BowManager import nl.sugcube.dirtyarrows.command.DirtyArrowsCommandManager import nl.sugcube.dirtyarrows.effect.* import nl.sugcube.dirtyarrows.recipe.RecipeManager import nl.sugcube.dirtyarrows.region.RegionManager import nl.sugcube.dirtyarrows.util.Update import org.bukkit.Bukkit import org.bukkit.configuration.file.FileConfiguration import org.bukkit.plugin.java.JavaPlugin import java.util.logging.Level /** * DirtyArrows (DA) bukkit plugin. * * @author SugarCaney */ class DirtyArrows : JavaPlugin() { /** * The plugin's version number as defined in plugin.yml */ val version: String get() = description.version /** * Handles all configuration and data files. */ val configurationManager = ConfigurationManager(this) /** * The data file configuration. */ val data: FileConfiguration get() = configurationManager.data /** * Manages all DA commands. */ val commandManager = DirtyArrowsCommandManager(this) /** * Manages all DA protection regions. */ val regionManager = RegionManager(this) /** * Manages all custom recipes of DA. */ val recipeManager = RecipeManager(this) /** * Manages all registered bows. */ val bowManager = BowManager(this) /** * Manages if DA is turned on or off for what entities. * DA should only apply the effects of the bows when DA is enabled. */ val activationManager = ActivationManager(this::isMinigameVersion) /** * Shows the help menu messages. */ val help = Help(this) /** * Whether the plugin runs in a DirtyArrows minigame. * * @return `true` when part of a minigame, `false` otherwise. */ fun isMinigameVersion() = config.getBoolean("minigame-mode") /** * Registers all DA commands. */ private fun registerCommands() { getCommand("dirtyarrows")?.apply { setExecutor(commandManager) tabCompleter = commandManager } } /** * Registers all events. */ private fun registerEvents() = with(server.pluginManager) { val plugin = this@DirtyArrows registerEvents(UpdateCheck(plugin), plugin) registerEvents(AutoActivation(plugin), plugin) registerEvents(AnvilLevelModification(plugin), plugin) registerEvents(Headshot(plugin), plugin) registerEvents(LootingOnBow(plugin), plugin) registerEvents(ExplosionProtection(plugin), plugin) registerEvents(Blood(plugin), plugin) registerEvents(DamageEffects(), plugin) registerEvents(ZombieFlint(plugin), plugin) registerEvents(recipeManager, plugin) } /** * Checks if there is an update available, and prints the result of this check to the console. * Does nothing when the 'updates.check-for-updates' setting is set to `false`. */ private fun checkForUpdates() { if (config.getBoolean("updates.check-for-updates").not()) return val updateChecker = Update(BUKKIT_DEV_PROJECT_ID, description.version) if (updateChecker.query()) { logger.log(Level.INFO, "A new version of DirtyArrows is available: v${updateChecker.latestVersion}") } else logger.log(Level.INFO, "DirtyArrows is up-to-date!") } /** * Enables Dirty Arrows for all online players that have the dirtyarrows permission. */ private fun enableForAllPlayers() = Bukkit.getOnlinePlayers().forEach { player -> if (config.getBoolean("auto-enable").not()) return if (player.hasPermission("dirtyarrows").not()) return@forEach activationManager.activateFor(player) if (config.getBoolean("show-enable-message")) { player.sendMessage(Broadcast.enabledMessage(this, enabled = true)) } } /** * Create all necessary directories for the plugin to work. */ private fun createDirectories() { if (dataFolder.exists().not()) { dataFolder.mkdirs() } } override fun onEnable() { createDirectories() configurationManager.initialise() registerCommands() registerEvents() regionManager.loadRegions() bowManager.reload() checkForUpdates() enableForAllPlayers() logger.info("DirtyArrows has been enabled!") } override fun onDisable() { regionManager.saveRegions() logger.info("DirtyArrows has been disabled!") } companion object { /** * The project ID of the plugin on BukkitDev. */ const val BUKKIT_DEV_PROJECT_ID = 57131 } }
gpl-3.0
9eb23a8b3e42913b1afbe34206e3ae52
27.963855
112
0.652382
4.539188
false
true
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Worker.kt
1
19667
package info.nightscout.androidaps.plugins.iob.iobCobCalculator import android.content.Context import android.os.SystemClock import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.events.Event import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.extensions.target import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.workflow.CalculationWorkflow import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.roundToLong class IobCobOref1Worker( context: Context, params: WorkerParameters ) : Worker(context, params) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var context: Context @Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @Inject lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var profiler: Profiler @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var dateUtil: DateUtil @Inject lateinit var repository: AppRepository @Inject lateinit var dataWorker: DataWorker @Inject lateinit var calculationWorkflow: CalculationWorkflow init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) } class IobCobOref1WorkerData( val injector: HasAndroidInjector, val iobCobCalculator: IobCobCalculator, // cannot be injected : HistoryBrowser uses different instance val from: String, val end: Long, val limitDataToOldestAvailable: Boolean, val cause: Event? ) override fun doWork(): Result { val data = dataWorker.pickupObject(inputData.getLong(DataWorker.STORE_KEY, -1)) as IobCobOref1WorkerData? ?: return Result.success(workDataOf("Error" to "missing input data")) val start = dateUtil.now() try { aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: ${data.from}") if (!profileFunction.isProfileValid("IobCobThread")) { aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No profile): ${data.from}") return Result.success(workDataOf("Error" to "app still initializing")) } //log.debug("Locking calculateSensitivityData"); val oldestTimeWithData = data.iobCobCalculator.calculateDetectionStart(data.end, data.limitDataToOldestAvailable) // work on local copy and set back when finished val ads = data.iobCobCalculator.ads.clone() val bucketedData = ads.bucketedData val autosensDataTable = ads.autosensDataTable if (bucketedData == null || bucketedData.size < 3) { aapsLogger.debug(LTag.AUTOSENS, {"Aborting calculation thread (No bucketed data available): ${data.from}"}) return Result.success(workDataOf("Error" to "Aborting calculation thread (No bucketed data available): ${data.from}")) } val prevDataTime = ads.roundUpTime(bucketedData[bucketedData.size - 3].timestamp) aapsLogger.debug(LTag.AUTOSENS, {"Prev data time: " + dateUtil.dateAndTimeString(prevDataTime)}) var previous = autosensDataTable[prevDataTime] // start from oldest to be able sub cob for (i in bucketedData.size - 4 downTo 0) { rxBus.send(EventIobCalculationProgress(CalculationWorkflow.ProgressData.IOB_COB_OREF, 100 - (100.0 * i / bucketedData.size).toInt(), data.cause)) if (isStopped) { aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (trigger): ${data.from}") return Result.failure(workDataOf("Error" to "Aborting calculation thread (trigger): ${data.from}")) } // check if data already exists var bgTime = bucketedData[i].timestamp bgTime = ads.roundUpTime(bgTime) if (bgTime > ads.roundUpTime(dateUtil.now())) continue var existing: AutosensData? if (autosensDataTable[bgTime].also { existing = it } != null) { previous = existing continue } val profile = profileFunction.getProfile(bgTime) if (profile == null) { aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (no profile): ${data.from}") continue // profile not set yet } aapsLogger.debug(LTag.AUTOSENS, "Processing calculation thread: ${data.from} ($i/${bucketedData.size})") val sens = profile.getIsfMgdl(bgTime) val autosensData = AutosensData(data.injector) autosensData.time = bgTime if (previous != null) autosensData.activeCarbsList = previous.cloneCarbsList() else autosensData.activeCarbsList = ArrayList() //console.error(bgTime , bucketed_data[i].glucose); var avgDelta: Double var delta: Double val bg: Double = bucketedData[i].value if (bg < 39 || bucketedData[i + 3].value < 39) { aapsLogger.error("! value < 39") continue } autosensData.bg = bg delta = bg - bucketedData[i + 1].value avgDelta = (bg - bucketedData[i + 3].value) / 3 val iob = data.iobCobCalculator.calculateFromTreatmentsAndTemps(bgTime, profile) val bgi = -iob.activity * sens * 5 val deviation = delta - bgi val avgDeviation = ((avgDelta - bgi) * 1000).roundToLong() / 1000.0 var slopeFromMaxDeviation = 0.0 var slopeFromMinDeviation = 999.0 // https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169 if (i < bucketedData.size - 16) { // we need 1h of data to calculate minDeviationSlope @Suppress("UNUSED_VARIABLE") var maxDeviation = 0.0 @Suppress("UNUSED_VARIABLE") var minDeviation = 999.0 val hourAgo = bgTime + 10 * 1000 - 60 * 60 * 1000L val hourAgoData = ads.getAutosensDataAtTime(hourAgo) if (hourAgoData != null) { val initialIndex = autosensDataTable.indexOfKey(hourAgoData.time) aapsLogger.debug(LTag.AUTOSENS, { ">>>>> bucketed_data.size()=" + bucketedData.size + " i=" + i + " hourAgoData=" + hourAgoData.toString()}) var past = 1 try { while (past < 12) { val ad = autosensDataTable.valueAt(initialIndex + past) aapsLogger.debug(LTag.AUTOSENS, {">>>>> past=" + past + " ad=" + ad?.toString()}) if (ad == null) { aapsLogger.debug(LTag.AUTOSENS, {autosensDataTable.toString()}) aapsLogger.debug(LTag.AUTOSENS, {bucketedData.toString()}) //aapsLogger.debug(LTag.AUTOSENS, iobCobCalculatorPlugin.getBgReadingsDataTable().toString()) val notification = Notification(Notification.SEND_LOGFILES, rh.gs(R.string.sendlogfiles), Notification.LOW) rxBus.send(EventNewNotification(notification)) sp.putBoolean("log_AUTOSENS", true) break } // let it here crash on NPE to get more data as i cannot reproduce this bug val deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5 if (ad.avgDeviation > maxDeviation) { slopeFromMaxDeviation = min(0.0, deviationSlope) maxDeviation = ad.avgDeviation } if (ad.avgDeviation < minDeviation) { slopeFromMinDeviation = max(0.0, deviationSlope) minDeviation = ad.avgDeviation } past++ } } catch (e: Exception) { aapsLogger.error("Unhandled exception", e) fabricPrivacy.logException(e) aapsLogger.debug(autosensDataTable.toString()) aapsLogger.debug(bucketedData.toString()) //aapsLogger.debug(iobCobCalculatorPlugin.getBgReadingsDataTable().toString()) val notification = Notification(Notification.SEND_LOGFILES, rh.gs(R.string.sendlogfiles), Notification.LOW) rxBus.send(EventNewNotification(notification)) sp.putBoolean("log_AUTOSENS", true) break } } else { aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketedData.size + " i=" + i + " hourAgoData=" + "null") } } val recentCarbTreatments = repository.getCarbsDataFromTimeToTimeExpanded(bgTime - T.mins(5).msecs(), bgTime, true).blockingGet() for (recentCarbTreatment in recentCarbTreatments) { autosensData.carbsFromBolus += recentCarbTreatment.amount val isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled() autosensData.activeCarbsList.add(autosensData.CarbsInPast(recentCarbTreatment, isAAPSOrWeighted)) autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.amount) + "g]" } // if we are absorbing carbs if (previous != null && previous.cob > 0) { // calculate sum of min carb impact from all active treatments val totalMinCarbsImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact) // figure out how many carbs that represents // but always assume at least 3mg/dL/5m (default) absorption per active treatment val ci = max(deviation, totalMinCarbsImpact) if (ci != deviation) autosensData.failOverToMinAbsorptionRate = true autosensData.absorbed = ci * profile.getIc(bgTime) / sens // and add that to the running total carbsAbsorbed autosensData.cob = max(previous.cob - autosensData.absorbed, 0.0) autosensData.mealCarbs = previous.mealCarbs autosensData.deductAbsorbedCarbs() autosensData.usedMinCarbsImpact = totalMinCarbsImpact autosensData.absorbing = previous.absorbing autosensData.mealStartCounter = previous.mealStartCounter autosensData.type = previous.type autosensData.uam = previous.uam } val isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled() autosensData.removeOldCarbs(bgTime, isAAPSOrWeighted) autosensData.cob += autosensData.carbsFromBolus autosensData.mealCarbs += autosensData.carbsFromBolus autosensData.deviation = deviation autosensData.bgi = bgi autosensData.delta = delta autosensData.avgDelta = avgDelta autosensData.avgDeviation = avgDeviation autosensData.slopeFromMaxDeviation = slopeFromMaxDeviation autosensData.slopeFromMinDeviation = slopeFromMinDeviation // If mealCOB is zero but all deviations since hitting COB=0 are positive, exclude from autosens if (autosensData.cob > 0 || autosensData.absorbing || autosensData.mealCarbs > 0) { autosensData.absorbing = deviation > 0 // stop excluding positive deviations as soon as mealCOB=0 if meal has been absorbing for >5h if (autosensData.mealStartCounter > 60 && autosensData.cob < 0.5) { autosensData.absorbing = false } if (!autosensData.absorbing && autosensData.cob < 0.5) { autosensData.mealCarbs = 0.0 } // check previous "type" value, and if it wasn't csf, set a mealAbsorption start flag if (autosensData.type != "csf") { // process.stderr.write("("); autosensData.mealStartCounter = 0 } autosensData.mealStartCounter++ autosensData.type = "csf" } else { // check previous "type" value, and if it was csf, set a mealAbsorption end flag val currentBasal = profile.getBasal(bgTime) // always exclude the first 45m after each carb entry //if (iob.iob > currentBasal || uam ) { if (iob.iob > 2 * currentBasal || autosensData.uam || autosensData.mealStartCounter < 9) { autosensData.mealStartCounter++ autosensData.uam = deviation > 0 autosensData.type = "uam" } else { autosensData.type = "non-meal" } } // Exclude meal-related deviations (carb absorption) from autosens when (autosensData.type) { "non-meal" -> { when { abs(deviation) < Constants.DEVIATION_TO_BE_EQUAL -> { autosensData.pastSensitivity += "=" autosensData.validDeviation = true } deviation > 0 -> { autosensData.pastSensitivity += "+" autosensData.validDeviation = true } else -> { autosensData.pastSensitivity += "-" autosensData.validDeviation = true } } } "uam" -> { autosensData.pastSensitivity += "u" } else -> { autosensData.pastSensitivity += "x" } } // add an extra negative deviation if a high temp target is running and exercise mode is set // TODO AS-FIX @Suppress("SimplifyBooleanWithConstants") if (false && sp.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)) { val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing && tempTarget.value.target() >= 100) { autosensData.extraDeviation.add(-(tempTarget.value.target() - 100) / 20) } } // add one neutral deviation every 2 hours to help decay over long exclusion periods val calendar = GregorianCalendar() calendar.timeInMillis = bgTime val min = calendar[Calendar.MINUTE] val hours = calendar[Calendar.HOUR_OF_DAY] if (min in 0..4 && hours % 2 == 0) autosensData.extraDeviation.add(0.0) previous = autosensData if (bgTime < dateUtil.now()) autosensDataTable.put(bgTime, autosensData) aapsLogger.debug( LTag.AUTOSENS, {"Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + ads.lastDataTime(dateUtil)} ) val sensitivity = activePlugin.activeSensitivity.detectSensitivity(ads, oldestTimeWithData, bgTime) aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity") autosensData.autosensResult = sensitivity aapsLogger.debug(LTag.AUTOSENS, {autosensData.toString()}) } data.iobCobCalculator.ads = ads Thread { SystemClock.sleep(1000) rxBus.send(EventAutosensCalculationFinished(data.cause)) }.start() } finally { rxBus.send(EventIobCalculationProgress(CalculationWorkflow.ProgressData.IOB_COB_OREF, 100, data.cause)) aapsLogger.debug(LTag.AUTOSENS, {"AUTOSENSDATA thread ended: ${data.from}"}) profiler.log(LTag.AUTOSENS, "IobCobOref1Thread", start) } return Result.success() } }
agpl-3.0
9b0f1d1e02cd16829828f1f80fff72d5
56.677419
200
0.587583
5.128292
false
false
false
false
unbroken-dome/gradle-xjc-plugin
src/test/kotlin/org/unbrokendome/gradle/plugins/xjc/testutil/assertions/GradleTask.kt
1
2228
package org.unbrokendome.gradle.plugins.xjc.testutil.assertions import assertk.Assert import assertk.assertions.containsAll import assertk.assertions.containsOnly import assertk.assertions.support.expected import assertk.assertions.support.show import org.gradle.api.Task import org.unbrokendome.gradle.plugins.xjc.testutil.isSkipped val Assert<Task>.taskDependencies get() = transform { actual -> actual.taskDependencies.getDependencies(actual) } fun Assert<Task>.hasTaskDependency(taskName: String) = given { actual -> val dependencies = actual.taskDependencies.getDependencies(actual) if (dependencies.none { it.name == taskName }) { expected("to have a dependency on task \"${taskName}\", but dependencies were: ${show(dependencies)}") } } fun Assert<Task>.hasOnlyTaskDependency(taskName: String) = given { actual -> val dependencies = actual.taskDependencies.getDependencies(actual) if (dependencies.size != 1 || dependencies.firstOrNull()?.name != taskName) { expected("to have a single dependency on task \"${taskName}\", but dependencies were: ${show(dependencies)}") } } fun Assert<Task>.hasTaskDependencies(vararg taskNames: String, exactly: Boolean = false) = given { actual -> val dependencies = actual.taskDependencies.getDependencies(actual) val dependencyTaskNames = dependencies.map { it.name }.toSet() val assert = assertThat(dependencyTaskNames, name = "task \"${actual.name}\" dependencies") if (exactly) { assert.containsOnly(*taskNames) } else { assert.containsAll(*taskNames) } } fun Assert<Task>.doesNotHaveTaskDependency(taskName: String) = given { actual -> val dependencies = actual.taskDependencies.getDependencies(actual) if (dependencies.any { it.name == taskName }) { expected("to have no dependency on task \"${taskName}\", but dependencies were: ${show(dependencies)}") } } fun Assert<Task>.isSkipped() = given { actual -> if (!actual.isSkipped()) { expected("to be skipped, but was not skipped") } } fun Assert<Task>.isNotSkipped() = given { actual -> if (actual.isSkipped()) { expected("not to be skipped, but was skipped") } }
mit
beffd05255bcf99fc9e9696c4afebe40
31.764706
117
0.706912
4.385827
false
false
false
false
Saketme/JRAW
lib/src/main/kotlin/net/dean/jraw/pagination/RotatingSearchList.kt
2
2292
package net.dean.jraw.pagination /** * This class is a very simple data structure which functions similarly to a LRU cache with no max age, but with a fixed * size. Until capacity is reached, adding new data functions exactly like a normal list. However, once the capacity has * been reached, new data is added at index 0, then to 1, 2, etc, overwriting older data. * * @param capacity The maximum number of elements to store */ internal class RotatingSearchList<T>(val capacity: Int) { // All are internal for testing purposes only internal val backingArray: Array<Any?> = arrayOfNulls(capacity) internal var currentIndex = 0 private var _size = 0 /** The amount of elements currently being stored */ val size: Int get() = _size /** * Adds some data. Returns whatever data was overwritten by this call. */ fun add(data: T): T? { @Suppress("UNCHECKED_CAST") val overwrittenData: T? = backingArray[currentIndex] as T? backingArray[currentIndex] = data if (++currentIndex >= backingArray.size) currentIndex = 0 // If we haven't overwritten anything, then we've added new data if (overwrittenData == null) _size++ return overwrittenData } /** * Checks if some data is currently being stored. This function assumes the data is likely to have been inserted * recently */ fun contains(data: T): Boolean { // Start at currentIndex because in our case it's more likely that the data we're looking for (if it's in here) // is going to be added more recently for (i in 0 until size) { // We have to add backingArray.size here because Java does not do the mod operation properly (at least // according to the mathematical definition of mod). In Python: -1 % 5 --> 4. In Java: -1 % 5 --> -1. We // want the Python result, and to ensure that, we have to add backingArray.size (5 in the previous example). // (-1 + 5) % 5 --> 4 in both languages. val index = (currentIndex - 1 - i + backingArray.size) % backingArray.size if (backingArray[index] == data) { return true } } return false } }
mit
e3ae02a8ca8077c4bdf2f0f42e56006a
37.847458
120
0.631326
4.416185
false
false
false
false
Adventech/sabbath-school-android-2
common/lessons-data/src/main/java/app/ss/lessons/data/repository/media/AudioDataSource.kt
1
3292
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.lessons.data.repository.media import app.ss.lessons.data.api.SSMediaApi import app.ss.lessons.data.repository.DataSource import app.ss.lessons.data.repository.DataSourceMediator import app.ss.lessons.data.repository.LocalDataSource import app.ss.models.media.SSAudio import app.ss.storage.db.dao.AudioDao import com.cryart.sabbathschool.core.extensions.connectivity.ConnectivityHelper import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider import com.cryart.sabbathschool.core.response.Resource import javax.inject.Inject import javax.inject.Singleton @Singleton internal class AudioDataSource @Inject constructor( private val mediaApi: SSMediaApi, private val audioDao: AudioDao, dispatcherProvider: DispatcherProvider, connectivityHelper: ConnectivityHelper ) : DataSourceMediator<SSAudio, AudioDataSource.Request>( dispatcherProvider = dispatcherProvider, connectivityHelper = connectivityHelper ) { data class Request(val lessonIndex: String) override val cache: LocalDataSource<SSAudio, Request> = object : LocalDataSource<SSAudio, Request> { override suspend fun get(request: Request): Resource<List<SSAudio>> { val data = audioDao.getBy(request.queryIndex) return if (data.isNotEmpty()) Resource.success(data.map { it.toSSAudio() }) else Resource.loading() } override suspend fun update(request: Request, data: List<SSAudio>) { audioDao.delete(request.queryIndex) audioDao.insertAll(data.map { it.toEntity() }) } } override val network: DataSource<SSAudio, Request> = object : DataSource<SSAudio, Request> { override suspend fun get(request: Request): Resource<List<SSAudio>> { val data = request.lessonIndex.toMediaRequest()?.let { mediaApi.getAudio(it.language, it.quarterlyId).body() } ?: emptyList() val lessonAudios = data.filter { it.targetIndex.startsWith(request.lessonIndex) } return Resource.success(lessonAudios) } } private val Request.queryIndex: String get() = "$lessonIndex%" }
mit
eea05c176a287675302a406359fa235f
42.315789
111
0.740887
4.436658
false
false
false
false
ismail-s/JTime
JTime-android/src/main/kotlin/com/ismail_s/jtime/android/fragment/AllMasjidsFragment.kt
1
3252
package com.ismail_s.jtime.android.fragment import android.location.Location import android.location.Location.distanceBetween import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.ismail_s.jtime.android.R import com.ismail_s.jtime.android.RestClient import com.ismail_s.jtime.android.MasjidRecyclerViewAdapter import com.ismail_s.jtime.android.pojo.MasjidPojo import kotlinx.android.synthetic.main.fragment_item_list.* import nl.komponents.kovenant.ui.failUi import nl.komponents.kovenant.ui.successUi import org.jetbrains.anko.find import org.jetbrains.anko.support.v4.act import org.jetbrains.anko.support.v4.longToast /** * Display a list of all masjids on the rest server. */ class AllMasjidsFragment : BaseFragment(), SwipeRefreshLayout.OnRefreshListener { private fun hideRefreshIcon() { pull_to_refresh_container?.isRefreshing = false } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater?.inflate(R.layout.fragment_item_list, container, false) override fun onStart() { super.onStart() pull_to_refresh_container.setOnRefreshListener(this) masjid_list.setHasFixedSize(true) pull_to_refresh_container.post { pull_to_refresh_container.isRefreshing = true } onRefresh() } override fun onStop() { super.onStop() hideRefreshIcon() } override fun onRefresh() { cancelPromiseOnFragmentDestroy { RestClient(act).getMasjids() successUi { masjids -> if (activity != null) { mainAct.location successUi { hideRefreshIcon() if (activity != null) masjid_list.adapter = MasjidRecyclerViewAdapter(sortMasjidsByLocation(masjids, it), mainAct) } failUi { hideRefreshIcon() if (activity != null) masjid_list.adapter = MasjidRecyclerViewAdapter(sortMasjidsByName(masjids), mainAct) } } } failUi { hideRefreshIcon() if (activity != null) longToast(getString(R.string.get_masjids_failure_toast, it.message)) } } } override fun onLocationChanged(loc: Location) { pull_to_refresh_container.isRefreshing = true onRefresh() } private fun sortMasjidsByLocation(masjids: List<MasjidPojo>, userLocation: Location): List<MasjidPojo> { return masjids.sortedBy { //For some weird reason, distanceBetween doesn't return the distance, but instead //stores the computed distance on a result array that is passed in val result = FloatArray(size = 1) distanceBetween(userLocation.latitude, userLocation.longitude, it.latitude, it.longitude, result) result[0] } } private fun sortMasjidsByName(masjids: List<MasjidPojo>) = masjids.sortedBy {it.name} }
gpl-2.0
3fe394c21aee4a86d17276e4c25d8fff
36.37931
120
0.658979
4.330226
false
false
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/bot/commands/Warn.kt
1
5544
/* * Copyright 2018 Duncan Casteleyn * * 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 be.duncanc.discordmodbot.bot.commands import be.duncanc.discordmodbot.bot.services.GuildLogger import be.duncanc.discordmodbot.bot.utils.extractReason import be.duncanc.discordmodbot.bot.utils.findMemberAndCheckCanInteract import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername import be.duncanc.discordmodbot.data.entities.GuildWarnPointsSettings import be.duncanc.discordmodbot.data.repositories.jpa.GuildWarnPointsSettingsRepository import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.MessageBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Member import net.dv8tion.jda.api.entities.MessageEmbed import net.dv8tion.jda.api.entities.PrivateChannel import net.dv8tion.jda.api.events.message.MessageReceivedEvent import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.awt.Color import java.util.* /** * Created by Duncan on 24/02/2017. * * * This class creates a command that allowed you to warn users by sending them a dm and logging. */ @Component class Warn @Autowired constructor( private val guildWarnPointsSettingsRepository: GuildWarnPointsSettingsRepository ) : CommandModule( arrayOf("Warn"), "[User mention] [Reason~]", "Warns as user by sending the user mentioned a message and logs the warning to the log channel.", true, true, requiredPermissions = arrayOf(Permission.KICK_MEMBERS) ) { public override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { val guildWarnPointsSettings = guildWarnPointsSettingsRepository.findById(event.guild.idLong) .orElse(GuildWarnPointsSettings(event.guild.idLong, announceChannelId = -1)) if (guildWarnPointsSettings.overrideWarnCommand) { return } event.author.openPrivateChannel().queue( { privateChannel -> commandExec(event, arguments, privateChannel) } ) { commandExec(event, arguments, null as PrivateChannel?) } } private fun commandExec(event: MessageReceivedEvent, arguments: String?, privateChannel: PrivateChannel?) { if (event.message.mentionedUsers.size < 1) { privateChannel?.sendMessage("Illegal argumentation, you need to mention a user that is still in the server.") ?.queue() } else { val reason: String = extractReason(arguments) val toWarn = findMemberAndCheckCanInteract(event) val guildLogger = event.jda.registeredListeners.firstOrNull { it is GuildLogger } as GuildLogger? if (guildLogger != null) { val logEmbed = EmbedBuilder() .setColor(Color.YELLOW) .setTitle("User warned") .addField("UUID", UUID.randomUUID().toString(), false) .addField("User", toWarn.nicknameAndUsername, true) .addField("Moderator", event.member!!.nicknameAndUsername, true) .addField("Reason", reason, false) guildLogger.log(logEmbed, toWarn.user, event.guild, null, GuildLogger.LogTypeAction.MODERATOR) } val userWarning = EmbedBuilder() .setColor(Color.YELLOW) .setAuthor(event.member!!.nicknameAndUsername, null, event.author.effectiveAvatarUrl) .setTitle(event.guild.name + ": You have been warned by " + event.member!!.nicknameAndUsername, null) .addField("Reason", reason, false) toWarn.user.openPrivateChannel().queue( { privateChannelUserToWarn -> privateChannelUserToWarn.sendMessageEmbeds(userWarning.build()).queue( { onSuccessfulWarnUser(privateChannel!!, toWarn, userWarning.build()) } ) { throwable -> onFailToWarnUser(privateChannel!!, toWarn, throwable) } } ) { throwable -> onFailToWarnUser(privateChannel!!, toWarn, throwable) } } } private fun onSuccessfulWarnUser(privateChannel: PrivateChannel, toWarn: Member, userWarning: MessageEmbed) { val creatorMessage = MessageBuilder() .append("Warned ").append(toWarn.toString()).append(".\n\nThe following message was sent to the user:") .setEmbeds(userWarning) .build() privateChannel.sendMessage(creatorMessage).queue() } private fun onFailToWarnUser(privateChannel: PrivateChannel, toWarn: Member, throwable: Throwable) { val creatorMessage = MessageBuilder() .append("Warned ").append(toWarn.toString()) .append(".\n\nWas unable to send a DM to the user please inform the user manually.\n") .append(throwable.javaClass.simpleName).append(": ").append(throwable.message) .build() privateChannel.sendMessage(creatorMessage).queue() } }
apache-2.0
0b258851c8a37415a502bf900515c343
44.818182
121
0.690837
4.551724
false
false
false
false
JohnnyShieh/Gank
app/src/main/kotlin/com/johnny/gank/main/WebviewActivity.kt
1
5314
package com.johnny.gank.main /* * Copyright (C) 2016 Johnny Shieh 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. */ import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.os.Bundle import android.view.KeyEvent import android.view.Menu import android.view.MenuItem import android.view.ViewGroup import android.webkit.* import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.johnny.gank.R import com.johnny.gank.base.BaseActivity import com.johnny.gank.model.StatName import kotlinx.android.synthetic.main.activity_webview.* import org.jetbrains.anko.browse import org.jetbrains.anko.share import org.jetbrains.anko.startActivity /** * description * * @author Johnny Shieh ([email protected]) * @version 1.0 */ class WebviewActivity : BaseActivity(), SwipeRefreshLayout.OnRefreshListener { companion object { const val EXTRA_URL = "URL" const val EXTRA_TITLE = "TITLE" @JvmStatic fun openUrl(context: Context, url: String, title: String) { context.startActivity<WebviewActivity>(EXTRA_URL to url, EXTRA_TITLE to title) } } private lateinit var mUrl: String private lateinit var mTitle: String override val pageName = StatName.PAGE_WEBVIEW override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_webview) setSupportActionBar(toolbar) supportActionBar!!.setDisplayShowHomeEnabled(true) supportActionBar!!.setDisplayHomeAsUpEnabled(true) refresh_layout.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent) setUpWebView() if (null != intent) { mUrl = intent.getStringExtra(EXTRA_URL).orEmpty() mTitle = intent.getStringExtra(EXTRA_TITLE).orEmpty() } title = mTitle webview.loadUrl(mUrl) } @SuppressLint("SetJavaScriptEnabled") private fun setUpWebView() { webview.settings.javaScriptEnabled = true webview.settings.loadWithOverviewMode = true webview.webViewClient = object : WebViewClient() { override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) refresh_layout.isRefreshing = true } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) refresh_layout.isRefreshing = false } override fun onReceivedError(view: WebView?, request: WebResourceRequest, error: WebResourceError) { super.onReceivedError(view, request, error) refresh_layout.isRefreshing = false } } webview.webChromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView?, newProgress: Int) { super.onProgressChanged(view, newProgress) if (newProgress >= 80) refresh_layout.isRefreshing = false } } } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) { webview.goBack() return true } return super.onKeyDown(keyCode, event) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_webview, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { if (webview.canGoBack()) { webview.goBack() return true } } R.id.action_share -> { sharePage() return true } R.id.action_open_in_browser -> { openInBrowser() return true } } return super.onOptionsItemSelected(item) } private fun sharePage() { share(getString(R.string.share_page, webview.title, webview.url)) } private fun openInBrowser() { browse(webview.url) } override fun onRefresh() { webview.reload() } override fun onDestroy() { super.onDestroy() // After Android 5.1, there has a problem in Webview: // if onDetach is called after destroy, AwComponentCallbacks object will be leaked. val tmpWebView = webview if(null != webview.parent) { (webview.parent as ViewGroup).removeView(webview) } tmpWebView.destroy() } }
apache-2.0
e10200924e584cea3e1fdc32a3a74cc6
31.601227
115
0.641889
4.774483
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/ndarray/ShapeSpec.kt
1
4330
/* 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 ndarray import com.kotlinnlp.simplednn.simplemath.ndarray.Shape import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals import kotlin.test.assertNotEquals /** * */ class ShapeSpec : Spek({ describe("a Shape") { context("shape of dimensions (1, 1)") { val shape = Shape(1, 1) val inverted = shape.inverse context("equals") { it("should return true if called passing a Shape with same dimensions") { assertEquals(Shape(1, 1), shape) } it("should return true if called passing a Shape with inverted dimensions") { assertEquals(inverted, shape) } it("should return true if called passing its inverse") { assertEquals(inverted, shape) } it("should return false if called passing a Shape with different dimensions") { assertNotEquals(Shape(5), shape) } } context("inverted") { it("should have the expected dim 1") { assertEquals(inverted.dim1, 1) } it("should have the expected dim 2") { assertEquals(inverted.dim2, 1) } } } context("vertical shape of length 4") { val shape = Shape(4) val inverted = shape.inverse context("equals") { it("should return true if called passing a Shape with same dimensions") { assertEquals(Shape(4), shape) } it("should return false if called passing a Shape with inverted dimensions") { assertNotEquals(Shape(1, 4), shape) } it("should return false if called passing its inverse") { assertNotEquals(inverted, shape) } it("should return false if called passing a Shape with different dimensions") { assertNotEquals(Shape(6), shape) } } context("inverted") { it("should return a horizontal shape") { assertEquals(inverted.dim1, 1) } it("should have length 4") { assertEquals(inverted.dim2, 4) } } } context("horizontal shape of length 4") { val shape = Shape(1, 4) val inverted = shape.inverse context("equals") { it("should return true if called passing a Shape with same dimensions") { assertEquals(Shape(1, 4), shape) } it("should return false if called passing a Shape with inverted dimensions") { assertNotEquals(Shape(4), shape) } it("should return false if called passing its inverse") { assertNotEquals(inverted, shape) } it("should return false if called passing a Shape with different dimensions") { assertNotEquals(Shape(6), shape) } } context("inverted") { it("should return a vertical shape") { assertEquals(inverted.dim2, 1) } it("should have length 4") { assertEquals(inverted.dim1, 4) } } } context("bi-dimensional shape") { val shape = Shape(3, 4) val inverted = shape.inverse context("equals") { it("should return true if called passing a Shape with same dimensions") { assertEquals(Shape(3, 4), shape) } it("should return false if called passing a Shape with inverted dimensions") { assertNotEquals(Shape(4, 3), shape) } it("should return false if called passing its inverse") { assertNotEquals(inverted, shape) } it("should return false if called passing a Shape with different dimensions") { assertNotEquals(Shape(4, 6), shape) } } context("inverted") { it("should have the expected dim 1") { assertEquals(inverted.dim1, 4) } it("should have the expected dim 2") { assertEquals(inverted.dim2, 3) } } } } })
mpl-2.0
70713c20114a3bd7c9a422f962cfe15f
24.928144
87
0.584988
4.621131
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/feedforward/simple/FeedforwardBackwardHelper.kt
1
1945
/* 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.feedforward.simple import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper import com.kotlinnlp.simplednn.core.arrays.getInputErrors import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray /** * The helper which executes the backward on a [layer]. * * @property layer the [FeedforwardLayer] in which the backward is executed */ internal class FeedforwardBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>( override val layer: FeedforwardLayer<InputNDArrayType> ) : BackwardHelper<InputNDArrayType>(layer) { /** * Executes the backward calculating the errors of the parameters and eventually of the input through the SGD * algorithm, starting from the preset errors of the output array. * * @param propagateToInput whether to propagate the errors to the input array */ override fun execBackward(propagateToInput: Boolean) { this.layer.applyOutputActivationDeriv() this.assignParamsGradients() if (propagateToInput) { this.assignLayerGradients() } } /** * gb = gy * 1 * gw = gy (dot) x */ private fun assignParamsGradients() { this.layer.outputArray.assignParamsGradients( gw = this.layer.params.unit.weights.errors.values, gb = this.layer.params.unit.biases.errors.values, x = this.layer.inputArray.values) } /** * gx = gy (dot) w */ private fun assignLayerGradients() { this.layer.inputArray.assignErrors( errors = this.layer.outputArray.getInputErrors(w = this.layer.params.unit.weights.values) ) } }
mpl-2.0
0a40cd66c4f5bed6688a04bdee95c842
30.885246
111
0.703342
4.380631
false
false
false
false
abeemukthees/Arena
spectacle/src/main/java/com/abhi/spectacle/staggergrid/StaggeredGridActivity.kt
1
5229
package com.abhi.spectacle.staggergrid import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.abhi.spectacle.R import com.abhi.spectacle.data.ImgurService import com.abhi.spectacle.data.poko.ImgurEntities import com.abhi.spectacle.utilities.ImageLoader import kotlinx.android.synthetic.main.activity_staggered_grid.* import kotlinx.android.synthetic.main.content_staggered_grid.* import kotlinx.android.synthetic.main.item_stagger_grid_0.view.* import kotlinx.coroutines.experimental.Dispatchers import kotlinx.coroutines.experimental.GlobalScope import kotlinx.coroutines.experimental.android.Main import kotlinx.coroutines.experimental.async import org.jetbrains.anko.coroutines.experimental.asReference import java.util.* import kotlin.collections.ArrayList class StaggeredGridActivity : AppCompatActivity() { private val TAG = StaggeredGridActivity::class.simpleName val staggeredLayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) val simpleRecyclerViewAdapter = SimpleRecyclerViewAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_staggered_grid) setSupportActionBar(toolbar) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } recyclerView_stagger.layoutManager = staggeredLayoutManager recyclerView_stagger.adapter = simpleRecyclerViewAdapter //setRvItems() getImgurImages() } private fun setRvItems() { val simpleItems = ArrayList<SimpleItem>() for (i in 0..20) { simpleItems.add(SimpleItem(i.toString(), randomStringGenerator(), "")) } simpleRecyclerViewAdapter.simpleItems = simpleItems } @Suppress("DeferredResultUnused") private fun getImgurImages() { val ref = asReference() GlobalScope.async(Dispatchers.Main, CoroutineStart.DEFAULT, null, { try { val result = ImgurService.getImgurService(applicationContext).getImages() ref.invoke().processData(result.await()) } catch (e: Exception) { e.printStackTrace() } }) } private fun processData(imgurEntities: ImgurEntities) { Log.d(TAG, "Received size = ${imgurEntities.data.size}") val simpleItems = ArrayList<SimpleItem>() Log.d(TAG, "Data to be added = ${simpleItems.size}") for (imgurData in imgurEntities.data) { imgurData.images?.let { for (image in imgurData.images) { simpleItems.add(SimpleItem(imgurData.id, randomStringGenerator(), image.link)) Log.d(TAG, "Image ${imgurData.id} = ${image.id}") } } Log.d(TAG, imgurData.id) } //println("Data processed") Log.d(TAG, "Data processed = ${simpleItems.size}") simpleRecyclerViewAdapter.simpleItems = simpleItems } private fun randomStringGenerator(): String { val data = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" val random = Random() val length = random.nextInt(50) + 1 val sb = StringBuilder(length) for (i in 0 until length) { sb.append(data.toCharArray()[random.nextInt(data.length)]) } return sb.toString() } } data class SimpleItem(val id: String, val title: String, val imageUrl: String) class StaggeredGridItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val constraintLayout = itemView.constraintLayout_stagGrid val imageView = itemView.imageView val titleTextView = itemView.text_title } class SimpleRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var simpleItems = ArrayList<SimpleItem>() set(value) { field = value notifyDataSetChanged() println("notifyDataSetChanged") } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return StaggeredGridItemHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_stagger_grid_0, parent, false)) } override fun getItemCount(): Int { return simpleItems.size } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val simpleItem = simpleItems[position] if (holder is StaggeredGridItemHolder) { holder.titleTextView.text = simpleItem.id holder.imageView.layout(0, 0, 0, 0) //holder.imageView.loadUrlMaintaingAspectRatio(simpleItem.imageUrl, holder.constraintLayout) ImageLoader.loadImage(holder.imageView, holder.constraintLayout, simpleItem.imageUrl) } } }
apache-2.0
7b1918ad487820a6b6cac766efd8b484
27.889503
128
0.686938
4.677102
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/unwrap/KotlinFunctionParameterUnwrapper.kt
1
8141
// 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.codeInsight.unwrap import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.elementType import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText import org.jetbrains.kotlin.idea.util.isComma import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.util.takeWhileIsInstance import org.jetbrains.kotlin.utils.addToStdlib.ifTrue import org.jetbrains.kotlin.utils.addToStdlib.safeAs class KotlinFunctionParameterUnwrapper(val key: String) : KotlinUnwrapRemoveBase(key) { override fun isApplicableTo(element: PsiElement): Boolean { val argumentToUnwrap = argumentToUnwrap(element) ?: return false deletionTarget(argumentToUnwrap) ?: return false return true } private fun argumentToUnwrap(element: PsiElement?): KtValueArgument? { if (element == null) return null nearbySingleArg(element)?.let { return it } when (element) { is KtValueArgument -> return element else -> { if (element.parent !is KtValueArgumentList) return null if (element.isComma || element.elementType == KtTokens.RPAR || element is PsiWhiteSpace || element is PsiComment) { return findAdjacentValueArgumentInsideParen(element) } else return null } } } /** * When outside a function call's parenthesized arguments but the function has a single argument, choose that * ``` * β”Œ LPAR * β”‚ * v * methodCall(arguments) * ^^^^^^^^^^ * β”‚ * β”” Identifier * ``` * */ private fun nearbySingleArg(element: PsiElement): KtValueArgument? { // a.b.c.d(123) // ^^^^^^^ // walk up chained dot expressions until we find the one that has a call as rhs // we use this complicated rather than just have isApplicableTo apply to a KtQualifiedExpression to get priority over // "Remove" unwrap item fun caretOnQualifier(qualifiedExpression: KtQualifiedExpression): KtCallExpression? = qualifiedExpression.parentsWithSelf.takeWhileIsInstance<KtQualifiedExpression>().last().selectorExpression as? KtCallExpression val callExpression: KtCallExpression = when (element.elementType) { KtTokens.LPAR -> { element.parent?.safeAs<KtValueArgumentList>() ?.parent?.safeAs<KtCallExpression>() ?: return null } KtTokens.DOT, KtTokens.SAFE_ACCESS -> { element.parent?.safeAs<KtQualifiedExpression>() ?.let { caretOnQualifier(it) } ?: return null } KtTokens.IDENTIFIER -> { val referenceExpression = element.parent?.safeAs<KtReferenceExpression>() when (val parent = referenceExpression?.parent) { is KtCallExpression -> parent is KtQualifiedExpression -> { caretOnQualifier(parent) } else -> null } ?: return null // we could just handle this on } else -> return null } val ktValueArgumentList = callExpression.valueArgumentList if (ktValueArgumentList?.arguments.isNullOrEmpty()) { // if there's no parenthesized arguments, unwrap trailing lambda if any return callExpression.lambdaArguments.singleOrNull() } // there are parenthesized arguments, only consider if there's exactly one return ktValueArgumentList?.arguments?.singleOrNull() } /** * When inside a function call's parenthesized arguments. * * * for Comma and RPAR, we scan towards the left * * for whitespace, we scan leftwards and rightwards * * ``` * β”Œ COMMA * β”‚ β”Œ RPAR * β”‚ β”‚ * v v * methodCall(1, 2 , 3 ) * ^ ^ ^ * β”‚ β”‚ β”‚ * Whitespace β”΄β”€β”€β”€β”΄β”€β”˜ * ``` * */ private fun findAdjacentValueArgumentInsideParen(element: PsiElement): KtValueArgument? { if (element.parent !is KtValueArgumentList) { return null } return when { element.elementType == KtTokens.RPAR -> { // caret after last argument before closing paren, argument is the last element val valueArgumentList = element.parent as? KtValueArgumentList ?: return null if (valueArgumentList.parent !is KtCallExpression) return null return valueArgumentList.arguments.lastOrNull() } element.isComma -> { // caret before comma, choose previous argument val previous = element.getPrevSiblingIgnoringWhitespaceAndComments() isCallArgument(previous).ifTrue { previous as KtValueArgument } } element is PsiWhiteSpace || element is PsiComment -> { // caret before blank or in comment, argument could be towards the left or the right val previous = element.getPrevSiblingIgnoringWhitespaceAndComments() if (isCallArgument(previous)) return previous as KtValueArgument val next = element.getNextSiblingIgnoringWhitespaceAndComments() if (isCallArgument(next)) return next as KtValueArgument null } else -> null } } private fun isCallArgument(element: PsiElement?): Boolean { if (element is KtLambdaArgument) return false if (element !is KtValueArgument) return false val argumentList = element.parent as KtValueArgumentList if (argumentList.parent !is KtCallExpression) return false return true } override fun doUnwrap(element: PsiElement?, context: Context?) { val valueArgument = argumentToUnwrap(element) ?: return val deletionTarget = deletionTarget(valueArgument) ?: return val argument = valueArgument.getArgumentExpression() ?: return context?.extractFromExpression(argument, deletionTarget) context?.delete(deletionTarget) } private fun deletionTarget(valueArgument: KtValueArgument): KtElement? { var function: KtElement = valueArgument.getStrictParentOfType<KtCallExpression>() ?: return null val parent = function.parent if (parent is KtQualifiedExpression) { function = parent } return function } override fun collectAffectedElements(e: PsiElement, toExtract: MutableList<PsiElement>): PsiElement { super.collectAffectedElements(e, toExtract) return argumentToUnwrap(e)?.let { deletionTarget(it) } ?: e } override fun getDescription(e: PsiElement): String { // necessary because the base implementation expects to be called for KtElement // but because we support the caret to be on LPAR/COMMA and other tokens this doesn't work val target = argumentToUnwrap(e) ?: error("Description asked for a non applicable unwrapper") val callee = target.getStrictParentOfType<KtCallExpression>()?.calleeExpression ?.let(::getExpressionShortText) ?: "?" return KotlinBundle.message(key, callee, getExpressionShortText(target)) } }
apache-2.0
79c0a919edcc3239dbd52c3d58b1ab3d
40.768041
158
0.639516
5.515997
false
false
false
false
androidthings/sample-button
kotlin/app/src/main/kotlin/com/example/androidthings/button/ButtonActivity.kt
1
3251
/* * Copyright 2016, 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.androidthings.button import android.app.Activity import android.os.Bundle import android.util.Log import android.view.KeyEvent import com.google.android.things.contrib.driver.button.Button import com.google.android.things.contrib.driver.button.ButtonInputDriver import com.google.android.things.pio.Gpio import com.google.android.things.pio.PeripheralManager /** * Example of using Button driver for toggling a LED. * * This activity initialize an InputDriver to emit key events when the button GPIO pin state change * and flip the state of the LED GPIO pin. * * You need to connect an LED and a push button switch to pins specified in [BoardDefaults] * according to the schematic provided in the sample README. */ class ButtonActivity : Activity() { private lateinit var ledGpio: Gpio private lateinit var buttonInputDriver: ButtonInputDriver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.i(TAG, "Starting ButtonActivity") val pioService = PeripheralManager.getInstance() Log.i(TAG, "Configuring GPIO pins") ledGpio = pioService.openGpio(BoardDefaults.gpioForLED) ledGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW) Log.i(TAG, "Registering button driver") // Initialize and register the InputDriver that will emit SPACE key events // on GPIO state changes. buttonInputDriver = ButtonInputDriver( BoardDefaults.gpioForButton, Button.LogicState.PRESSED_WHEN_LOW, KeyEvent.KEYCODE_SPACE) buttonInputDriver.register() } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_SPACE) { // Turn on the LED setLedValue(true) return true } return super.onKeyDown(keyCode, event) } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_SPACE) { // Turn off the LED setLedValue(false) return true } return super.onKeyUp(keyCode, event) } /** * Update the value of the LED output. */ private fun setLedValue(value: Boolean) { Log.d(TAG, "Setting LED value to $value") ledGpio.value = value } override fun onStop() { buttonInputDriver.unregister() buttonInputDriver.close() ledGpio.close() super.onStop() } companion object { private val TAG = ButtonActivity::class.java.simpleName } }
apache-2.0
772afaa5b3b655d036c8df6938c89f50
30.563107
99
0.683174
4.260813
false
false
false
false
MasuqaT-NET/BlogSamples
Misc/kotlin-webgl/src/main/kotlin/Vector3.kt
2
1018
import org.khronos.webgl.Float32Array import kotlin.js.Math data class Vector3(val x: Float, val y: Float, val z: Float) { operator fun plus(another: Vector3) = Vector3(x + another.x, y + another.y, z + another.z) operator fun minus(another: Vector3) = Vector3(x - another.x, y - another.y, z - another.z) operator fun unaryMinus() = Vector3(-x, -y, -z) operator fun div(another: Float) = Vector3(x / another, y / another, z / another) infix fun dot(another: Vector3) = x * another.x + y * another.y + z * another.z infix fun cross(another: Vector3) = Vector3( y * another.z - z * another.y, z * another.x - x * another.z, x * another.y - y * another.x ) fun norm2(): Float { val x = this.x.toDouble() val y = this.y.toDouble() val z = this.z.toDouble() return Math.sqrt(x * x + y * y + z * z).toFloat() } } fun Array<Vector3>.toFloat32Array() = Float32Array(flatMap { listOf(it.x, it.y, it.z) }.toTypedArray())
mit
5a015facfd9c4fe2613e5c67034b3f25
41.458333
103
0.604126
3.132308
false
false
false
false
androidstarters/androidstarters.com
templates/buffer-clean-architecture-components-kotlin/remote/src/test/java/org/buffer/android/boilerplate/remote/test/factory/BufferooFactory.kt
1
1101
package <%= appPackage %>.remote.test.factory import <%= appPackage %>.remote.BufferooService import <%= appPackage %>.remote.model.BufferooModel import <%= appPackage %>.remote.test.factory.DataFactory.Factory.randomLong import <%= appPackage %>.remote.test.factory.DataFactory.Factory.randomUuid /** * Factory class for Bufferoo related instances */ class BufferooFactory { companion object Factory { fun makeBufferooResponse(): BufferooService.BufferooResponse { val bufferooResponse = BufferooService.BufferooResponse() bufferooResponse.team = makeBufferooModelList(5) return bufferooResponse } fun makeBufferooModelList(count: Int): List<BufferooModel> { val bufferooEntities = mutableListOf<BufferooModel>() repeat(count) { bufferooEntities.add(makeBufferooModel()) } return bufferooEntities } fun makeBufferooModel(): BufferooModel { return BufferooModel(randomLong(), randomUuid(), randomUuid(), randomUuid()) } } }
mit
9e4020078b49e56abc938a4855be0a78
30.485714
88
0.669391
5.370732
false
true
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/habit/widget/HabitWidgetProvider.kt
1
6474
package io.ipoli.android.habit.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.view.View import android.widget.RemoteViews import io.ipoli.android.Constants import io.ipoli.android.MyPoliApp import io.ipoli.android.R import io.ipoli.android.common.IntentUtil import io.ipoli.android.common.di.BackgroundModule import io.ipoli.android.habit.receiver.CompleteHabitReceiver import io.ipoli.android.habit.receiver.UndoCompleteHabitReceiver import io.ipoli.android.store.powerup.PowerUp import kotlinx.coroutines.experimental.Dispatchers import kotlinx.coroutines.experimental.GlobalScope import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.withContext import space.traversal.kapsule.Injects import space.traversal.kapsule.inject import space.traversal.kapsule.required /** * Created by Polina Zhelyazkova <[email protected]> * on 7/27/18. */ class HabitWidgetProvider : AppWidgetProvider(), Injects<BackgroundModule> { private val playerRepository by required { playerRepository } companion object { const val WIDGET_HABIT_LIST_ACTION = "mypoli.android.intent.actions.WIDGET_HABIT_LIST_ACTION" const val HABIT_ACTION_EXTRA_KEY = "habit_action" const val HABIT_ACTION_COMPLETE = 1 const val HABIT_ACTION_UNDO_COMPLETE = 2 } override fun onReceive(context: Context, intent: Intent) { if (WIDGET_HABIT_LIST_ACTION == intent.action) { val habitId = intent.getStringExtra(Constants.HABIT_ID_EXTRA_KEY) val habitAction = intent.getIntExtra(HABIT_ACTION_EXTRA_KEY, 0) if (habitAction == HABIT_ACTION_COMPLETE) { onCompleteHabit(context, habitId) } else if (habitAction == HABIT_ACTION_UNDO_COMPLETE) { onUndoCompleteHabit(context, habitId) } else throw IllegalArgumentException("Unknown habit widget habit list action $habitAction") } super.onReceive(context, intent) } private fun onCompleteHabit(context: Context, habitId: String) { val i = Intent(context, CompleteHabitReceiver::class.java) i.putExtra(Constants.HABIT_ID_EXTRA_KEY, habitId) context.sendBroadcast(i) } private fun onUndoCompleteHabit(context: Context, habitId: String) { val i = Intent(context, UndoCompleteHabitReceiver::class.java) i.putExtra(Constants.HABIT_ID_EXTRA_KEY, habitId) context.sendBroadcast(i) } override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { inject(MyPoliApp.backgroundModule(context)) appWidgetIds.forEach { GlobalScope.launch(Dispatchers.IO) { val player = playerRepository.find() withContext(Dispatchers.Main) { val rv = RemoteViews(context.packageName, R.layout.widget_habits) if (player == null) { showEmptyView(rv) } else if (!player.isMember) { showNoPowerUp(rv, context) } else if(player.isDead) { showDeadView(rv, context) } else { showHabitList(rv, context, it) appWidgetManager.notifyAppWidgetViewDataChanged(it, R.id.widgetHabitList) } appWidgetManager.updateAppWidget(it, rv) super.onUpdate(context, appWidgetManager, appWidgetIds) } } } } private fun showHabitList( rv: RemoteViews, context: Context, widgetId: Int ) { rv.setViewVisibility(R.id.habitWidgetLockedContainer, View.GONE) rv.setRemoteAdapter( R.id.widgetHabitList, createHabitListIntent(context, widgetId) ) rv.setPendingIntentTemplate( R.id.widgetHabitList, createHabitClickIntent(context, widgetId) ) rv.setEmptyView(R.id.widgetHabitList, R.id.widgetHabitEmpty) } private fun showDeadView(rv: RemoteViews, context: Context) { rv.setViewVisibility(R.id.habitWidgetPlayerDiedContainer, View.VISIBLE) rv.setViewVisibility(R.id.habitWidgetLockedContainer, View.GONE) rv.setViewVisibility(R.id.widgetHabitEmpty, View.GONE) rv.setViewVisibility(R.id.widgetHabitList, View.GONE) rv.setOnClickPendingIntent( R.id.widgetHabitRevive, createStartAppIntent(context) ) } private fun showNoPowerUp(rv: RemoteViews, context: Context) { rv.setViewVisibility(R.id.habitWidgetLockedContainer, View.VISIBLE) rv.setViewVisibility(R.id.widgetHabitEmpty, View.GONE) rv.setViewVisibility(R.id.widgetHabitList, View.GONE) rv.setOnClickPendingIntent( R.id.widgetHabitUnlock, createShowBuyPowerUpIntent(context) ) } private fun showEmptyView(rv: RemoteViews) { rv.setViewVisibility(R.id.habitWidgetLockedContainer, View.GONE) rv.setViewVisibility(R.id.widgetHabitEmpty, View.VISIBLE) rv.setViewVisibility(R.id.widgetHabitList, View.GONE) } private fun createHabitClickIntent(context: Context, widgetId: Int): PendingIntent { val intent = Intent(context, HabitWidgetProvider::class.java) intent.action = HabitWidgetProvider.WIDGET_HABIT_LIST_ACTION intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId) return PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ) } private fun createShowBuyPowerUpIntent(context: Context) = IntentUtil.getActivityPendingIntent( context, IntentUtil.showBuyPowerUp(context, PowerUp.Type.HABIT_WIDGET) ) private fun createHabitListIntent(context: Context, widgetId: Int) = Intent(context, HabitWidgetService::class.java).apply { putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId) } private fun createStartAppIntent(context: Context) = IntentUtil.getActivityPendingIntent( context, IntentUtil.startApp(context) ) }
gpl-3.0
a72eeaa550877ef3b4ed7bd904a2d682
35.376404
104
0.667748
4.667628
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/DebuggerFieldSyntheticScopeProvider.kt
2
10106
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.evaluate import org.jetbrains.kotlin.codegen.state.GenerationState import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.PropertyGetterDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.PropertySetterDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.core.util.CodeFragmentUtils import org.jetbrains.kotlin.incremental.KotlinLookupLocation import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.load.java.components.JavaSourceElementFactoryImpl import org.jetbrains.kotlin.load.java.components.TypeUsage import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaClassDescriptor import org.jetbrains.kotlin.load.java.lazy.types.toAttributes import org.jetbrains.kotlin.load.java.structure.classId import org.jetbrains.kotlin.load.kotlin.internalName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtCodeFragment import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.DescriptorFactory import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.SyntheticScope import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.synthetic.JavaSyntheticPropertiesScope import org.jetbrains.kotlin.synthetic.SyntheticScopeProviderExtension import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections import org.jetbrains.org.objectweb.asm.Type class DebuggerFieldSyntheticScopeProvider : SyntheticScopeProviderExtension { override fun getScopes( moduleDescriptor: ModuleDescriptor, javaSyntheticPropertiesScope: JavaSyntheticPropertiesScope ): List<SyntheticScope> { return listOf<SyntheticScope>(DebuggerFieldSyntheticScope(javaSyntheticPropertiesScope)) } } class DebuggerFieldSyntheticScope(private val javaSyntheticPropertiesScope: JavaSyntheticPropertiesScope) : SyntheticScope.Default() { private val javaSourceElementFactory = JavaSourceElementFactoryImpl() override fun getSyntheticExtensionProperties( receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation ): Collection<PropertyDescriptor> { return getSyntheticExtensionProperties(receiverTypes, location).filter { it.name == name } } override fun getSyntheticExtensionProperties( receiverTypes: Collection<KotlinType>, location: LookupLocation ): Collection<PropertyDescriptor> { if (!isInEvaluator(location)) { return emptyList() } val result = mutableListOf<PropertyDescriptor>() for (type in receiverTypes) { val clazz = type.constructor.declarationDescriptor as? ClassDescriptor ?: continue result += getSyntheticPropertiesForClass(clazz) } return result } private fun isInEvaluator(location: LookupLocation): Boolean { val element = (location as? KotlinLookupLocation)?.element ?: return false val containingFile = element.containingFile?.takeIf { it.isValid } as? KtFile ?: return false val platform = containingFile.platform if (!platform.isJvm() && !platform.isCommon()) { return false } return containingFile is KtCodeFragment && containingFile.getCopyableUserData(CodeFragmentUtils.RUNTIME_TYPE_EVALUATOR) != null } private fun getSyntheticPropertiesForClass(clazz: ClassDescriptor): Collection<PropertyDescriptor> { val collected = mutableMapOf<Name, PropertyDescriptor>() val syntheticPropertyNames = javaSyntheticPropertiesScope .getSyntheticExtensionProperties(listOf(clazz.defaultType), NoLookupLocation.FROM_SYNTHETIC_SCOPE) .mapTo(mutableSetOf()) { it.name } collectPropertiesWithParent(clazz, syntheticPropertyNames, collected) return collected.values } private tailrec fun collectPropertiesWithParent( clazz: ClassDescriptor, syntheticNames: Set<Name>, consumer: MutableMap<Name, PropertyDescriptor> ) { when (clazz) { is LazyJavaClassDescriptor -> collectJavaProperties(clazz, syntheticNames, consumer) is JavaClassDescriptor -> error("Unsupported Java class type") else -> collectKotlinProperties(clazz, consumer) } val superClass = clazz.getSuperClassNotAny() if (superClass != null) { collectPropertiesWithParent(superClass, syntheticNames, consumer) } } private fun collectKotlinProperties(clazz: ClassDescriptor, consumer: MutableMap<Name, PropertyDescriptor>) { for (descriptor in clazz.unsubstitutedMemberScope.getDescriptorsFiltered(DescriptorKindFilter.VARIABLES)) { val propertyDescriptor = descriptor as? PropertyDescriptor ?: continue val name = propertyDescriptor.name if (propertyDescriptor.backingField == null || name in consumer) continue val type = propertyDescriptor.type val sourceElement = propertyDescriptor.source val isVar = propertyDescriptor.isVar consumer[name] = createSyntheticPropertyDescriptor( clazz, type, name, isVar, KotlinDebuggerEvaluationBundle.message("backing.field"), sourceElement ) { state -> state.typeMapper.mapType(clazz.defaultType) } } } private fun collectJavaProperties( clazz: LazyJavaClassDescriptor, syntheticNames: Set<Name>, consumer: MutableMap<Name, PropertyDescriptor> ) { val javaClass = clazz.jClass for (field in javaClass.fields) { val fieldName = field.name if (field.isEnumEntry || field.isStatic || fieldName in consumer || fieldName !in syntheticNames) continue val ownerClassName = javaClass.classId?.internalName ?: continue val typeResolver = clazz.outerContext.typeResolver val type = typeResolver.transformJavaType(field.type, TypeUsage.COMMON.toAttributes()).replaceArgumentsWithStarProjections() val sourceElement = javaSourceElementFactory.source(field) val isVar = !field.isFinal consumer[fieldName] = createSyntheticPropertyDescriptor( clazz, type, fieldName, isVar, KotlinDebuggerEvaluationBundle.message("java.field"), sourceElement ) { Type.getObjectType(ownerClassName) } } } private fun createSyntheticPropertyDescriptor( clazz: ClassDescriptor, type: KotlinType, fieldName: Name, isVar: Boolean, description: String, sourceElement: SourceElement, ownerType: (GenerationState) -> Type ): PropertyDescriptor { val propertyDescriptor = DebuggerFieldPropertyDescriptor(clazz, fieldName.asString(), description, ownerType, isVar) val extensionReceiverParameter = DescriptorFactory.createExtensionReceiverParameterForCallable( propertyDescriptor, clazz.defaultType.replaceArgumentsWithStarProjections(), Annotations.EMPTY ) propertyDescriptor.setType(type, emptyList(), null, extensionReceiverParameter, emptyList()) val getter = PropertyGetterDescriptorImpl( propertyDescriptor, Annotations.EMPTY, Modality.FINAL, DescriptorVisibilities.PUBLIC, false, false, false, CallableMemberDescriptor.Kind.SYNTHESIZED, null, sourceElement ).apply { initialize(type) } val setter = if (isVar) PropertySetterDescriptorImpl( propertyDescriptor, Annotations.EMPTY, Modality.FINAL, DescriptorVisibilities.PUBLIC, false, false, false, CallableMemberDescriptor.Kind.SYNTHESIZED, null, sourceElement ).apply { val setterValueParameter = ValueParameterDescriptorImpl( this, null, 0, Annotations.EMPTY, Name.identifier("value"), type, declaresDefaultValue = false, isCrossinline = false, isNoinline = false, varargElementType = null, source = sourceElement ) initialize(setterValueParameter) } else null propertyDescriptor.initialize(getter, setter) return propertyDescriptor } } internal class DebuggerFieldPropertyDescriptor( containingDeclaration: DeclarationDescriptor, val fieldName: String, val description: String, val ownerType: (GenerationState) -> Type, isVar: Boolean ) : PropertyDescriptorImpl( containingDeclaration, null, Annotations.EMPTY, Modality.FINAL, DescriptorVisibilities.PUBLIC, /*isVar = */isVar, Name.identifier(fieldName + "_field"), CallableMemberDescriptor.Kind.SYNTHESIZED, SourceElement.NO_SOURCE, /*lateInit = */false, /*isConst = */false, /*isExpect = */false, /*isActual = */false, /*isExternal = */false, /*isDelegated = */false ) { override val getter: PropertyGetterDescriptorImpl? get() = null }
apache-2.0
25f6138f1fcdc87a5960da6f8fe08820
40.93361
158
0.713833
5.459751
false
false
false
false
GunoH/intellij-community
plugins/refactoring-detector/src/com/intellij/refactoring/detector/semantic/diff/SemanticDiffBlocks.kt
3
3565
package com.intellij.refactoring.detector.semantic.diff import com.intellij.diff.FrameDiffTool.DiffViewer import com.intellij.diff.tools.combined.* import com.intellij.diff.tools.util.base.DiffViewerBase import com.intellij.icons.AllIcons import com.intellij.ide.actions.CloseTabToolbarAction import com.intellij.openapi.actionSystem.* import com.intellij.openapi.ui.VerticalFlowLayout import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.ui.IdeBorderFactory import com.intellij.ui.SideBorder import com.intellij.ui.SimpleColoredComponent import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import javax.swing.JPanel internal class SemanticDiffFragmentBlockFactory : CombinedDiffBlockFactory<CombinedPathBlockId> { override fun isApplicable(content: CombinedDiffBlockContent): Boolean { val viewer = (content.viewer as? DiffViewerBase) ?: return false return viewer.request is SemanticFragmentDiffRequest } override fun createBlock(content: CombinedDiffBlockContent, withBorder: Boolean): CombinedDiffBlock<CombinedPathBlockId> { val request = (content.viewer as DiffViewerBase).request as SemanticFragmentDiffRequest return SemanticCombinedDiffBlock(request.title, content, request.closeAction) } } internal class SemanticCombinedDiffBlock(val title: String, val content: CombinedDiffBlockContent, onCloseAction: () -> Unit) : JPanel(VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, true)), CombinedDiffBlock<CombinedPathBlockId>, CombinedDiffGlobalBlockHeaderProvider { override val id get() = content.blockId as CombinedPathBlockId override val globalHeader = SemanticCombinedDiffHeader(title, content.viewer) { onCloseAction(); Disposer.dispose(this) } override val header = SemanticCombinedDiffHeader(title, content.viewer) { onCloseAction(); Disposer.dispose(this) } override val body = content.viewer.component init { add(header) add(body) } override val component = this override fun dispose() {} } internal class SemanticCombinedDiffHeader(title: @NlsSafe String, viewer: DiffViewer, closeAction: () -> Unit) : BorderLayoutPanel() { init { background = UIUtil.getListBackground() border = IdeBorderFactory.createBorder(SideBorder.TOP) addToCenter( SimpleColoredComponent().append(title) .apply { border = JBEmptyBorder(UIUtil.PANEL_SMALL_INSETS) font = JBUI.Fonts.label(16f) }) val rightToolbarGroup = DefaultActionGroup() val myCloseAction = MyCloseAction(closeAction) viewer.editors.forEach { myCloseAction.registerCustomShortcutSet(it.component, null) } rightToolbarGroup.add(myCloseAction) val toolbar = ActionManager.getInstance().createActionToolbar("CombinedDiffHeaderRightToolbar", rightToolbarGroup, true) toolbar.targetComponent = this toolbar.layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY toolbar.component.isOpaque = false addToRight(toolbar.component) } private class MyCloseAction(private val closeAction: () -> Unit) : CloseTabToolbarAction(), RightAlignedToolbarAction { override fun getActionUpdateThread() = ActionUpdateThread.EDT override fun update(e: AnActionEvent) { super.update(e) e.presentation.icon = AllIcons.Actions.CloseDarkGrey e.presentation.isEnabledAndVisible = true } override fun actionPerformed(e: AnActionEvent) { closeAction() } } }
apache-2.0
514cf3e088981c37a70fb41086e7dc06
38.611111
134
0.780926
4.558824
false
false
false
false