repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
sandrozbinden/hackerrank
src/algorithm/Quicksort1Partition.java
/* ============================================================================ * Copyright (c) 2015 Imagic Bildverarbeitung AG, CH-8152 Glattbrugg. * All rights reserved. * * http://www.imagic.ch/ * ============================================================================ */ package algorithm; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * * @version $Revision$ * @version $Date$ * @author $Author$ * @owner <NAME> */ public class Quicksort1Partition { public static class Solution { public static void quicksortPartition(int[] a) { int pivot = a[0]; List<Integer> leftPartion = new ArrayList<>(); List<Integer> rightPartion = new ArrayList<>(); for (int i = 1; i < a.length; i++) { if (a[i] > pivot) { rightPartion.add(a[i]); } else { leftPartion.add(a[i]); } } List<Integer> result = new ArrayList<>(); result.addAll(leftPartion); result.add(pivot); result.addAll(rightPartion); printArray(result); } static void printArray(List<Integer> ar) { for (int n : ar) { System.out.print(n + " "); } } public static void main(String[] args) { try (Scanner in = new Scanner(System.in)) { int n = in.nextInt(); int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = in.nextInt(); } quicksortPartition(ar); } } } public static void main(String[] args) { Solution.main(null); } }
build-test-conflicts/dynjs
src/main/java/org/dynjs/ir/Builder.java
<reponame>build-test-conflicts/dynjs /* * Copyright 2014 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dynjs.ir; import org.dynjs.compiler.CompilationContext; import org.dynjs.ir.instructions.Add; import org.dynjs.ir.instructions.BEQ; import org.dynjs.ir.instructions.Call; import org.dynjs.ir.instructions.Constructor; import org.dynjs.ir.instructions.Copy; import org.dynjs.ir.instructions.DefineFunction; import org.dynjs.ir.instructions.Instanceof; import org.dynjs.ir.instructions.Jump; import org.dynjs.ir.instructions.LE; import org.dynjs.ir.instructions.LT; import org.dynjs.ir.instructions.LabelInstr; import org.dynjs.ir.instructions.Mul; import org.dynjs.ir.instructions.PropertyLookup; import org.dynjs.ir.instructions.Raise; import org.dynjs.ir.instructions.ReceiveFunctionParameter; import org.dynjs.ir.instructions.Return; import org.dynjs.ir.instructions.Sub; import org.dynjs.ir.operands.BooleanLiteral; import org.dynjs.ir.operands.DynamicVariable; import org.dynjs.ir.operands.FloatNumber; import org.dynjs.ir.operands.IntegerNumber; import org.dynjs.ir.operands.Label; import org.dynjs.ir.operands.Null; import org.dynjs.ir.operands.StringLiteral; import org.dynjs.ir.operands.TemporaryVariable; import org.dynjs.ir.operands.This; import org.dynjs.ir.operands.Undefined; import org.dynjs.ir.operands.Variable; import org.dynjs.parser.CodeVisitor; import org.dynjs.parser.Statement; import org.dynjs.parser.ast.AdditiveExpression; import org.dynjs.parser.ast.ArrayLiteralExpression; import org.dynjs.parser.ast.AssignmentExpression; import org.dynjs.parser.ast.BitwiseExpression; import org.dynjs.parser.ast.BitwiseInversionOperatorExpression; import org.dynjs.parser.ast.BlockStatement; import org.dynjs.parser.ast.BooleanLiteralExpression; import org.dynjs.parser.ast.BracketExpression; import org.dynjs.parser.ast.BreakStatement; import org.dynjs.parser.ast.CaseClause; import org.dynjs.parser.ast.CatchClause; import org.dynjs.parser.ast.CommaOperator; import org.dynjs.parser.ast.CompoundAssignmentExpression; import org.dynjs.parser.ast.ContinueStatement; import org.dynjs.parser.ast.DefaultCaseClause; import org.dynjs.parser.ast.DeleteOpExpression; import org.dynjs.parser.ast.DoWhileStatement; import org.dynjs.parser.ast.DotExpression; import org.dynjs.parser.ast.EmptyStatement; import org.dynjs.parser.ast.EqualityOperatorExpression; import org.dynjs.parser.ast.Expression; import org.dynjs.parser.ast.ExpressionStatement; import org.dynjs.parser.ast.FloatingNumberExpression; import org.dynjs.parser.ast.ForExprInStatement; import org.dynjs.parser.ast.ForExprOfStatement; import org.dynjs.parser.ast.ForExprStatement; import org.dynjs.parser.ast.ForVarDeclInStatement; import org.dynjs.parser.ast.ForVarDeclOfStatement; import org.dynjs.parser.ast.ForVarDeclStatement; import org.dynjs.parser.ast.FunctionCallExpression; import org.dynjs.parser.ast.FunctionDeclaration; import org.dynjs.parser.ast.FunctionDescriptor; import org.dynjs.parser.ast.FunctionExpression; import org.dynjs.parser.ast.IdentifierReferenceExpression; import org.dynjs.parser.ast.IfStatement; import org.dynjs.parser.ast.IllegalFunctionMemberExpression; import org.dynjs.parser.ast.InOperatorExpression; import org.dynjs.parser.ast.InstanceofExpression; import org.dynjs.parser.ast.IntegerNumberExpression; import org.dynjs.parser.ast.LogicalExpression; import org.dynjs.parser.ast.LogicalNotOperatorExpression; import org.dynjs.parser.ast.MultiplicativeExpression; import org.dynjs.parser.ast.NamedValue; import org.dynjs.parser.ast.NewOperatorExpression; import org.dynjs.parser.ast.NullLiteralExpression; import org.dynjs.parser.ast.ObjectLiteralExpression; import org.dynjs.parser.ast.OfOperatorExpression; import org.dynjs.parser.ast.PostOpExpression; import org.dynjs.parser.ast.PreOpExpression; import org.dynjs.parser.ast.ProgramTree; import org.dynjs.parser.ast.PropertyGet; import org.dynjs.parser.ast.PropertySet; import org.dynjs.parser.ast.RegexpLiteralExpression; import org.dynjs.parser.ast.RelationalExpression; import org.dynjs.parser.ast.ReturnStatement; import org.dynjs.parser.ast.StrictEqualityOperatorExpression; import org.dynjs.parser.ast.StringLiteralExpression; import org.dynjs.parser.ast.SwitchStatement; import org.dynjs.parser.ast.TernaryExpression; import org.dynjs.parser.ast.ThisExpression; import org.dynjs.parser.ast.ThrowStatement; import org.dynjs.parser.ast.TryStatement; import org.dynjs.parser.ast.TypeOfOpExpression; import org.dynjs.parser.ast.UnaryMinusExpression; import org.dynjs.parser.ast.UnaryPlusExpression; import org.dynjs.parser.ast.VariableDeclaration; import org.dynjs.parser.ast.VariableStatement; import org.dynjs.parser.ast.VoidOperatorExpression; import org.dynjs.parser.ast.WhileStatement; import org.dynjs.parser.ast.WithStatement; import org.dynjs.runtime.JSProgram; import java.util.List; public class Builder implements CodeVisitor { private static Builder BUILDER = new Builder(); public static JSProgram compile(CompilationContext compilationContext, ProgramTree program) { Scope scope = new Scope(null, program.getPosition().getFileName(), program.isStrict()); program.accept(scope, BUILDER, program.isStrict()); // FIXME: Add processing stage here/somewhere to do instr process/cfg/passes. return new IRJSProgram(program.getSource(), compilationContext.getBlockManager(), scope); } @Override public Object visit(Object context, AdditiveExpression expr, boolean strict) { Scope scope = (Scope) context; Operand lhs = (Operand) expr.getLhs().accept(context, this, strict); Operand rhs = (Operand) expr.getRhs().accept(context, this, strict); boolean subtract = expr.getOp().equals("-"); Operand value; // FIXME: Review numeric representation of JS to figure out overflow etc.. if (lhs instanceof IntegerNumber) { if (rhs instanceof IntegerNumber) { if (subtract) { value = new IntegerNumber(((IntegerNumber) lhs).getValue() - ((IntegerNumber) rhs).getValue()); } else { value = new IntegerNumber(((IntegerNumber) lhs).getValue() + ((IntegerNumber) rhs).getValue()); } } else if (rhs instanceof FloatNumber) { if (subtract) { value = new FloatNumber(((FloatNumber) rhs).getValue() - ((IntegerNumber) lhs).getValue()); } else { value = new FloatNumber(((FloatNumber) rhs).getValue() + ((IntegerNumber) lhs).getValue()); } } else { Variable tmp = scope.createTemporaryVariable(); if (subtract) { scope.addInstruction(new Sub(tmp, lhs, rhs)); } else { scope.addInstruction(new Add(tmp, lhs, rhs)); } value = tmp; } } else { Variable tmp = scope.createTemporaryVariable(); if (subtract) { scope.addInstruction(new Sub(tmp, lhs, rhs)); } else { scope.addInstruction(new Add(tmp, lhs, rhs)); } value = tmp; } return value; } @Override public Object visit(Object context, BitwiseExpression bitwiseExpression, boolean strict) { return unimplemented(context, bitwiseExpression, strict); } @Override public Object visit(Object context, ArrayLiteralExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, AssignmentExpression expr, boolean strict) { Scope scope = (Scope) context; Variable lhs = (Variable) expr.getLhs().accept(context, this, strict); Operand rhs = (Operand) expr.getRhs().accept(context, this, strict); scope.addInstruction(new Copy(lhs, rhs)); return rhs; } @Override public Object visit(Object context, BitwiseInversionOperatorExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, BlockStatement block, boolean strict) { Scope scope = (Scope) context; buildDeclaredFunctions(scope, block.getFunctionDeclarations()); // FIXME: How can we use what the parser provides to good effect? Operand value = Undefined.UNDEFINED; for (Statement statement: block.getBlockContent()) { value = (Operand) statement.accept(context, this, strict); } return value; } @Override public Object visit(Object context, BooleanLiteralExpression expr, boolean strict) { return expr.getValue() ? BooleanLiteral.TRUE : BooleanLiteral.FALSE; } @Override public Object visit(Object context, BreakStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, CaseClause clause, boolean strict) { return unimplemented(context, clause, strict); } @Override public Object visit(Object context, DefaultCaseClause clause, boolean strict) { return unimplemented(context, clause, strict); } @Override public Object visit(Object context, CatchClause clause, boolean strict) { return unimplemented(context, clause, strict); } @Override public Object visit(Object context, CompoundAssignmentExpression expr, boolean strict) { Scope scope = (Scope) context; // FIXME: If name of lhs is 'eval' or 'assignments' then generate a raise error instance of doing copy. // This is a little out of order with basicinterp where we check this before eval'ing value below. // Of s += 1 this is (s + 1) Operand value = (Operand) expr.getRootExpr().accept(context, this, strict); Variable lhs = (Variable) expr.getRootExpr().getLhs().accept(context, this, strict); scope.addInstruction(new Copy(lhs, value)); return value; } @Override public Object visit(Object context, ContinueStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, DeleteOpExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, DoWhileStatement statement, boolean strict) { Scope scope = (Scope) context; final Label startLabel = scope.getNewLabel(); final Label doneLabel = scope.getNewLabel(); scope.addInstruction(new LabelInstr(startLabel)); // BODY statement.getBlock().accept(context, this, strict); // TEST scope.addInstruction(new BEQ((Operand) statement.getTest().accept(context, this, strict), BooleanLiteral.FALSE, doneLabel)); scope.addInstruction(new Jump(startLabel)); // END scope.addInstruction(new LabelInstr(doneLabel)); return Undefined.UNDEFINED; } @Override public Object visit(Object context, EmptyStatement statement, boolean strict) { return Undefined.UNDEFINED; } @Override public Object visit(Object context, EqualityOperatorExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, CommaOperator expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, ExpressionStatement statement, boolean strict) { return acceptOrUndefined(context, statement.getExpr(), strict); } @Override public Object visit(Object context, FloatingNumberExpression expr, boolean strict) { return new FloatNumber(expr.getValue()); } @Override public Object visit(Object context, ForExprInStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, ForExprOfStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, ForExprStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, ForVarDeclInStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, ForVarDeclOfStatement statement, boolean strict) { return unimplemented(context, statement, strict); } // FIXME: flow control may or may not be an issue but old runtime handles it explicitly after accept. @Override public Object visit(Object context, ForVarDeclStatement statement, boolean strict) { Scope scope = (Scope) context; List<VariableDeclaration> decls = statement.getDeclarationList(); for (VariableDeclaration each : decls) { each.accept(context, this, strict); } final Label startLabel = scope.getNewLabel(); final Label doneLabel = scope.getNewLabel(); scope.addInstruction(new LabelInstr(startLabel)); // TEST scope.addInstruction(new BEQ((Operand) statement.getTest().accept(context, this, strict), BooleanLiteral.FALSE, doneLabel)); // BODY statement.getBlock().accept(context, this, strict); // INCREMENT statement.getIncrement().accept(context, this, strict); scope.addInstruction(new Jump(startLabel)); // END scope.addInstruction(new LabelInstr(doneLabel)); return Undefined.UNDEFINED; } @Override public Object visit(Object context, FunctionCallExpression expr, boolean strict) { Scope scope = (Scope) context; Variable result = scope.createTemporaryVariable(); List<Expression> argumentExpressions = expr.getArgumentExpressions(); int argsLength = argumentExpressions.size(); Operand[] args = new Operand[argsLength]; for (int i = 0; i < argsLength; i++) { args[i] = (Operand) acceptOrUndefined(context, argumentExpressions.get(i), strict); } Expression memberExpression = expr.getMemberExpression(); // We can statically replace an attempt at calls to illegal member types with an exception // raise. This should eliminate needing to actually check this within the runtime. if (memberExpression instanceof IllegalFunctionMemberExpression) { scope.addInstruction(new Raise("TypeError", memberExpression + " is not callable")); return Undefined.UNDEFINED; } final Operand name = (Operand) acceptOrUndefined(context, expr.getMemberExpression(), strict); scope.addInstruction(new Call(result, This.THIS, name, args)); return result; } @Override public Object visit(Object context, FunctionDeclaration statement, boolean strict) { // We need to be able to define function decl before any code in the block // they live in is executed so when we see them inline while building instructions // we just ignore them. return Undefined.UNDEFINED; } @Override public Object visit(Object context, FunctionExpression expr, boolean strict) { Scope scope = (Scope) context; FunctionDescriptor descriptor = expr.getDescriptor(); Variable result = scope.createTemporaryVariable(); String[] parameterNames = descriptor.getFormalParameterNames(); FunctionScope functionScope = new FunctionScope(scope, descriptor.getPosition().getFileName(), descriptor.isStrict(), parameterNames, null); // 1. receive arguments are first before any mandatory items like nested functions // Recieve all declared parameters int paramsLength = parameterNames.length; for (int i = 0; i < paramsLength; i++) { functionScope.addInstruction(new ReceiveFunctionParameter(functionScope.acquireLocalVariable(parameterNames[i]), i)); } // 2. named functions must be visible before any code in the block executed so right after parms buildDeclaredFunctions(functionScope, descriptor.getBlock().getFunctionDeclarations()); // 3. the actual block code. descriptor.getBlock().accept(functionScope, this, strict); scope.addInstruction(new DefineFunction(result, functionScope)); return result; } private void buildDeclaredFunctions(Scope parentScope, List<FunctionDeclaration> functionDeclarations) { // ENEBO: reusing the temp var here since it is not actually used. Variable result = parentScope.createTemporaryVariable(); for (FunctionDeclaration declaration: functionDeclarations) { String[] parameterNames = declaration.getFormalParameters(); FunctionScope functionScope = new FunctionScope(parentScope, declaration.getPosition().getFileName(), declaration.isStrict(), declaration.getFormalParameters(), declaration.getIdentifier()); // 1. receive arguments are first before any mandatory items like nested functions // Recieve all declared parameters int paramsLength = parameterNames.length; for (int i = 0; i < paramsLength; i++) { functionScope.addInstruction(new ReceiveFunctionParameter(functionScope.acquireLocalVariable(parameterNames[i]), i)); } // 2. named functions must be visible before any code in the block executed so right after parms buildDeclaredFunctions(functionScope, declaration.getBlock().getFunctionDeclarations()); // 3. the actual block code. declaration.getBlock().accept(functionScope, this, declaration.isStrict()); parentScope.addInstruction(new DefineFunction(result, functionScope)); } } @Override public Object visit(Object context, IdentifierReferenceExpression expr, boolean strict) { Scope scope = (Scope) context; Variable variable = scope.findVariable(expr.getIdentifier()); // FIXME: Should this error out in strict mode? if (variable == null) { return new DynamicVariable(expr.getIdentifier()); } return variable; } @Override public Object visit(Object context, IfStatement ifNode, boolean strict) { Scope scope = (Scope) context; Label elseLabel = scope.getNewLabel(); Label doneLabel = scope.getNewLabel(); // IF scope.addInstruction(new BEQ((Operand) ifNode.getTest().accept(context, this, strict), BooleanLiteral.FALSE, elseLabel)); // THEN ifNode.getThenBlock().accept(context, this, strict); scope.addInstruction(new Jump(doneLabel)); // ELSE scope.addInstruction(new LabelInstr(elseLabel)); if (ifNode.getElseBlock() != null) { ifNode.getElseBlock().accept(context, this, strict); } // END scope.addInstruction(new LabelInstr(doneLabel)); return Undefined.UNDEFINED; } @Override public Object visit(Object context, InOperatorExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, OfOperatorExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, InstanceofExpression expr, boolean strict) { Scope scope = (Scope) context; Variable result = scope.createTemporaryVariable(); Operand lhs = (Variable) expr.getLhs().accept(context, this, strict); Operand rhs = (Operand) expr.getRhs().accept(context, this, strict); scope.addInstruction(new Instanceof(result, lhs, rhs)); return result; } @Override public Object visit(Object context, IntegerNumberExpression expr, boolean strict) { return new IntegerNumber(expr.getValue()); } @Override public Object visit(Object context, LogicalExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, LogicalNotOperatorExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, DotExpression expr, boolean strict) { Scope scope = (Scope) context; Variable result = scope.createTemporaryVariable(); Operand base = (Operand) expr.getLhs().accept(context, this, strict); scope.addInstruction(new PropertyLookup(result, base, expr.getIdentifier())); return result; } @Override public Object visit(Object context, BracketExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, MultiplicativeExpression expr, boolean strict) { Scope scope = (Scope) context; Operand lhs = (Operand) expr.getLhs().accept(context, this, strict); Operand rhs = (Operand) expr.getRhs().accept(context, this, strict); Operand value; // FIXME: Review numeric representation of JS to figure out overflow etc.. if (lhs instanceof IntegerNumber) { if (rhs instanceof IntegerNumber) { value = new IntegerNumber(((IntegerNumber) lhs).getValue() * ((IntegerNumber) rhs).getValue()); } else if (rhs instanceof FloatNumber) { value = new FloatNumber(((FloatNumber) rhs).getValue() * ((IntegerNumber) lhs).getValue()); } else { Variable tmp = scope.createTemporaryVariable(); scope.addInstruction(new Mul(tmp, lhs, rhs)); value = tmp; } } else { Variable tmp = scope.createTemporaryVariable(); scope.addInstruction(new Mul(tmp, lhs, rhs)); value = tmp; } return value; } @Override public Object visit(Object context, NewOperatorExpression expr, boolean strict) { Scope scope = (Scope) context; // We can statically replace an attempt at calls to illegal member types with an exception // raise. This should eliminate needing to actually check this within the runtime. if (expr.getExpr() instanceof IllegalFunctionMemberExpression) { scope.addInstruction(new Raise("TypeError", expr.getExpr() + " is not callable")); return Undefined.UNDEFINED; } Operand memberExpression = (Operand) expr.getExpr().accept(context, this, strict); Variable tmp = scope.createTemporaryVariable(); List<Expression> argumentExpressions = expr.getArgumentExpressions(); Operand args[] = new Operand[argumentExpressions.size()]; for (int i = 0; i < args.length; i++) { args[i] = (Operand) argumentExpressions.get(i).accept(context, this, strict); } scope.addInstruction(new Constructor(tmp, memberExpression, args)); return tmp; } @Override public Object visit(Object context, NullLiteralExpression expr, boolean strict) { return Null.NULL; } @Override public Object visit(Object context, ObjectLiteralExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, PostOpExpression expr, boolean strict) { Scope scope = (Scope) context; Variable tmp = scope.createTemporaryVariable(); Variable variable = (Variable) expr.getExpr().accept(context, this, strict); boolean subtract = expr.getOp().equals("-"); if (subtract) { scope.addInstruction(new Sub(tmp, variable, new IntegerNumber(1))); } else { scope.addInstruction(new Add(tmp, variable, new IntegerNumber(1))); } scope.addInstruction(new Copy(variable, tmp)); return variable; } @Override public Object visit(Object context, PreOpExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, PropertyGet propertyGet, boolean strict) { return unimplemented(context, propertyGet, strict); } @Override public Object visit(Object context, PropertySet propertySet, boolean strict) { return unimplemented(context, propertySet, strict); } @Override public Object visit(Object context, NamedValue namedValue, boolean strict) { return unimplemented(context, namedValue, strict); } @Override public Object visit(Object context, RegexpLiteralExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, RelationalExpression expr, boolean strict) { Scope scope = (Scope) context; Variable result = scope.createTemporaryVariable(); Operand lhsValue = (Operand) expr.getLhs().accept(context, this, strict); Operand rhsValue = (Operand) expr.getRhs().accept(context, this, strict); switch (expr.getOp()) { case "<": scope.addInstruction(new LT(result, lhsValue, rhsValue)); break; case ">": scope.addInstruction(new LT(result, rhsValue, lhsValue)); break; case "<=": scope.addInstruction(new LE(result, lhsValue, rhsValue)); break; case ">=": scope.addInstruction(new LE(result, rhsValue, lhsValue)); break; } return result; } @Override public Object visit(Object context, ReturnStatement statement, boolean strict) { Scope scope = (Scope) context; Operand returnValue = (Operand) acceptOrUndefined(context, statement.getExpr(), strict); scope.addInstruction(new Return(returnValue)); return returnValue; } @Override public Object visit(Object context, StrictEqualityOperatorExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, StringLiteralExpression expr, boolean strict) { return new StringLiteral(expr.getLiteral()); } @Override public Object visit(Object context, SwitchStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, TernaryExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, ThisExpression expr, boolean strict) { return This.THIS; } @Override public Object visit(Object context, ThrowStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, TryStatement statement, boolean strict) { return unimplemented(context, statement, strict); } @Override public Object visit(Object context, TypeOfOpExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, UnaryMinusExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, UnaryPlusExpression expr, boolean strict) { return unimplemented(context, expr, strict); } @Override public Object visit(Object context, VariableDeclaration expr, boolean strict) { Scope scope = (Scope) context; Variable variable = scope.acquireLocalVariable(expr.getIdentifier()); Operand value = (Operand) acceptOrUndefined(context, expr.getExpr(), strict); scope.addInstruction(new Copy(variable, value)); return value; } @Override public Object visit(Object context, VariableStatement statement, boolean strict) { for (VariableDeclaration decl: statement.getVariableDeclarations()) { decl.accept(context, this, strict); } return Undefined.UNDEFINED; } @Override public Object visit(Object context, VoidOperatorExpression expr, boolean strict) { // 11.4.2 (GetValue must be called even if we never use the value) expr.getExpr().accept(context, this, strict); return Undefined.UNDEFINED; } @Override public Object visit(Object context, WhileStatement statement, boolean strict) { Scope scope = (Scope) context; final Label startLabel = scope.getNewLabel(); final Label doneLabel = scope.getNewLabel(); scope.addInstruction(new LabelInstr(startLabel)); // TEST scope.addInstruction(new BEQ((Operand) statement.getTest().accept(context, this, strict), BooleanLiteral.FALSE, doneLabel)); // BODY statement.getBlock().accept(context, this, strict); scope.addInstruction(new Jump(startLabel)); // END scope.addInstruction(new LabelInstr(doneLabel)); return Undefined.UNDEFINED; } @Override public Object visit(Object context, WithStatement statement, boolean strict) { return unimplemented(context, statement, strict); } private Object unimplemented(Object context, Object expr, boolean strict) { throw new RuntimeException("EXPR: '" + expr + "' is unimplemented."); } private Object acceptOrUndefined(Object context, Expression expr, boolean strict) { return expr != null ? expr.accept(context, this, strict) : Undefined.UNDEFINED; } private Variable copyAndReturnValue(Scope scope, Operand value) { Variable variable = scope.createTemporaryVariable(); scope.addInstruction(new Copy(variable, value)); return variable; } private Variable getValueInTemporaryVariable(Scope scope, Operand value) { if (value != null && value instanceof TemporaryVariable) return (Variable) value; return copyAndReturnValue(scope, value); } }
ISCDtoolbox/FaciLe
projects/morphing/src/solve.c
<reponame>ISCDtoolbox/FaciLe #include "sparse.h" #define CS_EPSD 1.0e-30 #define CS_EPSD2 1.0e-200 #define CS_KRYL 100 #define CS_KRY1 CS_KRYL*(CS_KRYL+3) / 2 #define CS_OMEGA 1.2 /* >1 to speed up convergence of slow-converging process */ /* SSOR preconditioner to solve (L*d*L^t)x = b * input: L=A^t lower triangular, x,b vectors * output: x modified */ int csrSSOR(pCsr A,pCsr L,double *x,double *b) { double *dia,sum,dd,omega; int i,j; omega = CS_OMEGA; dia = (double*)calloc(L->nr,sizeof(double)); assert(dia); for (i=0; i<L->nr; i++) { sum = 0.0; for (j=L->row[i]; j<L->row[i+1]-1; j++) sum += L->val[j] * x[L->col[j]]; dia[i] = L->val[j]; /* optim: diag term is in last position */ x[i] = (b[i] - sum) * omega / dia[i]; } /* diagonal terms */ dd = (2.0 - omega) / omega; for (i=0; i<L->nr; i++) x[i] = x[i] * dd * dia[i]; for (i=A->nr-1; i>=0; i--) { sum = 0.0; for (j=A->row[i]+1; j<A->row[i+1]; j++) sum += A->val[j] * x[A->col[j]]; x[i] = (x[i] - sum) * omega / dia[i]; } free(dia); return(1); } /* solve Ax=b, using gradient. Return code: >0 upon completion, <0 no convergence 0 memory problem -1 ill conditioned matrix -2 max it reached */ int csrGradient(pCsr A,double *x,double *b,double *er,int *ni) { double *y,*ay,dp,rm,rmp,tol,alpha,err; int i,n,it,ier,nit; if ( !x || !b ) return(0); n = A->nr; y = (double*)calloc(n,sizeof(double)); if ( !y ) return(0); /* compute r0 = b - A x0 */ memcpy(y,b,n*sizeof(double)); if ( !csrAxpy(A,x,y,NULL,-1.,1.) ) { free(y); return(0); } err = *er; nit = *ni; it = 0; ier = 1; rm = 0.0; for (i=0; i<n; i++) rm += y[i] * y[i]; rmp = rm; if ( fabs(rmp) < CS_EPSD2 ) { free(y); return(1); } else if ( rmp > CS_TGV2 ) rmp /= CS_TGV2; tol = err*err*rm; ay = (double*)malloc(n*sizeof(double)); if ( !ay ) { free(y); return(0); } if ( nit < 0 ) nit = CS_MAXIT; while ( (tol < rm) && (it < nit) ) { dp = csrAxdotx(A,y,ay); if ( fabs(dp) <= CS_EPSD2 ) break; /* x = x-alpha.y; y = y-alpha.<A,y> */ alpha = rm / dp; rm = 0.0; for (i=0; i<n; i++) { x[i] -= alpha * y[i]; } for (i=0; i<n; i++) { y[i] -= alpha * ay[i]; rm += y[i]*y[i]; } if ( rm > 2.0*rmp ) { ier = -1; break; } rmp = rm; it++; } if ( it > nit ) ier = -2; *er = sqrt(rm); *ni = it; free(y); free(ay); return(ier); } /* solve Ax=b, using conjugate gradient. Return code: >0 upon completion, <0 no convergence 0 memory problem -1 ill conditioned matrix -2 max it reached */ int csrConjGrad(pCsr A,double *x,double *b,double *er,int *ni) { double *y,*ap,*p,dp,nn,rm,rmp,rmn,alpha,beta,err; int i,n,it,ier,nit; if ( !x || !b ) return(0); n = A->nr; y = (double*)malloc(n*sizeof(double)); assert(y); nn = csrXY(x,x,A->nr); /* compute R0 = b - A.x0 */ if ( nn < CS_EPSD2 ) { memcpy(y,b,A->nr*sizeof(double)); } else { csrAxpy(A,x,b,y,-1.,1.); } rm = csrXY(y,y,n); rmp = rm; if ( fabs(rmp) < CS_EPSD2 ) { free(y); return(1); } else if ( rmp > CS_TGV2 ) rmp /= CS_TGV2; p = (double*)malloc(n*sizeof(double)); ap = (double*)malloc(n*sizeof(double)); assert(p); assert(ap); /* p1 = r0 */ memcpy(p,y,n*sizeof(double)); err = *er; err = err*err*rmp; nit = *ni; it = 0; ier = 1; while ( (err < rm) && (++it <= nit) ) { /* alpha_m = <R_m-1,R_m-1> / <AP_m,P_m> */ dp = csrAxdotx(A,p,ap); if ( fabs(dp) <= CS_EPSD2 ) break; /* X_m = X_m-1 + alpha_m.P_m; R_m = R_m-1 - alpha_m AP_m */ alpha = rm / dp; rmn = 0.0; csrlXmY(x,p,x,1.0,alpha,n); csrlXmY(y,ap,y,1.0,-alpha,n); rmn = csrXY(y,y,n); /* for (i=0; i<n; i++) { x[i] = x[i] + alpha * p[i]; y[i] = y[i] - alpha * ap[i]; rmn += y[i] * y[i]; } */ /* P_m+1 = R_m + beta_m P_m */ beta = rmn / rm; for (i=0; i<n; i++) { p[i] = y[i] + beta * p[i]; } rm = rmn; // printf(" GC1: it %d err %E rm %E\n",it,err,rmn); } if ( it > nit ) ier = -2; *er = sqrt(rm / rmp); *ni = it; free(y); free(p); free(ap); return(ier); } /* GC modified */ int csrConjGradGen(pCsr A,double *x,double *b,double *ud,char *udt,char nohom,double *er,int *ni) { double *y,*ap,*p,dp,rm,rmp,rmn,alpha,beta,err; int i,n,it,ier,nit; if ( !x || !b ) return(0); if ( nohom && (!ud || !udt ) ) return(0); n = A->nr; y = (double*)malloc(n*sizeof(double)); if ( !y ) return(0); memcpy(y,b,n*sizeof(double)); if ( nohom ) csrAxpy(A,ud,b,y,-1.0,1.0); /* modify x0 */ for (i=0; i<n; i++) { if ( udt[i] ) x[i] = 0.0; } /* compute R0 = y - A.x0 */ csrAxpy(A,x,y,y,-1.,1.); /* modify y, compute R0*R0 */ rmp = 0.0; for (i=0; i<n; i++) { if ( udt[i] ) y[i] = 0.0; else rmp += y[i] * y[i]; } if ( rmp < CS_EPSD ) { if ( nohom ) for (i=0; i<n; i++) if ( udt[i] ) x[i] = ud[i]; *er = rmp; *ni = 0; free(y); return(1); } else if ( rmp > CS_TGV2 ) rmp /= CS_TGV2; p =(double*)malloc(n*sizeof(double)); assert(p); ap = (double*)malloc(n*sizeof(double)); assert(ap); /* p1 = r0 */ memcpy(p,y,n*sizeof(double)); it = 0; ier = 1; err = *er; err = err*err*rmp; nit = *ni; rm = rmp; if ( nit < 0 ) nit = CS_MAXIT; while ( (err < rm) && (++it <= nit) ) { /* alpha_m = <R_m-1,R_m-1> / <AP_m,P_m> */ dp = csrAxdotx(A,p,ap); if ( fabs(dp) <= CS_EPSD2 ) break; /* X_m = X_m-1 + alpha_m.P_m; R_m = R_m-1 - alpha_m AP_m */ alpha = rm / dp; rmn = 0.0; for (i=0; i<n; i++) { if ( udt[i] ) ap[i] = 0.0; x[i] += alpha * p[i]; y[i] -= alpha * ap[i]; rmn += y[i] * y[i]; } /* P_m+1 = R_m + beta_m P_m */ if ( fabs(rm) <= CS_EPSD ) break; beta = rmn / rm; for (i=0; i<n; i++) p[i] = y[i] + beta * p[i]; rm = rmn; } if ( nohom ) for (i=0; i<n; i++) if ( udt[i] ) x[i] = ud[i]; if ( it > nit ) ier = -2; *er = sqrt(rm / rmp); *ni = it; free(y); free(p); free(ap); return(ier); } /* solve Ax = b using preconditionned conjugate gradient method. Return code: >0 upon completion, <0 no convergence 0 memory problem -1 ill conditioned matrix -2 max it reached */ int csrPrecondGrad(pCsr A,double *x,double *b,double *er,int *ni,char tgv) { pCsr L; double *ap,*p,*q,*y; double dp,nn,rmp,rm,rm2,alpha,beta,err; int n,it,ier,nit; /* allocation */ if ( !x || !b ) return(0); assert(A->nr == A->nc); n = A->nr; y = (double*)malloc(A->nr*sizeof(double)); assert(y); /* compute R0 = y = b - A.x0 */ nn = csrXY(x,x,A->nr); if ( nn < CS_EPSD2 ) { memcpy(y,b,A->nr*sizeof(double)); } else { csrAxpy(A,x,b,y,-1.,1.); } rmp = csrXY(y,y,A->nr); if ( fabs(rmp) < CS_EPSD2 ) { free(y); return(1); } else if ( tgv ) { rmp /= CS_TGV2; } /* P_1 = P^-1.R_0 */ p = (double*)malloc(A->nr*sizeof(double)); q = (double*)malloc(A->nr*sizeof(double)); ap = (double*)malloc(A->nr*sizeof(double)); assert(p); assert(q); assert(ap); /* incomplete SSOR factorization */ L = csrTr(A); csrSSOR(A,L,p,y); err = *er; err = err * err * rmp; nit = *ni; ier = 1; it = 0; rm = rmp; while ( (err < rm) && ++it <= nit ) { /* alpha_m = <P^-1.R_m-1,R_m-1> / <AP_m,P_m> */ rm = csrXY(p,y,n); if ( fabs(rm) <= CS_EPSD2 ) break; dp = csrAxdotx(A,p,ap); if ( fabs(dp) <= CS_EPSD2 ) break; /* X_m = X_m-1 + alpha_m.P_m , R_m = R_m-1 - alpha_m AP_m */ alpha = (rm / dp); csrlXmY(p,x,x,alpha,1.0,n); csrlXmY(ap,y,y,-alpha,1.0,n); /* beta_m = <P^-1.R_m,R_m> / <P^-1.R_m-1,R_m-1> */ csrSSOR(A,L,q,y); rm2 = csrXY(q,y,n); if ( fabs(rm2) <= CS_EPSD2 ) break; /* P_m+1 = P^-1.R_m + beta_m P_m */ beta = rm2 / rm; csrlXmY(p,q,p,beta,1.0,n); //printf(" GC1: it %d err %E rm %E\n",it,err,rm2); rm = rm2; } if ( it > nit ) ier = -2; *er = sqrt(rm / rmp); *ni = it; free(p); free(q); free(y); free(ap); csrFree(L); return(ier); } /* Solve Ax=b using GMRES Return code: >0 upon completion, <0 no convergence 0 memory problem -1 ill conditioned matrix -2 max it reached */ int csrGMRES(pCsr A,double *x,double *b,double *er,int *ni,int krylov,int prec) { double *r,*V,h[CS_KRY1+1],y[CS_KRYL],g[CS_KRYL+1],c[CS_KRYL],s[CS_KRYL]; double beta,tol,dd,err; int i,j,ier,restart,m,iadr,nit,it; if ( !x || !b ) return(0); assert(A->nr > 0); restart = krylov ? CS_MAX(krylov,CS_KRYL) : CS_KRYL; r = (double *)malloc(A->nr*sizeof(double)); assert(r); /* compute R0 = b - A.x0 */ memcpy(r,b,A->nr*sizeof(double)); /* diagonal pre-cond */ beta = 0.0; for (i=0; i<A->nr; i++) { if ( prec ) { for (j=A->row[i]; j<A->row[i+1]; j++) { if ( i == A->col[j] ) { assert(A->val[j]); r[i] /= A->val[j]; break; } } } beta += r[i] * r[i]; } if ( beta < CS_EPSD2 ) { fprintf(stdout," ## GMRES Pb: beta NULL %E\n",beta); free(r); return(0); } else if ( beta >= CS_TGV2 ) { beta /= CS_TGV2; } beta = sqrt(beta); dd = 1.0 / beta; csrAxpy(A,x,r,NULL,-1.,1.); /* V1 = R0 / beta */ V = (double *)malloc(A->nr*(restart+1)*sizeof(double)); assert(V); for (i=0; i<A->nr; i++) V[i] = r[i] * dd; it = 0; nit = *ni; err = *er; tol = beta * err; ier = 1; while ( tol < beta && it < nit ) { m = 0; iadr = 0; g[0] = beta; while ( (tol < fabs(g[m])) && (m < restart) ) { g[m+1] = 0; /* hi,m = (AVm, Vi) , i=1,..,m */ csrAx(A,&V[m*A->nr],&V[(m+1)*A->nr]); if ( prec ) { for (i=0; i<A->nr; i++) { for (j=A->row[i]; j<A->row[i+1]; j++) { if ( i == A->col[j] ) { V[(m+1)*A->nr+i] /= A->val[j]; break; } } } } for (i=m; i>=0; i--) { h[iadr+i] = 0.; for (j=0; j<A->nr; j++) h[iadr+i] += V[(m+1)*A->nr+j] * V[i*A->nr+j]; } /* Vm+1 = AVm - sum(0,m, hi,m.Vi) */ for (j=0; j<=m; j++) { for (i=0; i<A->nr; i++) V[(m+1)*A->nr+i] -= h[iadr+j] * V[j*A->nr+i]; } /* hm+1,m = || Vm+1 || */ h[iadr+m+1] = 0.0; for (i=0; i<A->nr; i++) h[iadr+m+1] += V[(m+1)*A->nr+i] * V[(m+1)*A->nr+i]; h[iadr+m+1] = sqrt(h[iadr+m+1]); if ( h[iadr+m+1] > CS_EPSD2 ) { /* Vm+1 = Vm+1 / hm+1,m */ dd = 1.0 / h[iadr+m+1]; for (i=0; i<A->nr; i++) V[(m+1)*A->nr+i] *= dd; } else fprintf(stdout," ## GMRES Pb: H NULL\n"); /* update H */ for (i=0; i<m; i++) { beta = h[iadr+i]; h[iadr+i] = c[i]*h[iadr+i] + s[i]*h[iadr+i+1]; h[iadr+i+1] = c[i]*h[iadr+i+1] - s[i]*beta; } beta = sqrt(h[iadr+m]*h[iadr+m] + h[iadr+m+1]*h[iadr+m+1]); if ( beta < CS_EPSD2 ) { fprintf(stdout, " ## GMRES Pb: beta NULL\n"); free(r); free(V); return(0); } dd = 1.0 / beta; c[m] = h[iadr+m] * dd; s[m] = h[iadr+m+1] * dd; beta = h[iadr+m]; h[iadr+m] = c[m]*h[iadr+m] + s[m]*h[iadr+m+1]; h[iadr+m+1] = c[m]*h[iadr+m+1] - s[m]*beta; /* update g */ g[m+1] = -1.0 * s[m]*g[m]; g[m] = c[m]*g[m]; it++; m++; iadr = iadr + m + 1; if ( iadr > CS_KRY1 ) break; } /* compute y */ iadr = iadr - m - 1; m--; for (j=m; j>=0; j--) { y[j] = g[j] / h[iadr+j]; for (i=0; i<j; i++) g[i] -= h[iadr+i] * y[j]; iadr = iadr -j -1; } /* Compute Un */ for (j=0; j<=m; j++) { for (i=0; i<A->nr; i++) x[i] += y[j] * V[j*A->nr+i]; } if ( it < nit && tol < fabs(g[m+1]) ) { /* Compute Un */ memcpy(r,b,A->nr*sizeof(double)); csrAxpy(A,x,r,NULL,-1.,1.); beta = 0.0; for (i=0; i<A->nr; i++) { for (j=A->row[i]; j<A->row[i+1]; j++) { if ( prec && (i == A->col[j]) ) { assert(fabs(A->val[j]) > CS_EPSD2); r[i] /= A->val[j]; } } beta += r[i] * r[i]; } if ( beta < CS_EPSD2 ) { fprintf(stdout," ## GMRES Pb: Beta NULL\n"); free(r); free(V); return(0); } dd = 1.0 / sqrt(beta); for (i=0; i<A->nr; i++) V[i] = r[i] * dd; } beta = fabs(g[m+1]); } /* Memory free */ free(r); free(V); if ( it == nit ) ier = -2; *er = beta; *ni = it; return(ier); }
svendahlstrand/indiekit
packages/endpoint-micropub/tests/integration/202-action-delete.js
<gh_stars>0 import 'dotenv/config.js'; // eslint-disable-line import/no-unassigned-import import test from 'ava'; import nock from 'nock'; import {server} from '@indiekit-test/server'; test('Deletes post', async t => { nock('https://tokens.indieauth.com') .get('/token') .twice() .reply(200, { me: process.env.TEST_PUBLICATION_URL, scope: 'create delete' }); nock('https://api.github.com') .put(uri => uri.includes('foobar.md')) .reply(200); nock('https://api.github.com') .get(uri => uri.includes('foobar.md')) .reply(200); nock('https://api.github.com') .delete(uri => uri.includes('foobar.md')) .reply(200); const request = await server(); // Create post const response = await request.post('/micropub') .auth(process.env.TEST_BEARER_TOKEN, {type: 'bearer'}) .send({ type: ['h-entry'], properties: { name: ['Foobar'], content: ['Micropub test of creating an h-entry with a JSON request containing multiple categories.'], category: ['test1', 'test2'] } }); // Delete post const result = await request.post('/micropub') .auth(process.env.TEST_BEARER_TOKEN, {type: 'bearer'}) .send({ action: 'delete', url: response.header.location }); t.is(result.statusCode, 200); t.regex(result.body.success_description, /\bPost deleted\b/); });
nmdis1999/LintCode-1
0050-Product of Array Exclude Itself/0050-Product of Array Exclude Itself.cpp
<filename>0050-Product of Array Exclude Itself/0050-Product of Array Exclude Itself.cpp<gh_stars>10-100 class Solution { public: /** * @param A: Given an integers array A * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] */ vector<long long> productExcludeItself(vector<int> &nums) { // write your code here int n = nums.size(); if (n == 0) { return {}; } vector<long long> result(n, 1); for (int i = 1; i < n; ++i) { result[i] = result[i - 1] * nums[i - 1]; } long long temp = 1; for (int i = n - 2; i >= 0; --i) { temp *= nums[i + 1]; result[i] *= temp; } return result; } };
zhiyaluo/LongUI
include/text/ui_attribute.h
<filename>include/text/ui_attribute.h #pragma once #include <cstdint> #include <core/ui_core_type.h> // ui namespace namespace LongUI{ /// <summary> /// text-align /// </summary> enum AttributeTextAlign : uint8_t { TAlign_Start = 0, TAlign_End, TAlign_Center, TAlign_Justified, // --------------- TAlign_Left = TAlign_Start, TAlign_Right = TAlign_End, }; /// <summary> /// font weight /// </summary> enum AttributeFontWeight : uint16_t { /// <summary> /// Predefined font weight : Thin (100). /// </summary> Weight_Thin = 100, /// <summary> /// Predefined font weight : Extra-light (200). /// </summary> Weight_ExtraLight = 200, /// <summary> /// Predefined font weight : Light (300). /// </summary> Weight_Light = 300, /// <summary> /// Predefined font weight : Normal (400). /// </summary> Weight_Normal = 400, /// <summary> /// Predefined font weight : Medium (500). /// </summary> Weight_Medium = 500, /// <summary> /// Predefined font weight : Semi-bold (600). /// </summary> Weight_SemiBold = 600, /// <summary> /// Predefined font weight : Bold (700). /// </summary> Weight_Bold = 700, /// <summary> /// Predefined font weight : Extra-bold (800). /// </summary> Weight_ExtraBold = 800, /// <summary> /// Predefined font weight : Heavy (900). /// </summary> Weight_Heavy = 900, }; /// <summary> /// font style /// </summary> enum AttributeFontStyle : uint8_t { /// <summary> /// Font slope style : Normal. /// </summary> Style_Normal = 0, /// <summary> /// Font slope style : Oblique. /// </summary> Style_Oblique, /// <summary> /// Font slope style : Italic. /// </summary> Style_Italic }; /// <summary> /// font stretch /// </summary> enum AttributeFontStretch : uint8_t { /// <summary> /// Predefined font stretch : Not known (0). /// </summary> Stretch_Undefined = 0, /// <summary> /// Predefined font stretch : Ultra-condensed (1). /// </summary> Stretch_UltraCondensed = 1, /// <summary> /// Predefined font stretch : Extra-condensed (2). /// </summary> Stretch_ExtraCondensed = 2, /// <summary> /// Predefined font stretch : Condensed (3). /// </summary> Stretch_Condensed = 3, /// <summary> /// Predefined font stretch : Semi-condensed (4). /// </summary> Stretch_SemiCondensed = 4, /// <summary> /// Predefined font stretch : Normal (5). /// </summary> Stretch_Normal = 5, /// <summary> /// Predefined font stretch : Semi-expanded (6). /// </summary> Stretch_SemiExpanded = 6, /// <summary> /// Predefined font stretch : Expanded (7). /// </summary> Stretch_Expanded = 7, /// <summary> /// Predefined font stretch : Extra-expanded (8). /// </summary> Stretch_ExtraExpanded = 8, /// <summary> /// Predefined font stretch : Ultra-expanded (9). /// </summary> Stretch_UltraExpanded = 9 }; // parse the attribute struct TFAttrParser { // font-style static auto Style(U8View) noexcept->AttributeFontStyle; // font-weight static auto Weight(U8View) noexcept->AttributeFontWeight; // font stretch static auto Stretch(U8View) noexcept->AttributeFontStretch; // Align static auto TextAlign(U8View) noexcept->AttributeTextAlign; }; }
Vizzuality/aqueduct-flood
src/components/widgets/specs/risk/benchmark.js
export default { "$schema": "https://vega.github.io/schema/vega/v4.json", "autosize": { "type": "fit", "resize": true, "contains": "padding" }, "height": 200, "signals": [ { "name": "Year", "value": "2010", "bind": { "name":"Year", "input": "radio", "options": [ "2010", "2030", "2050", "2080" ] } }, { "name": "calc", "value": "Total", "bind": { "name":"Calculation", "input": "radio", "options": [ "Total", "Percentage" ] } }, { "name": "margin", "value": 0 }, { "name": "hover", "on": [ {"events": "*:mouseover", "encode": "hover"}, {"events": "*:mouseout", "encode": "leave"}, {"events": "*:mousedown", "encode": "select"}, {"events": "*:mouseup", "encode": "release"} ] }, { "name": "xrange", "update": "[0, width]" }, { "name": "yrange", "update": "[height, 0]" }, { "name": "down", "value": null, "on": [ {"events": "touchend", "update": "null"}, {"events": "mousedown, touchstart", "update": "xy()"} ] }, { "name": "xcur", "value": null, "on": [ { "events": "mousedown, touchstart, touchend", "update": "slice(xdom)" } ] }, { "name": "ycur", "value": null, "on": [ { "events": "mousedown, touchstart, touchend", "update": "slice(ydom)" } ] }, { "name": "delta", "value": [0, 0], "on": [ { "events": [ { "source": "window", "type": "mousemove", "consume": true, "between": [{"type": "mousedown"}, {"source": "window", "type": "mouseup"}] }, { "type": "touchmove", "consume": true, "filter": "event.touches.length === 1" } ], "update": "down ? [down[0]-x(), y()-down[1]] : [0,0]" } ] }, { "name": "anchor", "value": [0, 0], "on": [ { "events": "wheel", "update": "[invert('x', x()), invert('y', y())]" }, { "events": {"type": "touchstart", "filter": "event.touches.length===2"}, "update": "[(xdom[0] + xdom[1]) / 2, (ydom[0] + ydom[1]) / 2]" } ] }, { "name": "zoom", "value": 1, "on": [ { "events": "wheel!", "force": true, "update": "pow(1.001, event.deltaY * pow(16, event.deltaMode))" }, { "events": {"signal": "dist2"}, "force": true, "update": "dist1 / dist2" } ] }, { "name": "dist1", "value": 0, "on": [ { "events": {"type": "touchstart", "filter": "event.touches.length===2"}, "update": "pinchDistance(event)" }, { "events": {"signal": "dist2"}, "update": "dist2" } ] }, { "name": "dist2", "value": 0, "on": [{ "events": {"type": "touchmove", "consume": true, "filter": "event.touches.length===2"}, "update": "pinchDistance(event)" }] }, { "name": "xdom", "update": "slice(xext)", "on": [ { "events": {"signal": "delta"}, "update": "[xcur[0] + span(xcur) * delta[0] / width, xcur[1] + span(xcur) * delta[0] / width]" }, { "events": {"signal": "zoom"}, "update": "[anchor[0] + (xdom[0] - anchor[0]) * zoom, anchor[0] + (xdom[1] - anchor[0]) * zoom]" } ] }, { "name": "ydom", "update": "slice(yext)", "on": [ { "events": {"signal": "delta"}, "update": "[ycur[0] + span(ycur) * delta[1] / height, ycur[1] + span(ycur) * delta[1] / height]" }, { "events": {"signal": "zoom"}, "update": "[anchor[1] + (ydom[0] - anchor[1]) * zoom, anchor[1] + (ydom[1] - anchor[1]) * zoom]" } ] }, { "name": "size", "update": "80" } ], "data": [ { "name": "table", "values": [ ], "transform": [ {"type": "filter", "expr": "datum.year == Year"}, {"type": "filter", "expr": "if(calc=='Percentage',datum.type =='per',datum.type =='tot')"}, { "type": "extent", "field": "value", "signal": "xext" }, { "type": "extent", "field": "prot", "signal": "yext" } ] } ], "scales": [ { "name": "x", "type": "linear", "round": true, "clamp":true, "nice": true, "zero": true, "domain": {"signal": "xdom"}, "range": {"signal": "xrange"} }, { "name": "y", "type": "linear", "round": true, "nice": true, "clamp":true, "zero": true, "domain": {"signal": "ydom"}, "range": {"signal": "yrange"} } ], "axes": [ { "scale": "x", "orient": "top", "ticks": true, "tickCount": 10, "encode": { "labels": { "update": { "text": {"signal": "if(calc=='Percentage', format(datum.value,'.3')+'%', format(datum.value,'.3s'))"} } } } }, { "scale": "y", "orient": "left", "ticks": true, "titlePadding": 5, "tickCount": 5, "title": "Estimated Flood Protection Standard" } ], "marks": [ { "name": "points", "type": "symbol", "from": {"data": "table"}, "encode": { "update": { "x": {"scale": "x", "field": "value"}, "y": {"scale": "y", "field": "prot"}, "shape": {"value": "circle"}, "size": {"signal": "size"}, "opacity": [ { "test": "datum.id !=='{{geogunit_name}}'", "value": 0.3 }, {"value": 0.8} ], "zindex":[ { "test": "datum.id !=='{{geogunit_name}}'", "value": 1 }, {"value": 2} ], "fill": [ { "test": "datum.id !=='{{geogunit_name}}'", "value": "#ef8e3b" }, {"value": "#2955B3"} ] }, "hover": { "opacity": {"value": 1}, "size": {"signal": "size", "mult": 2}, "tooltip":{"signal": "{'Location': datum.id, 'Protection Standard': datum.prot +' years', 'Damage': if(calc=='Percentage', format(datum.value, '.4')+'%', format(datum.value, '.4s'))}"} } } } ] };
raiyanla/compute-runtime
opencl/test/unit_test/os_interface/linux/driver_info_tests.cpp
<reponame>raiyanla/compute-runtime /* * Copyright (C) 2017-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "opencl/source/device/driver_info.h" #include "gtest/gtest.h" #include <memory> #include <string> namespace NEO { TEST(DriverInfo, GivenCreateDriverInfoWhenLinuxThenReturnNewInstance) { std::unique_ptr<DriverInfo> driverInfo(DriverInfo::create(nullptr)); EXPECT_NE(nullptr, driverInfo.get()); } TEST(DriverInfo, GivenDriverInfoWhenLinuxThenReturnDefault) { std::unique_ptr<DriverInfo> driverInfo(DriverInfo::create(nullptr)); std::string defaultName = "testName"; std::string defaultVersion = "testVersion"; auto resultName = driverInfo.get()->getDeviceName(defaultName); auto resultVersion = driverInfo.get()->getVersion(defaultVersion); EXPECT_STREQ(defaultName.c_str(), resultName.c_str()); EXPECT_STREQ(defaultVersion.c_str(), resultVersion.c_str()); } } // namespace NEO
Apanatshka/spoofax-pie
core/tego.runtime/src/test/java/mb/tego/strategies/PrintableStrategyTests.java
<reponame>Apanatshka/spoofax-pie package mb.tego.strategies; import mb.tego.sequences.InterruptibleBiConsumer; import mb.tego.sequences.InterruptibleBiFunction; import mb.tego.sequences.InterruptibleBiPredicate; import mb.tego.sequences.InterruptibleConsumer; import mb.tego.sequences.InterruptibleFunction; import mb.tego.sequences.InterruptiblePredicate; import mb.tego.sequences.InterruptibleSupplier; import mb.tego.strategies.runtime.TegoEngine; import org.checkerframework.checker.nullness.qual.Nullable; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import static org.junit.jupiter.api.Assertions.*; /** * Tests the {@link PrintableStrategy} interface. */ public final class PrintableStrategyTests { @Test public void getName_shouldReturnAFormattedClassNameByDefault() { // Arrange final MyTest2 strategy = new MyTest2(); // Act final String name = strategy.getName(); // Assert assertEquals("my-test-2", name); } @Test public void getName_shouldRemoveStrategySuffixByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); // Act final String name = strategy.getName(); // Assert assertEquals("my-test", name); } @Test public void getParamName_shouldReturnAParameterNameByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); // Act final String param0 = strategy.getParamName(0); final String param1 = strategy.getParamName(1); final String param2 = strategy.getParamName(2); // Assert assertEquals("a0", param0); assertEquals("a1", param1); assertEquals("a2", param2); } @Test public void isAnonymous_shouldReturnTrueByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); // Act final boolean anonymous = strategy.isAnonymous(); // Assert assertTrue(anonymous); } @Test public void getPrecedence_shouldReturnIntegerMAX_VALUEByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); // Act final int precedence = strategy.getPrecedence(); // Assert assertEquals(Integer.MAX_VALUE, precedence); } @Test public void isAtom_shouldReturnTrueByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); // Act final boolean anonymous = strategy.isAtom(); // Assert assertTrue(anonymous); } @Test public void writeArg_shouldCallWriteToForAWritableByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); final StringBuilder sb = new StringBuilder(); final AtomicInteger calls = new AtomicInteger(); final Writable writable = new Writable() { @Override public StringBuilder writeTo(StringBuilder sb) { calls.getAndIncrement(); sb.append("!! writable !!"); return sb; } @Override public String toString() { return "!! tostring !!"; } }; // Act strategy.writeArg(sb, 0, writable); // Assert assertEquals("!! writable !!", sb.toString()); assertEquals(1, calls.get()); } @Test public void writeArg_shouldNotWriteFunctionsByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); final StringBuilder sb = new StringBuilder(); final Predicate<Integer> predicate = it -> it % 2 == 0; final BiPredicate<String, Integer> bipredicate = (s, l) -> s.length() == l; final Function<String, Integer> function = String::length; final BiFunction<String, Integer, Integer> bifunction = (it, s) -> it.length() + s; final Consumer<Integer> consumer = it -> { }; final BiConsumer<String, Integer> biconsumer = (s, it) -> { }; final Supplier<Integer> supplier = () -> 42; // Act/Assert strategy.writeArg(sb, 0, predicate); assertEquals("<predicate>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, bipredicate); assertEquals("<bipredicate>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, function); assertEquals("<function>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, bifunction); assertEquals("<bifunction>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, consumer); assertEquals("<consumer>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, biconsumer); assertEquals("<biconsumer>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, supplier); assertEquals("<supplier>", sb.toString()); sb.setLength(0); } @Test public void writeArg_shouldNotWriteInterruptibleFunctionsByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); final StringBuilder sb = new StringBuilder(); final InterruptiblePredicate<Integer> predicate = it -> it % 2 == 0; final InterruptibleBiPredicate<String, Integer> bipredicate = (s, l) -> s.length() == l; final InterruptibleFunction<String, Integer> function = String::length; final InterruptibleBiFunction<String, Integer, Integer> bifunction = (it, s) -> it.length() + s; final InterruptibleConsumer<Integer> consumer = it -> { }; final InterruptibleBiConsumer<String, Integer> biconsumer = (s, it) -> { }; final InterruptibleSupplier<Integer> supplier = () -> 42; // Act/Assert strategy.writeArg(sb, 0, predicate); assertEquals("<predicate>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, bipredicate); assertEquals("<bipredicate>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, function); assertEquals("<function>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, bifunction); assertEquals("<bifunction>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, consumer); assertEquals("<consumer>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, biconsumer); assertEquals("<biconsumer>", sb.toString()); sb.setLength(0); strategy.writeArg(sb, 0, supplier); assertEquals("<supplier>", sb.toString()); sb.setLength(0); } @Test public void writeArg_shouldWriteClassNameByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); final StringBuilder sb = new StringBuilder(); // Act strategy.writeArg(sb, 0, String.class); // Assert assertEquals("String", sb.toString()); } @Test public void writeArg_shouldWriteStringQuotedAndEscapedByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); final StringBuilder sb = new StringBuilder(); // Act strategy.writeArg(sb, 0, "On a\nnew line!"); // Assert assertEquals("\"On a\\nnew line!\"", sb.toString()); } @Test public void writeArg_shouldWriteStringRepresentationByDefault() { // Arrange final MyTestStrategy strategy = new MyTestStrategy(); final StringBuilder sb = new StringBuilder(); // Act strategy.writeArg(sb, 0, new Object() { @Override public String toString() { return "!! tostring !!"; } }); // Assert assertEquals("!! tostring !!", sb.toString()); } @Test public void writeLeft_shouldParenthesizeWhenStrategyHasLowerPrecedence() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return -1; } // Lower precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("x + y"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act final StringBuilder sb2 = PrintableStrategy.writeLeft(sb, strategy, 0, PrintableStrategy.Associativity.None); sb.append(" * z"); // Assert assertSame(sb, sb2); assertEquals("(x + y) * z", sb.toString()); } @Test public void writeLeft_shouldParenthesizeWhenStrategyHasEqualPrecedenceButRightAssociative() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return 0; } // Equal precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("x ?: y"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act final StringBuilder sb2 = PrintableStrategy.writeLeft(sb, strategy, 0, PrintableStrategy.Associativity.Right); sb.append(" ?: z"); // Assert assertSame(sb, sb2); assertEquals("(x ?: y) ?: z", sb.toString()); } @Test public void writeLeft_shouldNotParenthesizeWhenStrategyHasHigherPrecedence() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return 1; } // Higher precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("x * y"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act final StringBuilder sb2 = PrintableStrategy.writeLeft(sb, strategy, 0, PrintableStrategy.Associativity.Right); sb.append(" + z"); // Assert assertSame(sb, sb2); assertEquals("x * y + z", sb.toString()); } @Test public void writeLeft_shouldNotParenthesizeWhenStrategyHasEqualPrecedenceButNotRightAssociative() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return 0; } // Equal precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("x + y"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act final StringBuilder sb2 = PrintableStrategy.writeLeft(sb, strategy, 0, PrintableStrategy.Associativity.Left); sb.append(" + z"); // Assert assertSame(sb, sb2); assertEquals("x + y + z", sb.toString()); } @Test public void writeLeft_shouldNotParenthesizeWhenStrategyIsAtom() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return true; } @Override public int getArity() { return 0; } @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("x"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act final StringBuilder sb2 = PrintableStrategy.writeLeft(sb, strategy, 0, PrintableStrategy.Associativity.Left); sb.append(" + z"); // Assert assertSame(sb, sb2); assertEquals("x + z", sb.toString()); } @Test public void writeRight_shouldParenthesizeWhenStrategyHasLowerPrecedence() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return -1; } // Lower precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("y + z"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x * "); final StringBuilder sb2 = PrintableStrategy.writeRight(sb, strategy, 0, PrintableStrategy.Associativity.None); // Assert assertSame(sb, sb2); assertEquals("x * (y + z)", sb.toString()); } @Test public void writeRight_shouldParenthesizeWhenStrategyHasEqualPrecedenceButLeftAssociative() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return 0; } // Equal precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("y ?: z"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x ?: "); final StringBuilder sb2 = PrintableStrategy.writeRight(sb, strategy, 0, PrintableStrategy.Associativity.Left); // Assert assertSame(sb, sb2); assertEquals("x ?: (y ?: z)", sb.toString()); } @Test public void writeRight_shouldNotParenthesizeWhenStrategyHasHigherPrecedence() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return 1; } // Higher precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("y * z"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x + "); final StringBuilder sb2 = PrintableStrategy.writeRight(sb, strategy, 0, PrintableStrategy.Associativity.Left); // Assert assertSame(sb, sb2); assertEquals("x + y * z", sb.toString()); } @Test public void writeRight_shouldNotParenthesizeWhenStrategyHasEqualPrecedenceButNotLeftAssociative() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return 0; } // Equal precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("y + z"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x + "); final StringBuilder sb2 = PrintableStrategy.writeRight(sb, strategy, 0, PrintableStrategy.Associativity.Right); // Assert assertSame(sb, sb2); assertEquals("x + y + z", sb.toString()); } @Test public void writeRight_shouldNotParenthesizeWhenStrategyIsAtom() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return true; } @Override public int getArity() { return 0; } @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("z"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x + "); final StringBuilder sb2 = PrintableStrategy.writeRight(sb, strategy, 0, PrintableStrategy.Associativity.Right); // Assert assertSame(sb, sb2); assertEquals("x + z", sb.toString()); } @Test public void writeMiddle_shouldParenthesizeWhenStrategyHasLowerPrecedence() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return -1; } // Lower precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("a < b + c"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x < "); final StringBuilder sb2 = PrintableStrategy.writeMiddle(sb, strategy, 0); sb.append(" + z"); // Assert assertSame(sb, sb2); assertEquals("x < (a < b + c) + z", sb.toString()); } @Test public void writeMiddle_shouldNotParenthesizeWhenStrategyHasEqualPrecedence() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return 1; } // Higher precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("a ? b : c"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x ? "); final StringBuilder sb2 = PrintableStrategy.writeMiddle(sb, strategy, 0); sb.append(" : z"); // Assert assertSame(sb, sb2); assertEquals("x ? a ? b : c : z", sb.toString()); } @Test public void writeMiddle_shouldNotParenthesizeWhenStrategyHasHigherPrecedence() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return false; } @Override public int getArity() { return 0; } @Override public int getPrecedence() { return 1; } // Higher precedence @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("a * b"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x ? "); final StringBuilder sb2 = PrintableStrategy.writeMiddle(sb, strategy, 0); sb.append(" : z"); // Assert assertSame(sb, sb2); assertEquals("x ? a * b : z", sb.toString()); } @Test public void writeMiddle_shouldNotParenthesizeWhenStrategyIsAtom() { // Arrange final StringBuilder sb = new StringBuilder(); final PrintableStrategy strategy = new PrintableStrategy() { @Override public boolean isAtom() { return true; } @Override public int getArity() { return 0; } @Override public StringBuilder writeTo(StringBuilder sb) { sb.append("y"); return sb; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } }; // Act sb.append("x ? "); final StringBuilder sb2 = PrintableStrategy.writeMiddle(sb, strategy, 0); sb.append(" : z"); // Assert assertSame(sb, sb2); assertEquals("x ? y : z", sb.toString()); } private static class MyTestStrategy implements PrintableStrategy { @Override public int getArity() { return 3; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } } private static class MyTest2 implements PrintableStrategy { @Override public int getArity() { return 3; } @Override public @Nullable Object evalInternal(TegoEngine engine, Object[] args, Object input) { return null; } } }
vvaltchev/experimentOs
include/tilck/kernel/fs/vfs_base.h
<reponame>vvaltchev/experimentOs /* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> #include <tilck/common/atomics.h> #include <tilck/kernel/list.h> #include <tilck/kernel/hal_types.h> /* Forward declarations */ struct process; struct user_mapping; struct fs_ops; struct locked_file; /* * Opaque type for file handles. * * The only requirement for such handles is that they must have at their * beginning all the members of fs_handle_base. Therefore, a fs_handle MUST * always be castable to fs_handle_base *. */ typedef void *fs_handle; /* Directory entry types */ enum vfs_entry_type { VFS_NONE = 0, VFS_FILE = 1, VFS_DIR = 2, VFS_SYMLINK = 3, VFS_CHAR_DEV = 4, VFS_BLOCK_DEV = 5, VFS_PIPE = 6, }; /* * VFS opaque inode pointer. * * It is the primary member the struct fs_path and it's used by functions like * (stat, fstat), (truncate, ftruncate) in order to have a common implementation * in the FS layer. */ typedef void *vfs_inode_ptr_t; #define CREATE_FS_PATH_STRUCT(name, inode_type, fs_entry_type) \ \ STATIC_ASSERT(sizeof(inode_type) == sizeof(vfs_inode_ptr_t)); \ STATIC_ASSERT(sizeof(fs_entry_type) == sizeof(void *)); \ \ struct name { \ inode_type inode; \ inode_type dir_inode; \ fs_entry_type dir_entry; \ enum vfs_entry_type type; \ } \ CREATE_FS_PATH_STRUCT(fs_path, vfs_inode_ptr_t, void *); struct vfs_path { struct mnt_fs *fs; struct fs_path fs_path; /* other fields */ const char *last_comp; }; #define VFS_FS_RW (1 << 0) /* struct mnt_fs mounted in RW mode */ #define VFS_FS_RQ_DE_SKIP (1 << 1) /* FS requires vfs dents skip */ /* This struct is Tilck's analogue of Linux's "superblock" */ struct mnt_fs { REF_COUNTED_OBJECT; struct locked_file *pss_lock_root; /* Per SubSystem lock tree root */ const char *fs_type_name; /* Statically allocated: do NOT free() */ u32 device_id; u32 flags; void *device_data; const struct fs_ops *fsops; }; /* * Each fs_handle struct should contain at its beginning the fields of the * following base struct [a rough attempt to emulate inheritance in C]. * * TODO: introduce a ref-count in the fs_base_handle struct when implementing * thread support. */ #define FS_HANDLE_BASE_FIELDS \ struct process *pi; \ struct mnt_fs *fs; \ const struct file_ops *fops; \ int fl_flags; \ u16 fd_flags; \ u16 spec_flags; \ struct locked_file *lf; \ union { \ offt h_fpos; /* file offset */ \ offt dir_pos; /* dir position */ \ }; struct fs_handle_base { FS_HANDLE_BASE_FIELDS }; #define MAX_FS_HANDLE_SIZE (32 * sizeof(void *)) /* 128 or 256 bytes */ /* File handle's special flags (spec_flags) */ #define VFS_SPFL_NO_USER_COPY (1 << 0) #define VFS_SPFL_MMAP_SUPPORTED (1 << 1) #define VFS_SPFL_NO_LF (1 << 2) /* * vfs_mmap()'s flags * * By default the mmap() function (called by vfs_mmap) is expected to both do * the actual memory-map and to register the user mapping in inode's * mappings_list (not all file-systems do that, e.g. ramfs does, fat doesn't). * For more about where the mappings_list play a role in ramfs, see the func * ramfs_unmap_past_eof_mappings(). * * However, in certain contexts, like partial un-mapping we might want to just * register the new user-mapping, without actually doing it. That's where the * VFS_MM_DONT_MMAP flag play a role. At the same way, in other exceptional * situations we might not want the FS to register the mapping, but to do it * anyway. */ #define VFS_MM_DONT_MMAP (1 << 0) #define VFS_MM_DONT_REGISTER (1 << 1) int vfs_mmap(struct user_mapping *um, pdir_t *pdir, int flags); int vfs_munmap(struct user_mapping *um, void *vaddr, size_t len); bool vfs_handle_fault(struct user_mapping *um, void *va, bool p, bool rw); int vfs_dup(fs_handle h, fs_handle *dup_h); void vfs_close(fs_handle h); fs_handle get_fs_handle(int fd); static ALWAYS_INLINE bool is_mmap_supported(fs_handle h) { struct fs_handle_base *hb = (struct fs_handle_base *)h; return !!(hb->spec_flags & VFS_SPFL_MMAP_SUPPORTED); }
337240552/opencore-amr-iOS
opencore/codecs_v2/audio/gsm_amr/amr_nb/common/src/shr.cpp
<reponame>337240552/opencore-amr-iOS<filename>opencore/codecs_v2/audio/gsm_amr/amr_nb/common/src/shr.cpp /* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.073 ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec Available from http://www.3gpp.org (C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* Filename: shr.cpp ------------------------------------------------------------------------------ MODULE DESCRIPTION Shift right function with overflow control ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "basic_op.h" /*---------------------------------------------------------------------------- ; MACROS ; [Define module specific macros here] ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; [Include all pre-processor statements here. Include conditional ; compile variables also.] ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; [List function prototypes here] ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL VARIABLE DEFINITIONS ; [Variable declaration - defined here and used outside this module] ----------------------------------------------------------------------------*/ /* ------------------------------------------------------------------------------ FUNCTION NAME: shr ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Inputs: var1 = 16 bit short signed integer (Word16) whose value falls in the range : 0xffff 8000 <= var1 <= 0x0000 7fff. var2 = 16 bit short signed integer (Word16) whose value falls in the range : 0xffff 8000 <= var2 <= 0x0000 7fff. pOverflow = pointer to overflow (Flag) Outputs: pOverflow -> 1 if the shift operation resulted in overflow Returns: product = Shifted result limited to 16 bits (Word16) Global Variables Used: None Local Variables Needed: None ------------------------------------------------------------------------------ FUNCTION DESCRIPTION This function arithmetically shifts the 16 bit input var1 right var2 positions with sign extension. If var2 is negative, arithmetically shift var1 left by -var2 with sign extension. Saturate the result in case of underflows or overflows. ------------------------------------------------------------------------------ REQUIREMENTS None ------------------------------------------------------------------------------ REFERENCES [1] shr() function in basic_op2.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001 ------------------------------------------------------------------------------ PSEUDO-CODE Word16 shr_std (Word16 var1, Word16 var2) { Word16 var_out; if (var2 < 0) { if (var2 < -16) var2 = -16; var_out = shl_std (var1, -var2); #if (WMOPS) mult_stdiCounter[currCounter].shl_std--; #endif } else { if (var2 >= 15) { var_out = (var1 < 0) ? -1 : 0; } else { if (var1 < 0) { var_out = ~((~var1) >> var2); } else { var_out = var1 >> var2; } } } #if (WMOPS) mult_stdiCounter[currCounter].shr_std++; #endif return (var_out); } ------------------------------------------------------------------------------ CAUTION [optional] [State any special notes, constraints or cautions for users of this function] ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ OSCL_EXPORT_REF Word16 shr(register Word16 var1, register Word16 var2, Flag *pOverflow) { register Word16 result; if (var2 != 0) { if (var2 > 0) { if (var2 > 15) { var2 = 15; } result = var1 >> var2; } else { var2 = -var2; /* Shift right negative is equivalent */ if (var2 > 15) { var2 = 15; } result = (var1 << var2); if ((result >> var2) != var1) { *pOverflow = 1; result = ((var1 > 0) ? MAX_16 : MIN_16); } } } else { result = var1; } return (result); }
VivXwan/LeetCodeSolutions
Java/ShuffleString.java
<gh_stars>100-1000 /* Source: https://leetcode.com/problems/shuffle-string/ Time: O(n), maximum number of possible iterations is 2 * n, so O(2n) ~ O(n) Space: O(n), not in-place as we need a char array of size equal to the length of the provided string */ class Solution { public String restoreString(String s, int[] indices) { char[] res = s.toCharArray(); int len = indices.length; for(int i = 0; i < len; ++i) { while(i != indices[i]) { int index = indices[i]; // swap characters according to the indexes provided in the given indices array char temp = res[index]; res[index] = res[i]; res[i] = temp; // swap indexes given in the indices array of corresponding characters int temp1 = indices[index]; indices[index] = indices[i]; indices[i] = temp1; } } return String.valueOf(res); } }
kieferca/qualm
Teilimplementierungen_QUALM/Trainingsdatenselektion/src/Prototype/src/main/java/studienarbeit/prototype/InputOutput.java
package studienarbeit.prototype; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Scanner; import org.apache.commons.io.FilenameUtils; import org.apache.uima.UIMAException; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.fit.factory.JCasFactory; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import de.tudarmstadt.ukp.dkpro.core.opennlp.OpenNlpSegmenter; import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngine; /**Provides methods for input and output */ public class InputOutput { StopwordRemoval stopWordRemoval; AnalysisEngine segmenter; /**Initialize the segmenter to be used, as well as the stopword removal * * @throws ResourceInitializationException */ InputOutput () throws ResourceInitializationException { stopWordRemoval = new StopwordRemoval(); segmenter = createEngine( OpenNlpSegmenter.class, OpenNlpSegmenter.PARAM_LANGUAGE, "en"); } /**Read and processes the training data. * * All .txt files in the training_data folder are read, creating a corpus representation * for each one, with the name of the file used as identifier. * * @return list of training corpora * @throws FileNotFoundException * @throws UIMAException */ public List<TextData> getTrainingData() throws FileNotFoundException, UIMAException { String training_data_folder = "./training_data"; File folder = new File (training_data_folder); List<TextData> training_data = new ArrayList<TextData>(); // read all .txt files in the training data folder, ignore all other files and folders for (File file : folder.listFiles()) { if (file.isFile()) { String filename = file.getName(); String extension = FilenameUtils.getExtension(filename); if (extension.equals("txt")) { String input = readFile(training_data_folder + "/" + filename); List<String> data = processInput(input); //the name of the corpus is the name of the file, without the file extension String corpus_name = filename.substring(0, filename.lastIndexOf(".")); training_data.add(new TextData(corpus_name, data)); } } } return training_data; } /**Read input.txt located in the input folder, and return a corpus representation. * * @return the content of the input.txt as a corpus representation * @throws FileNotFoundException * @throws UIMAException */ public TextData getInputData() throws FileNotFoundException, UIMAException { String name = "Input Data"; List<String> data = new ArrayList<String>(); String string = readFile("./input/input.txt"); data = processInput(string); TextData inputData = new TextData(name, data); return inputData; } /**Write the output to the specified file in the output directory. * Fails with error when the file cannot be written, for example if it is write-protected or locked. * Also fails if the output directory does not exist. * * @param filename name of the file * @param the text to be written */ public void writeOutputFile(String filename, String data) { String directory = "output/"; try { PrintWriter out = new PrintWriter(directory + filename); out.write(data); out.close(); } catch (FileNotFoundException e) { System.out.println("Error: could not write output file"); } } /**helper method to read a text file * @param name name of the file * @return content of the file as String * @throws FileNotFoundException */ private String readFile (String name) throws FileNotFoundException { Scanner scanner = new Scanner(new File(name)); String content = scanner.useDelimiter("\\Z").next(); scanner.close(); return content; } /**Process the input string by segmenting the input string and removing stopwords. * @param input input string * @return corpus representation as a list of tokens * @throws UIMAException */ private List<String> processInput (String input) throws UIMAException { List<String> corpus = new ArrayList<String>(); JCas jCas = segment(input); jCas = stopWordRemoval.process(jCas); corpus = getStringList(jCas); return corpus; } /**Segment the input string, splitting it into tokens * @param input the input string * @return document representation * @throws UIMAException */ private JCas segment (String input) throws UIMAException { JCas jCas = JCasFactory.createJCas(); jCas.setDocumentText(input); segmenter.process(jCas); return jCas; } /**Converts the jcas document into a list of tokens, represented as list of strings * * @param jcas the document to be converted * @return corpus representation as a list of tokens */ private static List<String> getStringList (JCas jcas) { List<String> corpus = new ArrayList<String>(); Collection<Token> tokens = JCasUtil.select(jcas, Token.class); for (Token t : tokens) { corpus.add(t.getCoveredText()); } return corpus; } }
arnoldlankamp/parser
src/test/java/gtd/tests/SplitAndMerge3.java
<reponame>arnoldlankamp/parser package gtd.tests; import gtd.Parser; import gtd.generator.FromClassGenerator; import gtd.generator.ParserStructure; import gtd.grammar.structure.Alternative; import gtd.grammar.symbols.Char; import gtd.grammar.symbols.Sort; import gtd.result.AbstractNode; /* S ::= A | C A ::= Ba | a B ::= Aa | a C ::= B */ public class SplitAndMerge3{ public static Alternative[] S(){ return new Alternative[]{ new Alternative(new Sort("A")), new Alternative(new Sort("C")) }; } public static Alternative[] A(){ return new Alternative[]{ new Alternative(new Sort("B"), new Char('a')), new Alternative(new Char('a')) }; } public static Alternative[] B(){ return new Alternative[]{ new Alternative(new Sort("A"), new Char('a')), new Alternative(new Char('a')) }; } public static Alternative[] C(){ return new Alternative[]{ new Alternative(new Sort("B")) }; } public static void main(String[] args){ ParserStructure structure = new FromClassGenerator(SplitAndMerge3.class).generate(); Parser sm3 = new Parser("aaa".toCharArray(), structure); AbstractNode result = sm3.parse("S"); System.out.println(result); System.out.println("[S(C(B(A(B('a'),'a'),'a'))),S(A(B(A('a'),'a'),'a'))] <- good"); } }
docwhat/networktest
vendor/github.com/docker/swarmkit/agent/exec/executor.go
package exec import ( "github.com/docker/swarmkit/api" "golang.org/x/net/context" ) // Executor provides controllers for tasks. type Executor interface { // Describe returns the underlying node description. Describe(ctx context.Context) (*api.NodeDescription, error) // Configure uses the node object state to propagate node // state to the underlying executor. Configure(ctx context.Context, node *api.Node) error // Controller provides a controller for the given task. Controller(t *api.Task) (Controller, error) // SetNetworkBootstrapKeys passes the symmetric keys from the // manager to the executor. SetNetworkBootstrapKeys([]*api.EncryptionKey) error } // SecretsProvider is implemented by objects that can store secrets, typically // an executor. type SecretsProvider interface { Secrets() SecretsManager } // SecretGetter contains secret data necessary for the Controller. type SecretGetter interface { // Get returns the the secret with a specific secret ID, if available. // When the secret is not available, the return will be nil. Get(secretID string) *api.Secret } // SecretsManager is the interface for secret storage and updates. type SecretsManager interface { SecretGetter Add(secrets ...api.Secret) // add one or more secrets Remove(secrets []string) // remove the secrets by ID Reset() // remove all secrets }
jaguiar/customer-api
customer-java-resttemplate/src/main/java/com/prez/db/CustomerPreferencesRepository.java
<reponame>jaguiar/customer-api package com.prez.db; import com.prez.model.CustomerPreferences; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; public interface CustomerPreferencesRepository extends MongoRepository<CustomerPreferences, String> { List<CustomerPreferences> findByCustomerId(String customerId); }
stwalking/wind-im
windchat-storage/src/main/java/com/windchat/im/storage/api/IPluginDao.java
package com.windchat.im.storage.api; import java.sql.SQLException; import java.util.List; import com.windchat.im.storage.bean.PluginBean; public interface IPluginDao { public boolean addPlugin(PluginBean bean) throws SQLException; public boolean updatePlugin(PluginBean bean) throws SQLException; public boolean deletePlugin(int pluginId) throws SQLException; public PluginBean getPluginProfile(int pluginId) throws SQLException; public List<PluginBean> getPluginPageList(int pageNum, int pageSize, int position, int permissionStatus) throws SQLException; public List<PluginBean> getPluginPageList(int pageNum, int pageSize, int position) throws SQLException; public List<PluginBean> getAllPluginList(int pageNum, int pageSize) throws SQLException; String reSetAuthKey(int pluginId) throws SQLException; }
best08618/asylo
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/libstdc++-prettyprinters/debug_cxx11.cc
<gh_stars>1-10 // { dg-do run { target c++11 } } // { dg-options "-g -O0" } // { dg-skip-if "" { *-*-* } { "-D_GLIBCXX_PROFILE" } } // Copyright (C) 2016-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library 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 library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #define _GLIBCXX_DEBUG #include <forward_list> #include <unordered_map> #include <unordered_set> #include <iostream> int main() { std::forward_list<std::string> flst; std::forward_list<std::string>::iterator flstiter0; // { dg-final { note-test flstiter0 {invalid iterator}} } flst.push_front("dum"); std::forward_list<std::string>::iterator flstiter1 = flst.begin(); // { dg-final { note-test *flstiter1 {"dum"}} } flst.push_front("dee"); std::forward_list<std::string>::iterator flstiter2 = flst.begin(); // { dg-final { note-test *flstiter2 {"dee"}} } // { dg-final { note-test flst {std::__debug::forward_list = {[0] = "dee", [1] = "dum"}} } } std::forward_list<std::string>::const_iterator flstciter = flst.begin(); // { dg-final { note-test *flstciter {"dee"}} } std::unordered_map<std::string, int> um{ {"zardoz", 23} }; // { dg-final { note-test um {std::__debug::unordered_map with 1 element = {["zardoz"] = 23}} } } std::unordered_map<std::string, int>::iterator umiter = um.begin(); // { dg-final { note-test umiter->first {"zardoz"} } } std::unordered_set<std::string> us{"barrel"}; // { dg-final { note-test us {std::__debug::unordered_set with 1 element = {[0] = "barrel"}} } } std::unordered_set<std::string>::const_iterator usciter = us.begin(); // { dg-final { note-test *usciter {"barrel"} } } // N.B. printers.py does not define printers for the iterator types // that belong to C++11 containers, so tests above dereference the // iterators, and to make that work we need to ensure the operator // definitions are in the debug info: std::string tem; tem = *flstiter1; tem = *flstciter; tem = umiter->first; tem = *usciter; std::cout << "\n"; return 0; // Mark SPOT } // { dg-final { gdb-test SPOT } }
resaba-kaypee/reactjs-realhomes
client/src/components/PropertyDetails/Mortgage/MortgageCalculator.js
<reponame>resaba-kaypee/reactjs-realhomes import React, { useEffect, useState } from "react"; const MortgageCalculator = ({ price = 0 }) => { const [settings, setSettings] = useState({ currencysym: "$", currency: "Dollars", termtype: "years", // years or months term: 30, principal: price, dptype: "percentage", // percentage or downlump dpamount: "20%", rate: 6.5, result: 0, }); const [isConvertingDP, setIsConvertingDP] = useState(false); const [isConvertingTerm, setIsConvertingTerm] = useState(false); const convertDownPayment = () => { const total = parseInt(settings.principal); const amount = parseInt(settings.dpamount); if (settings.dptype === "percentage") { setSettings({ ...settings, dpamount: (amount / total) * 100 + "%", }); } else { const perc = amount / 100; setSettings({ ...settings, dpamount: total * perc, }); } }; const convertTermLength = () => { const term = settings.term; if (settings.termtype === "months") { setSettings({ ...settings, term: parseInt(term * 12), }); } else { setSettings({ ...settings, term: parseInt(term / 12), }); } }; const amountLeft = () => { const purchasePrice = parseInt(settings.principal); const downPayment = parseInt(settings.dpamount); if (settings.dptype === "percentage") { const perc = downPayment / 100; return purchasePrice - purchasePrice * perc; } else { return purchasePrice - downPayment; } }; const paymentsLeft = () => { return settings.termtype === "months" ? settings.term : settings.term * 12; }; const calculate = () => { // Standard Mortgage Formula: // M = P[i(1+i)n] / [(1+i)n - 1] // x = (1+i)n const P = amountLeft(); const i = settings.rate / 100 / 12; const n = paymentsLeft(); const x = Math.pow(1 + i, n); const M = (P * ((i * x) / (x - 1))).toFixed(2); setSettings({ ...settings, result: M, }); }; const handleTermChange = (e) => { setSettings({ ...settings, termtype: e.target.value, }); setIsConvertingTerm(true); }; const handleDPChange = (e) => { setSettings({ ...settings, dptype: e.target.value, }); setIsConvertingDP(true); }; const handleChange = (e) => { setSettings({ ...settings, [e.target.name]: e.target.value, }); }; useEffect(() => { calculate(); // eslint-disable-next-line }, []); useEffect(() => { if (isConvertingDP) { convertDownPayment(); } // eslint-disable-next-line }, [isConvertingDP, settings.dptype]); useEffect(() => { if (isConvertingTerm) { convertTermLength(); } // eslint-disable-next-line }, [isConvertingTerm, settings.termtype]); return ( <div className="flex justify-center w-full mt-24"> <form id="homenote" className="w-full"> {/* // Purchase Price */} <div className="flex mb-6"> <label className="block w-1/3 pr-4 mb-1 font-bold text-gray-500 md:text-right md:mb-0" htmlFor="principal"> Purchase Price {settings.currencysym} </label> <input onChange={handleChange} type="text" className="w-2/3 px-4 py-2 leading-tight text-gray-700 bg-gray-200 border-2 border-gray-200 rounded appearance-none sm md:w-2/3 focus:outline-none focus:bg-white focus:border-purple-500" name="principal" value={settings.principal} /> </div> {/* // Down Payment */} <div className="flex mb-6"> <label className="block w-1/3 pr-4 mb-1 font-bold text-gray-500 md:text-right md:mb-0" htmlFor="dpamount"> Down Payment </label> <input onChange={handleChange} type="text" className="w-2/3 px-4 py-2 leading-tight text-gray-700 bg-gray-200 border-2 border-gray-200 rounded appearance-none md:w-2/3 focus:outline-none focus:bg-white focus:border-purple-500" name="dpamount" value={settings.dpamount} /> </div> <div className="flex mb-6"> <div className="w-1/3"></div> <div className="flex w-2/3 justify-evenly"> {/* // Down Payment Type - Percentage */} <label className="w-full font-bold text-gray-500"> <input onChange={handleDPChange} className="mr-2 leading-tight" checked={settings.dptype === "percentage"} type="radio" name="dptype" value="percentage" /> Percent (%) </label> {/* // Down Payment Type - Lump Sum */} <label className="w-full font-bold text-gray-500"> <input onChange={handleDPChange} className="mr-2 leading-tight" checked={settings.dptype === "downlump"} type="radio" name="dptype" value="downlump" /> {settings.currency} {settings.currencysym} </label> </div> </div> {/* // Rate */} <div className="flex mb-6"> <label className="block w-1/3 pr-4 mb-1 font-bold text-gray-500 md:text-right md:mb-0" htmlFor="rate"> Rate (%) </label> <input onChange={handleChange} type="text" className="w-2/3 px-4 py-2 leading-tight text-gray-700 bg-gray-200 border-2 border-gray-200 rounded appearance-none md:w-2/3 focus:outline-none focus:bg-white focus:border-purple-500" name="rate" value={settings.rate} /> </div> {/* // Term */} <div className="flex mb-6"> <label className="block w-1/3 pr-4 mb-1 font-bold text-gray-500 md:text-right md:mb-0" htmlFor="term"> Term </label> <input onChange={handleChange} type="text" className="w-2/3 px-4 py-2 leading-tight text-gray-700 bg-gray-200 border-2 border-gray-200 rounded appearance-none md:w-2/3 focus:outline-none focus:bg-white focus:border-purple-500" name="term" value={settings.term} /> </div> <div className="flex mb-6"> <div className="w-1/3"></div> <div className="flex w-2/3 justify-evenly"> {/* // Term in Years */} <label className="w-full font-bold text-gray-500"> <input onChange={handleTermChange} className="mr-2 leading-tight" checked={settings.termtype === "years"} type="radio" name="termtype" value="years" /> Years </label> {/* // Term in Months */} <label className="w-full font-bold text-gray-500"> <input onChange={handleTermChange} className="mr-2 leading-tight" checked={settings.termtype === "months"} type="radio" name="termtype" value="months" /> Months </label> </div> </div> {/* // Results */} <div className="flex mb-6"> <label className="block w-1/3 pr-4 mb-1 font-bold text-gray-500 md:text-right md:mb-0" htmlFor="rate"> Results </label> <input type="text" className="w-2/3 px-4 py-2 leading-tight text-gray-700 bg-gray-200 border-2 border-gray-200 rounded appearance-none md:w-2/3 focus:outline-none focus:bg-white focus:border-purple-500" readOnly value={settings.result} /> </div> <div className="flex items-center"> <div className="w-1/3"></div> <div className="w-2/3"> <button onClick={() => calculate()} type="button" className="px-4 py-2 font-bold text-white bg-purple-500 rounded shadow hover:bg-purple-400 focus:shadow-outline focus:outline-none"> Calculate </button> </div> </div> </form> </div> ); }; export default MortgageCalculator;
brumm/tako
src/components/styled.js
import styled from 'styled-components' export const Table = styled.div(({ singleColumn }) => ({ display: 'grid', gridTemplateColumns: singleColumn ? '1fr' : 'minmax(300px, auto) minmax(0, 1fr) 150px', gridAutoRows: 37, width: singleColumn && 300, position: 'relative', })) export const Cell = styled.div(({ alignRight }) => ({ whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', justifyContent: alignRight ? 'flex-end' : 'flex-start', ':nth-child(1)': { paddingLeft: 16, paddingRight: 4, }, ':nth-child(2)': { paddingLeft: 10, paddingRight: 4, }, ':nth-child(3)': { paddingLeft: 4, paddingRight: 16, }, })) export const Row = styled.div(({ highlighted }) => ({ display: 'contents', [`&:hover ${Cell}`]: { backgroundColor: 'var(--color-bg-tertiary)', }, [`& + & ${Cell}`]: { borderTop: '1px solid var(--color-border-secondary)', }, [Cell]: highlighted && { backgroundColor: 'var(--color-bg-tertiary) !important', }, })) export const Truncateable = styled.span({ display: 'inline-block', maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', verticalAlign: 'top', whiteSpace: 'nowrap', }) export const FullScreenCenter = styled.div({ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', })
06needhamt/intellij-community
json/tests/test/com/jetbrains/jsonSchema/remote/JsonSchemaCatalogManagerTest.java
<gh_stars>0 // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.jsonSchema.remote; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.fixtures.BasePlatformTestCase; import com.jetbrains.jsonSchema.JsonSchemaHeavyAbstractTest; import com.jetbrains.jsonSchema.ide.JsonSchemaService; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Assert; public class JsonSchemaCatalogManagerTest extends BasePlatformTestCase { private JsonSchemaCatalogManager myCatalogManager; @Override public void setUp() throws Exception { super.setUp(); myCatalogManager = configureCatalog(); } @Override protected String getTestDataPath() { return JsonSchemaHeavyAbstractTest.getJsonSchemaTestDataFilePath("schemaStore/"); } public void testPackageJson() { doTest("package.json", "https://json.schemastore.org/package"); doTest("package1.json", null); } public void testCircleCI() { doTest(".circleci/config.yml", "https://json.schemastore.org/circleciconfig"); doTest(".circleci/config.disable.yml", null); } public void testGithubWorkflow() { doTest(".github/workflows/nodejs.yml", "https://json.schemastore.org/github-workflow"); doTest(".github/workflows/main.yaml", "https://json.schemastore.org/github-workflow"); doTest(".github/workflows/a/linter.yml", "https://json.schemastore.org/github-workflow"); doTest(".github/workflows/b/main.yaml", "https://json.schemastore.org/github-workflow"); } public void testMisc() { doTest("jenkins-x.yml", "https://jenkins-x.io/schemas/jx-schema.json"); doTest("jenkins-x1.yml", "https://jenkins-x.io/schemas/jx-schema.json"); doTest("jenkins-y.yml", null); doTest("my.schema.json", "https://jsonapi.org/schema"); doTest("schema.json", null); } public void testPerformance() { VirtualFile file = myFixture.addFileToProject("some/unknown.json", "").getVirtualFile(); VirtualFile schemaFile = myCatalogManager.getSchemaFileForFile(file); Assert.assertNull(schemaFile); PlatformTestUtil.startPerformanceTest(getTestName(false), 2000, () -> { for (int i = 0; i < 1000000; i++) { VirtualFile result = myCatalogManager.getSchemaFileForFile(file); Assert.assertNull(result); } }).usesAllCPUCores().assertTiming(); } private void doTest(@NotNull String filePath, @Nullable String expectedSchemaUrl) { VirtualFile file = myFixture.addFileToProject(filePath, "").getVirtualFile(); VirtualFile schemaFile = myCatalogManager.getSchemaFileForFile(file); String schemaUrl = schemaFile != null ? schemaFile.getUrl() : null; Assert.assertEquals(expectedSchemaUrl, schemaUrl); } @NotNull private JsonSchemaCatalogManager configureCatalog() { JsonSchemaCatalogManager catalogManager = JsonSchemaService.Impl.get(getProject()).getCatalogManager(); String path = JsonSchemaHeavyAbstractTest.getJsonSchemaTestDataFilePath("schemaStore/catalog.json"); VirtualFile catalogFile = LocalFileSystem.getInstance().findFileByPath(path); Assert.assertNotNull(catalogFile); catalogManager.registerTestSchemaStoreFile(catalogFile, getTestRootDisposable()); return catalogManager; } }
bsmsnd/LeetCode-CharlieChen
1103.distribute-candies-to-people.cpp
<reponame>bsmsnd/LeetCode-CharlieChen<filename>1103.distribute-candies-to-people.cpp /* * @lc app=leetcode id=1103 lang=cpp * * [1103] Distribute Candies to People */ // @lc code=start class Solution { public: vector<int> distributeCandies(int candies, int num_people) { int l = 1, r = sqrt(2 * candies) + 2; while(r - l > 1){ int m = (l+r)/2; if ((m*m + m) / 2 <= candies) l = m; else r = m; } vector<int> ans; ans.resize(num_people, 0); int round = l / num_people; cout << l << " " << round << endl; for (int i = 0;i < num_people; i++) ans[i] = round * ((round - 1) * num_people + 2 * (i+1)) / 2; for (int i = 0; i < l%num_people; i++) ans[i] += (round * num_people + i + 1); int remain = candies - ((l+1) * l / 2), who = l % num_people; cout << remain << " " << who; ans[who] += remain; return ans; } }; // @lc code=end
bfsgr/insomnia
packages/insomnia-app/app/ui/components/proto-file/proto-file-list-item.js
// @flow import * as React from 'react'; import type { ProtoFile } from '../../../models/proto-file'; import type { DeleteProtoFileHandler, RenameProtoFileHandler, SelectProtoFileHandler, UpdateProtoFileHandler, } from './proto-file-list'; import { Button, AsyncButton } from 'insomnia-components'; import Editable from '../base/editable'; import ProtoListItem from './proto-list-item'; type Props = { protoFile: ProtoFile, isSelected?: boolean, handleSelect: SelectProtoFileHandler, indentLevel: number, handleDelete: DeleteProtoFileHandler, handleRename: RenameProtoFileHandler, handleUpdate: UpdateProtoFileHandler, }; const spinner = <i className="fa fa-spin fa-refresh" />; const ProtoFileListItem = ({ protoFile, isSelected, handleSelect, handleDelete, handleRename, handleUpdate, indentLevel, }: Props) => { const { name, _id } = protoFile; // Don't re-instantiate the callbacks if the dependencies have not changed const handleSelectCallback = React.useCallback(() => handleSelect(_id), [handleSelect, _id]); const handleDeleteCallback = React.useCallback( async (e: SyntheticEvent<HTMLButtonElement>) => { e.stopPropagation(); await handleDelete(protoFile); }, [handleDelete, protoFile], ); const handleRenameCallback = React.useCallback( async (newName: string) => { await handleRename(protoFile, newName); }, [handleRename, protoFile], ); const handleUpdateCallback = React.useCallback( async (e: SyntheticEvent<HTMLButtonElement>) => { e.stopPropagation(); await handleUpdate(protoFile); }, [handleUpdate, protoFile], ); const isReadOnly = indentLevel > 0; return ( <ProtoListItem selectable isSelected={isSelected} onClick={handleSelectCallback} indentLevel={indentLevel}> {isReadOnly && ( <span className="wide"> <i className="fa fa-file-o pad-right-sm" /> {name} </span> )} {!isReadOnly && ( <> <span className="wide"> <i className="fa fa-file-o pad-right-sm" /> <Editable className="wide" onSubmit={handleRenameCallback} value={name} preventBlank /> </span> <div className="row"> <AsyncButton variant="text" title="Re-upload Proto File" onClick={handleUpdateCallback} loadingNode={spinner} className="space-right"> <i className="fa fa-upload" /> </AsyncButton> <Button variant="text" title="Delete Proto File" bg="danger" onClick={handleDeleteCallback}> <i className="fa fa-trash-o" /> </Button> </div> </> )} </ProtoListItem> ); }; export default ProtoFileListItem;
lucteo/concore
src/include/concore/data/concurrent_dequeue.hpp
<filename>src/include/concore/data/concurrent_dequeue.hpp /** * @file concurrent_dequeue.hpp * @brief Definition of @ref concore::v1::concurrent_dequeue "concurrent_dequeue" * * @see @ref concore::v1::concurrent_dequeue "concurrent_dequeue" */ #pragma once #include "concore/low_level/spin_backoff.hpp" #include <atomic> #include <vector> #include <deque> #include <mutex> #include <cassert> #include <utility> #include <type_traits> namespace concore { namespace detail { //! Does a spin-loop and change the atomic from a given state to another. //! The transition must always start in the "from" state. inline void spin_switch_state(std::atomic<int>& state, int from, int to) noexcept { int old = from; spin_backoff spinner; while (!state.compare_exchange_strong( old, to, std::memory_order_acq_rel, std::memory_order_relaxed)) { old = from; spinner.pause(); } } template <typename T, bool can_move_assign = std::is_nothrow_move_assignable_v<T>> void safe_move(T&& src, T& dest) { if constexpr (can_move_assign) { dest = std::move((T &&) src); } else { dest.~T(); new (&dest) T((T &&) src); } } //! Bounded deque implementation, to be used if we the number of elements are relatively low. template <typename T> struct bounded_dequeue { //! The state of an item in the fast queue enum class item_state { freed, constructing, valid, destructing, }; //! The storage type for our elements using storage_t = typename std::aligned_storage<sizeof(T), alignof(T)>::type; //! We need to add an atomic to the element, to know the state of each element. struct wrapped_elem { // NOLINT(cppcoreguidelines-pro-type-member-init) //! Indicates that the 'elem_' is considered part of the queue, and can be popped. //! This may be true while trying to move away data from it. //! While constructing the element this is false. std::atomic<int> state_{0}; //! The element that we store in our queue storage_t elem_; }; //! The size of the queue with fast access const uint16_t size_; //! Circular buffer that contains the elements std::vector<wrapped_elem> circular_buffer_; //! The range of elements valid in our circular buffer std::atomic<uint32_t> fast_range_{0}; //! Union for the [start, end) range in the fast vector, used to access the atomic union fast_range { uint32_t int_value; struct { uint16_t start; //!< The start index in our fast queue uint16_t end; //!< The end index in our fast queue }; }; bounded_dequeue(size_t size) : size_(static_cast<uint16_t>(size)) , circular_buffer_(size) {} //! Reserve one slot at the back of the fast queue. Yields the position of the reserved item. //! Returns false if we don't have enough room to add new elements. bool reserve_back(uint16_t& pos) noexcept { const auto max_dist = static_cast<uint16_t>(size_ - 3); fast_range old{}, desired{}; old.int_value = fast_range_.load(std::memory_order_relaxed); while (true) { if (uint16_t(old.end - old.start) > max_dist) return false; desired = old; desired.end++; if (fast_range_.compare_exchange_weak(old.int_value, desired.int_value, std::memory_order_acq_rel, std::memory_order_relaxed)) { pos = old.end; return true; } } } //! Reserve one slot at the front of the fast queue. Yields the position of the reserved item. //! Returns false if we don't have enough room to add new elements. bool reserve_front(uint16_t& pos) noexcept { const auto max_dist = static_cast<uint16_t>(size_ - 3); fast_range old{}, desired{}; old.int_value = fast_range_.load(std::memory_order_relaxed); while (true) { if (uint16_t(old.end - old.start) > max_dist) return false; desired = old; desired.start--; if (fast_range_.compare_exchange_weak(old.int_value, desired.int_value, std::memory_order_acq_rel, std::memory_order_relaxed)) { pos = desired.start; return true; } } } //! Consumes one slot at the front of the fast queue. Yields the position of the consumed item. bool consume_front(uint16_t& pos) noexcept { fast_range old{}, desired{}; old.int_value = fast_range_.load(std::memory_order_relaxed); while (true) { if (old.start == old.end) return false; desired = old; desired.start++; if (fast_range_.compare_exchange_weak(old.int_value, desired.int_value, std::memory_order_acq_rel, std::memory_order_relaxed)) { pos = old.start; return true; } } } //! Consumes one slot at the front of the fast queue. Yields the position of the reserved item. bool consume_back(uint16_t& pos) noexcept { fast_range old{}, desired{}; old.int_value = fast_range_.load(std::memory_order_relaxed); while (true) { if (old.start == old.end) return false; desired = old; desired.end--; if (fast_range_.compare_exchange_weak(old.int_value, desired.int_value, std::memory_order_acq_rel, std::memory_order_relaxed)) { pos = desired.end; return true; } } } //! Construct an element in the fast queue. //! The place at position 'pos' is already reserved void construct_in_fast(uint16_t pos, T&& elem) noexcept { wrapped_elem& item = circular_buffer_[pos % size_]; // Typically, the item is not being used by anybody else; but in rare conditions it might // not have finished to be destructed. In that case, wait for it to become free. spin_switch_state(item.state_, static_cast<int>(item_state::freed), static_cast<int>(item_state::constructing)); // Ok. Now we can finally construct the element new (&item.elem_) T(std::forward<T>(elem)); assert(item.state_.load() == static_cast<int>(item_state::constructing)); item.state_.store(static_cast<int>(item_state::valid), std::memory_order_release); } //! Extract an element from the fast queue. //! The place at position 'pos' is already marked as free void extract_from_fast(uint16_t pos, T& elem) noexcept { wrapped_elem& item = circular_buffer_[pos % size_]; // Typically, the item is valid; but in rare conditions it might not have finished to be // constructed. In that case, wait for it to become valid, before getting the data out of // it. spin_switch_state(item.state_, static_cast<int>(item_state::valid), static_cast<int>(item_state::destructing)); // Ok. Now we can finally pop the element T& el = reinterpret_cast<T&>(item.elem_); // NOLINT safe_move(std::move(el), elem); el.~T(); // NOLINT(bugprone-use-after-move) assert(item.state_.load() == static_cast<int>(item_state::destructing)); item.state_.store(static_cast<int>(item_state::freed), std::memory_order_release); } //! Clears the content of the queue. //! Not thread-safe. void unsafe_clear() noexcept { for (auto& el : circular_buffer_) { auto old_state = el.state_.load(std::memory_order_relaxed); if (old_state == static_cast<int>(item_state::valid)) { el.state_.store(static_cast<int>(item_state::freed), std::memory_order_relaxed); reinterpret_cast<T&>(el.elem_).~T(); // NOLINT } } fast_range_.store(0, std::memory_order_release); } }; } // namespace detail inline namespace v1 { /** * @brief Concurrent double-ended queue implementation, for a small number of elements. * * @tparam T The type of elements to store * * @details * * This will try to preallocate a vector with enough elements to cover the most common cases. * Operations on the concurrent queue when we have few elements are fast: we only make atomic * operations, no memory allocation. We only use spin mutexes in this case. * * If we have less than a configured number of elements (see constructor) then we would only use the * fast queue. If the number of elements grows above this limit, we would switch to the slow queue. * * If we have too many elements in the queue, we switch to a slower implementation that can grow to * a very large number of elements. For this we use regular mutexes. * * Note 1: when switching between fast and slow, the FIFO ordering of the queue is lost. * * Note 2: for efficiency reasons, the element size should be at least as a cache line (otherwise we * can have false sharing when accessing adjacent elements) * * Note 3: we expect very-low contention on the front of the queue, and some contention at the end * of the queue. And of course, there will be more contention when the queue is empty or close to * empty. * * Note 4: we expect contention over the atomic that stores the begin/end position in the fast queue * * One main use of this queue is to hold tasks in the task system. There, we typically add any * enqueued tasks to the end of the queue. The tasks that are spawned while working on some task are * pushed to the front of the queue. The popping of the tasks is typically done on the front of the * queue, but when stealing tasks, popping is done from the back of the queue -- trying to maximize * locality for nearby tasks. * * @warning: The move constructor of the given type must not throw. * * Exceptions guarantees: * - fast queue: never throws * - slow queue: push might throw while allocating memory; in this case, the element is not added to * the dequeue * - if exception is thrown when allocating memory, the data is not moved away from the object * passed in * * Thread safety: except the following methods, everything else can be used concurrently: * - constructors * - copy/move assignments * - @ref unsafe_clear() * * The dequeue does not provide any iterators, as those would be thread unsafe. * * @see concurrent_queue */ template <typename T> class concurrent_dequeue { public: //! The value type stored in the concurrent dequeue using value_type = T; //! Default constructor concurrent_dequeue(); /** * @brief Constructs a new instance of the queue, with the given preallocated size. * * @param expected_size How many elements to preallocate in our fast queue. * * If we ever add more elements in our queue than the given limit, our queue starts to become * slower. * * The number of reserved elements should be bigger than the expected concurrency. */ explicit concurrent_dequeue(size_t expected_size); //! Destructor ~concurrent_dequeue() = default; //! Copy constructor concurrent_dequeue(const concurrent_dequeue&) = default; //! Copy assignment concurrent_dequeue& operator=(const concurrent_dequeue&) = default; //! Move constructor // NOLINTNEXTLINE(performance-noexcept-move-constructor) concurrent_dequeue(concurrent_dequeue&&) = default; //! Move assignment // NOLINTNEXTLINE(performance-noexcept-move-constructor) concurrent_dequeue& operator=(concurrent_dequeue&&) = default; //! Pushes one element in the back of the queue. //! This is considered the default pushing operation. void push_back(T&& elem); //! Push one element to the front of the queue. void push_front(T&& elem); //! Try to pop one element from the front of the queue. Returns false if the queue is empty. //! This is considered the default popping operation. bool try_pop_front(T& elem) noexcept; //! Try to pop one element from the back of the queue. Returns false if the queue is empty. bool try_pop_back(T& elem) noexcept; //! Clears the queue void unsafe_clear() noexcept; private: //! The fast dequeue implementation; uses a fixed number of elements. detail::bounded_dequeue<T> fast_deque_; //! Deque of elements that have slow access; we use this if we go beyond our threshold std::deque<T> slow_access_elems_; //! Protects the access to slow_access_elems_ std::mutex bottleneck_; //! The number of elements stored in slow_access_elems_; used it before trying to take the lock std::atomic<int> num_elements_slow_{0}; }; template <typename T> inline concurrent_dequeue<T>::concurrent_dequeue() : fast_deque_(1024) {} template <typename T> inline concurrent_dequeue<T>::concurrent_dequeue(size_t expected_size) : fast_deque_(expected_size) {} template <typename T> inline void concurrent_dequeue<T>::push_back(T&& elem) { // If we have enough space in the 'fast' queue, construct the element there uint16_t pos{0}; if (fast_deque_.reserve_back(pos)) { fast_deque_.construct_in_fast(pos, std::forward<T>(elem)); } else { // Otherwise take the slow approach std::lock_guard<std::mutex> lock{bottleneck_}; num_elements_slow_++; slow_access_elems_.push_back(std::forward<T>(elem)); } } template <typename T> inline void concurrent_dequeue<T>::push_front(T&& elem) { // If we have enough space in the 'fast' queue, construct the element there uint16_t pos{0}; if (fast_deque_.reserve_front(pos)) { fast_deque_.construct_in_fast(pos, std::forward<T>(elem)); } else { // Otherwise take the slow approach std::lock_guard<std::mutex> lock{bottleneck_}; num_elements_slow_++; slow_access_elems_.push_front(std::forward<T>(elem)); } } template <typename T> inline bool concurrent_dequeue<T>::try_pop_front(T& elem) noexcept { // If we can extract one element from the fast queue, move an element from there uint16_t pos{0}; if (fast_deque_.consume_front(pos)) { fast_deque_.extract_from_fast(pos, elem); return true; } else if (num_elements_slow_.load() > 0) { // Otherwise take the slow approach std::lock_guard<std::mutex> lock{bottleneck_}; if (slow_access_elems_.empty()) return false; num_elements_slow_--; detail::safe_move(std::move(slow_access_elems_.front()), elem); slow_access_elems_.pop_front(); return true; } else return false; } template <typename T> inline bool concurrent_dequeue<T>::try_pop_back(T& elem) noexcept { // If we can extract one element from the fast queue, move an element from there uint16_t pos{0}; if (fast_deque_.consume_back(pos)) { fast_deque_.extract_from_fast(pos, elem); return true; } else if (num_elements_slow_.load() > 0) { // Otherwise take the slow approach std::lock_guard<std::mutex> lock{bottleneck_}; if (slow_access_elems_.empty()) return false; num_elements_slow_--; detail::safe_move(std::move(slow_access_elems_.back()), elem); slow_access_elems_.pop_back(); return true; } else return false; } template <typename T> inline void concurrent_dequeue<T>::unsafe_clear() noexcept { // Clear the slow access elements slow_access_elems_.clear(); num_elements_slow_ = 0; // Clear the fast access elements fast_deque_.unsafe_clear(); } } // namespace v1 } // namespace concore
karkason/pywinsandbox
winsandbox/utils/errors.py
_WINDOWS_SANDBOX_ARTICLE_LINK = "https://techcommunity.microsoft.com/t5/windows-kernel-internals/windows-sandbox" \ "/ba-p/301849" class SandboxFeatureIsNotAvailableError(RuntimeError): """ Raised when failed getting any information about the windows sandbox feature. """ def __init__(self): super(SandboxFeatureIsNotAvailableError, self).__init__( 'Could not find the windows sandbox feature on this computer.\n' 'Please visit "{}"\n' 'for prerequisites for using this feature.'.format(_WINDOWS_SANDBOX_ARTICLE_LINK)) class SandboxFeatureIsNotEnabledError(RuntimeError): def __init__(self): """ Raised when the windows sandbox is available on the computer but isn't enabled. """ super(SandboxFeatureIsNotEnabledError, self).__init__( 'The optional feature of windows sandbox is not enabled!\n' 'Please visit "{}"\n' 'for information on how to enable it.'.format(_WINDOWS_SANDBOX_ARTICLE_LINK))
johnmous/sfaira
sfaira/unit_tests/tests_by_submodule/data/dataset/test_meta_data_streamlining.py
import os import anndata import pytest from sfaira.unit_tests.data_for_tests.loaders import RELEASE_HUMAN, PrepareData from sfaira.unit_tests.directories import DIR_TEMP @pytest.mark.parametrize("out_format", ["sfaira", "cellxgene"]) @pytest.mark.parametrize("clean_obs", [True, False]) @pytest.mark.parametrize("clean_var", [True, False]) @pytest.mark.parametrize("clean_uns", [True, False]) @pytest.mark.parametrize("clean_obs_names", [True, False]) @pytest.mark.parametrize("keep_id_obs", [True]) @pytest.mark.parametrize("keep_orginal_obs", [False]) @pytest.mark.parametrize("keep_symbol_obs", [True]) def test_dsgs_streamline_metadata(out_format: str, clean_obs: bool, clean_var: bool, clean_uns: bool, clean_obs_names: bool, keep_id_obs: bool, keep_orginal_obs: bool, keep_symbol_obs: bool): ds = PrepareData().prepare_dsg(load=False) ds.subset(key="organism", values=["Homo sapiens"]) ds.subset(key="organ", values=["lung"]) if out_format == "cellxgene": # Other data data sets do not have complete enough annotation ds.subset(key="doi_journal", values=["no_doi_mock1", "no_doi_mock3"]) ds.load() ds.streamline_features(remove_gene_version=False, match_to_release=RELEASE_HUMAN, subset_genes_to_type=None) ds.streamline_metadata(schema=out_format, clean_obs=clean_obs, clean_var=clean_var, clean_uns=clean_uns, clean_obs_names=clean_obs_names, keep_id_obs=keep_id_obs, keep_orginal_obs=keep_orginal_obs, keep_symbol_obs=keep_symbol_obs) @pytest.mark.parametrize("schema_version", ["2_0_0"]) @pytest.mark.parametrize("organism", ["Homo sapiens", "Mus musculus"]) def test_cellxgene_export(schema_version: str, organism: str): """ This test can be extended by future versions. """ from cellxgene_schema import validate class ValidatorInMemory(validate.Validator): """ Helper class to validate adata in memory and raise errors as in error stream rather than outstream. The switch in log stream allows this test to be used as a unit test. """ def validate_adata_inmemory(self, adata: anndata.AnnData): self.errors = [] self.adata = adata self._set_schema_def() if not self.errors: self._deep_check() if self.warnings: self.warnings = ["WARNING: " + i for i in self.warnings] if self.errors: self.errors = ["ERROR: " + i for i in self.errors] if self.warnings or self.errors: print(self.warnings[:20]) print(self.errors[:20]) assert False ds = PrepareData().prepare_dsg(load=False) if organism == "Homo sapiens": ds.subset(key="doi_journal", values=["no_doi_mock1"]) else: ds.subset(key="doi_journal", values=["no_doi_mock2"]) ds.load() ds.streamline_features(schema="cellxgene:" + schema_version) ds.streamline_metadata(schema="cellxgene:" + schema_version, clean_obs=False, clean_var=True, clean_uns=True, clean_obs_names=False, keep_id_obs=True, keep_orginal_obs=False, keep_symbol_obs=True) counter = 0 for ds in ds.datasets.values(): # Validate in memory: # This directly tests the raw object. val = ValidatorInMemory() val.validate_adata_inmemory(adata=ds.adata) # Validate on disk: # This guards against potential issues that arise from h5 formatting. fn_temp = os.path.join(DIR_TEMP, "temp.h5ad") val = ValidatorInMemory() ds.adata.write_h5ad(filename=fn_temp) val.validate_adata(h5ad_path=fn_temp) counter += 1 assert counter > 0, "no data sets to test"
pmp163/danbooru
app/logical/moderator/dashboard/queries/post_appeal.rb
module Moderator module Dashboard module Queries class PostAppeal attr_reader :post, :count def self.all(min_date) sql = <<-EOS SELECT post_appeals.post_id, count(*) FROM post_appeals JOIN posts ON posts.id = post_appeals.post_id WHERE post_appeals.created_at > ? and posts.is_deleted = true and posts.is_pending = false GROUP BY post_appeals.post_id ORDER BY count(*) DESC LIMIT 10 EOS ActiveRecord::Base.select_all_sql(sql, min_date).map {|x| new(x)} end def initialize(hash) @post = ::Post.find(hash["post_id"]) @count = hash["count"] end end end end end
elastisys/scale.commons
json/src/test/java/com/elastisys/scale/commons/json/SomeNestedClass.java
package com.elastisys.scale.commons.json; import java.util.Map; import java.util.Objects; import org.joda.time.DateTime; public class SomeNestedClass { private final int primitiveValue; private final String string; private final Map<String, DateTime> timestamps; private final SomeClassWithTimestamp nestedObject; public SomeNestedClass(int primitiveValue, String string, Map<String, DateTime> timestamps, SomeClassWithTimestamp nestedObject) { this.primitiveValue = primitiveValue; this.string = string; this.timestamps = timestamps; this.nestedObject = nestedObject; } /** * @return the primitiveValue */ public int getPrimitiveValue() { return this.primitiveValue; } /** * @return the string */ public String getString() { return this.string; } public Map<String, DateTime> getTimestamps() { return this.timestamps; } /** * @return the nestedObject */ public SomeClassWithTimestamp getNestedObject() { return this.nestedObject; } @Override public boolean equals(Object obj) { if (obj instanceof SomeNestedClass) { SomeNestedClass that = (SomeNestedClass) obj; return Objects.equals(this.primitiveValue, that.primitiveValue) // && Objects.equals(this.string, that.string) // && Objects.equals(this.timestamps, that.timestamps) // && Objects.equals(this.nestedObject, that.nestedObject); } return false; } }
nakamura5akihito/opensec-oval
src/main/java/io/opensec/oval/model/windows/MetabaseItem.java
/** * Opensec OVAL - https://nakamura5akihito.github.io/ * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.opensec.oval.model.windows; import io.opensec.oval.model.ComponentType; import io.opensec.oval.model.Family; import io.opensec.oval.model.sc.EntityItemAnySimpleType; import io.opensec.oval.model.sc.EntityItemIntType; import io.opensec.oval.model.sc.EntityItemStringType; import io.opensec.oval.model.sc.ItemType; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * The metabase item gathers information from the specified metabase keys. * * @author <NAME>, AIST * @see <a href="http://oval.mitre.org/language/">OVAL Language</a> */ public class MetabaseItem extends ItemType { private EntityItemStringType key; //{0..1} private EntityItemIntType id; //{0..1, nillable="true"} private EntityItemStringType name; //{0..1} private EntityItemStringType user_type; //{0..1} private EntityItemStringType data_type; //{0..1} // private final Map<MetabaseProperty, EntityAttributeGroup> _properties = // new EnumMap<MetabaseProperty, EntityAttributeGroup>( MetabaseProperty.class ); private final Collection<EntityItemAnySimpleType> data = new ArrayList<EntityItemAnySimpleType>(); //{0..*} /** * Constructor. */ public MetabaseItem() { this( 0 ); } public MetabaseItem( final int id ) { super( id ); _oval_family = Family.WINDOWS; _oval_component = ComponentType.METABASE; } /** */ public void setKey( final EntityItemStringType key ) { this.key = key; // _properties.put( MetabaseProperty.KEY, key ); } public EntityItemStringType getKey() { return key; // return (EntityItemStringType)_properties.get( MetabaseProperty.KEY ); } /** * This property is renamed from "id" to "objectID" * because the super class ItemType has the property of the same name. */ public void setObjectId( final EntityItemIntType id ) { this.id = id; } public EntityItemIntType getObjectId() { return id; } /** */ public void setObjectName( final EntityItemStringType name ) { this.name = name; } public EntityItemStringType getObjectName() { return name; } /** */ public void setUserType( final EntityItemStringType user_type ) { this.user_type = user_type; // _properties.put( MetabaseProperty.USER_TYPE, type ); } public EntityItemStringType getUserType() { return user_type; // return (EntityItemStringType)_properties.get( MetabaseProperty.USER_TYPE ); } /** */ public void setDataType( final EntityItemStringType data_type ) { this.data_type = data_type; // _properties.put( MetabaseProperty.DATA_TYPE, type ); } public EntityItemStringType getDataType() { return data_type; // return (EntityItemStringType)_properties.get( MetabaseProperty.DATA_TYPE ); } /** */ public void setData( final Collection<? extends EntityItemAnySimpleType> data ) { if (data != this.data) { this.data.clear(); if (data != null && data.size() > 0) { this.data.addAll( data ); } } } public Collection<EntityItemAnySimpleType> getData() { return data; } public Iterator<EntityItemAnySimpleType> iterateData() { return data.iterator(); } //************************************************************** // java.lang.Object //************************************************************** @Override public String toString() { return "mtabase_item[" + super.toString() + ", key=" + getKey() + ", id=" + getObjectId() + ", name=" + getObjectName() + ", user_type=" + getUserType() + ", data_type=" + getDataType() + ", data=" + getData() + "]"; } } // MetabaseItem
NuclearManD/NTIOS_2.0
platforms/atmega328/platform.h
#ifndef PLATFORM_H #define PLATFORM_H #include "drv_uart/drv_uart.cpp" #include "drv_gpio/drv_gpio.cpp" extern int entry(void); int main(void); #endif
menty44/tutorials
testing-modules/testing-libraries/src/test/java/com/baeldung/cucumberbackground/books/BookStoreRunSteps.java
package com.baeldung.cucumberbackground.books; import io.cucumber.datatable.DataTable; import io.cucumber.java.Before; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class BookStoreRunSteps { private BookStore store; private List<Book> foundBooks; private Book foundBook; @Before public void setUp() { store = new BookStore(); foundBooks = new ArrayList<>(); } @Given("^I have the following books in the store$") public void haveBooksInTheStore(DataTable table) { List<List<String>> rows = table.asLists(String.class); for (List<String> columns : rows) { store.addBook(new Book(columns.get(0), columns.get(1))); } } @When("^I search for books by author (.+)$") public void searchForBooksByAuthor(String author) { foundBooks = store.booksByAuthor(author); } @When("^I search for a book titled (.+)$") public void searchForBookByTitle(String title) { foundBook = store.bookByTitle(title).orElse(null); } @Then("^I find (\\d+) books$") public void findBooks(int count) { assertEquals(count, foundBooks.size()); } @Then("^I find a book$") public void findABook() { assertNotNull(foundBook); } @Then("^I find no book$") public void findNoBook() { assertNull(foundBook); } }
seakers/ExtUtils
dakota-6.3.0.Windows.x86/include/Teuchos_LAPACK.hpp
<reponame>seakers/ExtUtils // @HEADER // *********************************************************************** // // Teuchos: Common Tools Package // Copyright (2004) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact <NAME> (<EMAIL>) // // *********************************************************************** // @HEADER #ifndef _TEUCHOS_LAPACK_HPP_ #define _TEUCHOS_LAPACK_HPP_ /*! \file Teuchos_LAPACK.hpp \brief Templated interface class to LAPACK routines. */ /** \example LAPACK/cxx_main.cpp This is an example of how to use the Teuchos::LAPACK class. */ #include "Teuchos_ConfigDefs.hpp" #include "Teuchos_ScalarTraits.hpp" /*! \class Teuchos::LAPACK \brief The Templated LAPACK Wrapper Class. The Teuchos::LAPACK class is a wrapper that encapsulates LAPACK (Linear Algebra Package). LAPACK provides portable, high- performance implementations of linear, eigen, SVD, etc solvers. The standard LAPACK interface is Fortran-specific. Unfortunately, the interface between C++ and Fortran is not standard across all computer platforms. The Teuchos::LAPACK class provides C++ wrappers for the LAPACK kernels in order to insulate the rest of Teuchos from the details of C++ to Fortran translation. A Teuchos::LAPACK object is essentially nothing, but allows access to the LAPACK wrapper functions. Teuchos::LAPACK is a serial interface only. This is appropriate since the standard LAPACK are only specified for serial execution (or shared memory parallel). \note <ol> <li>These templates are specialized to use the Fortran LAPACK routines for scalar types \c float and \c double. <li>If Teuchos is configured with \c -DTeuchos_ENABLE_COMPLEX:BOOL=ON then these templates are specialized for scalar types \c std::complex<float> and \c std::complex<double> also. <li>A short description is given for each method. For more detailed documentation, see the LAPACK website (\c http://www.netlib.org/lapack/ ). </ol> */ namespace Teuchos { template<class T> struct UndefinedLAPACKRoutine { // This function should not compile if there is an attempt to instantiate! static inline T notDefined() { return T::LAPACK_routine_not_defined_for_this_type(); } }; template<typename OrdinalType, typename ScalarType> class LAPACK { public: typedef typename Teuchos::ScalarTraits<ScalarType>::magnitudeType MagnitudeType; //! @name Constructors/Destructors. //@{ //! Default Constructor. inline LAPACK(void) {} //! Copy Constructor. inline LAPACK(const LAPACK<OrdinalType, ScalarType>& lapack) {} //! Destructor. inline virtual ~LAPACK(void) {} //@} //! @name Symmetric Positive Definite Linear System Routines. //@{ //! Computes the \c L*D*L' factorization of a Hermitian/symmetric positive definite tridiagonal matrix \c A. void PTTRF(const OrdinalType n, ScalarType* d, ScalarType* e, OrdinalType* info) const; //! Solves a tridiagonal system \c A*X=B using the \L*D*L' factorization of \c A computed by PTTRF. void PTTRS(const OrdinalType n, const OrdinalType nrhs, const ScalarType* d, const ScalarType* e, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const; //! Computes Cholesky factorization of a real symmetric positive definite matrix \c A. void POTRF(const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* info) const; //! Solves a system of linear equations \c A*X=B, where \c A is a symmetric positive definite matrix factored by POTRF and the \c nrhs solutions are returned in \c B. void POTRS(const char UPLO, const OrdinalType n, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const; //! Computes the inverse of a real symmetric positive definite matrix \c A using the Cholesky factorization \c A from POTRF. void POTRI(const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* info) const; //! Estimates the reciprocal of the condition number (1-norm) of a real symmetric positive definite matrix \c A using the Cholesky factorization from POTRF. void POCON(const char UPLO, const OrdinalType n, const ScalarType* A, const OrdinalType lda, const ScalarType anorm, ScalarType* rcond, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const; //! Computes the solution to a real system of linear equations \c A*X=B, where \c A is a symmetric positive definite matrix and the \c nrhs solutions are returned in \c B. void POSV(const char UPLO, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const; //! Computes row and column scalings intended to equilibrate a symmetric positive definite matrix \c A and reduce its condition number (w.r.t. 2-norm). void POEQU(const OrdinalType n, const ScalarType* A, const OrdinalType lda, ScalarType* S, ScalarType* scond, ScalarType* amax, OrdinalType* info) const; //! Improves the computed solution to a system of linear equations when the coefficient matrix is symmetric positive definite, and provides error bounds and backward error estimates for the solution. void PORFS(const char UPLO, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, const ScalarType* AF, const OrdinalType ldaf, const ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const; //! Uses the Cholesky factorization to compute the solution to a real system of linear equations \c A*X=B, where \c A is symmetric positive definite. System can be equilibrated by POEQU and iteratively refined by PORFS, if requested. void POSVX(const char FACT, const char UPLO, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* AF, const OrdinalType ldaf, char EQUED, ScalarType* S, ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* rcond, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const; //@} //! @name General Linear System Routines. //@{ //! Solves an over/underdetermined real \c m by \c n linear system \c A using QR or LQ factorization of A. void GELS(const char TRANS, const OrdinalType m, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /// \brief Use the SVD to solve a possibly rank-deficient linear least-squares problem. /// /// GELSS uses the singular value decomposition (SVD) to compute /// the minimum-norm solution to a possibly rank-deficient linear /// least-squares problem. The problem may be under- or /// overdetermined. /// /// LAPACK's _GELSS routines take different arguments, depending /// on whether they are for real or complex arithmetic. This is /// because _GELSS imitates the interface of LAPACK's SVD routine. /// LAPACK's SVD routine takes an additional RWORK workspace array /// argument for COMPLEX*8 (CGELSS) and COMPLEX*16 (ZGELSS). /// LAPACK's real SVD routines (SGELSS and DGELSS) do not take the /// RWORK argument. /// /// This class had already exposed GELSS for ScalarType = float /// and double that does <i>not</i> include an RWORK argument. /// Backwards compatibility requirements prevent us from simply /// changing that interface. We could provide a different /// interface for LAPACK specializations with ScalarType = /// std::complex<T>, but that would make the GELSS interface not /// generic at compile time. This would make using GELSS in /// generic code harder (for example, you would need to specialize /// code that <i>uses</i> GELSS on a Boolean, which specifies /// whether ScalarType is complex). /// /// We fix this problem by providing an overloaded generic GELSS /// interface that does take an RWORK argument. This does not /// change the existing interface, but provides the additional /// capability to solve complex-valued least-squares problems. /// The RWORK argument is ignored when ScalarType is real, and may /// therefore be set to NULL in that case. /// void GELSS(const OrdinalType m, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, MagnitudeType* S, const MagnitudeType rcond, OrdinalType* rank, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info) const; //! Legacy GELSS interface for real-valued ScalarType. void GELSS(const OrdinalType m, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, ScalarType* S, const ScalarType rcond, OrdinalType* rank, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; //! Solves the linear equality-constrained least squares (LSE) problem where \c A is an \c m by \c n matrix,\c B is a \c p by \c n matrix \c C is a given \c m-vector, and D is a given \c p-vector. void GGLSE(const OrdinalType m, const OrdinalType n, const OrdinalType p, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, ScalarType* C, ScalarType* D, ScalarType* X, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; //! Computes a QR factorization of a general \c m by \c n matrix \c A. void GEQRF( const OrdinalType m, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; //! Computes an LU factorization of a general \c m by \c n matrix \c A using partial pivoting with row interchanges. void GETRF(const OrdinalType m, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* IPIV, OrdinalType* info) const; //! Solves a system of linear equations \c A*X=B or \c A'*X=B with a general \c n by \c n matrix \c A using the LU factorization computed by GETRF. void GETRS(const char TRANS, const OrdinalType n, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, const OrdinalType* IPIV, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const; //! Computes a QR factorization with column pivoting of a matrix \c A: A*P = Q*R using Level 3 BLAS void GEQP3(const OrdinalType m, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType *jpvt, ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info ) const; //! Apply a series of row interchanges to the matrix A. void LASWP (const OrdinalType N, ScalarType A[], const OrdinalType LDA, const OrdinalType K1, const OrdinalType K2, const OrdinalType IPIV[], const OrdinalType INCX) const; //! Computes an LU factorization of a general banded \c m by \c n matrix \c A using partial pivoting with row interchanges. void GBTRF(const OrdinalType m, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, ScalarType* A, const OrdinalType lda, OrdinalType* IPIV, OrdinalType* info) const; //! Solves a system of linear equations \c A*X=B or \c A'*X=B with a general banded \c n by \c n matrix \c A using the LU factorization computed by GBTRF. void GBTRS(const char TRANS, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, const OrdinalType* IPIV, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const; //! Computes an LU factorization of a \c n by \c n tridiagonal matrix \c A using partial pivoting with row interchanges. void GTTRF(const OrdinalType n, ScalarType* dl, ScalarType* d, ScalarType* du, ScalarType* du2, OrdinalType* IPIV, OrdinalType* info) const; //! Solves a system of linear equations \c A*X=B or \c A'*X=B or \c A^H*X=B with a tridiagonal matrix \c A using the LU factorization computed by GTTRF. void GTTRS(const char TRANS, const OrdinalType n, const OrdinalType nrhs, const ScalarType* dl, const ScalarType* d, const ScalarType* du, const ScalarType* du2, const OrdinalType* IPIV, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const; //! Computes the inverse of a matrix \c A using the LU factorization computed by GETRF. void GETRI(const OrdinalType n, ScalarType* A, const OrdinalType lda, const OrdinalType* IPIV, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /// \brief Robustly solve a possibly singular triangular linear system. /// /// \note This routine is slower than the BLAS' TRSM, but can /// detect possible singularity of A. void LATRS (const char UPLO, const char TRANS, const char DIAG, const char NORMIN, const OrdinalType N, ScalarType* A, const OrdinalType LDA, ScalarType* X, MagnitudeType* SCALE, MagnitudeType* CNORM, OrdinalType* INFO) const; //! Estimates the reciprocal of the condition number of a general real matrix \c A, in either the 1-norm or the infinity-norm, using the LU factorization computed by GETRF. void GECON(const char NORM, const OrdinalType n, const ScalarType* A, const OrdinalType lda, const ScalarType anorm, ScalarType* rcond, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const; //! Estimates the reciprocal of the condition number of a general banded real matrix \c A, in either the 1-norm or the infinity-norm, using the LU factorization computed by GETRF. void GBCON(const char NORM, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const ScalarType* A, const OrdinalType lda, OrdinalType* IPIV, const ScalarType anorm, ScalarType* rcond, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const; //! Returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of an \c n by \c n band matrix \c A, with \c kl sub-diagonals and \c ku super-diagonals. typename ScalarTraits<ScalarType>::magnitudeType LANGB(const char NORM, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const ScalarType* A, const OrdinalType lda, MagnitudeType* WORK) const; //! Computes the solution to a real system of linear equations \c A*X=B, where \c A is factored through GETRF and the \c nrhs solutions are computed through GETRS. void GESV(const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, OrdinalType* IPIV, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const; //! Computes row and column scalings intended to equilibrate an \c m by \c n matrix \c A and reduce its condition number. void GEEQU(const OrdinalType m, const OrdinalType n, const ScalarType* A, const OrdinalType lda, ScalarType* R, ScalarType* C, ScalarType* rowcond, ScalarType* colcond, ScalarType* amax, OrdinalType* info) const; //! Improves the computed solution to a system of linear equations and provides error bounds and backward error estimates for the solution. Use after GETRF/GETRS. void GERFS(const char TRANS, const OrdinalType n, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, const ScalarType* AF, const OrdinalType ldaf, const OrdinalType* IPIV, const ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const; //! Computes row and column scalings intended to equilibrate an \c m by \c n banded matrix \c A and reduce its condition number. void GBEQU(const OrdinalType m, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const ScalarType* A, const OrdinalType lda, MagnitudeType* R, MagnitudeType* C, MagnitudeType* rowcond, MagnitudeType* colcond, MagnitudeType* amax, OrdinalType* info) const; //! Improves the computed solution to a banded system of linear equations and provides error bounds and backward error estimates for the solution. Use after GBTRF/GBTRS. void GBRFS(const char TRANS, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, const ScalarType* AF, const OrdinalType ldaf, const OrdinalType* IPIV, const ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const; //! Uses the LU factorization to compute the solution to a real system of linear equations \c A*X=B, returning error bounds on the solution and a condition estimate. void GESVX(const char FACT, const char TRANS, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* AF, const OrdinalType ldaf, OrdinalType* IPIV, char EQUED, ScalarType* R, ScalarType* C, ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* rcond, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const; /*! \brief Reduces a real symmetric matrix \c A to tridiagonal form by orthogonal similarity transformations. \note This method is not defined when the ScalarType is \c std::complex<float> or \c std::complex<double>. */ void SYTRD(const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* D, ScalarType* E, ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; //! Reduces a real general matrix \c A to upper Hessenberg form by orthogonal similarity transformations. void GEHRD(const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, ScalarType* A, const OrdinalType lda, ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; //! Solves a triangular linear system of the form \c A*X=B or \c A**T*X=B, where \c A is a triangular matrix. void TRTRS(const char UPLO, const char TRANS, const char DIAG, const OrdinalType n, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const; //! Computes the inverse of an upper or lower triangular matrix \c A. void TRTRI(const char UPLO, const char DIAG, const OrdinalType n, const ScalarType* A, const OrdinalType lda, OrdinalType* info) const; //@} //! @name Symmetric Eigenproblem Routines //@{ /*! \brief Computes the eigenvalues and, optionally, eigenvectors of a symmetric \c n by \c n matrix \c A in packed storage. \note This method is not defined when the ScalarType is \c std::complex<float> or \c std::complex<double>. */ void SPEV(const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* AP, ScalarType* W, ScalarType* Z, const OrdinalType ldz, ScalarType* WORK, OrdinalType* info) const; /*! \brief Computes all the eigenvalues and, optionally, eigenvectors of a symmetric \c n by \c n matrix A. \note This method is not defined when the ScalarType is \c std::complex<float> or \c std::complex<double>. */ void SYEV(const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* W, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /*! \brief Computes all the eigenvalues and, optionally, eigenvectors of a symmetric \c n by \c n matrix pencil \c {A,B}, where \c A is symmetric and \c B is symmetric positive-definite. \note This method is not defined when the ScalarType is \c std::complex<float> or \c std::complex<double>. */ void SYGV(const OrdinalType itype, const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, ScalarType* W, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /*! \brief Computes all the eigenvalues and, optionally, eigenvectors of a Hermitian \c n by \c n matrix A. \note This method will call SYEV when ScalarType is \c float or \c double. */ void HEEV(const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, MagnitudeType* W, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info) const; /*! \brief Computes all the eigenvalues and, optionally, eigenvectors of a generalized Hermitian-definite \c n by \c n matrix pencil \c {A,B}, where \c A is Hermitian and \c B is Hermitian positive-definite. \note This method will call SYGV when ScalarType is \c float or \c double. */ void HEGV(const OrdinalType itype, const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, MagnitudeType* W, ScalarType* WORK, const OrdinalType lwork, MagnitudeType *RWORK, OrdinalType* info) const; //! Computes the eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal \c n by \c n matrix \c A using implicit QL/QR. The eigenvectors can only be computed if \c A was reduced to tridiagonal form by SYTRD. void STEQR(const char COMPZ, const OrdinalType n, ScalarType* D, ScalarType* E, ScalarType* Z, const OrdinalType ldz, ScalarType* WORK, OrdinalType* info) const; //@} //! @name Non-Hermitian Eigenproblem Routines //@{ //! Computes the eigenvalues of a real upper Hessenberg matrix \c H and, optionally, the matrices \c T and \c Z from the Schur decomposition, where T is an upper quasi-triangular matrix and Z contains the Schur vectors. void HSEQR(const char JOB, const char COMPZ, const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, ScalarType* H, const OrdinalType ldh, ScalarType* WR, ScalarType* WI, ScalarType* Z, const OrdinalType ldz, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /*! Computes for an \c n by \c n nonsymmetric matrix \c A, the eigenvalues, the Schur form \c T, and, optionally, the matrix of Schur vectors \c Z. When \c ScalarType is \c float or \c double, the real Schur form is computed. \note (This is the version used for \c float and \c double, where \c select requires two arguments to represent a complex eigenvalue.) */ void GEES(const char JOBVS, const char SORT, OrdinalType (*ptr2func)(ScalarType*, ScalarType*), const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* sdim, ScalarType* WR, ScalarType* WI, ScalarType* VS, const OrdinalType ldvs, ScalarType* WORK, const OrdinalType lwork, OrdinalType* BWORK, OrdinalType* info) const; /*! Computes for an \c n by \c n nonsymmetric matrix \c A, the eigenvalues, the Schur form \c T, and, optionally, the matrix of Schur vectors \c Z. When \c ScalarType is \c float or \c double, the real Schur form is computed. \note (This is the version used for \c std::complex<float> and \c std::complex<double>, where \c select requires one arguments to represent a complex eigenvalue.) */ void GEES(const char JOBVS, const char SORT, OrdinalType (*ptr2func)(ScalarType*), const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* sdim, ScalarType* W, ScalarType* VS, const OrdinalType ldvs, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* BWORK, OrdinalType* info) const; /*! Computes for an \c n by \c n nonsymmetric matrix \c A, the eigenvalues, the Schur form \c T, and, optionally, the matrix of Schur vectors \c Z. When \c ScalarType is \c float or \c double, the real Schur form is computed. \note (This is the version used for any \c ScalarType, when the user doesn't want to enable the sorting functionality.) */ void GEES(const char JOBVS, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* sdim, MagnitudeType* WR, MagnitudeType* WI, ScalarType* VS, const OrdinalType ldvs, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* BWORK, OrdinalType* info) const; //! Computes for an \c n by \c n real nonsymmetric matrix \c A, the eigenvalues and, optionally, the left and/or right eigenvectors. void GEEV(const char JOBVL, const char JOBVR, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* WR, ScalarType* WI, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /*! Computes for an \c n by \c n real nonsymmetric matrix \c A, the eigenvalues and, optionally, the left and/or right eigenvectors. Optionally, it can compute a balancing transformation to improve the conditioning of the eigenvalues and eigenvectors. \note (This is the function is only defined for \c ScalarType = \c float or \c double.) */ void GEEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* WR, ScalarType* WI, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, OrdinalType* ilo, OrdinalType* ihi, MagnitudeType* SCALE, MagnitudeType* abnrm, MagnitudeType* RCONDE, MagnitudeType* RCONDV, ScalarType* WORK, const OrdinalType lwork, OrdinalType* IWORK, OrdinalType* info) const; /*! Computes for a pair of \c n by \c n nonsymmetric matrices (\c A,\c B) the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors. Optionally, it can compute a balancing transformation to improve the conditioning of the eigenvalues and eigenvectors. \note (This is the function is only defined for \c ScalarType = \c float or \c double.) */ void GGEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, MagnitudeType* ALPHAR, MagnitudeType* ALPHAI, ScalarType* BETA, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, OrdinalType* ilo, OrdinalType* ihi, MagnitudeType* LSCALE, MagnitudeType* RSCALE, MagnitudeType* abnrm, MagnitudeType* bbnrm, MagnitudeType* RCONDE, MagnitudeType* RCONDV, ScalarType* WORK, const OrdinalType lwork, OrdinalType* IWORK, OrdinalType* BWORK, OrdinalType* info) const; /*! Computes for a pair of \c n by \c n nonsymmetric matrices (\c A,\c B) the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors. \note (This is the function is only defined for \c ScalarType = \c float or \c double.) */ void GGEV(const char JOBVL, const char JOBVR, const OrdinalType n, ScalarType *A, const OrdinalType lda, ScalarType *B, const OrdinalType ldb, MagnitudeType *ALPHAR, MagnitudeType *ALPHAI, ScalarType *BETA, ScalarType *VL, const OrdinalType ldvl, ScalarType *VR, const OrdinalType ldvr, ScalarType *WORK, const OrdinalType lwork, OrdinalType *info) const; //@} //! @name Singular Value Decompositon Routines //@{ //! Computes the singular values (and optionally, vectors) of a real matrix \c A. void GESVD(const char JOBU, const char JOBVT, const OrdinalType m, const OrdinalType n, ScalarType* A, const OrdinalType lda, MagnitudeType* S, ScalarType* U, const OrdinalType ldu, ScalarType* V, const OrdinalType ldv, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info) const; //@} //! @name Orthogonal matrix routines //@{ /// Apply Householder reflectors (real case). /// /// Overwrite the general real \c m by \c n matrix \c C with the /// product of \c Q and \c C, whiere Q is the product of \c k /// elementary (Householder) reflectors as returned by \c GEQRF. /// /// \note This method is not defined when ScalarType is complex. /// Call \c UNMQR in that case. ("OR" stands for "orthogonal"; /// "UN" stands for "unitary.") void ORMQR(const char SIDE, const char TRANS, const OrdinalType m, const OrdinalType n, const OrdinalType k, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* C, const OrdinalType ldc, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /// \brief Apply Householder reflectors (complex case). /// /// Overwrite the general complex \c m by \c n matrix \c C with /// the product of \c Q and \c C, where Q is the product of \c k /// elementary (Householder) reflectors as returned by \c GEQRF. /// /// \note This method will call \c ORMQR when ScalarType is real. /// (Unitary real matrices are orthogonal.) void UNMQR(const char SIDE, const char TRANS, const OrdinalType m, const OrdinalType n, const OrdinalType k, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* C, const OrdinalType ldc, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /// \brief Compute explicit Q factor from QR factorization (GEQRF) (real case). /// /// Generate the \c m by \c n matrix Q with orthonormal columns /// corresponding to the first \c n columns of a product of \c k /// elementary reflectors of order \c m, as returned by \c GEQRF. /// /// \note This method is not defined when ScalarType is complex. /// Call \c UNGQR in that case. ("OR" stands for "orthogonal"; /// "UN" stands for "unitary.") void ORGQR(const OrdinalType m, const OrdinalType n, const OrdinalType k, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /// \brief Compute explicit QR factor from QR factorization (GEQRF) (complex case). /// /// Generate the \c m by \c n matrix Q with orthonormal columns /// corresponding tothe first \c n columns of a product of \c k /// elementary reflectors of order \c m, as returned by \c GEQRF. /// /// \note This method will call \c ORGQR when ScalarType is real. /// (Unitary real matrices are orthogonal.) void UNGQR(const OrdinalType m, const OrdinalType n, const OrdinalType k, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /*! \brief Generates a real orthogonal matrix \c Q which is the product of \c ihi-ilo elementary reflectors of order \c n, as returned by GEHRD. On return \c Q is stored in \c A. \note This method is not defined when ScalarType is complex. */ void ORGHR(const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; /*! \brief Overwrites the general real \c m by \c n matrix \c C with the product of \c C and \c Q, which is a product of \c ihi-ilo elementary reflectors, as returned by GEHRD. \note This method is not defined when ScalarType is complex. */ void ORMHR(const char SIDE, const char TRANS, const OrdinalType m, const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, const ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* C, const OrdinalType ldc, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const; //@} //! @name Triangular Matrix Routines //@{ /*! Computes some or all of the right and/or left eigenvectors of an upper triangular matrix \c T. If ScalarType is \c float or \c double, then the matrix is quasi-triangular and arugments \c RWORK is ignored. */ void TREVC(const char SIDE, const char HOWMNY, OrdinalType* select, const OrdinalType n, const ScalarType* T, const OrdinalType ldt, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, const OrdinalType mm, OrdinalType* m, ScalarType* WORK, OrdinalType* info) const; /*! Computes some or all of the right and/or left eigenvectors of an upper triangular matrix \c T. If ScalarType is \c float or \c double, then the matrix is quasi-triangular and arugments \c RWORK is ignored. \note (This is the version used for any \c ScalarType, when the user doesn't want to enable the selecting functionality, with HOWMNY='A'.) */ void TREVC(const char SIDE, const OrdinalType n, const ScalarType* T, const OrdinalType ldt, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, const OrdinalType mm, OrdinalType* m, ScalarType* WORK, MagnitudeType* RWORK, OrdinalType* info) const; /*! Reorders the Schur factorization of a matrix \c T via unitary similarity transformations so that the diagonal element of \c T with row index \c ifst is moved to row \c ilst. If \c ScalarType is \c float or \c double, then \c T should be in real Schur form and the operation affects the diagonal block referenced by \c ifst. \note This method will ignore the WORK vector when ScalarType is \c std::complex<float> or \c std::complex<double>. */ void TREXC(const char COMPQ, const OrdinalType n, ScalarType* T, const OrdinalType ldt, ScalarType* Q, const OrdinalType ldq, OrdinalType ifst, OrdinalType ilst, ScalarType* WORK, OrdinalType* info) const; //@} //! @name Rotation/Reflection generators //@{ //! Gnerates a plane rotation that zeros out the second component of the input vector. void LARTG( const ScalarType f, const ScalarType g, MagnitudeType* c, ScalarType* s, ScalarType* r ) const; //! Generates an elementary reflector of order \c n that zeros out the last \c n-1 components of the input vector. void LARFG( const OrdinalType n, ScalarType* alpha, ScalarType* x, const OrdinalType incx, ScalarType* tau ) const; //@} //! @name Matrix Balancing Routines //@{ //! Balances a general matrix A, through similarity transformations to make the rows and columns as close in norm as possible. void GEBAL(const char JOBZ, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType ilo, OrdinalType ihi, MagnitudeType* scale, OrdinalType* info) const; //! Forms the left or right eigenvectors of a general matrix that has been balanced by GEBAL by backward transformation of the computed eigenvectors \c V. void GEBAK(const char JOBZ, const char SIDE, const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, const MagnitudeType* scale , const OrdinalType m, ScalarType* V, const OrdinalType ldv, OrdinalType* info) const; //@} //! @name Random number generators //@{ //! Returns a random number from a uniform or normal distribution. ScalarType LARND( const OrdinalType idist, OrdinalType* seed ) const; //! Returns a vector of random numbers from a chosen distribution. void LARNV( const OrdinalType idist, OrdinalType* seed, const OrdinalType n, ScalarType* v ) const; //@} //! @name Machine Characteristics Routines. //@{ /*! \brief Determines machine parameters for floating point characteristics. \note This method is not defined when the ScalarType is \c std::complex<float> or \c std::complex<double>. */ ScalarType LAMCH(const char CMACH) const; /*! \brief Chooses problem-dependent parameters for the local environment. \note This method should give parameters for good, but not optimal, performance on many currently available computers. */ OrdinalType ILAENV( const OrdinalType ispec, const std::string& NAME, const std::string& OPTS, const OrdinalType N1 = -1, const OrdinalType N2 = -1, const OrdinalType N3 = -1, const OrdinalType N4 = -1 ) const; //@} //! @name Miscellaneous Utilities. //@{ /*! \brief Computes x^2 + y^2 safely, to avoid overflow. \note This method is not defined when the ScalarType is \c std::complex<float> or \c std::complex<double>. */ ScalarType LAPY2(const ScalarType x, const ScalarType y) const; //@} }; // END GENERAL TEMPLATE DECLARATION // // BEGIN GENERAL TEMPLATE IMPLEMENTATION // template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::PTTRF(const OrdinalType n, ScalarType* d, ScalarType* e, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::PTTRS(const OrdinalType n, const OrdinalType nrhs, const ScalarType* d, const ScalarType* e, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::POTRF(const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::POTRS(const char UPLO, const OrdinalType n, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::POTRI(const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::POCON(const char UPLO, const OrdinalType n, const ScalarType* A, const OrdinalType lda, const ScalarType anorm, ScalarType* rcond, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::POSV(const char UPLO, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::POEQU(const OrdinalType n, const ScalarType* A, const OrdinalType lda, ScalarType* S, ScalarType* scond, ScalarType* amax, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::PORFS(const char UPLO, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, const ScalarType* AF, const OrdinalType ldaf, const ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::POSVX(const char FACT, const char UPLO, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* AF, const OrdinalType ldaf, char EQUED, ScalarType* S, ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* rcond, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GELS(const char TRANS, const OrdinalType m, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GELSS(const OrdinalType m, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, MagnitudeType* S, const MagnitudeType rcond, OrdinalType* rank, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GELSS(const OrdinalType m, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, ScalarType* S, const ScalarType rcond, OrdinalType* rank, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GGLSE(const OrdinalType m, const OrdinalType n, const OrdinalType p, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, ScalarType* C, ScalarType* D, ScalarType* X, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GEQRF( const OrdinalType m, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GETRF(const OrdinalType m, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* IPIV, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GETRS(const char TRANS, const OrdinalType n, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, const OrdinalType* IPIV, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>:: GEQP3 (const OrdinalType m, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType *jpvt, ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>:: LASWP (const OrdinalType N, ScalarType A[], const OrdinalType LDA, const OrdinalType K1, const OrdinalType K2, const OrdinalType IPIV[], const OrdinalType INCX) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GBTRF(const OrdinalType m, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, ScalarType* A, const OrdinalType lda, OrdinalType* IPIV, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GBTRS(const char TRANS, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, const OrdinalType* IPIV, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GTTRF(const OrdinalType n, ScalarType* dl, ScalarType* d, ScalarType* du, ScalarType* du2, OrdinalType* IPIV, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GTTRS(const char TRANS, const OrdinalType n, const OrdinalType nrhs, const ScalarType* dl, const ScalarType* d, const ScalarType* du, const ScalarType* du2, const OrdinalType* IPIV, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GETRI(const OrdinalType n, ScalarType* A, const OrdinalType lda, const OrdinalType* IPIV, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>:: LATRS (const char UPLO, const char TRANS, const char DIAG, const char NORMIN, const OrdinalType N, ScalarType* A, const OrdinalType LDA, ScalarType* X, MagnitudeType* SCALE, MagnitudeType* CNORM, OrdinalType* INFO) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GECON(const char NORM, const OrdinalType n, const ScalarType* A, const OrdinalType lda, const ScalarType anorm, ScalarType* rcond, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GBCON(const char NORM, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const ScalarType* A, const OrdinalType lda, OrdinalType* IPIV, const ScalarType anorm, ScalarType* rcond, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> typename ScalarTraits<ScalarType>::magnitudeType LAPACK<OrdinalType,ScalarType>::LANGB(const char NORM, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const ScalarType* A, const OrdinalType lda, MagnitudeType* WORK) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GESV(const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, OrdinalType* IPIV, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GEEQU(const OrdinalType m, const OrdinalType n, const ScalarType* A, const OrdinalType lda, ScalarType* R, ScalarType* C, ScalarType* rowcond, ScalarType* colcond, ScalarType* amax, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GERFS(const char TRANS, const OrdinalType n, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, const ScalarType* AF, const OrdinalType ldaf, const OrdinalType* IPIV, const ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GBEQU(const OrdinalType m, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const ScalarType* A, const OrdinalType lda, MagnitudeType* R, MagnitudeType* C, MagnitudeType* rowcond, MagnitudeType* colcond, MagnitudeType* amax, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GBRFS(const char TRANS, const OrdinalType n, const OrdinalType kl, const OrdinalType ku, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, const ScalarType* AF, const OrdinalType ldaf, const OrdinalType* IPIV, const ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GESVX(const char FACT, const char TRANS, const OrdinalType n, const OrdinalType nrhs, ScalarType* A, const OrdinalType lda, ScalarType* AF, const OrdinalType ldaf, OrdinalType* IPIV, char EQUED, ScalarType* R, ScalarType* C, ScalarType* B, const OrdinalType ldb, ScalarType* X, const OrdinalType ldx, ScalarType* rcond, ScalarType* FERR, ScalarType* BERR, ScalarType* WORK, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::SYTRD(const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* D, ScalarType* E, ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::GEHRD(const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, ScalarType* A, const OrdinalType lda, ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::TRTRS(const char UPLO, const char TRANS, const char DIAG, const OrdinalType n, const OrdinalType nrhs, const ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::TRTRI(const char UPLO, const char DIAG, const OrdinalType n, const ScalarType* A, const OrdinalType lda, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::SPEV(const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* AP, ScalarType* W, ScalarType* Z, const OrdinalType ldz, ScalarType* WORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::SYEV(const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* W, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::SYGV(const OrdinalType itype, const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, ScalarType* W, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::HEEV(const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, MagnitudeType* W, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::HEGV(const OrdinalType itype, const char JOBZ, const char UPLO, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, MagnitudeType* W, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType,ScalarType>::STEQR(const char COMPZ, const OrdinalType n, ScalarType* D, ScalarType* E, ScalarType* Z, const OrdinalType ldz, ScalarType* WORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::HSEQR(const char JOB, const char COMPZ, const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, ScalarType* H, const OrdinalType ldh, ScalarType* WR, ScalarType* WI, ScalarType* Z, const OrdinalType ldz, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GEES(const char JOBVS, const char SORT, OrdinalType (*ptr2func)(ScalarType*, ScalarType*), const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* sdim, ScalarType* WR, ScalarType* WI, ScalarType* VS, const OrdinalType ldvs, ScalarType* WORK, const OrdinalType lwork, OrdinalType* BWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GEES(const char JOBVS, const char SORT, OrdinalType (*ptr2func)(ScalarType*), const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* sdim, ScalarType* W, ScalarType* VS, const OrdinalType ldvs, ScalarType* WORK, const OrdinalType lwork, MagnitudeType *RWORK, OrdinalType* BWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GEES(const char JOBVS, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType* sdim, MagnitudeType* WR, MagnitudeType* WI, ScalarType* VS, const OrdinalType ldvs, ScalarType* WORK, const OrdinalType lwork, MagnitudeType *RWORK, OrdinalType* BWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GEEV(const char JOBVL, const char JOBVR, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* WR, ScalarType* WI, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GEEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* WR, ScalarType* WI, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, OrdinalType* ilo, OrdinalType* ihi, MagnitudeType* SCALE, MagnitudeType* abnrm, MagnitudeType* RCONDE, MagnitudeType* RCONDV, ScalarType* WORK, const OrdinalType lwork, OrdinalType* IWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GESVD(const char JOBU, const char JOBVT, const OrdinalType m, const OrdinalType n, ScalarType* A, const OrdinalType lda, MagnitudeType* S, ScalarType* U, const OrdinalType ldu, ScalarType* V, const OrdinalType ldv, ScalarType* WORK, const OrdinalType lwork, MagnitudeType* RWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GGEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const OrdinalType n, ScalarType* A, const OrdinalType lda, ScalarType* B, const OrdinalType ldb, MagnitudeType* ALPHAR, MagnitudeType* ALPHAI, ScalarType* BETA, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, OrdinalType* ilo, OrdinalType* ihi, MagnitudeType* LSCALE, MagnitudeType* RSCALE, MagnitudeType* abnrm, MagnitudeType* bbnrm, MagnitudeType* RCONDE, MagnitudeType* RCONDV, ScalarType* WORK, const OrdinalType lwork, OrdinalType* IWORK, OrdinalType* BWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GGEV(const char JOBVL, const char JOBVR, const OrdinalType n, ScalarType *A, const OrdinalType lda, ScalarType *B, const OrdinalType ldb, MagnitudeType *ALPHAR, MagnitudeType *ALPHAI, ScalarType *BETA, ScalarType *VL, const OrdinalType ldvl, ScalarType *VR, const OrdinalType ldvr, ScalarType *WORK, const OrdinalType lwork, OrdinalType *info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::ORMQR(const char SIDE, const char TRANS, const OrdinalType m, const OrdinalType n, const OrdinalType k, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* C, const OrdinalType ldc, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::UNMQR(const char SIDE, const char TRANS, const OrdinalType m, const OrdinalType n, const OrdinalType k, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* C, const OrdinalType ldc, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::ORGQR(const OrdinalType m, const OrdinalType n, const OrdinalType k, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::UNGQR(const OrdinalType m, const OrdinalType n, const OrdinalType k, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::ORGHR(const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::ORMHR(const char SIDE, const char TRANS, const OrdinalType m, const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, const ScalarType* A, const OrdinalType lda, const ScalarType* TAU, ScalarType* C, const OrdinalType ldc, ScalarType* WORK, const OrdinalType lwork, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::TREVC(const char SIDE, const char HOWMNY, OrdinalType* select, const OrdinalType n, const ScalarType* T, const OrdinalType ldt, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, const OrdinalType mm, OrdinalType* m, ScalarType* WORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::TREVC(const char SIDE, const OrdinalType n, const ScalarType* T, const OrdinalType ldt, ScalarType* VL, const OrdinalType ldvl, ScalarType* VR, const OrdinalType ldvr, const OrdinalType mm, OrdinalType* m, ScalarType* WORK, MagnitudeType* RWORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::TREXC(const char COMPQ, const OrdinalType n, ScalarType* T, const OrdinalType ldt, ScalarType* Q, const OrdinalType ldq, OrdinalType ifst, OrdinalType ilst, ScalarType* WORK, OrdinalType* info) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> ScalarType LAPACK<OrdinalType, ScalarType>::LAMCH(const char CMACH) const { return UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> OrdinalType LAPACK<OrdinalType, ScalarType>::ILAENV( const OrdinalType ispec, const std::string& NAME, const std::string& OPTS, const OrdinalType N1, const OrdinalType N2, const OrdinalType N3, const OrdinalType N4 ) const { return UndefinedLAPACKRoutine<OrdinalType>::notDefined(); } template<typename OrdinalType, typename ScalarType> ScalarType LAPACK<OrdinalType, ScalarType>::LAPY2(const ScalarType x, const ScalarType y) const { return UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::LARTG( const ScalarType f, const ScalarType g, MagnitudeType* c, ScalarType* s, ScalarType* r ) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::LARFG( const OrdinalType n, ScalarType* alpha, ScalarType* x, const OrdinalType incx, ScalarType* tau ) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GEBAL( const char JOBZ, const OrdinalType n, ScalarType* A, const OrdinalType lda, OrdinalType ilo, OrdinalType ihi, MagnitudeType* scale, OrdinalType* info ) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::GEBAK( const char JOBZ, const char SIDE, const OrdinalType n, const OrdinalType ilo, const OrdinalType ihi, const MagnitudeType* scale, const OrdinalType m, ScalarType* V, const OrdinalType ldv, OrdinalType* info ) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> ScalarType LAPACK<OrdinalType, ScalarType>::LARND( const OrdinalType idist, OrdinalType* seed ) const { return UndefinedLAPACKRoutine<ScalarType>::notDefined(); } template<typename OrdinalType, typename ScalarType> void LAPACK<OrdinalType, ScalarType>::LARNV( const OrdinalType idist, OrdinalType* seed, const OrdinalType n, ScalarType* v ) const { UndefinedLAPACKRoutine<ScalarType>::notDefined(); } // END GENERAL TEMPLATE IMPLEMENTATION // #ifndef DOXYGEN_SHOULD_SKIP_THIS // BEGIN INT, FLOAT SPECIALIZATION DECLARATION // template<> class TEUCHOS_LIB_DLL_EXPORT LAPACK<int, float> { public: inline LAPACK(void) {} inline LAPACK(const LAPACK<int, float>& lapack) {} inline virtual ~LAPACK(void) {} // Symmetric positive definite linear system routines void POTRF(const char UPLO, const int n, float* A, const int lda, int * info) const; void POTRS(const char UPLO, const int n, const int nrhs, const float* A, const int lda, float* B, const int ldb, int* info) const; void PTTRF(const int n, float* d, float* e, int* info) const; void PTTRS(const int n, const int nrhs, const float* d, const float* e, float* B, const int ldb, int* info) const; void POTRI(const char UPLO, const int n, float* A, const int lda, int* info) const; void POCON(const char UPLO, const int n, const float* A, const int lda, const float anorm, float* rcond, float* WORK, int* IWORK, int* info) const; void POSV(const char UPLO, const int n, const int nrhs, float* A, const int lda, float* B, const int ldb, int* info) const; void POEQU(const int n, const float* A, const int lda, float* S, float* scond, float* amax, int* info) const; void PORFS(const char UPLO, const int n, const int nrhs, float* A, const int lda, const float* AF, const int ldaf, const float* B, const int ldb, float* X, const int ldx, float* FERR, float* BERR, float* WORK, int* IWORK, int* info) const; void POSVX(const char FACT, const char UPLO, const int n, const int nrhs, float* A, const int lda, float* AF, const int ldaf, char EQUED, float* S, float* B, const int ldb, float* X, const int ldx, float* rcond, float* FERR, float* BERR, float* WORK, int* IWORK, int* info) const; // General Linear System Routines void GELS(const char TRANS, const int m, const int n, const int nrhs, float* A, const int lda, float* B, const int ldb, float* WORK, const int lwork, int* info) const; void GELSS(const int m, const int n, const int nrhs, float* A, const int lda, float* B, const int ldb, float* S, const float rcond, int* rank, float* WORK, const int lwork, float* RWORK, int* info) const; void GELSS(const int m, const int n, const int nrhs, float* A, const int lda, float* B, const int ldb, float* S, const float rcond, int* rank, float* WORK, const int lwork, int* info) const; void GGLSE(const int m, const int n, const int p, float* A, const int lda, float* B, const int ldb, float* C, float* D, float* X, float* WORK, const int lwork, int* info) const; void GEQRF( const int m, const int n, float* A, const int lda, float* TAU, float* WORK, const int lwork, int* info) const; void GETRF(const int m, const int n, float* A, const int lda, int* IPIV, int* info) const; void GETRS(const char TRANS, const int n, const int nrhs, const float* A, const int lda, const int* IPIV, float* B, const int ldb, int* info) const; void GEQP3 (const int m, const int n, float* A, const int lda, int *jpvt, float* TAU, float* WORK, const int lwork, float* RWORK, int* info) const; void LASWP (const int N, float A[], const int LDA, const int K1, const int K2, const int IPIV[], const int INCX) const; void GBTRF(const int m, const int n, const int kl, const int ku, float* A, const int lda, int* IPIV, int* info) const; void GBTRS(const char TRANS, const int n, const int kl, const int ku, const int nrhs, const float* A, const int lda, const int* IPIV, float* B, const int ldb, int* info) const; void GTTRF(const int n, float* dl, float* d, float* du, float* du2, int* IPIV, int* info) const; void GTTRS(const char TRANS, const int n, const int nrhs, const float* dl, const float* d, const float* du, const float* du2, const int* IPIV, float* B, const int ldb, int* info) const; void GETRI(const int n, float* A, const int lda, const int* IPIV, float* WORK, const int lwork, int* info) const; void LATRS (const char UPLO, const char TRANS, const char DIAG, const char NORMIN, const int N, float* A, const int LDA, float* X, float* SCALE, float* CNORM, int* INFO) const; void GECON(const char NORM, const int n, const float* A, const int lda, const float anorm, float* rcond, float* WORK, int* IWORK, int* info) const; void GBCON(const char NORM, const int n, const int kl, const int ku, const float* A, const int lda, int* IPIV, const float anorm, float* rcond, float* WORK, int* IWORK, int* info) const; float LANGB(const char NORM, const int n, const int kl, const int ku, const float* A, const int lda, float* WORK) const; void GESV(const int n, const int nrhs, float* A, const int lda, int* IPIV, float* B, const int ldb, int* info) const; void GEEQU(const int m, const int n, const float* A, const int lda, float* R, float* C, float* rowcond, float* colcond, float* amax, int* info) const; void GERFS(const char TRANS, const int n, const int nrhs, const float* A, const int lda, const float* AF, const int ldaf, const int* IPIV, const float* B, const int ldb, float* X, const int ldx, float* FERR, float* BERR, float* WORK, int* IWORK, int* info) const; void GBEQU(const int m, const int n, const int kl, const int ku, const float* A, const int lda, float* R, float* C, float* rowcond, float* colcond, float* amax, int* info) const; void GBRFS(const char TRANS, const int n, const int kl, const int ku, const int nrhs, const float* A, const int lda, const float* AF, const int ldaf, const int* IPIV, const float* B, const int ldb, float* X, const int ldx, float* FERR, float* BERR, float* WORK, int* IWORK, int* info) const; void GESVX(const char FACT, const char TRANS, const int n, const int nrhs, float* A, const int lda, float* AF, const int ldaf, int* IPIV, char EQUED, float* R, float* C, float* B, const int ldb, float* X, const int ldx, float* rcond, float* FERR, float* BERR, float* WORK, int* IWORK, int* info) const; void SYTRD(const char UPLO, const int n, float* A, const int lda, float* D, float* E, float* TAU, float* WORK, const int lwork, int* info) const; void GEHRD(const int n, const int ilo, const int ihi, float* A, const int lda, float* TAU, float* WORK, const int lwork, int* info) const; void TRTRS(const char UPLO, const char TRANS, const char DIAG, const int n, const int nrhs, const float* A, const int lda, float* B, const int ldb, int* info) const; void TRTRI(const char UPLO, const char DIAG, const int n, const float* A, const int lda, int* info) const; // Symmetric eigenvalue routines. void SPEV(const char JOBZ, const char UPLO, const int n, float* AP, float* W, float* Z, const int ldz, float* WORK, int* info) const; void SYEV(const char JOBZ, const char UPLO, const int n, float* A, const int lda, float* W, float* WORK, const int lwork, int* info) const; void SYGV(const int itype, const char JOBZ, const char UPLO, const int n, float* A, const int lda, float* B, const int ldb, float* W, float* WORK, const int lwork, int* info) const; void HEEV(const char JOBZ, const char UPLO, const int n, float* A, const int lda, float* W, float* WORK, const int lwork, float* RWORK, int* info) const; void HEGV(const int itype, const char JOBZ, const char UPLO, const int n, float* A, const int lda, float* B, const int ldb, float* W, float* WORK, const int lwork, float *RWORK, int* info) const; void STEQR(const char COMPZ, const int n, float* D, float* E, float* Z, const int ldz, float* WORK, int* info) const; // Non-Hermitian eigenvalue routines. void HSEQR(const char JOB, const char COMPZ, const int n, const int ilo, const int ihi, float* H, const int ldh, float* WR, float* WI, float* Z, const int ldz, float* WORK, const int lwork, int* info) const; void GEES(const char JOBVS, const char SORT, int (*ptr2func)(float*, float*), const int n, float* A, const int lda, int* sdim, float* WR, float* WI, float* VS, const int ldvs, float* WORK, const int lwork, int* BWORK, int* info) const; void GEES(const char JOBVS, const int n, float* A, const int lda, int* sdim, float* WR, float* WI, float* VS, const int ldvs, float* WORK, const int lwork, float* RWORK, int* BWORK, int* info) const; void GEEV(const char JOBVL, const char JOBVR, const int n, float* A, const int lda, float* WR, float* WI, float* VL, const int ldvl, float* VR, const int ldvr, float* WORK, const int lwork, int* info) const; void GEEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const int n, float* A, const int lda, float* WR, float* WI, float* VL, const int ldvl, float* VR, const int ldvr, int* ilo, int* ihi, float* SCALE, float* abnrm, float* RCONDE, float* RCONDV, float* WORK, const int lwork, int* IWORK, int* info) const; void GGEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const int n, float* A, const int lda, float* B, const int ldb, float* ALPHAR, float* ALPHAI, float* BETA, float* VL, const int ldvl, float* VR, const int ldvr, int* ilo, int* ihi, float* LSCALE, float* RSCALE, float* abnrm, float* bbnrm, float* RCONDE, float* RCONDV, float* WORK, const int lwork, int* IWORK, int* BWORK, int* info) const; void GGEV(const char JOBVL, const char JOBVR, const int n, float *A, const int lda, float *B, const int ldb, float *ALPHAR, float *ALPHAI, float *BETA, float *VL, const int ldvl, float *VR, const int ldvr, float *WORK, const int lwork, int *info) const; // SVD routine void GESVD(const char JOBU, const char JOBVT, const int m, const int n, float* A, const int lda, float* S, float* U, const int ldu, float* V, const int ldv, float* WORK, const int lwork, float* RWORK, int* info) const; // Orthogonal matrix routines. void ORMQR(const char SIDE, const char TRANS, const int m, const int n, const int k, float* A, const int lda, const float* TAU, float* C, const int ldc, float* WORK, const int lwork, int* info) const; void UNMQR(const char SIDE, const char TRANS, const int m, const int n, const int k, float* A, const int lda, const float* TAU, float* C, const int ldc, float* WORK, const int lwork, int* info) const; void ORGQR(const int m, const int n, const int k, float* A, const int lda, const float* TAU, float* WORK, const int lwork, int* info) const; void UNGQR(const int m, const int n, const int k, float* A, const int lda, const float* TAU, float* WORK, const int lwork, int* info) const; void ORGHR(const int n, const int ilo, const int ihi, float* A, const int lda, const float* TAU, float* WORK, const int lwork, int* info) const; void ORMHR(const char SIDE, const char TRANS, const int m, const int n, const int ilo, const int ihi, const float* A, const int lda, const float* TAU, float* C, const int ldc, float* WORK, const int lwork, int* info) const; // Triangular matrix routines. void TREVC(const char SIDE, const char HOWMNY, int* select, const int n, const float* T, const int ldt, float* VL, const int ldvl, float* VR, const int ldvr, const int mm, int* m, float* WORK, int* info) const; void TREVC(const char SIDE, const int n, const float* T, const int ldt, float* VL, const int ldvl, float* VR, const int ldvr, const int mm, int* m, float* WORK, float *RWORK, int* info) const; void TREXC(const char COMPQ, const int n, float* T, const int ldt, float* Q, const int ldq, int ifst, int ilst, float* WORK, int* info) const; // Rotation/reflection generators void LARTG( const float f, const float g, float* c, float* s, float* r ) const; void LARFG( const int n, float* alpha, float* x, const int incx, float* tau ) const; // Matrix balancing routines. void GEBAL(const char JOBZ, const int n, float* A, const int lda, int ilo, int ihi, float* scale, int* info) const; void GEBAK(const char JOBZ, const char SIDE, const int n, const int ilo, const int ihi, const float* scale, const int m, float* V, const int ldv, int* info) const; // Random number generators float LARND( const int idist, int* seed ) const; void LARNV( const int idist, int* seed, const int n, float* v ) const; // Machine characteristics. float LAMCH(const char CMACH) const; int ILAENV( const int ispec, const std::string& NAME, const std::string& OPTS, const int N1 = -1, const int N2 = -1, const int N3 = -1, const int N4 = -1 ) const; // Miscellaneous routines. float LAPY2(const float x, const float y) const; }; // END INT, FLOAT SPECIALIZATION DECLARATION // // BEGIN INT, DOUBLE SPECIALIZATION DECLARATION // template<> class TEUCHOS_LIB_DLL_EXPORT LAPACK<int, double> { public: inline LAPACK(void) {} inline LAPACK(const LAPACK<int, double>& lapack) {} inline virtual ~LAPACK(void) {} // Symmetric positive definite linear system routines void PTTRF(const int n, double* d, double* e, int* info) const; void PTTRS(const int n, const int nrhs, const double* d, const double* e, double* B, const int ldb, int* info) const; void POTRF(const char UPLO, const int n, double* A, const int lda, int* info) const; void POTRS(const char UPLO, const int n, const int nrhs, const double* A, const int lda, double* B, const int ldb, int* info) const; void POTRI(const char UPLO, const int n, double* A, const int lda, int* info) const; void POCON(const char UPLO, const int n, const double* A, const int lda, const double anorm, double* rcond, double* WORK, int* IWORK, int* info) const; void POSV(const char UPLO, const int n, const int nrhs, double* A, const int lda, double* B, const int ldb, int* info) const; void POEQU(const int n, const double* A, const int lda, double* S, double* scond, double* amax, int* info) const; void PORFS(const char UPLO, const int n, const int nrhs, double* A, const int lda, const double* AF, const int ldaf, const double* B, const int ldb, double* X, const int ldx, double* FERR, double* BERR, double* WORK, int* IWORK, int* info) const; void POSVX(const char FACT, const char UPLO, const int n, const int nrhs, double* A, const int lda, double* AF, const int ldaf, char EQUED, double* S, double* B, const int ldb, double* X, const int ldx, double* rcond, double* FERR, double* BERR, double* WORK, int* IWORK, int* info) const; // General linear system routines void GELS(const char TRANS, const int m, const int n, const int nrhs, double* A, const int lda, double* B, const int ldb, double* WORK, const int lwork, int* info) const; void GELSS(const int m, const int n, const int nrhs, double* A, const int lda, double* B, const int ldb, double* S, const double rcond, int* rank, double* WORK, const int lwork, double* RWORK, int* info) const; void GELSS(const int m, const int n, const int nrhs, double* A, const int lda, double* B, const int ldb, double* S, const double rcond, int* rank, double* WORK, const int lwork, int* info) const; void GGLSE(const int m, const int n, const int p, double* A, const int lda, double* B, const int ldb, double* C, double* D, double* X, double* WORK, const int lwork, int* info) const; void GEQRF( const int m, const int n, double* A, const int lda, double* TAU, double* WORK, const int lwork, int* info) const; void GETRF(const int m, const int n, double* A, const int lda, int* IPIV, int* info) const; void GETRS(const char TRANS, const int n, const int nrhs, const double* A, const int lda, const int* IPIV, double* B, const int ldb, int* info) const; void GEQP3 (const int m, const int n, double* A, const int lda, int *jpvt, double* TAU, double* WORK, const int lwork, double* RWORK, int* info) const; void LASWP (const int N, double A[], const int LDA, const int K1, const int K2, const int IPIV[], const int INCX) const; void GBTRF(const int m, const int n, const int kl, const int ku, double* A, const int lda, int* IPIV, int* info) const; void GBTRS(const char TRANS, const int n, const int kl, const int ku, const int nrhs, const double* A, const int lda, const int* IPIV, double* B, const int ldb, int* info) const; void GTTRF(const int n, double* dl, double* d, double* du, double* du2, int* IPIV, int* info) const; void GTTRS(const char TRANS, const int n, const int nrhs, const double* dl, const double* d, const double* du, const double* du2, const int* IPIV, double* B, const int ldb, int* info) const; void GETRI(const int n, double* A, const int lda, const int* IPIV, double* WORK, const int lwork, int* info) const; void LATRS (const char UPLO, const char TRANS, const char DIAG, const char NORMIN, const int N, double* A, const int LDA, double* X, double* SCALE, double* CNORM, int* INFO) const; void GECON(const char NORM, const int n, const double* A, const int lda, const double anorm, double* rcond, double* WORK, int* IWORK, int* info) const; void GBCON(const char NORM, const int n, const int kl, const int ku, const double* A, const int lda, int* IPIV, const double anorm, double* rcond, double* WORK, int* IWORK, int* info) const; double LANGB(const char NORM, const int n, const int kl, const int ku, const double* A, const int lda, double* WORK) const; void GESV(const int n, const int nrhs, double* A, const int lda, int* IPIV, double* B, const int ldb, int* info) const; void GEEQU(const int m, const int n, const double* A, const int lda, double* R, double* C, double* rowcond, double* colcond, double* amax, int* info) const; void GERFS(const char TRANS, const int n, const int nrhs, const double* A, const int lda, const double* AF, const int ldaf, const int* IPIV, const double* B, const int ldb, double* X, const int ldx, double* FERR, double* BERR, double* WORK, int* IWORK, int* info) const; void GBEQU(const int m, const int n, const int kl, const int ku, const double* A, const int lda, double* R, double* C, double* rowcond, double* colcond, double* amax, int* info) const; void GBRFS(const char TRANS, const int n, const int kl, const int ku, const int nrhs, const double* A, const int lda, const double* AF, const int ldaf, const int* IPIV, const double* B, const int ldb, double* X, const int ldx, double* FERR, double* BERR, double* WORK, int* IWORK, int* info) const; void GESVX(const char FACT, const char TRANS, const int n, const int nrhs, double* A, const int lda, double* AF, const int ldaf, int* IPIV, char EQUED, double* R, double* C, double* B, const int ldb, double* X, const int ldx, double* rcond, double* FERR, double* BERR, double* WORK, int* IWORK, int* info) const; void SYTRD(const char UPLO, const int n, double* A, const int lda, double* D, double* E, double* TAU, double* WORK, const int lwork, int* info) const; void GEHRD(const int n, const int ilo, const int ihi, double* A, const int lda, double* TAU, double* WORK, const int lwork, int* info) const; void TRTRS(const char UPLO, const char TRANS, const char DIAG, const int n, const int nrhs, const double* A, const int lda, double* B, const int ldb, int* info) const; void TRTRI(const char UPLO, const char DIAG, const int n, const double* A, const int lda, int* info) const; // Symmetric eigenproblem routines. void SPEV(const char JOBZ, const char UPLO, const int n, double* AP, double* W, double* Z, const int ldz, double* WORK, int* info) const; void SYEV(const char JOBZ, const char UPLO, const int n, double* A, const int lda, double* W, double* WORK, const int lwork, int* info) const; void SYGV(const int itype, const char JOBZ, const char UPLO, const int n, double* A, const int lda, double* B, const int ldb, double* W, double* WORK, const int lwork, int* info) const; void HEEV(const char JOBZ, const char UPLO, const int n, double* A, const int lda, double* W, double* WORK, const int lwork, double* RWORK, int* info) const; void HEGV(const int itype, const char JOBZ, const char UPLO, const int n, double* A, const int lda, double* B, const int ldb, double* W, double* WORK, const int lwork, double *RWORK, int* info) const; void STEQR(const char COMPZ, const int n, double* D, double* E, double* Z, const int ldz, double* WORK, int* info) const; // Non-Hermitian eigenproblem routines. void HSEQR(const char JOB, const char COMPZ, const int n, const int ilo, const int ihi, double* H, const int ldh, double* WR, double* WI, double* Z, const int ldz, double* WORK, const int lwork, int* info) const; void GEES(const char JOBVS, const char SORT, int (*ptr2func)(double*, double*), const int n, double* A, const int lda, int* sdim, double* WR, double* WI, double* VS, const int ldvs, double* WORK, const int lwork, int* BWORK, int* info) const; void GEES(const char JOBVS, const int n, double* A, const int lda, int* sdim, double* WR, double* WI, double* VS, const int ldvs, double* WORK, const int lwork, double* RWORK, int* BWORK, int* info) const; void GEEV(const char JOBVL, const char JOBVR, const int n, double* A, const int lda, double* WR, double* WI, double* VL, const int ldvl, double* VR, const int ldvr, double* WORK, const int lwork, int* info) const; void GEEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const int n, double* A, const int lda, double* WR, double* WI, double* VL, const int ldvl, double* VR, const int ldvr, int* ilo, int* ihi, double* SCALE, double* abnrm, double* RCONDE, double* RCONDV, double* WORK, const int lwork, int* IWORK, int* info) const; void GGEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const int n, double* A, const int lda, double* B, const int ldb, double* ALPHAR, double* ALPHAI, double* BETA, double* VL, const int ldvl, double* VR, const int ldvr, int* ilo, int* ihi, double* LSCALE, double* RSCALE, double* abnrm, double* bbnrm, double* RCONDE, double* RCONDV, double* WORK, const int lwork, int* IWORK, int* BWORK, int* info) const; void GGEV(const char JOBVL, const char JOBVR, const int n, double *A, const int lda, double *B, const int ldb, double *ALPHAR, double *ALPHAI, double *BETA, double *VL, const int ldvl, double *VR, const int ldvr, double *WORK, const int lwork, int *info) const; // SVD routine void GESVD(const char JOBU, const char JOBVT, const int m, const int n, double* A, const int lda, double* S, double* U, const int ldu, double* V, const int ldv, double* WORK, const int lwork, double* RWORK, int* info) const; // Orthogonal matrix routines. void ORMQR(const char SIDE, const char TRANS, const int m, const int n, const int k, double* A, const int lda, const double* TAU, double* C, const int ldc, double* WORK, const int lwork, int* info) const; void UNMQR(const char SIDE, const char TRANS, const int m, const int n, const int k, double* A, const int lda, const double* TAU, double* C, const int ldc, double* WORK, const int lwork, int* info) const; void ORGQR(const int m, const int n, const int k, double* A, const int lda, const double* TAU, double* WORK, const int lwork, int* info) const; void UNGQR(const int m, const int n, const int k, double* A, const int lda, const double* TAU, double* WORK, const int lwork, int* info) const; void ORGHR(const int n, const int ilo, const int ihi, double* A, const int lda, const double* TAU, double* WORK, const int lwork, int* info) const; void ORMHR(const char SIDE, const char TRANS, const int m, const int n, const int ilo, const int ihi, const double* A, const int lda, const double* TAU, double* C, const int ldc, double* WORK, const int lwork, int* info) const; // Triangular matrix routines. void TREVC(const char SIDE, const char HOWMNY, int* select, const int n, const double* T, const int ldt, double* VL, const int ldvl, double* VR, const int ldvr, const int mm, int* m, double* WORK, int* info) const; void TREVC(const char SIDE, const int n, const double* T, const int ldt, double* VL, const int ldvl, double* VR, const int ldvr, const int mm, int* m, double* WORK, double* RWORK, int* info) const; void TREXC(const char COMPQ, const int n, double* T, const int ldt, double* Q, const int ldq, int ifst, int ilst, double* WORK, int* info) const; // Rotation/reflection generators void LARTG( const double f, const double g, double* c, double* s, double* r ) const; void LARFG( const int n, double* alpha, double* x, const int incx, double* tau ) const; // Matrix balancing routines. void GEBAL(const char JOBZ, const int n, double* A, const int lda, int ilo, int ihi, double* scale, int* info) const; void GEBAK(const char JOBZ, const char SIDE, const int n, const int ilo, const int ihi, const double* scale, const int m, double* V, const int ldv, int* info) const; // Random number generators double LARND( const int idist, int* seed ) const; void LARNV( const int idist, int* seed, const int n, double* v ) const; // Machine characteristic routines. double LAMCH(const char CMACH) const; int ILAENV( const int ispec, const std::string& NAME, const std::string& OPTS, const int N1 = -1, const int N2 = -1, const int N3 = -1, const int N4 = -1 ) const; // Miscellaneous routines. double LAPY2(const double x, const double y) const; }; // END INT, DOUBLE SPECIALIZATION DECLARATION // #ifdef HAVE_TEUCHOS_COMPLEX // BEGIN INT, COMPLEX<FLOAT> SPECIALIZATION DECLARATION // template<> class TEUCHOS_LIB_DLL_EXPORT LAPACK<int, std::complex<float> > { public: inline LAPACK(void) {} inline LAPACK(const LAPACK<int, std::complex<float> >& lapack) {} inline virtual ~LAPACK(void) {} // Symmetric positive definite linear system routines void PTTRF(const int n, std::complex<float>* d, std::complex<float>* e, int* info) const; void PTTRS(const int n, const int nrhs, const std::complex<float>* d, const std::complex<float>* e, std::complex<float>* B, const int ldb, int* info) const; void POTRF(const char UPLO, const int n, std::complex<float>* A, const int lda, int* info) const; void POTRS(const char UPLO, const int n, const int nrhs, const std::complex<float>* A, const int lda, std::complex<float>* B, const int ldb, int* info) const; void POTRI(const char UPLO, const int n, std::complex<float>* A, const int lda, int* info) const; void POCON(const char UPLO, const int n, const std::complex<float>* A, const int lda, const float anorm, float* rcond, std::complex<float>* WORK, float* rwork, int* info) const; void POSV(const char UPLO, const int n, const int nrhs, std::complex<float>* A, const int lda, std::complex<float>* B, const int ldb, int* info) const; void POEQU(const int n, const std::complex<float>* A, const int lda, float* S, float* scond, float* amax, int* info) const; void PORFS(const char UPLO, const int n, const int nrhs, std::complex<float>* A, const int lda, const std::complex<float>* AF, const int ldaf, const std::complex<float>* B, const int ldb, std::complex<float>* X, const int ldx, float* FERR, float* BERR, std::complex<float>* WORK, float* RWORK, int* info) const; void POSVX(const char FACT, const char UPLO, const int n, const int nrhs, std::complex<float>* A, const int lda, std::complex<float>* AF, const int ldaf, char EQUED, float* S, std::complex<float>* B, const int ldb, std::complex<float>* X, const int ldx, float* rcond, float* FERR, float* BERR, std::complex<float>* WORK, float* RWORK, int* info) const; // General Linear System Routines void GELS(const char TRANS, const int m, const int n, const int nrhs, std::complex<float>* A, const int lda, std::complex<float>* B, const int ldb, std::complex<float>* WORK, const int lwork, int* info) const; void GELSS(const int m, const int n, const int nrhs, std::complex<float>* A, const int lda, std::complex<float>* B, const int ldb, float* S, const float rcond, int* rank, std::complex<float>* WORK, const int lwork, float* RWORK, int* info) const; void GEQRF( const int m, const int n, std::complex<float>* A, const int lda, std::complex<float>* TAU, std::complex<float>* WORK, const int lwork, int* info) const; void UNGQR(const int m, const int n, const int k, std::complex<float>* A, const int lda, const std::complex<float>* TAU, std::complex<float>* WORK, const int lwork, int* info) const; void UNMQR(const char SIDE, const char TRANS, const int m, const int n, const int k, std::complex<float>* A, const int lda, const std::complex<float>* TAU, std::complex<float>* C, const int ldc, std::complex<float>* WORK, const int lwork, int* info) const; void GETRF(const int m, const int n, std::complex<float>* A, const int lda, int* IPIV, int* info) const; void GETRS(const char TRANS, const int n, const int nrhs, const std::complex<float>* A, const int lda, const int* IPIV, std::complex<float>* B, const int ldb, int* info) const; void GEQP3 (const int m, const int n, std::complex<float>* A, const int lda, int *jpvt, std::complex<float>* TAU, std::complex<float>* WORK, const int lwork, float* RWORK, int* info) const; void LASWP (const int N, std::complex<float> A[], const int LDA, const int K1, const int K2, const int IPIV[], const int INCX) const; void GBTRF(const int m, const int n, const int kl, const int ku, std::complex<float>* A, const int lda, int* IPIV, int* info) const; void GBTRS(const char TRANS, const int n, const int kl, const int ku, const int nrhs, const std::complex<float>* A, const int lda, const int* IPIV, std::complex<float>* B, const int ldb, int* info) const; void GTTRF(const int n, std::complex<float>* dl, std::complex<float>* d, std::complex<float>* du, std::complex<float>* du2, int* IPIV, int* info) const; void GTTRS(const char TRANS, const int n, const int nrhs, const std::complex<float>* dl, const std::complex<float>* d, const std::complex<float>* du, const std::complex<float>* du2, const int* IPIV, std::complex<float>* B, const int ldb, int* info) const; void GETRI(const int n, std::complex<float>* A, const int lda, const int* IPIV, std::complex<float>* WORK, const int lwork, int* info) const; void LATRS (const char UPLO, const char TRANS, const char DIAG, const char NORMIN, const int N, std::complex<float>* A, const int LDA, std::complex<float>* X, float* SCALE, float* CNORM, int* INFO) const; void GECON(const char NORM, const int n, const std::complex<float>* A, const int lda, const float anorm, float* rcond, std::complex<float>* WORK, float* RWORK, int* info) const; void GBCON(const char NORM, const int n, const int kl, const int ku, const std::complex<float>* A, const int lda, int* IPIV, const float anorm, float* rcond, std::complex<float>* WORK, float* RWORK, int* info) const; float LANGB(const char NORM, const int n, const int kl, const int ku, const std::complex<float>* A, const int lda, float* WORK) const; void GESV(const int n, const int nrhs, std::complex<float>* A, const int lda, int* IPIV, std::complex<float>* B, const int ldb, int* info) const; void GEEQU(const int m, const int n, const std::complex<float>* A, const int lda, float* R, float* C, float* rowcond, float* colcond, float* amax, int* info) const; void GERFS(const char TRANS, const int n, const int nrhs, const std::complex<float>* A, const int lda, const std::complex<float>* AF, const int ldaf, const int* IPIV, const std::complex<float>* B, const int ldb, std::complex<float>* X, const int ldx, float* FERR, float* BERR, std::complex<float>* WORK, float* RWORK, int* info) const; void GBEQU(const int m, const int n, const int kl, const int ku, const std::complex<float>* A, const int lda, float* R, float* C, float* rowcond, float* colcond, float* amax, int* info) const; void GBRFS(const char TRANS, const int n, const int kl, const int ku, const int nrhs, const std::complex<float>* A, const int lda, const std::complex<float>* AF, const int ldaf, const int* IPIV, const std::complex<float>* B, const int ldb, std::complex<float>* X, const int ldx, float* FERR, float* BERR, std::complex<float>* WORK, float* RWORK, int* info) const; void GESVX(const char FACT, const char TRANS, const int n, const int nrhs, std::complex<float>* A, const int lda, std::complex<float>* AF, const int ldaf, int* IPIV, char EQUED, float* R, float* C, std::complex<float>* B, const int ldb, std::complex<float>* X, const int ldx, float* rcond, float* FERR, float* BERR, std::complex<float>* WORK, float* RWORK, int* info) const; void GEHRD(const int n, const int ilo, const int ihi, std::complex<float>* A, const int lda, std::complex<float>* TAU, std::complex<float>* WORK, const int lwork, int* info) const; void TRTRS(const char UPLO, const char TRANS, const char DIAG, const int n, const int nrhs, const std::complex<float>* A, const int lda, std::complex<float>* B, const int ldb, int* info) const; void TRTRI(const char UPLO, const char DIAG, const int n, const std::complex<float>* A, const int lda, int* info) const; // Symmetric eigenvalue routines. void STEQR(const char COMPZ, const int n, float* D, float* E, std::complex<float>* Z, const int ldz, float* WORK, int* info) const; void HEEV(const char JOBZ, const char UPLO, const int n, std::complex<float>* A, const int lda, float* W, std::complex<float>* WORK, const int lwork, float* RWORK, int* info) const; void HEGV(const int itype, const char JOBZ, const char UPLO, const int n, std::complex<float>* A, const int lda, std::complex<float>* B, const int ldb, float* W, std::complex<float>* WORK, const int lwork, float *RWORK, int* info) const; // Non-Hermitian eigenvalue routines. void HSEQR(const char JOB, const char COMPZ, const int n, const int ilo, const int ihi, std::complex<float>* H, const int ldh, std::complex<float>* W, std::complex<float>* Z, const int ldz, std::complex<float>* WORK, const int lwork, int* info) const; void GEES(const char JOBVS, const char SORT, int (*ptr2func)(std::complex<float>*), const int n, std::complex<float>* A, const int lda, int* sdim, std::complex<float>* W, std::complex<float>* VS, const int ldvs, std::complex<float>* WORK, const int lwork, float* RWORK, int* BWORK, int* info) const; void GEES(const char JOBVS, const int n, std::complex<float>* A, const int lda, int* sdim, float* WR, float* WI, std::complex<float>* VS, const int ldvs, std::complex<float>* WORK, const int lwork, float* RWORK, int* BWORK, int* info) const; void GEEV(const char JOBVL, const char JOBVR, const int n, std::complex<float>* A, const int lda, std::complex<float>* W, std::complex<float>* VL, const int ldvl, std::complex<float>* VR, const int ldvr, std::complex<float>* WORK, const int lwork, float* RWORK, int* info) const; void GEEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const int n, std::complex<float>* A, const int lda, std::complex<float>* W, std::complex<float>* VL, const int ldvl, std::complex<float>* VR, const int ldvr, int* ilo, int* ihi, float* SCALE, float* abnrm, float* RCONDE, float* RCONDV, std::complex<float>* WORK, const int lwork, float* RWORK, int* info) const; void GGEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const int n, std::complex<float>* A, const int lda, std::complex<float>* B, const int ldb, std::complex<float>* ALPHA, std::complex<float>* BETA, std::complex<float>* VL, const int ldvl, std::complex<float>* VR, const int ldvr, int* ilo, int* ihi, float* LSCALE, float* RSCALE, float* abnrm, float* bbnrm, float* RCONDE, float* RCONDV, std::complex<float>* WORK, const int lwork, float * RWORK, int* IWORK, int* BWORK, int* info) const; void GGEV(const char JOBVL, const char JOBVR, const int n, std::complex<float> *A, const int lda, std::complex<float> *B, const int ldb, std::complex<float>* ALPHA, std::complex<float>* BETA, std::complex<float>* VL, const int ldvl, std::complex<float>* VR, const int ldvr, std::complex<float> *WORK, const int lwork, float* RWORK, int* info) const; // SVD routine void GESVD(const char JOBU, const char JOBVT, const int m, const int n, std::complex<float>* A, const int lda, float* S, std::complex<float>* U, const int ldu, std::complex<float>* V, const int ldv, std::complex<float>* WORK, const int lwork, float* RWORK, int* info) const; // Triangular matrix routines. void TREVC(const char SIDE, const char HOWMNY, int* select, const int n, const std::complex<float>* T, const int ldt, std::complex<float>* VL, const int ldvl, std::complex<float>* VR, const int ldvr, const int mm, int* m, std::complex<float>* WORK, float* RWORK, int* info) const; void TREVC(const char SIDE, const int n, const std::complex<float>* T, const int ldt, std::complex<float>* VL, const int ldvl, std::complex<float>* VR, const int ldvr, const int mm, int* m, std::complex<float>* WORK, float* RWORK, int* info) const; void TREXC(const char COMPQ, const int n, std::complex<float>* T, const int ldt, std::complex<float>* Q, const int ldq, int ifst, int ilst, std::complex<float>* WORK, int* info) const; // Rotation/reflection generators void LARTG( const std::complex<float> f, const std::complex<float> g, float* c, std::complex<float>* s, std::complex<float>* r ) const; void LARFG( const int n, std::complex<float>* alpha, std::complex<float>* x, const int incx, std::complex<float>* tau ) const; // Matrix balancing routines. void GEBAL(const char JOBZ, const int n, std::complex<float>* A, const int lda, int ilo, int ihi, float* scale, int* info) const; void GEBAK(const char JOBZ, const char SIDE, const int n, const int ilo, const int ihi, const float* scale, const int m, std::complex<float>* V, const int ldv, int* info) const; // Random number generators std::complex<float> LARND( const int idist, int* seed ) const; void LARNV( const int idist, int* seed, const int n, std::complex<float>* v ) const; // Machine characteristics int ILAENV( const int ispec, const std::string& NAME, const std::string& OPTS, const int N1 = -1, const int N2 = -1, const int N3 = -1, const int N4 = -1 ) const; }; // END INT, COMPLEX<FLOAT> SPECIALIZATION DECLARATION // // BEGIN INT, COMPLEX<DOUBLE> SPECIALIZATION DECLARATION // template<> class TEUCHOS_LIB_DLL_EXPORT LAPACK<int, std::complex<double> > { public: inline LAPACK(void) {} inline LAPACK(const LAPACK<int, std::complex<double> >& lapack) {} inline virtual ~LAPACK(void) {} // Symmetric positive definite linear system routines void PTTRF(const int n, std::complex<double>* d, std::complex<double>* e, int* info) const; void PTTRS(const int n, const int nrhs, const std::complex<double>* d, const std::complex<double>* e, std::complex<double>* B, const int ldb, int* info) const; void POTRF(const char UPLO, const int n, std::complex<double>* A, const int lda, int* info) const; void POTRS(const char UPLO, const int n, const int nrhs, const std::complex<double>* A, const int lda, std::complex<double>* B, const int ldb, int* info) const; void POTRI(const char UPLO, const int n, std::complex<double>* A, const int lda, int* info) const; void POCON(const char UPLO, const int n, const std::complex<double>* A, const int lda, const double anorm, double* rcond, std::complex<double>* WORK, double* RWORK, int* info) const; void POSV(const char UPLO, const int n, const int nrhs, std::complex<double>* A, const int lda, std::complex<double>* B, const int ldb, int* info) const; void POEQU(const int n, const std::complex<double>* A, const int lda, double* S, double* scond, double* amax, int* info) const; void PORFS(const char UPLO, const int n, const int nrhs, std::complex<double>* A, const int lda, const std::complex<double>* AF, const int ldaf, const std::complex<double>* B, const int ldb, std::complex<double>* X, const int ldx, double* FERR, double* BERR, std::complex<double>* WORK, double* RWORK, int* info) const; void POSVX(const char FACT, const char UPLO, const int n, const int nrhs, std::complex<double>* A, const int lda, std::complex<double>* AF, const int ldaf, char EQUED, double* S, std::complex<double>* B, const int ldb, std::complex<double>* X, const int ldx, double* rcond, double* FERR, double* BERR, std::complex<double>* WORK, double* RWORK, int* info) const; // General Linear System Routines void GELS(const char TRANS, const int m, const int n, const int nrhs, std::complex<double>* A, const int lda, std::complex<double>* B, const int ldb, std::complex<double>* WORK, const int lwork, int* info) const; void GELSS(const int m, const int n, const int nrhs, std::complex<double>* A, const int lda, std::complex<double>* B, const int ldb, double* S, const double rcond, int* rank, std::complex<double>* WORK, const int lwork, double* RWORK, int* info) const; void GEQRF( const int m, const int n, std::complex<double>* A, const int lda, std::complex<double>* TAU, std::complex<double>* WORK, const int lwork, int* info) const; void UNGQR(const int m, const int n, const int k, std::complex<double>* A, const int lda, const std::complex<double>* TAU, std::complex<double>* WORK, const int lwork, int* info) const; void UNMQR(const char SIDE, const char TRANS, const int m, const int n, const int k, std::complex<double>* A, const int lda, const std::complex<double>* TAU, std::complex<double>* C, const int ldc, std::complex<double>* WORK, const int lwork, int* info) const; void GETRF(const int m, const int n, std::complex<double>* A, const int lda, int* IPIV, int* info) const; void GETRS(const char TRANS, const int n, const int nrhs, const std::complex<double>* A, const int lda, const int* IPIV, std::complex<double>* B, const int ldb, int* info) const; void GEQP3 (const int m, const int n, std::complex<double>* A, const int lda, int *jpvt, std::complex<double>* TAU, std::complex<double>* WORK, const int lwork, double* RWORK, int* info) const; void LASWP (const int N, std::complex<double> A[], const int LDA, const int K1, const int K2, const int IPIV[], const int INCX) const; void GBTRF(const int m, const int n, const int kl, const int ku, std::complex<double>* A, const int lda, int* IPIV, int* info) const; void GBTRS(const char TRANS, const int n, const int kl, const int ku, const int nrhs, const std::complex<double>* A, const int lda, const int* IPIV, std::complex<double>* B, const int ldb, int* info) const; void GTTRF(const int n, std::complex<double>* dl, std::complex<double>* d, std::complex<double>* du, std::complex<double>* du2, int* IPIV, int* info) const; void GTTRS(const char TRANS, const int n, const int nrhs, const std::complex<double>* dl, const std::complex<double>* d, const std::complex<double>* du, const std::complex<double>* du2, const int* IPIV, std::complex<double>* B, const int ldb, int* info) const; void GETRI(const int n, std::complex<double>* A, const int lda, const int* IPIV, std::complex<double>* WORK, const int lwork, int* info) const; void LATRS (const char UPLO, const char TRANS, const char DIAG, const char NORMIN, const int N, std::complex<double>* A, const int LDA, std::complex<double>* X, double* SCALE, double* CNORM, int* INFO) const; void GECON(const char NORM, const int n, const std::complex<double>* A, const int lda, const double anorm, double* rcond, std::complex<double>* WORK, double* RWORK, int* info) const; void GBCON(const char NORM, const int n, const int kl, const int ku, const std::complex<double>* A, const int lda, int* IPIV, const double anorm, double* rcond, std::complex<double>* WORK, double* RWORK, int* info) const; double LANGB(const char NORM, const int n, const int kl, const int ku, const std::complex<double>* A, const int lda, double* WORK) const; void GESV(const int n, const int nrhs, std::complex<double>* A, const int lda, int* IPIV, std::complex<double>* B, const int ldb, int* info) const; void GEEQU(const int m, const int n, const std::complex<double>* A, const int lda, double* R, double* C, double* rowcond, double* colcond, double* amax, int* info) const; void GERFS(const char TRANS, const int n, const int nrhs, const std::complex<double>* A, const int lda, const std::complex<double>* AF, const int ldaf, const int* IPIV, const std::complex<double>* B, const int ldb, std::complex<double>* X, const int ldx, double* FERR, double* BERR, std::complex<double>* WORK, double* RWORK, int* info) const; void GBEQU(const int m, const int n, const int kl, const int ku, const std::complex<double>* A, const int lda, double* R, double* C, double* rowcond, double* colcond, double* amax, int* info) const; void GBRFS(const char TRANS, const int n, const int kl, const int ku, const int nrhs, const std::complex<double>* A, const int lda, const std::complex<double>* AF, const int ldaf, const int* IPIV, const std::complex<double>* B, const int ldb, std::complex<double>* X, const int ldx, double* FERR, double* BERR, std::complex<double>* WORK, double* RWORK, int* info) const; void GESVX(const char FACT, const char TRANS, const int n, const int nrhs, std::complex<double>* A, const int lda, std::complex<double>* AF, const int ldaf, int* IPIV, char EQUED, double* R, double* C, std::complex<double>* B, const int ldb, std::complex<double>* X, const int ldx, double* rcond, double* FERR, double* BERR, std::complex<double>* WORK, double* RWORK, int* info) const; void GEHRD(const int n, const int ilo, const int ihi, std::complex<double>* A, const int lda, std::complex<double>* TAU, std::complex<double>* WORK, const int lwork, int* info) const; void TRTRS(const char UPLO, const char TRANS, const char DIAG, const int n, const int nrhs, const std::complex<double>* A, const int lda, std::complex<double>* B, const int ldb, int* info) const; void TRTRI(const char UPLO, const char DIAG, const int n, const std::complex<double>* A, const int lda, int* info) const; // Symmetric eigenvalue routines. void STEQR(const char COMPZ, const int n, double* D, double* E, std::complex<double>* Z, const int ldz, double* WORK, int* info) const; void HEEV(const char JOBZ, const char UPLO, const int n, std::complex<double>* A, const int lda, double* W, std::complex<double>* WORK, const int lwork, double* RWORK, int* info) const; void HEGV(const int itype, const char JOBZ, const char UPLO, const int n, std::complex<double>* A, const int lda, std::complex<double>* B, const int ldb, double* W, std::complex<double>* WORK, const int lwork, double *RWORK, int* info) const; // Non-hermitian eigenvalue routines. void HSEQR(const char JOB, const char COMPZ, const int n, const int ilo, const int ihi, std::complex<double>* H, const int ldh, std::complex<double>* W, std::complex<double>* Z, const int ldz, std::complex<double>* WORK, const int lwork, int* info) const; void GEES(const char JOBVS, const char SORT, int (*ptr2func)(std::complex<double>*), const int n, std::complex<double>* A, const int lda, int* sdim, std::complex<double>* W, std::complex<double>* VS, const int ldvs, std::complex<double>* WORK, const int lwork, double* RWORK, int* BWORK, int* info) const; void GEES(const char JOBVS, const int n, std::complex<double>* A, const int lda, int* sdim, double* WR, double* WI, std::complex<double>* VS, const int ldvs, std::complex<double>* WORK, const int lwork, double* RWORK, int* BWORK, int* info) const; void GEEV(const char JOBVL, const char JOBVR, const int n, std::complex<double>* A, const int lda, std::complex<double>* W, std::complex<double>* VL, const int ldvl, std::complex<double>* VR, const int ldvr, std::complex<double>* WORK, const int lwork, double* RWORK, int* info) const; void GEEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const int n, std::complex<double>* A, const int lda, std::complex<double>* W, std::complex<double>* VL, const int ldvl, std::complex<double>* VR, const int ldvr, int* ilo, int* ihi, double* SCALE, double* abnrm, double* RCONDE, double* RCONDV, std::complex<double>* WORK, const int lwork, double* RWORK, int* info) const; void GGEVX(const char BALANC, const char JOBVL, const char JOBVR, const char SENSE, const int n, std::complex<double>* A, const int lda, std::complex<double>* B, const int ldb, std::complex<double>* ALPHA, std::complex<double>* BETA, std::complex<double>* VL, const int ldvl, std::complex<double>* VR, const int ldvr, int* ilo, int* ihi, double* LSCALE, double* RSCALE, double* abnrm, double* bbnrm, double* RCONDE, double* RCONDV, std::complex<double>* work, const int lwork, double* RWORK, int* IWORK, int* BWORK, int* info) const; void GGEV(const char JOBVL, const char JOBVR, const int n, std::complex<double> *A, const int lda, std::complex<double> *B, const int ldb, std::complex<double>* ALPHA, std::complex<double>* BETA, std::complex<double>* VL, const int ldvl, std::complex<double>*VR, const int ldvr, std::complex<double> *WORK, const int lwork, double* RWORK, int* info) const; // SVD routine void GESVD(const char JOBU, const char JOBVT, const int m, const int n, std::complex<double>* A, const int lda, double* S, std::complex<double>* U, const int ldu, std::complex<double>* V, const int ldv, std::complex<double>* WORK, const int lwork, double* RWORK, int* info) const; // Triangular matrix routines. void TREVC(const char SIDE, const char HOWMNY, int* select, const int n, const std::complex<double>* T, const int ldt, std::complex<double>* VL, const int ldvl, std::complex<double>* VR, const int ldvr, const int mm, int* m, std::complex<double>* WORK, double* RWORK, int* info) const; void TREVC(const char SIDE, const int n, const std::complex<double>* T, const int ldt, std::complex<double>* VL, const int ldvl, std::complex<double>* VR, const int ldvr, const int mm, int* m, std::complex<double>* WORK, double* RWORK, int* info) const; void TREXC(const char COMPQ, const int n, std::complex<double>* T, const int ldt, std::complex<double>* Q, const int ldq, int ifst, int ilst, std::complex<double>* WORK, int* info) const; // Rotation/reflection generators void LARTG( const std::complex<double> f, const std::complex<double> g, double* c, std::complex<double>* s, std::complex<double>* r ) const; void LARFG( const int n, std::complex<double>* alpha, std::complex<double>* x, const int incx, std::complex<double>* tau ) const; // Matrix balancing routines. void GEBAL(const char JOBZ, const int n, std::complex<double>* A, const int lda, int ilo, int ihi, double* scale, int* info) const; void GEBAK(const char JOBZ, const char SIDE, const int n, const int ilo, const int ihi, const double* scale, const int m, std::complex<double>* V, const int ldv, int* info) const; // Random number generators std::complex<double> LARND( const int idist, int* seed ) const; void LARNV( const int idist, int* seed, const int n, std::complex<double>* v ) const; // Machine characteristics int ILAENV( const int ispec, const std::string& NAME, const std::string& OPTS, const int N1 = -1, const int N2 = -1, const int N3 = -1, const int N4 = -1 ) const; }; // END INT, COMPLEX<DOUBLE> SPECIALIZATION DECLARATION // #endif // HAVE_TEUCHOS_COMPLEX #endif // DOXYGEN_SHOULD_SKIP_THIS } // namespace Teuchos #endif // _TEUCHOS_LAPACK_HPP_
azhirnov/AE
engine_tools/res_pack/pipeline_compiler/Public/PipelinePackSerializer.cpp
// Copyright (c) 2018-2020, <NAME>. For more information see 'LICENSE' #include "PipelinePack.h" #include "PipelinePackHash.h" #include "serializing/Serializer.h" #include "serializing/ObjectFactory.h" #include "stl/Algorithms/StringUtils.h" namespace AE::PipelineCompiler { /* ================================================= Serialize ================================================= */ bool DescriptorSetLayoutDesc::Serialize (Serializing::Serializer& ser) const { bool result = true; result &= ser( uint(uniforms.size()) ); result &= ser( uint(samplerStorage.size()) ); for (auto& id : samplerStorage) { result &= ser( id ); } const auto Serialize_Image = [&ser] (const DescriptorSetLayoutDesc::Image &img) { return ser( img.state, img.type ); }; for (auto&[name, un] : uniforms) { result &= ser( name ); } for (auto&[name, un] : uniforms) { result &= ser( un.type, un.index, un.arraySize ); BEGIN_ENUM_CHECKS(); switch ( un.type ) { case EDescriptorType::UniformBuffer : case EDescriptorType::StorageBuffer : result &= ser( un.buffer.state, un.buffer.dynamicOffsetIndex, un.buffer.staticSize, un.buffer.arrayStride ); break; case EDescriptorType::UniformTexelBuffer : case EDescriptorType::StorageTexelBuffer : result &= ser( un.texelBuffer.state ); break; case EDescriptorType::StorageImage : result &= Serialize_Image( un.storageImage ); break; case EDescriptorType::SampledImage : result &= Serialize_Image( un.sampledImage ); break; case EDescriptorType::CombinedImage : result &= Serialize_Image( un.combinedImage ); break; case EDescriptorType::CombinedImage_ImmutableSampler : CHECK_ERR( un.combinedImageWithSampler.samplerOffsetInStorage + un.arraySize <= samplerStorage.size() ); result &= Serialize_Image( un.combinedImageWithSampler.image ); result &= ser( un.combinedImageWithSampler.samplerOffsetInStorage ); break; case EDescriptorType::SubpassInput : result &= Serialize_Image( un.subpassInput ); break; case EDescriptorType::Sampler : result &= ser( un.sampler.stageFlags ); break; case EDescriptorType::ImmutableSampler : CHECK_ERR( un.immutableSampler.offsetInStorage + un.arraySize <= samplerStorage.size() ); result &= ser( un.immutableSampler.offsetInStorage ); break; case EDescriptorType::RayTracingScene : // TODO //break; case EDescriptorType::Unknown : default : RETURN_ERR( "unknown descriptor type" ); } END_ENUM_CHECKS(); } return result; } /* ================================================= Merge ================================================= */ bool DescriptorSetLayoutDesc::Merge (const DescriptorSetLayoutDesc &other, OUT size_t &merged) { merged = 0; auto src = other.uniforms.begin(); auto dst = uniforms.begin(); for (; dst != uniforms.end() and src != other.uniforms.end();) { if ( dst->first > src->first ) { ++src; continue; } if ( dst->first < src->first ) { ++dst; continue; } if ( dst->first == src->first ) { auto& dst_un = dst->second; auto& src_un = src->second; CHECK_ERR( dst_un.index == src_un.index ); CHECK_ERR( dst_un.type == src_un.type ); CHECK_ERR( dst_un.arraySize == src_un.arraySize ); // TODO: unsized arrays BEGIN_ENUM_CHECKS(); switch ( dst_un.type ) { case EDescriptorType::UniformBuffer : case EDescriptorType::StorageBuffer : { bool dst_has_dyn_idx = (dst_un.buffer.dynamicOffsetIndex != UMax); bool src_has_dyn_idx = (src_un.buffer.dynamicOffsetIndex != UMax); CHECK_ERR( dst_has_dyn_idx == src_has_dyn_idx ); CHECK_ERR( dst_un.buffer.staticSize == src_un.buffer.staticSize ); CHECK_ERR( dst_un.buffer.arrayStride == src_un.buffer.arrayStride ); CHECK_ERR( EnumEq( dst_un.buffer.state, src_un.buffer.state, EResourceState::_ShaderMask )); merged += (dst_un.buffer.state != src_un.buffer.state); dst_un.buffer.state |= (src_un.buffer.state & EResourceState::_ShaderMask); break; } case EDescriptorType::UniformTexelBuffer : case EDescriptorType::StorageTexelBuffer : { CHECK_ERR( EnumEq( dst_un.texelBuffer.state, src_un.texelBuffer.state, EResourceState::_ShaderMask )); merged += (dst_un.texelBuffer.state != src_un.texelBuffer.state); dst_un.texelBuffer.state |= (src_un.texelBuffer.state & EResourceState::_ShaderMask); break; } case EDescriptorType::StorageImage : { CHECK_ERR( EnumEq( dst_un.storageImage.state, src_un.storageImage.state, EResourceState::_ShaderMask )); CHECK_ERR( dst_un.storageImage.type == src_un.storageImage.type ); merged += (dst_un.storageImage.state != src_un.storageImage.state); dst_un.storageImage.state |= (src_un.storageImage.state & EResourceState::_ShaderMask); break; } case EDescriptorType::SampledImage : { CHECK_ERR( EnumEq( dst_un.sampledImage.state, src_un.sampledImage.state, EResourceState::_ShaderMask )); CHECK_ERR( dst_un.sampledImage.type == src_un.sampledImage.type ); merged += (dst_un.sampledImage.state != src_un.sampledImage.state); dst_un.sampledImage.state |= (src_un.sampledImage.state & EResourceState::_ShaderMask); break; } case EDescriptorType::CombinedImage : { CHECK_ERR( EnumEq( dst_un.combinedImage.state, src_un.combinedImage.state, EResourceState::_ShaderMask )); CHECK_ERR( dst_un.combinedImage.type == src_un.combinedImage.type ); merged += (dst_un.combinedImage.state != src_un.combinedImage.state); dst_un.combinedImage.state |= (src_un.combinedImage.state & EResourceState::_ShaderMask); break; } case EDescriptorType::CombinedImage_ImmutableSampler : { CHECK_ERR( dst_un.combinedImageWithSampler.samplerOffsetInStorage + dst_un.arraySize <= samplerStorage.size() ); CHECK_ERR( src_un.combinedImageWithSampler.samplerOffsetInStorage + src_un.arraySize <= other.samplerStorage.size() ); CHECK_ERR( EnumEq( dst_un.combinedImageWithSampler.image.state, src_un.combinedImageWithSampler.image.state, EResourceState::_ShaderMask )); CHECK_ERR( dst_un.combinedImageWithSampler.image.type == src_un.combinedImageWithSampler.image.type ); merged += (dst_un.combinedImageWithSampler.image.state != src_un.combinedImageWithSampler.image.state); dst_un.combinedImageWithSampler.image.state |= (src_un.combinedImageWithSampler.image.state & EResourceState::_ShaderMask); // compare samplers for (size_t i = 0; i < dst_un.arraySize; ++i) { auto& dst_samp = samplerStorage[ dst_un.combinedImageWithSampler.samplerOffsetInStorage + i ]; auto& src_samp = other.samplerStorage[ src_un.combinedImageWithSampler.samplerOffsetInStorage + i ]; CHECK_ERR( dst_samp == src_samp ); } break; } case EDescriptorType::SubpassInput : { CHECK_ERR( EnumEq( dst_un.subpassInput.state, src_un.subpassInput.state, EResourceState::_ShaderMask )); CHECK_ERR( dst_un.subpassInput.type == src_un.subpassInput.type ); merged += (dst_un.subpassInput.state != src_un.subpassInput.state); dst_un.subpassInput.state |= (src_un.subpassInput.state & EResourceState::_ShaderMask); break; } case EDescriptorType::Sampler : { dst_un.sampler.stageFlags |= src_un.sampler.stageFlags; break; } case EDescriptorType::ImmutableSampler : { for (size_t i = 0; i < dst_un.arraySize; ++i) { auto& dst_samp = samplerStorage[ dst_un.immutableSampler.offsetInStorage + i ]; auto& src_samp = other.samplerStorage[ src_un.immutableSampler.offsetInStorage + i ]; CHECK_ERR( dst_samp == src_samp ); } break; } case EDescriptorType::RayTracingScene : // TODO //break; case EDescriptorType::Unknown : default : RETURN_ERR( "unknown descriptor type" ); } END_ENUM_CHECKS(); ++src; ++dst; } } for (; src != other.uniforms.end(); ++src) { ++merged; auto& dst_un = uniforms.emplace_back( *src ).second; auto& src_un = src->second; if ( src_un.type == EDescriptorType::CombinedImage_ImmutableSampler ) { dst_un.combinedImageWithSampler.samplerOffsetInStorage = samplerStorage.size(); for (size_t i = 0; i < src_un.arraySize; ++i) { samplerStorage.push_back( other.samplerStorage[ src_un.combinedImageWithSampler.samplerOffsetInStorage + i ]); } } if ( src_un.type == EDescriptorType::ImmutableSampler ) { dst_un.immutableSampler.offsetInStorage = samplerStorage.size(); for (size_t i = 0; i < src_un.arraySize; ++i) { samplerStorage.push_back( other.samplerStorage[ src_un.immutableSampler.offsetInStorage + i ]); } } } SortUniforms(); return true; } /* ================================================= SortUniforms ================================================= */ void DescriptorSetLayoutDesc::SortUniforms () { std::sort( uniforms.begin(), uniforms.end(), [](auto& lhs, auto& rhs) { return lhs.first < rhs.first; }); } //----------------------------------------------------------------------------- /* ================================================= Merge ================================================= */ bool PushConstants::Merge (const PushConstants &other) { for (auto& src : other.items) { auto dst = items.find( src.first ); if ( dst != items.end() ) { CHECK_ERR( dst->second.offset == src.second.offset ); CHECK_ERR( dst->second.size == src.second.size ); dst->second.stageFlags |= src.second.stageFlags; } else { CHECK( items.insert( src ).second ); } } return true; } /* ================================================= Serialize ================================================= */ bool PushConstants::Serialize (Serializing::Serializer& ser) const { bool result = true; result &= ser( uint(items.size()) ); for (auto& pc : items) { result &= ser( pc.first, pc.second.stageFlags, pc.second.offset, pc.second.size ); } return result; } //----------------------------------------------------------------------------- /* ================================================= Serialize ================================================= */ bool PipelineLayoutDesc::Serialize (Serializing::Serializer& ser) const { return ser( descrSets, pushConstants ); } //----------------------------------------------------------------------------- /* ================================================= Serialize_VertexAttribs ================================================= */ namespace { static bool Serialize_VertexAttribs (Serializing::Serializer& ser, const GraphicsPipelineDesc::VertexAttribs_t &vertexAttribs) { bool result = ser( uint(vertexAttribs.size()) ); for (auto& attr : vertexAttribs) { result &= ser( attr.id, attr.index, attr.type ); } return result; } } // namespace /* ================================================= Serialize ================================================= */ bool GraphicsPipelineDesc::Serialize (Serializing::Serializer& ser) const { bool result = ser( layout, renderPass, shaders, supportedTopology, patchControlPoints, specialization, earlyFragmentTests ); result &= Serialize_VertexAttribs( ser, vertexAttribs ); return result; } //----------------------------------------------------------------------------- /* ================================================= Serialize ================================================= */ bool MeshPipelineDesc::Serialize (Serializing::Serializer& ser) const { bool result = true; result &= ser( layout, renderPass, shaders, topology, maxVertices, maxIndices, specialization ); result &= ser( defaultTaskGroupSize, taskSizeSpec, defaultMeshGroupSize, meshSizeSpec, earlyFragmentTests ); return result; } //----------------------------------------------------------------------------- /* ================================================= Serialize ================================================= */ bool ComputePipelineDesc::Serialize (Serializing::Serializer& ser) const { return ser( layout, shader, defaultLocalGroupSize, localSizeSpec, specialization ); } //----------------------------------------------------------------------------- /* ================================================= Serialize ================================================= */ bool SpirvShaderCode::Serialize (Serializing::Serializer &ser) const { return ser( spec, code ); } //----------------------------------------------------------------------------- /* ================================================= Serialize ================================================= */ bool RenderPassInfo::Serialize (Serializing::Serializer &ser) const { bool result = true; result &= ser( uint(fragmentOutputs.size()) ); for (auto& frag : fragmentOutputs) { result &= ser( frag.first, frag.second.index, frag.second.type ); } return result; } //----------------------------------------------------------------------------- /* ================================================= constructor ================================================= */ PipelineStorage::PipelineStorage () { _dsLayouts.reserve( 128 ); _dsLayoutMap.reserve( 128 ); _pplnLayouts.reserve( 128 ); _pplnLayoutMap.reserve( 128 ); _graphicsPipelines.reserve( 128 ); _gpipelineMap.reserve( 128 ); _meshPipelines.reserve( 128 ); _mpipelineMap.reserve( 128 ); _computePipelines.reserve( 128 ); _cpipelineMap.reserve( 128 ); _spirvShaders.reserve( 128 ); _spirvShaderMap.reserve( 128 ); } /* ================================================= AddDescriptorSetLayout ================================================= */ DescrSetUID PipelineStorage::AddDescriptorSetLayout (DescriptorSetLayoutDesc &&desc) { std::sort( desc.uniforms.begin(), desc.uniforms.end(), [](auto& lhs, auto& rhs) { return lhs.first < rhs.first; }); const size_t hash = size_t(DescriptorSetLayoutHash( desc )); auto iter = _dsLayoutMap.find( hash ); for (; iter != _dsLayoutMap.end() and iter->first == hash; ++iter) { auto& lhs = _dsLayouts[ size_t(iter->second) ]; if ( Equal( lhs, desc )) return iter->second; } auto uid = DescrSetUID(_dsLayouts.size()); _dsLayoutMap.insert({ hash, uid }); _dsLayouts.push_back( std::move(desc) ); return uid; } /* ================================================= AddPipelineLayout ================================================= */ PipelineLayoutUID PipelineStorage::AddPipelineLayout (PipelineLayoutDesc &&desc) { const size_t hash = size_t(PipelineLayoutHash( desc )); auto iter = _pplnLayoutMap.find( hash ); for (; iter != _pplnLayoutMap.end() and iter->first == hash; ++iter) { auto& lhs = _pplnLayouts[ size_t(iter->second) ]; if ( Equal( lhs, desc )) return iter->second; } auto uid = PipelineLayoutUID(_pplnLayouts.size()); _pplnLayoutMap.insert({ hash, uid }); _pplnLayouts.push_back( std::move(desc) ); return uid; } /* ================================================= AddPipeline ================================================= */ PipelineUID PipelineStorage::AddPipeline (const PipelineName &name, GraphicsPipelineDesc &&desc) { CHECK_ERR( name.IsDefined() ); const size_t hash = size_t(GraphicsPipelineHash( desc )); auto iter = _gpipelineMap.find( hash ); for (; iter != _gpipelineMap.end() and iter->first == hash; ++iter) { auto& lhs = _graphicsPipelines[ size_t(iter->second) & size_t(~PipelineUID::_Mask) ]; if ( Equal( lhs, desc )) { CHECK( _pipelineMap.insert_or_assign( name, iter->second ).second ); return iter->second; } } auto uid = PipelineUID(_graphicsPipelines.size() | uint(PipelineUID::Graphics)); _gpipelineMap.insert({ hash, uid }); _graphicsPipelines.push_back( std::move(desc) ); CHECK( _pipelineMap.insert_or_assign( name, uid ).second ); return uid; } /* ================================================= AddPipeline ================================================= */ PipelineUID PipelineStorage::AddPipeline (const PipelineName &name, MeshPipelineDesc &&desc) { CHECK_ERR( name.IsDefined() ); const size_t hash = size_t(MeshPipelineHash( desc )); auto iter = _mpipelineMap.find( hash ); for (; iter != _mpipelineMap.end() and iter->first == hash; ++iter) { auto& lhs = _meshPipelines[ size_t(iter->second) & size_t(~PipelineUID::_Mask) ]; if ( Equal( lhs, desc )) { CHECK( _pipelineMap.insert_or_assign( name, iter->second ).second ); return iter->second; } } auto uid = PipelineUID(_meshPipelines.size() | uint(PipelineUID::Mesh)); _mpipelineMap.insert({ hash, uid }); _meshPipelines.push_back( std::move(desc) ); CHECK( _pipelineMap.insert_or_assign( name, uid ).second ); return uid; } /* ================================================= AddPipeline ================================================= */ PipelineUID PipelineStorage::AddPipeline (const PipelineName &name, ComputePipelineDesc &&desc) { CHECK_ERR( name.IsDefined() ); const size_t hash = size_t(ComputePipelineHash( desc )); auto iter = _cpipelineMap.find( hash ); for (; iter != _cpipelineMap.end() and iter->first == hash; ++iter) { auto& lhs = _computePipelines[ size_t(iter->second) & size_t(~PipelineUID::_Mask) ]; if ( Equal( lhs, desc )) { CHECK( _pipelineMap.insert_or_assign( name, iter->second ).second ); return iter->second; } } auto uid = PipelineUID(_computePipelines.size() | uint(PipelineUID::Compute)); _cpipelineMap.insert({ hash, uid }); _computePipelines.push_back( std::move(desc) ); CHECK( _pipelineMap.insert_or_assign( name, uid ).second ); return uid; } /* ================================================= AddShader ================================================= */ ShaderUID PipelineStorage::AddShader (Array<uint> &&spirv, const SpecConstants_t &spec) { SpirvShaderCode code { std::move(spirv), spec }; const size_t hash = size_t(SpirvShaderCodeHash( code )); auto iter = _spirvShaderMap.find( hash ); for (; iter != _spirvShaderMap.end() and iter->first == hash; ++iter) { auto& lhs = _spirvShaders[ size_t(iter->second) & ~uint(ShaderUID::_Mask) ]; if ( Equal( lhs, code )) return iter->second; } auto uid = ShaderUID(_spirvShaders.size() | uint(ShaderUID::SPIRV)); _spirvShaderMap.insert({ hash, uid }); _spirvShaders.push_back( std::move(code) ); return uid; } /* ================================================= AddRenderPass ================================================= */ RenderPassUID PipelineStorage::AddRenderPass (const RenderPassName &name, const RenderPassInfo &info) { for (size_t i = 0; i < _renderPasses.size(); ++i) { if ( _renderPasses[i].fragmentOutputs == info.fragmentOutputs ) { if ( name.IsDefined() ) { auto[iter, inserted] = _renderPassMap.insert({ name, RenderPassUID(i) }); if ( not inserted ) CHECK( iter->second == RenderPassUID(i) ); } return RenderPassUID(i); } } RenderPassName new_name = name; if ( new_name.GetName().empty() ) { // make unique name for (size_t i = 0; i < 1000; ++i) { new_name = RenderPassName{ "RP_"s << ToString(i) }; if ( not _renderPassMap.count( new_name )) break; } } const auto uid = RenderPassUID(_renderPasses.size()); _renderPasses.push_back( info ); CHECK( _renderPassMap.insert_or_assign( new_name, uid ).second ); return uid; } /* ================================================= Serialize ================================================= */ bool PipelineStorage::Serialize (Serializing::Serializer& ser) const { bool result = true; result &= ser( Version ); // TODO: write buffer size result &= ser( uint(EMarker::DescrSetLayouts), _dsLayouts ); ASSERT( result ); AE_LOGI( "Serialized descriptor set layouts: "s << ToString(_dsLayouts.size()) ); result &= ser( uint(EMarker::PipelineLayouts), _pplnLayouts ); ASSERT( result ); AE_LOGI( "Serialized pipeline layouts: "s << ToString(_pplnLayouts.size()) ); result &= ser( uint(EMarker::RenderPasses), _renderPasses ); { Array<Pair< RenderPassName, RenderPassUID >> rp_names; rp_names.reserve( _renderPassMap.size() ); for (auto& item : _renderPassMap) { rp_names.push_back( item ); } std::sort( rp_names.begin(), rp_names.end(), [](auto& lhs, auto& rhs) { return lhs.first < rhs.first; }); result &= ser( uint(EMarker::RenderPassNames), rp_names ); } ASSERT( result ); AE_LOGI( "Serialized render passes: "s << ToString(_renderPassMap.size()) ); result &= ser( uint(EMarker::SpirvShaders), _spirvShaders ); ASSERT( result ); AE_LOGI( "Serialized SPIRV shaders: "s << ToString(_spirvShaders.size()) ); result &= ser( uint(EMarker::GraphicsPipelines), _graphicsPipelines ); ASSERT( result ); AE_LOGI( "Serialized graphics pipelines: "s << ToString(_graphicsPipelines.size()) ); result &= ser( uint(EMarker::MeshPipelines), _meshPipelines ); ASSERT( result ); AE_LOGI( "Serialized mesh pipelines: "s << ToString(_meshPipelines.size()) ); result &= ser( uint(EMarker::ComputePipelines), _computePipelines ); ASSERT( result ); AE_LOGI( "Serialized compute pipelines: "s << ToString(_computePipelines.size()) ); // temp result &= ser( uint(EMarker::RayTracingPipelines), uint(0) ); ASSERT( result ); { Array<Pair< PipelineName, PipelineUID >> ppln_names; ppln_names.reserve( _pipelineMap.size() ); for (auto& item : _pipelineMap) { ppln_names.push_back( item ); } std::sort( ppln_names.begin(), ppln_names.end(), [](auto& lhs, auto& rhs) { return lhs.first < rhs.first; }); result &= ser( uint(EMarker::PipelineNames), ppln_names ); ASSERT( result ); } return result; } } // AE::PipelineCompiler
iplo/Chain
chrome/android/javatests/src/org/chromium/chrome/browser/ShortcutHelperTest.java
<reponame>iplo/Chain // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser; import android.content.Intent; import android.test.FlakyTest; import org.chromium.base.test.util.UrlUtils; import org.chromium.chrome.testshell.ChromiumTestShellActivity; import org.chromium.chrome.testshell.ChromiumTestShellApplication; import org.chromium.chrome.testshell.ChromiumTestShellApplicationObserver; import org.chromium.chrome.testshell.ChromiumTestShellTestBase; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; public class ShortcutHelperTest extends ChromiumTestShellTestBase { private static final String WEBAPP_ACTION_NAME = "WEBAPP_ACTION"; private static final String WEBAPP_TITLE = "Webapp shortcut"; private static final String WEBAPP_HTML = UrlUtils.encodeHtmlDataUri( "<html><head>" + "<meta name=\"mobile-web-app-capable\" content=\"yes\" />" + "<title>" + WEBAPP_TITLE + "</title>" + "</head><body>Webapp capable</body></html>"); private static final String EDITED_WEBAPP_TITLE = "Webapp shortcut edited"; private static final String SECOND_WEBAPP_TITLE = "Webapp shortcut #2"; private static final String SECOND_WEBAPP_HTML = UrlUtils.encodeHtmlDataUri( "<html><head>" + "<meta name=\"mobile-web-app-capable\" content=\"yes\" />" + "<title>" + SECOND_WEBAPP_TITLE + "</title>" + "</head><body>Webapp capable again</body></html>"); private static final String NORMAL_TITLE = "Plain shortcut"; private static final String NORMAL_HTML = UrlUtils.encodeHtmlDataUri( "<html>" + "<head><title>" + NORMAL_TITLE + "</title></head>" + "<body>Not Webapp capable</body></html>"); private static class TestObserver implements ChromiumTestShellApplicationObserver { Intent firedIntent; @Override public boolean onSendBroadcast(Intent intent) { if (intent.hasExtra(Intent.EXTRA_SHORTCUT_NAME)) { // Stop a shortcut from really being added. firedIntent = intent; return false; } return true; } public void reset() { firedIntent = null; } } private ChromiumTestShellActivity mActivity; private TestObserver mTestObserver; @Override public void setUp() throws Exception { ShortcutHelper.setFullScreenAction(WEBAPP_ACTION_NAME); mActivity = launchChromiumTestShellWithBlankPage(); // Set up the observer. mTestObserver = new TestObserver(); ChromiumTestShellApplication application = (ChromiumTestShellApplication) mActivity.getApplication(); application.addObserver(mTestObserver); super.setUp(); } /** * @MediumTest * @Feature("{Webapp}") * crbug.com/303486 */ @FlakyTest public void testAddWebappShortcuts() throws InterruptedException { // Add a webapp shortcut and make sure the intent's parameters make sense. addShortcutToURL(WEBAPP_HTML, ""); Intent firedIntent = mTestObserver.firedIntent; assertEquals(WEBAPP_TITLE, firedIntent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME)); Intent launchIntent = firedIntent.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); assertEquals(WEBAPP_HTML, launchIntent.getStringExtra(ShortcutHelper.EXTRA_URL)); assertEquals(WEBAPP_ACTION_NAME, launchIntent.getAction()); assertEquals(mActivity.getPackageName(), launchIntent.getPackage()); // Add a second shortcut and make sure it matches the second webapp's parameters. mTestObserver.reset(); addShortcutToURL(SECOND_WEBAPP_HTML, ""); Intent newFiredIntent = mTestObserver.firedIntent; assertEquals(SECOND_WEBAPP_TITLE, newFiredIntent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME)); Intent newLaunchIntent = newFiredIntent.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); assertEquals(SECOND_WEBAPP_HTML, newLaunchIntent.getStringExtra(ShortcutHelper.EXTRA_URL)); assertEquals(WEBAPP_ACTION_NAME, newLaunchIntent.getAction()); assertEquals(mActivity.getPackageName(), newLaunchIntent.getPackage()); } /** * @MediumTest * @Feature("{Webapp}") * crbug.com/303486 */ @FlakyTest public void testAddBookmarkShortcut() throws InterruptedException { addShortcutToURL(NORMAL_HTML, ""); // Make sure the intent's parameters make sense. Intent firedIntent = mTestObserver.firedIntent; assertEquals(NORMAL_TITLE, firedIntent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME)); Intent launchIntent = firedIntent.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); assertEquals(mActivity.getPackageName(), launchIntent.getPackage()); assertEquals(Intent.ACTION_VIEW, launchIntent.getAction()); assertEquals(NORMAL_HTML, launchIntent.getDataString()); } /** * @MediumTest * @Feature("{Webapp}") * crbug.com/303486 */ @FlakyTest public void testAddWebappShortcutsWithoutTitleEdit() throws InterruptedException { // Add a webapp shortcut to check unedited title. addShortcutToURL(WEBAPP_HTML, ""); Intent firedIntent = mTestObserver.firedIntent; assertEquals(WEBAPP_TITLE, firedIntent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME)); } /** * @MediumTest * @Feature("{Webapp}") * crbug.com/303486 */ @FlakyTest public void testAddWebappShortcutsWithTitleEdit() throws InterruptedException { // Add a webapp shortcut to check edited title. addShortcutToURL(WEBAPP_HTML, EDITED_WEBAPP_TITLE); Intent firedIntent = mTestObserver.firedIntent; assertEquals(EDITED_WEBAPP_TITLE , firedIntent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME)); } private void addShortcutToURL(String url, final String title) throws InterruptedException { loadUrlWithSanitization(url); assertTrue(waitForActiveShellToBeDoneLoading()); // Add the shortcut. getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { ShortcutHelper.addShortcut(mActivity.getApplicationContext(), mActivity.getActiveTab(), title); } }); // Make sure that the shortcut was added. assertTrue(CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { return mTestObserver.firedIntent != null; } })); } }
jeff5/jython-whinchat
tests/java/org/python/compiler/custom_proxymaker/CustomAnnotation.java
<reponame>jeff5/jython-whinchat package org.python.compiler.custom_proxymaker; /** * This Annotation contains most of the possible annotation fields, * used to test the annotation part of custom proxymaker */ import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD, ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE, ElementType.PACKAGE,ElementType.FIELD,ElementType.LOCAL_VARIABLE}) @Inherited public @interface CustomAnnotation { public enum Priority { LOW, MEDIUM, HIGH } String value(); String[] changedBy() default ""; Priority[] priorities(); Priority priority() default Priority.MEDIUM; String createdBy() default "<NAME>"; String lastChanged() default "08/06/2012"; }
zhangkn/iOS14Header
Applications/Setup/BuddyExpressRestoreController.h
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import "BuddyWelcomeController.h" #import "BYEnvironmentDependencyReceiver-Protocol.h" @class BuddyInternalSkipInfoProvider, MBManager, NSDateFormatter, NSString, RestorableBackupItem; @protocol BYDeviceProvider; @interface BuddyExpressRestoreController : BuddyWelcomeController <BYEnvironmentDependencyReceiver> { _Bool _shouldAttemptBackupPriorToRestore; // 8 = 0x8 _Bool _forceSoftwareUpdateRequiredForNewBackup; // 9 = 0x9 id <BYDeviceProvider> _deviceProvider; // 16 = 0x10 NSDateFormatter *_longDateFormatter; // 24 = 0x18 NSDateFormatter *_shortDateFormatter; // 32 = 0x20 MBManager *_backupManager; // 40 = 0x28 NSString *_sourceDeviceName; // 48 = 0x30 RestorableBackupItem *_backupItem; // 56 = 0x38 } + (_Bool)controllerNeedsToRun; // IMP=0x000000010009e248 + (id)cloudConfigSkipKey; // IMP=0x000000010009e240 - (void).cxx_destruct; // IMP=0x00000001000a0bc4 @property(nonatomic) _Bool forceSoftwareUpdateRequiredForNewBackup; // @synthesize forceSoftwareUpdateRequiredForNewBackup=_forceSoftwareUpdateRequiredForNewBackup; @property(nonatomic) _Bool shouldAttemptBackupPriorToRestore; // @synthesize shouldAttemptBackupPriorToRestore=_shouldAttemptBackupPriorToRestore; @property(retain, nonatomic) RestorableBackupItem *backupItem; // @synthesize backupItem=_backupItem; @property(copy, nonatomic) NSString *sourceDeviceName; // @synthesize sourceDeviceName=_sourceDeviceName; @property(retain, nonatomic) MBManager *backupManager; // @synthesize backupManager=_backupManager; @property(retain, nonatomic) NSDateFormatter *shortDateFormatter; // @synthesize shortDateFormatter=_shortDateFormatter; @property(retain, nonatomic) NSDateFormatter *longDateFormatter; // @synthesize longDateFormatter=_longDateFormatter; @property(retain, nonatomic) id <BYDeviceProvider> deviceProvider; // @synthesize deviceProvider=_deviceProvider; - (void)_manualButtonTapped; // IMP=0x00000001000a0964 - (void)_restoreButtonTapped; // IMP=0x00000001000a0844 - (void)_backupAndRestoreTapped; // IMP=0x00000001000a07b8 - (void)_showWiFiRequiredAlert; // IMP=0x00000001000a0404 - (_Bool)_shouldShowWiFiRequiredAlert; // IMP=0x00000001000a03b0 - (void)_queueRestoreWithBackup:(_Bool)arg1; // IMP=0x000000010009ff98 - (_Bool)_shouldAttemptBackupPriorToRestore:(id)arg1 softwareUpdateRequired:(out _Bool *)arg2; // IMP=0x000000010009f8a0 - (void)_setBackupItem:(id)arg1 deviceName:(id)arg2; // IMP=0x000000010009f810 - (_Bool)_isBackupFromProximityDevice:(id)arg1; // IMP=0x000000010009f6e4 - (void)_validateBackupIsCompatible:(id)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x000000010009f484 - (id)_restorableBackupItemFromCloud:(_Bool)arg1 deviceName:(out id *)arg2; // IMP=0x000000010009ef44 - (id)_restorableBackupItemFromProximity:(out id *)arg1 didAttempt:(out _Bool *)arg2; // IMP=0x000000010009ebe0 - (void)_automaticallySelectedRestorable:(CDUnknownBlockType)arg1; // IMP=0x000000010009e9ac - (void)performExtendedInitializationWithCompletion:(CDUnknownBlockType)arg1; // IMP=0x000000010009e434 - (void)viewDidLayoutSubviews; // IMP=0x000000010009e1d4 - (void)viewDidLoad; // IMP=0x000000010009da9c - (void)viewDidAppear:(_Bool)arg1; // IMP=0x000000010009da24 - (void)loadView; // IMP=0x000000010009d60c - (id)init; // IMP=0x000000010009d3f8 // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(retain, nonatomic) BuddyInternalSkipInfoProvider *internalSkipInfoProvider; @property(readonly) Class superclass; @end
incodehq/incode-examples
module-examples/communications/dom/src/main/java/org/incode/example/communications/dom/impl/commchannel/CommunicationChannelOwner_communicationChannelTitlesAbstract.java
package org.incode.example.communications.dom.impl.commchannel; import javax.inject.Inject; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Contributed; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; public abstract class CommunicationChannelOwner_communicationChannelTitlesAbstract { private final CommunicationChannelOwner owner; private String separator; private final CommunicationChannelType communicationChannelType; public CommunicationChannelOwner_communicationChannelTitlesAbstract( final CommunicationChannelOwner owner, final String separator, final CommunicationChannelType communicationChannelType) { this.owner = owner; this.separator = separator; this.communicationChannelType = communicationChannelType; } @Action(semantics = SemanticsOf.SAFE) @ActionLayout(contributed = Contributed.AS_ASSOCIATION) @Property(hidden = Where.OBJECT_FORMS) public String prop() { return communicationChannelTitleService.channelTitleJoined(owner, communicationChannelType, separator); } @Inject CommunicationChannelTitleService communicationChannelTitleService; }
gv2011/util-apis
src/main/java/com/github/gv2011/util/uc/UStrBuilderImp.java
package com.github.gv2011.util.uc; /*- * #%L * The MIT License (MIT) * %% * Copyright (C) 2016 - 2018 Vinz (https://github.com/gv2011) * %% * 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. * #L% */ public class UStrBuilderImp implements UStrBuilder{ private final Object lock = new Object(); private DelegateBuilder delegate = new Iso8859_1Builder(); private int size = 0; @Override public UStr build() { synchronized(lock){ return delegate.build(); } } @Override public UStrBuilder append(final UStr str) { synchronized(lock){ for(int i=0; i<str.size(); i++) append(str.getCodePoint(i)); } return this; } @Override public UStrBuilder append(final UChar ch) { return append(ch.codePoint()); } @Override public UStrBuilder append(final int codePoint) { synchronized(lock){ if(!delegate.fits(codePoint)){ switchBuilder(codePoint); } delegate.append(codePoint); size++; } return this; } private void switchBuilder(final int codePoint) { final UStr str = delegate.build(); if(codePoint<=UChar.MAX_BMP){ delegate = new BmpBuilder(); } else{ delegate = new UniBuilder(); } for(int i=0; i<str.size(); i++) append(str.get(i)); } @Override public final UStrBuilder set(final int index, final UChar ch) { return set(index, ch.codePoint()); } @Override public UStrBuilder set(final int index, final int codePoint) { synchronized(lock){ while(size<index) append(0); if(index==size) append(codePoint); else{ assert index<size; if(!delegate.fits(codePoint)){ switchBuilder(codePoint); } delegate.set(index, codePoint); } } return this; } }
manstis/mapper-xml
api/src/main/java/org/treblereel/gwt/xml/mapper/api/deser/array/PrimitiveLongArrayXMLDeserializer.java
/* * Copyright 2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.treblereel.gwt.xml.mapper.api.deser.array; import java.util.List; import javax.xml.stream.XMLStreamException; import org.treblereel.gwt.xml.mapper.api.XMLDeserializationContext; import org.treblereel.gwt.xml.mapper.api.XMLDeserializer; import org.treblereel.gwt.xml.mapper.api.XMLDeserializerParameters; import org.treblereel.gwt.xml.mapper.api.deser.BaseNumberXMLDeserializer; import org.treblereel.gwt.xml.mapper.api.stream.XMLReader; /** * Default {@link XMLDeserializer} implementation for array of long. * * @author <NAME> * @version $Id: $ */ public class PrimitiveLongArrayXMLDeserializer extends AbstractArrayXMLDeserializer<long[]> { /** * getInstance * * @return an instance of {@link PrimitiveLongArrayXMLDeserializer} */ public static PrimitiveLongArrayXMLDeserializer getInstance() { return new PrimitiveLongArrayXMLDeserializer(); } private PrimitiveLongArrayXMLDeserializer() {} /** {@inheritDoc} */ @Override public long[] doDeserializeArray( XMLReader reader, XMLDeserializationContext ctx, XMLDeserializerParameters params) throws XMLStreamException { List<Long> list = deserializeIntoList( reader, ctx, s -> BaseNumberXMLDeserializer.LongXMLDeserializer.getInstance(), params); long[] result = new long[list.size()]; int i = 0; for (Long value : list) { if (null != value) { result[i] = value; } i++; } return result; } /** {@inheritDoc} */ @Override protected long[] doDeserializeSingleArray( XMLReader reader, XMLDeserializationContext ctx, XMLDeserializerParameters params) throws XMLStreamException { return new long[] { BaseNumberXMLDeserializer.LongXMLDeserializer.getInstance().deserialize(reader, ctx, params) }; } }
CrazyForks/turms
turms-server-common/src/main/java/im/turms/server/common/property/env/service/business/StorageProperties.java
<gh_stars>1000+ /* * Copyright (C) 2019 The Turms Project * https://github.com/turms-im/turms * * 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.turms.server.common.property.env.service.business; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.util.MimeTypeUtils; import javax.validation.constraints.Min; import java.time.Duration; /** * There properties are "recommended" and optional for plugin providers to implement * * @author <NAME> */ @AllArgsConstructor @Builder(toBuilder = true) @Data @NoArgsConstructor public class StorageProperties { @Min(0) private int profileExpiration = 30; @Min(0) private int groupProfileExpiration = 30; // @Min(0) // private int storageExpiration = 30; @Min(0) private int attachmentExpiration = 30; private String profileContentType = MimeTypeUtils.ALL_VALUE; private String groupProfileContentType = MimeTypeUtils.ALL_VALUE; // private String storageContentType = MimeTypeUtils.ALL_VALUE; private String attachmentContentType = MimeTypeUtils.ALL_VALUE; private int profileSizeLimit = 1 * 1024 * 1024; private int groupProfileSizeLimit = 1 * 1024 * 1024; // private int storageSizeLimit = 10 * 1024 * 1024; private int attachmentSizeLimit = 10 * 1024 * 1024; private Duration signatureDurationForGet = Duration.ofMinutes(5); private Duration signatureDurationForPut = Duration.ofMinutes(5); }
herrerameri/rns-manager-react
src/app/containers/metamask/MetamaskFormContainer.js
import { MetamaskFormComponent } from '../../components'; import { start } from '../../auth' import { connect } from 'react-redux'; const mapStateToProps = state => ({ enabled: state.auth.address }) const mapDispatchToProps = (dispatch, ownProps) => ({ startAndSubmit: () => dispatch(start(ownProps.onSubmit)) }); export default connect( mapStateToProps, mapDispatchToProps )(MetamaskFormComponent);
leeonky/bean-util
src/main/java/com/github/leeonky/util/NoSuchAccessorException.java
<reponame>leeonky/bean-util package com.github.leeonky.util; public class NoSuchAccessorException extends IllegalArgumentException { public NoSuchAccessorException(String message) { super(message); } }
vaijira/geode-native
cppcache/src/AdminRegion.hpp
<reponame>vaijira/geode-native /* * 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. */ #pragma once #ifndef GEODE_ADMINREGION_H_ #define GEODE_ADMINREGION_H_ #include <memory> #include <string> #include <geode/Serializable.hpp> #include <geode/Serializable.hpp> #include "ReadWriteLock.hpp" #include "NonCopyable.hpp" #include "ErrType.hpp" namespace apache { namespace geode { namespace statistics { class HostStatSampler; } // namespace statistics namespace client { class CacheImpl; class ThinClientBaseDM; class TcrConnectionManager; class CacheableKey; class AdminRegion : private NonCopyable, private NonAssignable, public std::enable_shared_from_this<AdminRegion> { private: ThinClientBaseDM* m_distMngr; std::string m_fullPath; TcrConnectionManager* m_connectionMgr; ACE_RW_Thread_Mutex m_rwLock; bool m_destroyPending; GfErrType putNoThrow(const std::shared_ptr<CacheableKey>& keyPtr, const std::shared_ptr<Cacheable>& valuePtr); TcrConnectionManager* getConnectionManager(); public: AdminRegion() : m_distMngr(nullptr), m_fullPath("/__ADMIN_CLIENT_HEALTH_MONITORING__"), m_connectionMgr(nullptr), m_destroyPending(false) {} ~AdminRegion(); static std::shared_ptr<AdminRegion> create( CacheImpl* cache, ThinClientBaseDM* distMan = nullptr); ACE_RW_Thread_Mutex& getRWLock(); const bool& isDestroyed(); void close(); void init(); void put(const std::shared_ptr<CacheableKey>& keyPtr, const std::shared_ptr<Cacheable>& valuePtr); friend class apache::geode::statistics::HostStatSampler; }; } // namespace client } // namespace geode } // namespace apache #endif // GEODE_ADMINREGION_H_
tfsservice18/Test
view/src/tools/mockResponse.js
/** * Returns a mock response from server * @param {integer} status - Status server code * @param {string} statusText - Server text * @param {string} response - Server return in strings * @returns Response object */ export default (status, statusText, response) => new window.Response(response, { status, statusText, headers: { 'Content-type': 'application/json', }, });
Thorsten-Geppert/Warehouse
src/modules/warehouse/TextEditDialog.cpp
#include "TextEditDialog.h" #include "Configuration.h" #include "PrintPreviewDialog.h" #include "YesNoDialog.h" #include "resources/images/WarehouseIcon.xpm" #include <DSFile.h> #include <wx/clipbrd.h> BEGIN_EVENT_TABLE(TextEditDialog, wxDialog) EVT_CLOSE(TextEditDialog::OnClose) EVT_MENU(SAVE_EVENT, TextEditDialog::SaveKeyEvent) EVT_MENU(PRINT_EVENT, TextEditDialog::PrintKeyEvent) EVT_MENU(PRINT_PREVIEW_EVENT, TextEditDialog::PrintPreviewKeyEvent) EVT_MENU(COPY_EVENT, TextEditDialog::CopyKeyEvent) EVT_MENU(CUT_EVENT, TextEditDialog::CutKeyEvent) EVT_MENU(PASTE_EVENT, TextEditDialog::PasteKeyEvent) EVT_MENU(IMPORT_EVENT, TextEditDialog::ImportKeyEvent) EVT_MENU(EXPORT_EVENT, TextEditDialog::ExportKeyEvent) EVT_MENU(CANCEL_EVENT, TextEditDialog::CancelKeyEvent) END_EVENT_TABLE() TextEditDialog::TextEditDialog( wxWindow *parent, wxWindowID id, RuntimeInformationType *rit, bool *changed, wxString *value ) { this->rit = rit; this->changed = changed; this->value = value; this->innerChanged = false; wxXmlResource::Get()->Load(rit->GRP(_N("gui"), _N("TextEditDialog.xml"))); wxXmlResource::Get()->LoadDialog(this, parent, _N("TextEditDialog")); mainPanel = XRCCTRL(*this, "mainPanel", wxPanel); mainBoxSizer = static_cast<wxBoxSizer *>(mainPanel->GetSizer()); mainToolbar = XRCCTRL(*this, "mainToolbar", Toolbar); saveToolbarButton = XRCCTRL(*this, "saveToolbarButton", ToolbarButton); printToolbarButton = XRCCTRL(*this, "printToolbarButton", ToolbarButton); printPreviewToolbarButton = XRCCTRL(*this, "printPreviewToolbarButton", ToolbarButton); copyToolbarButton = XRCCTRL(*this, "copyToolbarButton", ToolbarButton); cutToolbarButton = XRCCTRL(*this, "cutToolbarButton", ToolbarButton); pasteToolbarButton = XRCCTRL(*this, "pasteToolbarButton", ToolbarButton); importToolbarButton = XRCCTRL(*this, "importToolbarButton", ToolbarButton); exportToolbarButton = XRCCTRL(*this, "exportToolbarButton", ToolbarButton); cancelToolbarButton = XRCCTRL(*this, "cancelToolbarButton", ToolbarButton); informationTextCtrl = XRCCTRL(*this, "informationTextCtrl", DSTextCtrl); mainBoxSizer->SetSizeHints(this); CONNECT_TOOLBARBUTTON(saveToolbarButton, TextEditDialog::SaveEvent); CONNECT_TOOLBARBUTTON(printToolbarButton, TextEditDialog::PrintEvent); CONNECT_TOOLBARBUTTON(printPreviewToolbarButton, TextEditDialog::PrintPreviewEvent); CONNECT_TOOLBARBUTTON(copyToolbarButton, TextEditDialog::CopyEvent); CONNECT_TOOLBARBUTTON(cutToolbarButton, TextEditDialog::CutEvent); CONNECT_TOOLBARBUTTON(pasteToolbarButton, TextEditDialog::PasteEvent); CONNECT_TOOLBARBUTTON(importToolbarButton, TextEditDialog::ImportEvent); CONNECT_TOOLBARBUTTON(exportToolbarButton, TextEditDialog::ExportEvent); CONNECT_TOOLBARBUTTON(cancelToolbarButton, TextEditDialog::CancelEvent); wxAcceleratorEntry acceleratorEntries[10]; acceleratorEntries[0].Set(wxACCEL_CTRL, (int) 's', SAVE_EVENT); acceleratorEntries[1].Set(wxACCEL_CTRL, (int) 'p', PRINT_EVENT); acceleratorEntries[2].Set(wxACCEL_CTRL | wxACCEL_SHIFT, (int) 'p', PRINT_PREVIEW_EVENT); acceleratorEntries[3].Set(wxACCEL_CTRL, (int) 'c', COPY_EVENT); acceleratorEntries[4].Set(wxACCEL_CTRL, (int) 'x', CUT_EVENT); acceleratorEntries[5].Set(wxACCEL_CTRL, (int) 'v', PASTE_EVENT); acceleratorEntries[6].Set(wxACCEL_CTRL, (int) 'i', IMPORT_EVENT); acceleratorEntries[7].Set(wxACCEL_CTRL, (int) 'e', EXPORT_EVENT); acceleratorEntries[8].Set(wxACCEL_NORMAL, WXK_ESCAPE, CANCEL_EVENT); acceleratorEntries[9].Set(wxACCEL_CTRL, (int) 'w', CANCEL_EVENT); wxAcceleratorTable acceleratorTable(10, acceleratorEntries); SetAcceleratorTable(acceleratorTable); SetSize(wxSize(1000, 600)); if(value) informationTextCtrl->SetValue(*value); informationTextCtrl->SetFocus(); informationTextCtrl->SetChange(&innerChanged); ICON(); } // Events void TextEditDialog::SaveEvent(wxMouseEvent &event) { Save(); SKIP(); } void TextEditDialog::CopyEvent(wxMouseEvent &event) { Copy(); SKIP(); } void TextEditDialog::CutEvent(wxMouseEvent &event) { Cut(); SKIP(); } void TextEditDialog::PasteEvent(wxMouseEvent &event) { Paste(); SKIP(); } void TextEditDialog::ImportEvent(wxMouseEvent &event) { Import(); SKIP(); } void TextEditDialog::ExportEvent(wxMouseEvent &event) { Export(); SKIP(); } void TextEditDialog::PrintPreviewEvent(wxMouseEvent &event) { Print(true); SKIP(); } void TextEditDialog::PrintEvent(wxMouseEvent &event) { Print(); SKIP(); } void TextEditDialog::CancelEvent(wxMouseEvent &event) { Cancel(); SKIP(); } // Key Events void TextEditDialog::SaveKeyEvent(wxCommandEvent &event) { Save(); } void TextEditDialog::CopyKeyEvent(wxCommandEvent &event) { Copy(); } void TextEditDialog::CutKeyEvent(wxCommandEvent &event) { Cut(); } void TextEditDialog::PasteKeyEvent(wxCommandEvent &event) { Paste(); } void TextEditDialog::ImportKeyEvent(wxCommandEvent &event) { Import(); } void TextEditDialog::ExportKeyEvent(wxCommandEvent &event) { Export(); } void TextEditDialog::PrintPreviewKeyEvent(wxCommandEvent &event) { Print(true); } void TextEditDialog::PrintKeyEvent(wxCommandEvent &event) { Print(); } void TextEditDialog::CancelKeyEvent(wxCommandEvent &event) { Cancel(); } // Methods void TextEditDialog::OnClose(wxCloseEvent &event) { bool ok = true; if(innerChanged) { YesNoDialog *yesNoDialog = new YesNoDialog( this, -1, rit, _("You have changed the data. Do you want to use the changes?"), _("Close"), _("Save"), _("Cancel") ); yesNoDialog->Center(); if(yesNoDialog->ShowModal() == wxID_YES) ok = Save(); yesNoDialog->Destroy(); } if(ok) { event.Skip(); } else { event.Veto(); } innerChanged = false; } bool TextEditDialog::Save() { if(!rit->Access(A_WRITE, _("You have no permission to save this text."), this)) return false; if(value) *value = informationTextCtrl->GetValue(); informationTextCtrl->SetFocus(); if(changed) *changed = true; else return false; return true; } void TextEditDialog::Copy() { long selectionFrom = 0, selectionTo = 0; informationTextCtrl->GetSelection(&selectionFrom, &selectionTo); informationTextCtrl->Copy(); informationTextCtrl->SetFocus(); informationTextCtrl->SetSelection(selectionFrom, selectionTo); } void TextEditDialog::Cut() { long selectionFrom = 0, selectionTo = 0; informationTextCtrl->GetSelection(&selectionFrom, &selectionTo); informationTextCtrl->Cut(); informationTextCtrl->SetFocus(); informationTextCtrl->SetSelection(0, 0); informationTextCtrl->SetInsertionPoint(selectionFrom); } void TextEditDialog::Paste() { wxString clipboard; if(wxTheClipboard->Open()) { if(wxTheClipboard->IsSupported(wxDF_TEXT)) { wxTextDataObject data; wxTheClipboard->GetData(data); clipboard = data.GetText(); } wxTheClipboard->Close(); } if(clipboard.IsEmpty()) return; long selectionFrom = 0, selectionTo = 0; informationTextCtrl->GetSelection(&selectionFrom, &selectionTo); if(selectionFrom != selectionTo) informationTextCtrl->Remove(selectionFrom, selectionTo); const long insertionPoint = informationTextCtrl->GetInsertionPoint(); informationTextCtrl->Paste(); informationTextCtrl->SetFocus(); informationTextCtrl->SetInsertionPoint(insertionPoint + clipboard.Length()); } void TextEditDialog::Import() { informationTextCtrl->SetFocus(); if(!rit->Access(A_WRITE, _("You have no permission to import text."), this)) return; wxFileDialog *browseFileDialog = new wxFileDialog( this, _("Choose a file"), lastImportFile, wxEmptyString, _N("*.*"), wxFD_OPEN ); browseFileDialog->Center(); if(browseFileDialog->ShowModal() == wxID_OK) { lastImportFile = browseFileDialog->GetPath(); DSFile file(lastImportFile, _N("r")); if(file.IsOpened()) { wxString tmp; if(!file.ReadAll(&tmp)) { wxMessageDialog *errorMessage = new wxMessageDialog( this, _("Could not write file."), _("Text edit") ); errorMessage->Center(); errorMessage->ShowModal(); errorMessage->Destroy(); } else { informationTextCtrl->SetValue(tmp); } if(!file.Close()) { wxMessageDialog *errorMessage = new wxMessageDialog( this, _("Could not close file."), _("Text exit") ); errorMessage->Center(); errorMessage->ShowModal(); errorMessage->Destroy(); } } } browseFileDialog->Destroy(); informationTextCtrl->SetSelection(0, 0); } void TextEditDialog::Export() { long selectionFrom = 0, selectionTo = 0; informationTextCtrl->GetSelection(&selectionFrom, &selectionTo); if(!rit->Access(A_READ, _("You have no permission to export text."), this)) return; wxFileDialog *browseFileDialog = new wxFileDialog( this, _("Choose a file"), lastExportFile, _N("export.txt"), _N("*.*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); browseFileDialog->Center(); if(browseFileDialog->ShowModal() == wxID_OK) { lastExportFile = browseFileDialog->GetPath(); DSFile file(lastExportFile, _N("w")); if(file.IsOpened()) { if(!file.Write(informationTextCtrl->GetValue())) { wxMessageDialog *errorMessage = new wxMessageDialog( this, _("Could not write file."), _("Text edit") ); errorMessage->Center(); errorMessage->ShowModal(); errorMessage->Destroy(); } if(!file.Close()) { wxMessageDialog *errorMessage = new wxMessageDialog( this, _("Could not close file."), _("Text edit") ); errorMessage->Center(); errorMessage->ShowModal(); errorMessage->Destroy(); } } else { wxMessageDialog *errorMessage = new wxMessageDialog( this, _("Could not open file."), _("Text edit") ); errorMessage->Center(); errorMessage->ShowModal(); errorMessage->Destroy(); } } browseFileDialog->Destroy(); informationTextCtrl->SetFocus(); informationTextCtrl->SetSelection(selectionFrom, selectionTo); } void TextEditDialog::Print(const bool preview) { informationTextCtrl->SetFocus(); if(!rit->Access(A_READ, _("You have no permission to print."), this)) return; //changed = false; if(*changed) { wxMessageDialog *errorMessage = new wxMessageDialog( this, _("Save first this entry and press print again. Only saved entries can be printed."), _("Print") ); errorMessage->Center(); errorMessage->ShowModal(); errorMessage->Destroy(); return; } HtmlPrintoutLibrary *htmlPrintoutLibrary = new HtmlPrintoutLibrary(_("Informationen"), rit); DSTemplate informationTemplate = htmlPrintoutLibrary->GetTemplateByFile(_N("Informationen.tpl")); wxString note(DSLib::HtmlSpecialChars(informationTextCtrl->GetValue())); note.Replace(_N("\t"), _N("&nbsp;&nbsp;&nbsp;&nbsp;")); informationTemplate.SetVariable( _N("text"), DSLib::nl2br(note) ); informationTemplate.Parse(); htmlPrintoutLibrary->SetWithContainer(informationTemplate.Get()); if(preview) { PrintPreviewDialog *printPreviewDialog = new PrintPreviewDialog(this, -1, rit, htmlPrintoutLibrary); printPreviewDialog->Center(); printPreviewDialog->ShowModal(); printPreviewDialog->Destroy(); } else { wxPrinter printer; printer.Print(this, htmlPrintoutLibrary, true); } delete htmlPrintoutLibrary; } void TextEditDialog::Cancel() { Close(); } wxString TextEditDialog::GetValue() const { return informationTextCtrl->GetValue(); } void TextEditDialog::SetValue(const wxString &value) { informationTextCtrl->SetValue(value); } void TextEditDialog::ResetValue() { informationTextCtrl->ChangeValue(*this->value); informationTextCtrl->SetInsertionPoint(0); } DSTextCtrl *TextEditDialog::GetTextCtrl() const { return informationTextCtrl; }
felipesqf/BEGINNER-CHALLENGES-Back-End-Javascript
node_modules/@polkadot/types/codec/Map.spec.js
"use strict"; var _create = require("../create"); var _primitive = require("../primitive"); var _ = require("."); // Copyright 2017-2020 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 const registry = new _create.TypeRegistry(); const mockU32TextMap = new Map(); mockU32TextMap.set(new _primitive.Text(registry, 'bazzing'), new _primitive.U32(registry, 69)); const mockU32TextMapString = '{"bazzing":69}'; const mockU32TextMapObject = { bazzing: 69 }; const mockU32TextMapHexString = '0x041c62617a7a696e6745000000'; const mockU32TextMapUint8Array = Uint8Array.from([4, 28, 98, 97, 122, 122, 105, 110, 103, 69, 0, 0, 0]); const mockU32U32Map = new Map(); mockU32U32Map.set(new _primitive.U32(registry, 1), new _primitive.U32(registry, 2)); mockU32U32Map.set(new _primitive.U32(registry, 23), new _primitive.U32(registry, 24)); mockU32U32Map.set(new _primitive.U32(registry, 28), new _primitive.U32(registry, 30)); mockU32U32Map.set(new _primitive.U32(registry, 45), new _primitive.U32(registry, 80)); const mockU32U32MapString = '{"1":2,"23":24,"28":30,"45":80}'; const mockU32U32MapObject = { 1: 2, 23: 24, 28: 30, 45: 80 }; const mockU32U32MapHexString = '0x10043102000000083233180000000832381e00000008343550000000'; const mockU32U32MapUint8Array = Uint8Array.from([16, 4, 49, 2, 0, 0, 0, 8, 50, 51, 24, 0, 0, 0, 8, 50, 56, 30, 0, 0, 0, 8, 52, 53, 80, 0, 0, 0]); describe('CodecMap', () => { describe('decoding', () => { const testDecode = (type, input, output) => it(`can decode from ${type}`, () => { const s = new _.CodecMap(registry, _primitive.Text, _primitive.U32, input); expect(s.toString()).toBe(output); }); testDecode('map', mockU32TextMap, mockU32TextMapString); testDecode('hex', mockU32TextMapHexString, mockU32TextMapString); testDecode('Uint8Array', mockU32TextMapUint8Array, mockU32TextMapString); testDecode('map', mockU32U32Map, mockU32U32MapString); testDecode('hex', mockU32U32MapHexString, mockU32U32MapString); testDecode('Uint8Array', mockU32U32MapUint8Array, mockU32U32MapString); }); describe('encoding', () => { const testEncode = (to, expected) => it(`can encode ${to}`, () => { const s = new _.CodecMap(registry, _primitive.Text, _primitive.U32, mockU32TextMap, 'BTreeMap'); expect(s[to]()).toEqual(expected); }); testEncode('toHex', mockU32TextMapHexString); testEncode('toJSON', mockU32TextMapObject); testEncode('toU8a', mockU32TextMapUint8Array); testEncode('toString', mockU32TextMapString); }); describe('encoding muple values', () => { const testEncode = (to, expected) => it(`can encode ${to}`, () => { const s = new _.CodecMap(registry, _primitive.Text, _primitive.U32, mockU32U32Map, 'BTreeMap'); expect(s[to]()).toEqual(expected); }); testEncode('toHex', mockU32U32MapHexString); testEncode('toJSON', mockU32U32MapObject); testEncode('toU8a', mockU32U32MapUint8Array); testEncode('toString', mockU32U32MapString); }); });
u5surf/keptn
cli/cmd/auth.go
package cmd import ( "bytes" "encoding/base64" "errors" "fmt" "net" "net/url" "strings" "time" "github.com/keptn/keptn/cli/pkg/credentialmanager" apiutils "github.com/keptn/go-utils/pkg/api/utils" "github.com/keptn/keptn/cli/pkg/logging" keptnutils "github.com/keptn/kubernetes-utils/pkg" "github.com/spf13/cobra" ) var endPoint *string var apiToken *string // authCmd represents the auth command var authCmd = &cobra.Command{ Use: "auth --endpoint=https://api.keptn.MY.DOMAIN.COM --api-token=<PASSWORD>_TOKEN", Short: "Authenticates the Keptn CLI against a Keptn installation", Long: `Authenticates the Keptn CLI against a Keptn installation using an endpoint and an API token. The endpoint and API token are automatically configured during the Keptn installation. If the authentication is successful, the endpoint and the API token are stored in a password store of the underlying operating system. More precisely, the keptn CLI stores the endpoint and API token using *pass* in case of Linux, using *Keychain* in case of macOS, or *Wincred* in case of Windows. **Note**: If you receive a warning *Using a file-based storage for the key because the password-store seems to be not set up.* this is because a password store could not be found in your environment. In this case, the credentials are stored in *~/.keptn/.keptn* in your home directory. `, Example: `keptn auth --endpoint=https://api.keptn.MY.DOMAIN.COM --api-token=<KEY>`, SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { logging.PrintLog("Starting to authenticate", logging.InfoLevel) url, err := url.Parse(*endPoint) if err != nil { logging.PrintLog("Error parsing Keptn API URL", logging.InfoLevel) return err } authHandler := apiutils.NewAuthenticatedAuthHandler(url.String(), *apiToken, "x-token", nil, "https") if !mocking { authenticated := false if !lookupHostname(url.Hostname()) { return fmt.Errorf("Authentication was unsuccessful - could not resolve hostname.") } // try to authenticate (and retry it) for retries := 0; retries < 3; time.Sleep(5 * time.Second) { _, err := authHandler.Authenticate() if err != nil { errMsg := fmt.Sprintf("Authentication was unsuccessful. %s", *err.Message) logging.PrintLog(errMsg, logging.QuietLevel) logging.PrintLog("Retrying...", logging.InfoLevel) retries++ } else { authenticated = true break } } if !authenticated { return fmt.Errorf("Authentication was unsuccessful - could not authenticate against the server.") } logging.PrintLog("Successfully authenticated", logging.InfoLevel) return credentialmanager.NewCredentialManager().SetCreds(*url, *apiToken) } fmt.Println("skipping auth due to mocking flag set to true") return nil }, } func init() { rootCmd.AddCommand(authCmd) endPoint = authCmd.Flags().StringP("endpoint", "e", "", "The endpoint exposed by the Keptn installation (e.g., api.keptn.127.0.0.1.xip.io)") authCmd.MarkFlagRequired("endpoint") apiToken = authCmd.Flags().StringP("api-token", "a", "", "The API token to communicate with the Keptn installation") authCmd.MarkFlagRequired("api-token") } func lookupHostname(hostname string) bool { if strings.HasSuffix(hostname, "xip.io") { logging.PrintLog("Skipping lookup of xip.io domain", logging.InfoLevel) return true } else { // first, try to resolve the domain (and retry it) for retries := 0; retries < 3; time.Sleep(5 * time.Second) { _, err := net.LookupHost(hostname) if err != nil { logging.PrintLog("Failed to resolve hostname "+hostname, logging.InfoLevel) logging.PrintLog("Retrying...", logging.InfoLevel) retries++ } else { return true } } } return false } // authenticate using secrets obtained via kubectl func authUsingKube() error { // get api token apiToken, err := getAPITokenUsingKube() const errorMsg = `Could not retrieve keptn API token: %s To manually set up your keptn CLI, please follow the instructions at https://keptn.sh/.` if err != nil { return fmt.Errorf(errorMsg, err) } // try to obtain endpoint using kubectl (retry a couple of times in case it is not yet available) var keptnEndpoint string for retries := 0; retries < 15; time.Sleep(5 * time.Second) { out, err := getEndpointUsingKube() if err != nil || strings.TrimSpace(string(out)) == "" { logging.PrintLog("API endpoint not yet available... trying again in 5s", logging.InfoLevel) } else { logging.PrintLog("Received Keptn Domain: "+string(out), logging.InfoLevel) keptnEndpoint = "https://api.keptn." + strings.TrimSpace(string(out)) break } retries++ } // fail if we did not receive a correct endpoint if keptnEndpoint == "" { return errors.New("Cannot obtain endpoint of api") } return authenticate(keptnEndpoint, apiToken) } func getEndpointUsingKube() (string, error) { ops := options{"get", "cm", "keptn-domain", "-n", "keptn", "-ojsonpath={.data.app_domain}"} ops.appendIfNotEmpty(kubectlOptions) return keptnutils.ExecuteCommand("kubectl", ops) } func getAPITokenUsingKube() (string, error) { ops := options{"get", "secret", "keptn-api-token", "-n", "keptn", "-ojsonpath={.data.keptn-api-token}"} ops.appendIfNotEmpty(kubectlOptions) out, err := keptnutils.ExecuteCommand("kubectl", ops) if err != nil { return out, err } apiToken, err := base64.StdEncoding.DecodeString(out) if err != nil { return "", err } return string(apiToken), nil } // try to authenticate towards the given endpoint with the provided apiToken func authenticate(endPoint string, apiToken string) error { buf := new(bytes.Buffer) rootCmd.SetOutput(buf) args := []string{ "auth", fmt.Sprintf("--endpoint=%s", endPoint), fmt.Sprintf("--api-token=%s", apiToken), } rootCmd.SetArgs(args) return rootCmd.Execute() }
Jefro/open-smart-grid-platform
osgp/platform/osgp-adapter-domain-smartmetering/src/test/java/org/opensmartgridplatform/adapter/domain/smartmetering/application/services/AlarmNotificationsMappingTest.java
/** * Copyright 2014-2016 Smart Society Services B.V. * * 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 */ package org.opensmartgridplatform.adapter.domain.smartmetering.application.services; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.Set; import java.util.TreeSet; import org.junit.jupiter.api.Test; import org.opensmartgridplatform.adapter.domain.smartmetering.application.mapping.ConfigurationMapper; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.AlarmNotification; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.AlarmNotifications; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.AlarmType; import org.opensmartgridplatform.dto.valueobjects.smartmetering.AlarmNotificationDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.AlarmNotificationsDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.AlarmTypeDto; public class AlarmNotificationsMappingTest { private final ConfigurationMapper configurationMapper = new ConfigurationMapper(); // The Set may never be null. Tests if NullPointerException is thrown // when constructor uses a Set that is null. @Test public void testWithNullSet() { // test data final Set<AlarmNotification> alarmNotificationSet = null; assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> { new AlarmNotifications(alarmNotificationSet); }); } // The Set may be empty. Tests if mapping with an empty Set succeeds. @Test public void testWithEmptySet() { // create test data final Set<AlarmNotification> alarmNotificationSet = new TreeSet<>(); final AlarmNotifications alarmNotifications = new AlarmNotifications(alarmNotificationSet); // actual mapping final AlarmNotificationsDto alarmNotificationsDto = this.configurationMapper.map(alarmNotifications, AlarmNotificationsDto.class); // check if mapping was successful assertThat(alarmNotificationsDto).isNotNull(); assertThat(alarmNotificationsDto.getAlarmNotificationsSet()).isNotNull(); assertThat(alarmNotificationsDto.getAlarmNotificationsSet()).isEmpty(); } // Tests if mapping with a Set with an entry succeeds. @Test public void testWithSet() { // create test data final AlarmNotification alarmNotification = new AlarmNotification(AlarmType.CLOCK_INVALID, true); final Set<AlarmNotification> alarmNotificationSet = new TreeSet<>(); alarmNotificationSet.add(alarmNotification); final AlarmNotifications alarmNotifications = new AlarmNotifications(alarmNotificationSet); // actual mapping final AlarmNotificationsDto alarmNotificationsDto = this.configurationMapper.map(alarmNotifications, AlarmNotificationsDto.class); // check if mapping was successful assertThat(alarmNotificationsDto).isNotNull(); assertThat(alarmNotificationsDto.getAlarmNotificationsSet()).isNotNull(); assertThat(alarmNotificationsDto.getAlarmNotificationsSet().size()).isEqualTo(alarmNotificationSet.size()); assertThat(alarmNotificationsDto.getAlarmNotificationsSet().isEmpty()).isFalse(); // To see if there is an AlarmNotifictionDto with the same variables as // the AlarmNotification in the Set. final AlarmNotificationDto alarmNotificationDto = new AlarmNotificationDto(AlarmTypeDto.CLOCK_INVALID, true); assertThat(alarmNotificationsDto.getAlarmNotificationsSet().contains(alarmNotificationDto)).isTrue(); } }
gxrwes/MCRPGSERVER
MinecraftServer/work/decompile-e0c6d16a/net/minecraft/world/level/block/BlockLadder.java
<reponame>gxrwes/MCRPGSERVER package net.minecraft.world.level.block; import javax.annotation.Nullable; import net.minecraft.core.BlockPosition; import net.minecraft.core.EnumDirection; import net.minecraft.world.item.context.BlockActionContext; import net.minecraft.world.level.GeneratorAccess; import net.minecraft.world.level.IBlockAccess; import net.minecraft.world.level.IWorldReader; import net.minecraft.world.level.World; import net.minecraft.world.level.block.state.BlockBase; import net.minecraft.world.level.block.state.BlockStateList; import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.block.state.properties.BlockProperties; import net.minecraft.world.level.block.state.properties.BlockStateBoolean; import net.minecraft.world.level.block.state.properties.BlockStateDirection; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidType; import net.minecraft.world.level.material.FluidTypes; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShapeCollision; public class BlockLadder extends Block implements IBlockWaterlogged { public static final BlockStateDirection FACING = BlockFacingHorizontal.FACING; public static final BlockStateBoolean WATERLOGGED = BlockProperties.WATERLOGGED; protected static final float AABB_OFFSET = 3.0F; protected static final VoxelShape EAST_AABB = Block.box(0.0D, 0.0D, 0.0D, 3.0D, 16.0D, 16.0D); protected static final VoxelShape WEST_AABB = Block.box(13.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); protected static final VoxelShape SOUTH_AABB = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 3.0D); protected static final VoxelShape NORTH_AABB = Block.box(0.0D, 0.0D, 13.0D, 16.0D, 16.0D, 16.0D); protected BlockLadder(BlockBase.Info blockbase_info) { super(blockbase_info); this.registerDefaultState((IBlockData) ((IBlockData) ((IBlockData) this.stateDefinition.any()).setValue(BlockLadder.FACING, EnumDirection.NORTH)).setValue(BlockLadder.WATERLOGGED, false)); } @Override public VoxelShape getShape(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { switch ((EnumDirection) iblockdata.getValue(BlockLadder.FACING)) { case NORTH: return BlockLadder.NORTH_AABB; case SOUTH: return BlockLadder.SOUTH_AABB; case WEST: return BlockLadder.WEST_AABB; case EAST: default: return BlockLadder.EAST_AABB; } } private boolean canAttachTo(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { IBlockData iblockdata = iblockaccess.getBlockState(blockposition); return iblockdata.isFaceSturdy(iblockaccess, blockposition, enumdirection); } @Override public boolean canSurvive(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { EnumDirection enumdirection = (EnumDirection) iblockdata.getValue(BlockLadder.FACING); return this.canAttachTo(iworldreader, blockposition.relative(enumdirection.getOpposite()), enumdirection); } @Override public IBlockData updateShape(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { if (enumdirection.getOpposite() == iblockdata.getValue(BlockLadder.FACING) && !iblockdata.canSurvive(generatoraccess, blockposition)) { return Blocks.AIR.defaultBlockState(); } else { if ((Boolean) iblockdata.getValue(BlockLadder.WATERLOGGED)) { generatoraccess.scheduleTick(blockposition, (FluidType) FluidTypes.WATER, FluidTypes.WATER.getTickDelay(generatoraccess)); } return super.updateShape(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); } } @Nullable @Override public IBlockData getStateForPlacement(BlockActionContext blockactioncontext) { IBlockData iblockdata; if (!blockactioncontext.replacingClickedOnBlock()) { iblockdata = blockactioncontext.getLevel().getBlockState(blockactioncontext.getClickedPos().relative(blockactioncontext.getClickedFace().getOpposite())); if (iblockdata.is((Block) this) && iblockdata.getValue(BlockLadder.FACING) == blockactioncontext.getClickedFace()) { return null; } } iblockdata = this.defaultBlockState(); World world = blockactioncontext.getLevel(); BlockPosition blockposition = blockactioncontext.getClickedPos(); Fluid fluid = blockactioncontext.getLevel().getFluidState(blockactioncontext.getClickedPos()); EnumDirection[] aenumdirection = blockactioncontext.getNearestLookingDirections(); int i = aenumdirection.length; for (int j = 0; j < i; ++j) { EnumDirection enumdirection = aenumdirection[j]; if (enumdirection.getAxis().isHorizontal()) { iblockdata = (IBlockData) iblockdata.setValue(BlockLadder.FACING, enumdirection.getOpposite()); if (iblockdata.canSurvive(world, blockposition)) { return (IBlockData) iblockdata.setValue(BlockLadder.WATERLOGGED, fluid.getType() == FluidTypes.WATER); } } } return null; } @Override public IBlockData rotate(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { return (IBlockData) iblockdata.setValue(BlockLadder.FACING, enumblockrotation.rotate((EnumDirection) iblockdata.getValue(BlockLadder.FACING))); } @Override public IBlockData mirror(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { return iblockdata.rotate(enumblockmirror.getRotation((EnumDirection) iblockdata.getValue(BlockLadder.FACING))); } @Override protected void createBlockStateDefinition(BlockStateList.a<Block, IBlockData> blockstatelist_a) { blockstatelist_a.add(BlockLadder.FACING, BlockLadder.WATERLOGGED); } @Override public Fluid getFluidState(IBlockData iblockdata) { return (Boolean) iblockdata.getValue(BlockLadder.WATERLOGGED) ? FluidTypes.WATER.getSource(false) : super.getFluidState(iblockdata); } }
BernardTsai/solar
src/tsai.eu/solar/model/event_test.go
<reponame>BernardTsai/solar package model import ( "testing" "os" ) //------------------------------------------------------------------------------ // TestEvent01 tests the basic functions of the event package. func TestEvent01(t *testing.T) { filename := "test.yaml" // cleanup routine defer func() {os.Remove(filename)}() event := NewEvent("demo", "task-uuid", EventTypeTaskExecution, "", "no comment") event.Save(filename) event.Load(filename) event.Show() } //------------------------------------------------------------------------------ // TestEvent02 tests the element related functions of the event package. func TestEvent02(t *testing.T) { event := NewEvent("demo", "task-uuid", EventTypeTaskExecution, "", "no comment") if event.GetUUID() != event.UUID { t.Errorf("<event>.GetUUID should have returned the uuid of the event") } } //------------------------------------------------------------------------------
phuongnd-relipa/religram-api
src/main/java/com/relipa/religram/entity/ResetPasswordToken.java
/* * Copyright (c) 2019. Relipa Software - 株式会社レリパ */ package com.relipa.religram.entity; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name="reset_password") public class ResetPasswordToken extends AbstractAuditableEntity<Long> implements Serializable { @OneToOne @JoinColumn(name = "user_id", referencedColumnName = "id") private User user; @Column(name = "reset_token") private String resetToken; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getResetToken() { return resetToken; } public void setResetToken(String resetToken) { this.resetToken = resetToken; } }
deep-1/haiku
src/add-ons/print/drivers/pdf/source/PageSetupWindow.h
/* PDF Writer printer driver. Copyright (c) 2001 OpenBeOS. Authors: <NAME> <NAME> <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef PAGESETUPWINDOW_H #define PAGESETUPWINDOW_H #include "BlockingWindow.h" #include <Message.h> #include <String.h> class BMenuField; class BSlider; class Fonts; class MarginView; class PageSetupWindow : public HWindow { typedef HWindow inherited; public: // Constructors, destructors, operators... PageSetupWindow(BMessage *msg, const char *printerName = NULL); ~PageSetupWindow(); virtual void MessageReceived(BMessage *msg); virtual bool QuitRequested(); status_t Go(); enum { OK_MSG = 'ok__', CANCEL_MSG = 'cncl', FONTS_MSG = 'font', ADVANCED_MSG = 'advc', PAGE_SIZE_CHANGED = 'pgsz', ORIENTATION_CHANGED = 'ornt' }; private: void _UpdateSetupMessage(); private: long fExitSem; status_t fResult; BMessage* fSetupMsg; BMenuField* fPageSizeMenu; BMenuField* fOrientationMenu; BMenuField* fPDFCompatibilityMenu; BSlider* fPDFCompressionSlider; Fonts* fFonts; BMessage fAdvancedSettings; MarginView * fMarginView; // used for saving settings BString fPrinterDirName; int32 fCurrentOrientation; }; #endif
cctiger36/batch_manager
lib/generators/batch/batch_generator.rb
require 'rails/generators' require 'rails/generators/named_base' module Rails module Generators class BatchGenerator < NamedBase desc "Generates batch file" def self.orm Rails::Generators.options[:rails][:orm] || :active_record end def self.source_root File.join(File.dirname(__FILE__), 'templates', (orm.to_s unless orm.class.eql?(String))) end def create_batch_file template 'batch.rb', File.join(BatchManager.batch_dir, class_path, "#{file_name}.rb") end end end end
MartinTschechne/ASL-hdbscan
src/hdbscan/cluster.cpp
#include <hdbscan/cluster.h> #include <float.h> #include <stdexcept> Cluster* CreateCluster(size_t label, Cluster* parent, double birth_level, size_t num_points) { Cluster* new_cluster = (Cluster*)malloc(sizeof(Cluster)); new_cluster->label = label; new_cluster->birth_level = birth_level; new_cluster->death_level = 0.0; new_cluster->num_points = num_points; new_cluster->file_offset = 0; new_cluster->stability = 0.0; new_cluster->propagated_stability = 0.0; new_cluster->propagated_lowest_child_death_level = DBL_MAX; new_cluster->num_constraints_satisfied = 0; new_cluster->propagated_num_constraints_satisfied = 0; new_cluster->parent = parent; new_cluster->has_children = false; new_cluster->propagated_descendants = (Vector*)malloc(sizeof(Vector)); vector_init(new_cluster->propagated_descendants); new_cluster->virtual_child_cluster = OS_create(); if(parent != nullptr) { parent->has_children = true; } return new_cluster; } void DetachPoints(Cluster* cluster, size_t num_points, double level) { if(num_points > cluster->num_points) { // I think assert is hidden by some gtest module throw std::invalid_argument("Number of points to detach cannot be greater than the number of points in the cluster"); } cluster->num_points -= num_points; cluster->stability += (num_points * (1.0 / level - 1.0 / cluster->birth_level)); if(cluster->num_points == 0) { cluster->death_level = level; } } void Propagate(Cluster* cluster) { if(cluster->parent == nullptr) { return; } //Propagate lowest death level of any descendants: if(cluster->propagated_lowest_child_death_level == DBL_MAX) { cluster->propagated_lowest_child_death_level = cluster->death_level; } if(cluster->propagated_lowest_child_death_level < cluster->parent->propagated_lowest_child_death_level) { cluster->parent->propagated_lowest_child_death_level = cluster->propagated_lowest_child_death_level; } //If this cluster has no children, it must propagate itself: if(!cluster->has_children) { cluster->parent->propagated_num_constraints_satisfied += cluster->num_constraints_satisfied; cluster->parent->propagated_stability += cluster->stability; vector_push_back(cluster->parent->propagated_descendants, (void*)cluster); } else if(cluster->num_constraints_satisfied > cluster->propagated_num_constraints_satisfied) { cluster->parent->propagated_num_constraints_satisfied += cluster->num_constraints_satisfied; cluster->parent->propagated_stability += cluster->stability; vector_push_back(cluster->parent->propagated_descendants, (void*)cluster); } else if(cluster->num_constraints_satisfied < cluster->propagated_num_constraints_satisfied) { cluster->parent->propagated_num_constraints_satisfied += cluster->propagated_num_constraints_satisfied; cluster->parent->propagated_stability += cluster->propagated_stability; for(size_t i = 0; i < cluster->propagated_descendants->size; ++i) { vector_push_back(cluster->parent->propagated_descendants, vector_get(cluster->propagated_descendants, i)); } // insert all } else if(cluster->num_constraints_satisfied == cluster->propagated_num_constraints_satisfied) { //Chose the parent over descendants if there is a tie in stability: if(cluster->stability >= cluster->propagated_stability) { cluster->parent->propagated_num_constraints_satisfied += cluster->num_constraints_satisfied; cluster->parent->propagated_stability += cluster->stability; vector_push_back(cluster->parent->propagated_descendants, cluster); } else { cluster->parent->propagated_num_constraints_satisfied += cluster->propagated_num_constraints_satisfied; cluster->parent->propagated_stability += cluster->propagated_stability; for(size_t i = 0; i < cluster->propagated_descendants->size; ++i) { vector_push_back(cluster->parent->propagated_descendants, vector_get(cluster->propagated_descendants, i)); } // insert all } } } void AddPointsToVirtualChildCluster(Cluster* cluster, const OrderedSet* const points) { for(size_t i = OS_begin(points); i < OS_end(points); i = OS_next(points, i)) { OS_insert(cluster->virtual_child_cluster, OS_get(points, i)); } } bool VirtualChildClusterContaintsPoint(Cluster* cluster, size_t point) { return OS_contains(cluster->virtual_child_cluster, point); } void AddVirtualChildConstraintsSatisfied(Cluster* cluster, size_t num_constraints) { cluster->propagated_num_constraints_satisfied += num_constraints; } void AddConstraintsSatisfied(Cluster* cluster, size_t num_constraints) { cluster->num_constraints_satisfied += num_constraints; } void ReleaseVirtualChildCluster(Cluster* cluster) { OS_clear(cluster->virtual_child_cluster); } void FreeCluster(Cluster* cluster) { vector_free(cluster->propagated_descendants); OS_free(cluster->virtual_child_cluster); free(cluster); }
krayz-clous/Discord.js-v13-bot-with-dashboard
src/database/mongo.js
const mongoose = require("mongoose"); const { MONGO_CONNECTION } = require("@root/config"); mongoose.plugin(require("mongoose-lean-defaults").default); module.exports = async () => { await mongoose.connect(MONGO_CONNECTION, { keepAlive: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, }); console.log("Database connection established"); };
xwheel/x-monitor
commons/src/main/java/com/xwheel/xmonitor/commons/beans/Page.java
package com.xwheel.xmonitor.commons.beans; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @description: 通用的分页对象 */ public class Page<T> implements Serializable { //------------------公共变量----------------// public static final String ASC = "asc"; public static final String DESC = "desc"; //------------------查询输入参数----------------// //排序字段 protected String orderBy; //排序方向 protected String order; //----- 分页参数 ----// //页码 protected int pageNo = 1; //每页记录数 默认为-1(不分页) protected int pageSize = -1; //手动分页 开始记录数 private int startPageNo; //手动分页 结束记录数 private int endPageNO; //-----------以下是查询后需要封装的返回参数-----------// //总记录数 private long totalCount; //总页数 private long totalPages; //起始页 private long startIndex; //结束页 private long lastIndex; //返回当前页结果 private List<T> currentPageResult = new ArrayList<T>(); //默认构造函数 public Page() { } //分页参数访问函数 public Page(int pageNo, int pageSize) { this.pageSize = pageSize; this.pageNo = pageNo; } /** * 获得当前页的页号,序号从1开始,默认为1. */ public int getPageNo() { return pageNo; } /** * 设置当前页的页号,序号从1开始,低于1时自动调整为1. */ public void setPageNo(final int pageNo) { this.pageNo = 1 > pageNo ? 1 : pageNo; } /** * 返回Page对象自身的setPageNo函数,可用于连续设置。 */ public Page<T> pageNo(final int thePageNo) { setPageNo(thePageNo); return this; } /** * 获得每页的记录数量, 默认为-1. */ public int getPageSize() { return pageSize; } /** * 设置每页的记录数量. */ public void setPageSize(final int pageSize) { this.pageSize = pageSize; } /** * 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从0开始. */ public int getStartIndex() { return (pageNo - 1) * pageSize; } /** * 根据pageNo和pageSize计算当前页最后一条记录在总结果集中的位置,序号从pageSize开始. */ public int getLastIndex() { return pageNo * pageSize; } public int getEndPageNO() { return endPageNO; } public void setEndPageNO(int endPageNO) { this.endPageNO = endPageNO; } public int getStartPageNo() { return startPageNo; } public void setStartPageNo(int startPageNo) { this.startPageNo = startPageNo; } /** * 获得排序字段,无默认值. 多个排序字段时用','分隔. */ public String getOrderBy() { return orderBy; } /** * 设置排序字段,多个排序字段时用','分隔. */ public void setOrderBy(final String orderBy) { this.orderBy = orderBy; } /** * 设置排序方向. * * @param order 可选值为desc或asc,多个排序字段时用','分隔. */ public void setOrder(final String order) { if (order != null) { String lowcaseOrder = StringUtils.lowerCase(order); //检查order字符串的合法值 String[] orders = StringUtils.split(lowcaseOrder, ','); for (String orderStr : orders) { if (!StringUtils.equals(DESC, orderStr) && !StringUtils.equals(ASC, orderStr)) { throw new IllegalArgumentException("排序方向" + orderStr + "不是合法值"); } } this.order = lowcaseOrder; } } /** * 获得order值 * * @return */ public String getOrder() { return this.order; } //-- 访问查询结果函数 --// /** * 获得当前页内的记录列表. */ public List<T> getCurrentPageResult() { return currentPageResult; } /** * 设置当前页内的记录列表. */ public void setCurrentPageResult(final List<T> currentPageResult) { this.currentPageResult = currentPageResult; } /** * 获得总记录数, 默认值为1. */ public long getTotalCount() { return totalCount; } /** * 总记录数决定总页数,所以设置总页数的方法也写在这个方法内 * 设置总记录数,总页数,以及判断当前页是否大于最大页 */ public void setTotalCount(final long totalCount) { //设置总记录数 this.totalCount = totalCount; //设置总页数 if (totalCount > 0) { long count = totalCount / pageSize; if (totalCount % pageSize > 0) { totalPages = count + 1; } else { totalPages = count; } } //判断当前页是否超过最大页,如果大于则当前页等于最大页 if (totalPages < pageNo) { pageNo = (int) totalPages; } } /** * 获得总页数 */ public long getTotalPages() { return totalPages; } public void setLastIndex(long lastIndex) { this.lastIndex = lastIndex; } public void setTotalPages(long totalPages) { this.totalPages = totalPages; } public void setStartIndex(long startIndex) { this.startIndex = startIndex; } @Override public String toString() { return "Page{" + "pageNo=" + pageNo + ", pageSize=" + pageSize + ", orderBy='" + orderBy + '\'' + ", order='" + order + '\'' + ", totalCount=" + totalCount + ", currentPageResult=" + currentPageResult + ", totalPages=" + totalPages + '}'; } }
paradoxnj/Genesis3D
source/GTest/Procedurals/fire.h
#ifndef FireProcedural_H #define FireProcedural_H #include "procedural.h" Procedural_Table * Fire_GetProcedural_Table(void); #endif
indutny/vowlink-electron
src/pages/SignIn.js
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { initNetwork, eraseNetwork, networkError } from '../redux/actions'; import './SignIn.css'; const MAX_DECRYPT_ATTEMPTS = 3; const SignIn = ({ network, initNetwork, eraseNetwork }) => { const [ passphrase, setPassphrase ] = useState(''); const [ confirm, setConfirm ] = useState(''); const [ confirmErase, setConfirmErase ] = useState(false); const isDisabled = network.isFirstRun ? confirm !== passphrase : false; const onPassphraseChange = (e) => { setPassphrase(e.target.value); }; const onConfirmChange = (e) => { setConfirm(e.target.value); }; const onErase = (e) => { e.preventDefault(); if (confirmErase) { eraseNetwork(); setConfirmErase(false); } else { setConfirmErase(true); } }; const onSubmit = (e) => { e.preventDefault(); if (isDisabled) { return; } initNetwork({ passphrase }); setPassphrase(''); setConfirm(''); }; let confirmField; if (network.isFirstRun) { confirmField = <div className='form-row'> <input className='form-input' type='password' required value={confirm} onChange={onConfirmChange} placeholder='Confirm passphrase'/> </div>; } let errorRow; if (network.error) { errorRow = <div className='form-row error'> Got error: {network.error} </div>; } let eraseRow; if (network.decryptAttempts >= MAX_DECRYPT_ATTEMPTS) { eraseRow = <div className='form-row'> <button className='button button-danger' onClick={onErase}> {confirmErase ? 'Are you sure?' : 'Erase all content' } </button> </div>; } const form = <form onSubmit={onSubmit}> {errorRow} <div className='form-row'> <h3 className='title'>{network.isFirstRun ? 'Encrypt private keys' : 'Decrypt private keys'}</h3> </div> <div className='form-row'> <input className='form-input' type='password' required autoFocus value={passphrase} onChange={onPassphraseChange} placeholder='Enter passphrase'/> </div> {confirmField} <div className='form-row'> <input className='button' type='submit' disabled={isDisabled} value='Sign In'/> </div> {eraseRow} </form>; return <div className='sign-in-container'> {network.isLoading ? <h3>Decrypting...</h3> : form} </div>; }; SignIn.propTypes = { network: PropTypes.shape({ isFirstRun: PropTypes.bool, error: PropTypes.string, decryptAttempts: PropTypes.number.isRequired, isLoading: PropTypes.bool, }), initNetwork: PropTypes.func.isRequired, eraseNetwork: PropTypes.func.isRequired, }; const mapStateToProps = (state) => { return { network: state.network, }; }; const mapDispatchToProps = (dispatch) => { return { initNetwork: (...args) => dispatch(initNetwork(...args)), eraseNetwork: (...args) => dispatch(eraseNetwork(...args)), networkError: (...args) => dispatch(networkError(...args)), }; }; export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
bdunne/miq_bot
lib/bot/githubapi/user.rb
<reponame>bdunne/miq_bot require_relative 'git_hub_api' module GitHubApi class User attr_accessor :username, :password, :client def initialize end def find_organization(organization_name) octokit_org = GitHubApi.execute(@client, :organization, organization_name) @organization = Organization.new(octokit_org, self) end end end
qianfei11/zstack
plugin/nfsPrimaryStorage/src/main/java/org/zstack/storage/primary/nfs/NfsSystemTags.java
package org.zstack.storage.primary.nfs; import org.zstack.header.storage.primary.PrimaryStorageVO; import org.zstack.header.tag.TagDefinition; import org.zstack.tag.PatternedSystemTag; /** * Created by xing5 on 2016/4/10. */ @TagDefinition public class NfsSystemTags { public static String MOUNT_OPTIONS_TOKEN = "options"; public static PatternedSystemTag MOUNT_OPTIONS = new PatternedSystemTag(String.format("nfs::mount::options::{%s}", MOUNT_OPTIONS_TOKEN), PrimaryStorageVO.class); }
DanPopa46/neo-mamba
neo3/contracts/native/nameservice.py
from __future__ import annotations import re import struct import ipaddress from enum import IntEnum from .nonfungible import NFTState, NonFungibleToken from . import register from typing import Optional, Iterator, Tuple from neo3 import contracts, storage, vm from neo3.core import serialization, types class RecordType(IntEnum): A = 1 CNAME = 5 TXT = 16 AAAA = 28 class NameState(NFTState): def __init__(self, owner: types.UInt160, name: str, expiration: int, admin: Optional[types.UInt160] = None): super(NameState, self).__init__(owner, name) self.expiration = expiration self.admin = admin if admin else types.UInt160.zero() self.id = name.encode() def __len__(self): return len(self.to_array()) def serialize(self, writer: serialization.BinaryWriter) -> None: super(NameState, self).serialize(writer) writer.write_uint32(self.expiration) writer.write_serializable(self.admin) def deserialize(self, reader: serialization.BinaryReader) -> None: super(NameState, self).deserialize(reader) self.expiration = reader.read_uint32() self.admin = reader.read_serializable(types.UInt160) @classmethod def _serializable_init(cls): return cls(types.UInt160.zero(), "", 0, types.UInt160.zero()) class StringList(list, serialization.ISerializable): def __len__(self): return len(self.to_array()) def serialize(self, writer: serialization.BinaryWriter) -> None: writer.write_var_int(len(self[:])) for i in self: writer.write_var_string(i) def deserialize(self, reader: serialization.BinaryReader) -> None: for _ in range(reader.read_var_int()): self.append(reader.read_var_string()) class NameService(NonFungibleToken): _id = -10 _symbol = "NNS" _service_name = None key_roots = storage.StorageKey(_id, b'\x0a') key_domain_price = storage.StorageKey(_id, b'\x16') key_expiration = storage.StorageKey(_id, b'\x14') key_record = storage.StorageKey(_id, b'\x12') ONE_YEAR = 365 * 24 * 3600 REGEX_ROOT = re.compile("^[a-z][a-z0-9]{0,15}$") REGEX_NAME = re.compile("^(?=.{3,255}$)([a-z0-9]{1,62}\\.)+[a-z][a-z0-9]{0,15}$") def init(self): super(NameService, self).init() def _initialize(self, engine: contracts.ApplicationEngine) -> None: super(NameService, self)._initialize(engine) engine.snapshot.storages.put(self.key_domain_price, storage.StorageItem(vm.BigInteger(1000000000).to_array())) engine.snapshot.storages.put(self.key_roots, storage.StorageItem(b'\x00')) @register("addRoot", contracts.CallFlags.STATES, cpu_price=1 << 15) def add_root(self, engine: contracts.ApplicationEngine, root: str) -> None: if not self.REGEX_ROOT.match(root): raise ValueError("Regex failure - root not found") if not self._check_committee(engine): raise ValueError("Check committee failed") storage_item_roots = engine.snapshot.storages.get(self.key_roots, read_only=False) roots = storage_item_roots.get(StringList) if root in roots: raise ValueError("The name already exists") roots.append(root) @register("setPrice", contracts.CallFlags.STATES, cpu_price=1 << 15) def set_price(self, engine: contracts.ApplicationEngine, price: int) -> None: if price <= 0 or price > 10000_00000000: raise ValueError(f"New price '{price}' exceeds limits") if not self._check_committee(engine): raise ValueError("Check committee failed") storage_item = engine.snapshot.storages.get(self.key_domain_price, read_only=False) storage_item.value = price.to_bytes(8, 'little') @register("getPrice", contracts.CallFlags.READ_STATES, cpu_price=1 << 15) def get_price(self, snapshot: storage.Snapshot) -> int: return int.from_bytes(snapshot.storages.get(self.key_domain_price, read_only=True).value, 'little') @register("isAvailable", contracts.CallFlags.READ_STATES, cpu_price=1 << 15) def is_available(self, snapshot: storage.Snapshot, name: str) -> bool: if not self.REGEX_NAME.match(name): raise ValueError("Regex failure - name is not valid") names = name.split(".") if len(names) != 2: raise ValueError("Invalid format") storage_item = snapshot.storages.try_get(self.key_token + name.encode(), read_only=True) if storage_item: return False storage_item_roots = snapshot.storages.get(self.key_roots, read_only=True) roots = storage_item_roots.get(StringList) if names[1] not in roots: raise ValueError(f"'{names[1]}' is not a registered root") return True @register("register", contracts.CallFlags.STATES, cpu_price=1 << 15) def do_register(self, engine: contracts.ApplicationEngine, name: str, owner: types.UInt160) -> bool: if not self.is_available(engine.snapshot, name): raise ValueError(f"Registration failure - '{name}' is not available") if not engine.checkwitness(owner): raise ValueError("CheckWitness failed") engine.add_gas(self.get_price(engine.snapshot)) state = NameState(owner, name, (engine.snapshot.persisting_block.timestamp // 1000) + self.ONE_YEAR) self.mint(engine, state) engine.snapshot.storages.put( self.key_expiration + state.expiration.to_bytes(4, 'big') + name.encode(), storage.StorageItem(b'\x00') ) return True @register("renew", contracts.CallFlags.STATES, cpu_price=1 << 15) def renew(self, engine: contracts.ApplicationEngine, name: str) -> int: if not self.REGEX_NAME.match(name): raise ValueError("Regex failure - name is not valid") names = name.split(".") if len(names) != 2: raise ValueError("Invalid format") storage_item_state = engine.snapshot.storages.get(self.key_token + name.encode(), read_only=False) state = storage_item_state.get(NameState) state.expiration += self.ONE_YEAR return state.expiration @register("setAdmin", contracts.CallFlags.STATES, cpu_price=1 << 15, storage_price=20) def set_admin(self, engine: contracts.ApplicationEngine, name: str, admin: types.UInt160) -> None: if not self.REGEX_NAME.match(name): raise ValueError("Regex failure - name is not valid") names = name.split(".") if len(names) != 2: raise ValueError("Invalid format") if admin != types.UInt160.zero() and not engine.checkwitness(admin): raise ValueError("New admin is not valid - check witness failed") storage_item = engine.snapshot.storages.get(self.key_token + name.encode()) state = storage_item.get(NameState) if not engine.checkwitness(state.owner): raise ValueError state.admin = admin @register("setRecord", contracts.CallFlags.STATES, cpu_price=1 << 15, storage_price=200) def set_record(self, engine: contracts.ApplicationEngine, name: str, record_type: RecordType, data: str) -> None: if not self.REGEX_NAME.match(name): raise ValueError("Regex failure - name is not valid") if record_type == RecordType.A: # we only validate if the data is a valid IPv4 address ipaddress.IPv4Address(data) elif record_type == RecordType.CNAME: if not self.REGEX_NAME.match(data): raise ValueError("Invalid CNAME") elif record_type == RecordType.TXT: if len(data) > 255: raise ValueError("TXT data exceeds maximum length of 255") elif record_type == RecordType.AAAA: # we only validate if the data is a valid IPv6 address ipaddress.IPv6Address(data) domain = '.'.join(name.split('.')[2:]) storage_item = engine.snapshot.storages.get(self.key_token + domain.encode()) state = storage_item.get(NameState) if not self._check_admin(engine, state): raise ValueError("Admin check failed") storage_key_record = self.key_record + domain.encode() + name.encode() + record_type.to_bytes(1, 'little') engine.snapshot.storages.update(storage_key_record, storage.StorageItem(data.encode())) @register("getRecord", contracts.CallFlags.READ_STATES, cpu_price=1 << 15) def get_record(self, snapshot: storage.Snapshot, name: str, record_type: RecordType) -> Optional[str]: if not self.REGEX_NAME.match(name): raise ValueError("Regex failure - name is not valid") domain = '.'.join(name.split('.')[2:]) storage_key_record = self.key_record + domain.encode() + name.encode() + record_type.to_bytes(1, 'little') storage_item = snapshot.storages.try_get(storage_key_record) if storage_item is None: return None return storage_item.value.decode() @register("deleteRecord", contracts.CallFlags.STATES, cpu_price=1 << 15) def delete_record(self, engine: contracts.ApplicationEngine, name: str, record_type: RecordType) -> None: if not self.REGEX_NAME.match(name): raise ValueError("Regex failure - name is not valid") domain = '.'.join(name.split('.')[2:]) storage_item = engine.snapshot.storages.get(self.key_token + domain.encode()) state = storage_item.get(NameState) if not self._check_admin(engine, state): raise ValueError("Admin check failed") storage_key_record = self.key_record + domain.encode() + name.encode() + record_type.to_bytes(1, 'little') engine.snapshot.storages.delete(storage_key_record) @register("resolve", contracts.CallFlags.READ_STATES, cpu_price=1 << 17) def resolve(self, snapshot: storage.Snapshot, name: str, record_type: RecordType, redirect_count: int = 2) -> Optional[str]: if redirect_count < 0: raise ValueError("Redirect count can't be negative") records = {} for key, value in self.get_records(snapshot, name): records.update({key: value}) if record_type in records: return records[record_type] data = records.get(RecordType.CNAME, None) if data is None: return None return self.resolve(snapshot, data, record_type, redirect_count - 1) def get_records(self, snapshot: storage.Snapshot, name: str) -> Iterator[Tuple[RecordType, str]]: if not self.REGEX_NAME.match(name): raise ValueError("Regex failure - name is not valid") domain = '.'.join(name.split('.')[2:]) storage_key = self.key_record + domain.encode() + name.encode() for key, value in snapshot.storages.find(storage_key.to_array()): record_type = RecordType(int.from_bytes(key.key[-1], 'little')) yield record_type, value.value.decode() def on_persist(self, engine: contracts.ApplicationEngine) -> None: now = (engine.snapshot.persisting_block.timestamp // 1000) + 1 start = (self.key_expiration + self._to_uint32(0)).to_array() end = (self.key_expiration + self._to_uint32(now)).to_array() for key, _ in engine.snapshot.storages.find_range(start, end): engine.snapshot.storages.delete(key) for key2, _ in engine.snapshot.storages.find(self.key_record + key.key[5:]).to_array(): engine.snapshot.storages.delete(key2) self.burn(engine, self.key_token + key.key[5:]) def on_transferred(self, engine: contracts.ApplicationEngine, from_account: types.UInt160, token: NFTState) -> None: token.owner = types.UInt160.zero() def _check_admin(self, engine: contracts.ApplicationEngine, state: NameState) -> bool: if engine.checkwitness(state.owner): return True if state.admin == types.UInt160.zero: return False return engine.checkwitness(state.admin) def _to_uint32(self, value: int) -> bytes: return struct.pack(">I", value)
sniperkit/colly
plugins/data/aggregate/rss/content/article_test.go
package content_test import ( "testing" "github.com/urandom/readeef/content" ) func TestArticle_Validate(t *testing.T) { type fields struct { ID content.ArticleID FeedID content.FeedID Link string } tests := []struct { name string fields fields wantErr bool }{ {"valid", fields{ID: 1, FeedID: 1, Link: "http://sugr.org"}, false}, {"link not absolute", fields{ID: 1, FeedID: 1, Link: "sugr.org"}, true}, {"no link", fields{ID: 1, FeedID: 1}, true}, {"no feed id", fields{ID: 1, Link: "http://sugr.org"}, true}, {"no id", fields{FeedID: 1, Link: "http://sugr.org"}, true}, {"nothing", fields{}, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { a := content.Article{ ID: tt.fields.ID, FeedID: tt.fields.FeedID, Link: tt.fields.Link, } if err := a.Validate(); (err != nil) != tt.wantErr { t.Errorf("Article.Validate() error = %v, wantErr %v", err, tt.wantErr) } }) } }
bestzy6/kiekerSQL
kieker-analysis/test/kieker/analysis/model/AbstractModelAssemblerTest.java
/*************************************************************************** * Copyright 2021 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.analysis.model; import org.eclipse.emf.common.util.EList; import org.junit.Assert; import org.junit.Test; import kieker.analysis.stage.model.AbstractSourceModelAssembler; import kieker.model.analysismodel.sources.SourceModel; import kieker.model.analysismodel.sources.SourcesFactory; import kieker.model.analysismodel.type.ComponentType; import kieker.model.analysismodel.type.TypeFactory; /** * Test the abstract model assembler which updates the sources model. * * @author <NAME> * @since 1.15 */ public class AbstractModelAssemblerTest { // NOCS NOPMD this is a test class private static final String LABEL = "LABEL"; private static final String SECOND = "SECOND"; @Test public void testUpdateSourceModel() { final SourceModel model = SourcesFactory.eINSTANCE.createSourceModel(); final ComponentType[] types = { this.createType("Type1"), this.createType("Type2"), this.createType("Type3"), this.createType("Type4"), }; final AbstractSourceModelAssembler assembler = new AbstractSourceModelAssembler(model, LABEL) { }; for (final ComponentType type : types) { assembler.updateSourceModel(type); } for (final ComponentType type : types) { assembler.updateSourceModel(type); } for (final ComponentType type : types) { assembler.updateSourceModel(type); } for (final ComponentType type : types) { final EList<String> labels = model.getSources().get(type); Assert.assertEquals("The list must have exactly the size 1, but", 1, labels.size()); Assert.assertEquals("The list values must be " + LABEL, LABEL, labels.get(0)); } } @Test public void testUpdateSourceModel2Label() { final SourceModel model = SourcesFactory.eINSTANCE.createSourceModel(); final ComponentType[] types = { this.createType("Type1"), this.createType("Type2"), this.createType("Type3"), this.createType("Type4"), }; final AbstractSourceModelAssembler assembler = new AbstractSourceModelAssembler(model, LABEL) { }; for (final ComponentType type : types) { assembler.updateSourceModel(type); } for (final ComponentType type : types) { assembler.updateSourceModel(type); } final AbstractSourceModelAssembler assembler2 = new AbstractSourceModelAssembler(model, SECOND) { }; for (final ComponentType type : types) { assembler2.updateSourceModel(type); assembler2.updateSourceModel(type); } for (final ComponentType type : types) { final EList<String> labels = model.getSources().get(type); Assert.assertEquals("The list must have exactly the size 1, but", 2, labels.size()); Assert.assertEquals("The list values must be " + LABEL, LABEL, labels.get(0)); Assert.assertEquals("The list values must be " + SECOND, SECOND, labels.get(1)); } } private ComponentType createType(final String name) { final ComponentType type = TypeFactory.eINSTANCE.createComponentType(); type.setName(name); return type; } }
gradle-update/data-transfer-project
portability-spi-transfer/src/main/java/org/datatransferproject/spi/transfer/types/CopyExceptionWithFailureReason.java
package org.datatransferproject.spi.transfer.types; import javax.annotation.Nonnull; /** * These exceptions can be thrown during a copy and should be caught by the JobProcessor which will * then add the failure reason to the job. */ public abstract class CopyExceptionWithFailureReason extends CopyException { public CopyExceptionWithFailureReason(String message, Throwable cause) { super(message, cause); } @Nonnull public abstract String getFailureReason(); }
JeremyShin/ActualReturnCalculator
ARC/src/main/java/my/examples/arc/servlet/ArcGoodsAdd.java
package my.examples.arc.servlet; import my.examples.arc.dao.ArcDAO; import my.examples.arc.dto.ArcGdsAddDTO; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/goodsAdd") public class ArcGoodsAdd extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 포워딩 RequestDispatcher requestDispatcher = req.getRequestDispatcher("WEB-INF/views/goodsAdd.jsp"); requestDispatcher.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 상품 이름, 수익률, 수수료를 검사한다 try { int gdsCd = Integer.parseInt(req.getParameter("goodsCode")); Float prfRto = Float.parseFloat(req.getParameter("profitRatio")); Float cms = Float.parseFloat(req.getParameter("commisions")); // 상품 이름, 수익률, 수수료를 DB에 저장한다. ArcGdsAddDTO arcGdsAddDto = new ArcGdsAddDTO(gdsCd, prfRto, cms); ArcDAO arcDAO = new ArcDAO(); arcDAO.addArc(arcGdsAddDto); }catch (NumberFormatException ex){ throw new RuntimeException("유효한 값 입력되지 않았습니다."+ ex.toString()); } // /list로 리다이렉션 resp.sendRedirect("/list"); } }
mumrah/castle
src/main/java/io/confluent/castle/cluster/CastleNode.java
/* * 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 io.confluent.castle.cluster; import io.confluent.castle.uplink.Uplink; import io.confluent.castle.common.CastleUtil; import io.confluent.castle.common.CastleLog; import io.confluent.castle.role.Role; import org.slf4j.Logger; import java.util.Collections; import java.util.Map; /** * Represents a node in the castle cluster. */ public final class CastleNode implements AutoCloseable { private final Logger clusterLog; /** * The index of this node in the cluster. The node with the alphabetically * first name will be index 0, and so on. */ private final int nodeIndex; /** * The castle cluster node name. */ private final String nodeName; /** * The log for this node. */ private final CastleLog castleLog; /** * The roles supported by this node. */ private final Map<Class<? extends Role>, Role> roles; /** * The Uplink associated with this node. */ private Uplink uplink; CastleNode(Logger clusterLog, int nodeIndex, String nodeName, CastleLog castleLog, Map<Class<? extends Role>, Role> roles) { this.clusterLog = clusterLog; this.nodeIndex = nodeIndex; this.nodeName = nodeName; this.castleLog = castleLog; this.roles = Collections.unmodifiableMap(roles); this.uplink = null; } public int nodeIndex() { return nodeIndex; } public String nodeName() { return nodeName; } public CastleLog log() { return castleLog; } @SuppressWarnings("unchecked") public <R extends Role> R getRole(Class<? extends Role> clazz) { Role role = roles.get(clazz); if (role == null) { return null; } return (R) role; } public synchronized Uplink uplink() { return uplink; } public synchronized void setUplink(Uplink uplink) { this.uplink = uplink; } public Map<Class<? extends Role>, Role> roles() { return roles; } @Override public void close() { CastleUtil.closeQuietly(clusterLog, castleLog, "castleLog for " + nodeName); } };
DiegoEliasCosta/gs-collections
collections-api/src/main/java/com/gs/collections/api/map/sorted/ImmutableSortedMap.java
/* * Copyright 2015 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.api.map.sorted; import java.util.SortedMap; import com.gs.collections.api.block.function.Function; import com.gs.collections.api.block.function.Function0; import com.gs.collections.api.block.function.Function2; import com.gs.collections.api.block.function.primitive.BooleanFunction; import com.gs.collections.api.block.function.primitive.ByteFunction; import com.gs.collections.api.block.function.primitive.CharFunction; import com.gs.collections.api.block.function.primitive.DoubleFunction; import com.gs.collections.api.block.function.primitive.FloatFunction; import com.gs.collections.api.block.function.primitive.IntFunction; import com.gs.collections.api.block.function.primitive.LongFunction; import com.gs.collections.api.block.function.primitive.ShortFunction; import com.gs.collections.api.block.predicate.Predicate; import com.gs.collections.api.block.predicate.Predicate2; import com.gs.collections.api.block.procedure.Procedure; import com.gs.collections.api.block.procedure.Procedure2; import com.gs.collections.api.list.ImmutableList; import com.gs.collections.api.list.primitive.ImmutableBooleanList; import com.gs.collections.api.list.primitive.ImmutableByteList; import com.gs.collections.api.list.primitive.ImmutableCharList; import com.gs.collections.api.list.primitive.ImmutableDoubleList; import com.gs.collections.api.list.primitive.ImmutableFloatList; import com.gs.collections.api.list.primitive.ImmutableIntList; import com.gs.collections.api.list.primitive.ImmutableLongList; import com.gs.collections.api.list.primitive.ImmutableShortList; import com.gs.collections.api.map.ImmutableMap; import com.gs.collections.api.map.ImmutableMapIterable; import com.gs.collections.api.multimap.list.ImmutableListMultimap; import com.gs.collections.api.multimap.sortedset.ImmutableSortedSetMultimap; import com.gs.collections.api.partition.list.PartitionImmutableList; import com.gs.collections.api.tuple.Pair; import net.jcip.annotations.Immutable; /** * An ImmutableSortedMap is different than a JCF SortedMap in that it has no mutating methods, but it shares * the read-only protocol of a SortedMap. */ @Immutable public interface ImmutableSortedMap<K, V> extends SortedMapIterable<K, V>, ImmutableMapIterable<K, V> { SortedMap<K, V> castToMap(); SortedMap<K, V> castToSortedMap(); // TODO: Keys could be ordered ImmutableSortedSetMultimap<V, K> flip(); ImmutableSortedMap<K, V> newWithKeyValue(K key, V value); ImmutableSortedMap<K, V> newWithAllKeyValues(Iterable<? extends Pair<? extends K, ? extends V>> keyValues); ImmutableSortedMap<K, V> newWithAllKeyValueArguments(Pair<? extends K, ? extends V>... keyValuePairs); ImmutableSortedMap<K, V> newWithoutKey(K key); ImmutableSortedMap<K, V> newWithoutAllKeys(Iterable<? extends K> keys); MutableSortedMap<K, V> toSortedMap(); // TODO: When we have implementations of linked hash maps // ImmutableOrderedMap<V, K> flipUniqueValues(); ImmutableSortedMap<K, V> select(Predicate2<? super K, ? super V> predicate); ImmutableSortedMap<K, V> reject(Predicate2<? super K, ? super V> predicate); ImmutableSortedMap<K, V> tap(Procedure<? super V> procedure); ImmutableList<V> select(Predicate<? super V> predicate); <P> ImmutableList<V> selectWith(Predicate2<? super V, ? super P> predicate, P parameter); ImmutableList<V> reject(Predicate<? super V> predicate); <P> ImmutableList<V> rejectWith(Predicate2<? super V, ? super P> predicate, P parameter); <S> ImmutableList<S> selectInstancesOf(Class<S> clazz); PartitionImmutableList<V> partition(Predicate<? super V> predicate); <P> PartitionImmutableList<V> partitionWith(Predicate2<? super V, ? super P> predicate, P parameter); <R> ImmutableList<R> collect(Function<? super V, ? extends R> function); <P, VV> ImmutableList<VV> collectWith(Function2<? super V, ? super P, ? extends VV> function, P parameter); <K2, V2> ImmutableMap<K2, V2> collect(Function2<? super K, ? super V, Pair<K2, V2>> function); <R> ImmutableSortedMap<K, R> collectValues(Function2<? super K, ? super V, ? extends R> function); <R> ImmutableList<R> collectIf( Predicate<? super V> predicate, Function<? super V, ? extends R> function); <R> ImmutableList<R> flatCollect(Function<? super V, ? extends Iterable<R>> function); ImmutableBooleanList collectBoolean(BooleanFunction<? super V> booleanFunction); ImmutableByteList collectByte(ByteFunction<? super V> byteFunction); ImmutableCharList collectChar(CharFunction<? super V> charFunction); ImmutableDoubleList collectDouble(DoubleFunction<? super V> doubleFunction); ImmutableFloatList collectFloat(FloatFunction<? super V> floatFunction); ImmutableIntList collectInt(IntFunction<? super V> intFunction); ImmutableLongList collectLong(LongFunction<? super V> longFunction); ImmutableShortList collectShort(ShortFunction<? super V> shortFunction); <S> ImmutableList<Pair<V, S>> zip(Iterable<S> that); ImmutableList<Pair<V, Integer>> zipWithIndex(); <VV> ImmutableListMultimap<VV, V> groupBy(Function<? super V, ? extends VV> function); <VV> ImmutableListMultimap<VV, V> groupByEach(Function<? super V, ? extends Iterable<VV>> function); <VV> ImmutableMap<VV, V> groupByUniqueKey(Function<? super V, ? extends VV> function); <K2, V2> ImmutableMap<K2, V2> aggregateInPlaceBy( Function<? super V, ? extends K2> groupBy, Function0<? extends V2> zeroValueFactory, Procedure2<? super V2, ? super V> mutatingAggregator); <K2, V2> ImmutableMap<K2, V2> aggregateBy( Function<? super V, ? extends K2> groupBy, Function0<? extends V2> zeroValueFactory, Function2<? super V2, ? super V, ? extends V2> nonMutatingAggregator); }
tsuruclient/tsuru
src/core/alloc/mstdn_streaming_data.js
// @flow import {Mastodon} from '../Services'; import Content from '../value/Content'; import Event from '../value/Event'; import type {allocatedObject} from "./allocatedObjectType"; import createAllocatedObject from "./createAllocatedObject"; const mentionOrEvent = (payload: Object) => { console.log(payload); return payload.type === 'mention' ? new Content(Mastodon, payload.status) : new Event(Mastodon, payload, true) }; export default (data: Array<Object> | Object): allocatedObject => { if(Array.isArray(data)){ return createAllocatedObject( data.filter(item => item.event === 'update').map(item => new Content(Mastodon, item)), data.filter(item => item.event === 'notification').map(item => mentionOrEvent(JSON.parse(item.payload))), [] ); }else{ return createAllocatedObject( data.event === 'update' ? [new Content(Mastodon, JSON.parse(data.payload))] : [], data.event === 'notification' ? [mentionOrEvent(JSON.parse(data.payload))] : [], [] ); } }
JavaSaBr/jmonkey-builder
src/main/java/com/ss/editor/util/EditorUtil.java
package com.ss.editor.util; import static com.ss.rlib.common.util.ClassUtils.cast; import static com.ss.rlib.common.util.ClassUtils.unsafeCast; import static com.ss.rlib.common.util.ObjectUtils.notNull; import static java.lang.Math.acos; import static java.lang.Math.toDegrees; import static java.lang.ThreadLocal.withInitial; import static java.util.stream.Collectors.toList; import com.jme3.app.state.AppStateManager; import com.jme3.asset.AssetKey; import com.jme3.asset.AssetManager; import com.jme3.environment.generation.JobProgressAdapter; import com.jme3.input.InputManager; import com.jme3.light.LightProbe; import com.jme3.material.Material; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.post.FilterPostProcessor; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.Renderer; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.system.JmeSystem; import com.jme3.system.Platform; import com.ss.editor.JfxApplication; import com.ss.editor.JmeApplication; import com.ss.editor.analytics.google.GAnalytics; import com.ss.editor.annotation.FromAnyThread; import com.ss.editor.annotation.FxThread; import com.ss.editor.annotation.JmeThread; import com.ss.editor.config.EditorConfig; import com.ss.editor.extension.scene.SceneLayer; import com.ss.editor.manager.ClasspathManager; import com.ss.editor.manager.ExecutorManager; import com.ss.editor.manager.ResourceManager; import com.ss.editor.model.undo.editor.ChangeConsumer; import com.ss.editor.model.undo.editor.SceneChangeConsumer; import com.ss.editor.ui.event.FxEventManager; import com.ss.editor.ui.event.impl.RequestedOpenFileEvent; import com.ss.editor.ui.scene.EditorFxScene; import com.ss.editor.ui.util.UiUtils; import com.ss.rlib.common.logging.Logger; import com.ss.rlib.common.logging.LoggerManager; import com.ss.rlib.common.util.ClassUtils; import com.ss.rlib.common.util.StringUtils; import com.ss.rlib.common.util.array.Array; import com.ss.rlib.common.util.dictionary.DictionaryFactory; import com.ss.rlib.common.util.dictionary.ObjectDictionary; import javafx.application.HostServices; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DataFormat; import javafx.scene.input.Dragboard; import javafx.stage.Stage; import javafx.stage.Window; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.net.MalformedURLException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; /** * The class with utility methods for the Editor. * * @author JavaSaBr */ public abstract class EditorUtil { private static final Logger LOGGER = LoggerManager.getLogger(EditorUtil.class); public static final DataFormat JAVA_PARAM = new DataFormat("jMB.javaParam"); public static final DataFormat GNOME_FILES = new DataFormat("x-special/gnome-copied-files"); private static final ThreadLocal<SimpleDateFormat> LOCATE_DATE_FORMAT = withInitial(() -> new SimpleDateFormat("HH:mm:ss:SSS")); private static ThreadLocal<ObjectDictionary<Class<?>, Enum<?>[]>> ENUM_VALUES_LOCAL = ThreadLocal.withInitial(DictionaryFactory::newObjectDictionary); private static JmeApplication jmeApplication; private static JfxApplication jfxApplication; public static void setJmeApplication(@NotNull JmeApplication jmeApplication) { EditorUtil.jmeApplication = jmeApplication; } public static void setJfxApplication(@NotNull JfxApplication jfxApplication) { EditorUtil.jfxApplication = jfxApplication; } /** * Get the asset manager. * * @return the asset manager. */ @FromAnyThread public static @NotNull AssetManager getAssetManager() { return jmeApplication.getAssetManager(); } /** * Get the input manager. * * @return the input manager. */ @FromAnyThread public static @NotNull InputManager getInputManager() { return jmeApplication.getInputManager(); } /** * Get the render manager. * * @return the render manager. */ @FromAnyThread public static @NotNull RenderManager getRenderManager() { return jmeApplication.getRenderManager(); } /** * Get the renderer. * * @return the renderer. */ @FromAnyThread public static @NotNull Renderer getRenderer() { return jmeApplication.getRenderer(); } /** * Get the root node. * * @return the root node. */ @JmeThread public static @NotNull Node getGlobalRootNode() { return jmeApplication.getRootNode(); } /** * Get the preview node. * * @return the preview node. */ @JmeThread public static @NotNull Node getPreviewNode() { return jmeApplication.getPreviewNode(); } /** * Get the preview camera. * * @return the preview camera. */ @JmeThread public static @NotNull Camera getPreviewCamera() { return jmeApplication.getPreviewCamera(); } /** * Get the camera. * * @return the camera. */ @FromAnyThread public static @NotNull Camera getGlobalCamera() { return jmeApplication.getCamera(); } /** * Get the global filter post processor. * * @return the global filter post processor. */ @JmeThread public static @NotNull FilterPostProcessor getGlobalFilterPostProcessor() { return jmeApplication.getPostProcessor(); } /** * Get the default material. * * @return the default material. */ @FromAnyThread public static @NotNull Material getDefaultMaterial() { return jmeApplication.getDefaultMaterial(); } /** * Disable the global PBR light probe. */ @JmeThread public static void disableGlobalLightProbe() { jmeApplication.disableLightProbe(); } /** * Enable the global PBR light probe. */ @JmeThread public static void enableGlobalLightProbe() { jmeApplication.enableLightProbe(); } /** * Update the light probe. * * @param progressAdapter the progress adapter */ @JmeThread public static void updateGlobalLightProbe(@NotNull JobProgressAdapter<LightProbe> progressAdapter) { jmeApplication.updateLightProbe(progressAdapter); } /** * Get the state manager. * * @return the state manager. */ @FromAnyThread public static @NotNull AppStateManager getStateManager() { return jmeApplication.getStateManager(); } /** * Gets the last opened window. * * @return the last opened window. */ @FxThread public static @NotNull Window getFxLastWindow() { return jfxApplication.getLastWindow(); } /** * Get the current JavaFX scene. * * @return the JavaFX scene. */ @FxThread public static @NotNull EditorFxScene getFxScene() { return jfxApplication.getScene(); } /** * Get the host services. * * @return the host services. */ @FxThread public static @NotNull HostServices getHostServices() { return jfxApplication.getHostServices(); } /** * Get the current stage of JavaFX. * * @return the current stage of JavaFX. */ @FxThread public static @NotNull Stage getFxStage() { return jfxApplication.getStage(); } /** * Register the opened new window. * * @param window the opened new window. */ @FromAnyThread public static void addFxWindow(@NotNull Window window) { jfxApplication.addWindow(window); } /** * Delete the closed window. * * @param window the closed window. */ @FromAnyThread public static void removeFxWindow(@NotNull Window window) { jfxApplication.removeWindow(window); } /** * Request focus to FX window. */ @FxThread public static void requestFxFocus() { jfxApplication.requestFocus(); } /** * Added files like files to copy to clipboard content. * * @param paths the list of files. * @param content the content to store. */ @FxThread public static @NotNull ClipboardContent addCopiedFile( @NotNull Array<Path> paths, @NotNull ClipboardContent content ) { var files = paths.stream() .map(Path::toFile) .collect(toList()); content.putFiles(files); content.put(EditorUtil.JAVA_PARAM, "copy"); var platform = JmeSystem.getPlatform(); if (platform == Platform.Linux64 || platform == Platform.Linux32) { var builder = new StringBuilder("copy\n"); paths.forEach(builder, (path, b) -> b.append(path.toUri().toASCIIString()).append('\n')); builder.delete(builder.length() - 1, builder.length()); var buffer = ByteBuffer.allocate(builder.length()); for (int i = 0, length = builder.length(); i < length; i++) { buffer.put((byte) builder.charAt(i)); } buffer.flip(); content.put(GNOME_FILES, buffer); } return content; } /** * Check exists boolean. * * @param path the path to resource. * @return true if the resource is exists. */ @FromAnyThread public static boolean checkExists(@NotNull String path) { var cs = EditorUtil.class; return cs.getResource(path) != null || cs.getResource("/" + path) != null; } /** * Check exists boolean. * * @param path the path to resource. * @param classLoader the class loader. * @return true if the resource is exists. */ @FromAnyThread public static boolean checkExists(@NotNull String path, @NotNull ClassLoader classLoader) { return classLoader.getResource(path) != null || classLoader.getResource("/" + path) != null; } /** * Convert classpath path to external path. * * @param path the path to resource. * @param classLoader the class loader. * @return the external form or null. */ @FromAnyThread public static @Nullable String toExternal(@NotNull String path, @NotNull ClassLoader classLoader) { if (!checkExists(path, classLoader)) { return null; } var resource = classLoader.getResource(path); if (resource == null) { resource = classLoader.getResource("/" + path); } return resource == null ? null : resource.toExternalForm(); } /** * Get the angle between these points. * * @param center the center. * @param first the first point. * @param second the second point. * @return the angle between these points. */ @FromAnyThread public static float getAngle( @NotNull Vector2f center, @NotNull Vector2f first, @NotNull Vector2f second ) { var x = center.getX(); var y = center.getY(); var ax = first.getX() - x; var ay = first.getY() - y; var bx = second.getX() - x; var by = second.getY() - y; var delta = (float) ((ax * bx + ay * by) / Math.sqrt((ax * ax + ay * ay) * (bx * bx + by * by))); if (delta > 1.0) { return 0.0F; } else if (delta < -1.0) { return 180.0F; } return (float) toDegrees(acos(delta)); } /** * Get an input stream. * * @param path the path to resource. * @return the input stream of the resource or null. */ @FromAnyThread public static @Nullable InputStream getInputStream(@NotNull String path) { return JfxApplication.class.getResourceAsStream(path); } /** * Get an input stream or throw an exception. * * @param path the path to resource. * @return the input stream of the resource or null. */ @FromAnyThread public static @NotNull InputStream requireInputStream(@NotNull String path) { return notNull(JfxApplication.class.getResourceAsStream(path)); } /** * Get the input stream. * * @param path the path to resource. * @param classLoader the class loader. * @return the input stream of the resource or null. */ @FromAnyThread public static @Nullable InputStream getInputStream(@NotNull String path, @NotNull ClassLoader classLoader) { return classLoader.getResourceAsStream(path); } /** * Get the user name of the computer user. * * @return the user name. */ @FromAnyThread public static @NotNull String getUserName() { return System.getProperty("user.name"); } /** * Check visibility the position on the screen. * * @param position the position for checking. * @param camera the camera of the screen. * @return true of we can see the position on the screen. */ @FromAnyThread public static boolean isVisibleOnScreen(@NotNull Vector3f position, @NotNull Camera camera) { var maxHeight = camera.getHeight(); var maxWidth = camera.getWidth(); var isBottom = position.getY() < 0; var isTop = position.getY() > maxHeight; var isLeft = position.getX() < 0; var isRight = position.getX() > maxWidth; return !isBottom && !isLeft && !isTop && !isRight && position.getZ() < 1F; } /** * Calculate new point from first point and using second point like a direction. * * @param first the first point. * @param second the second point. * @param store the container of the result. * @param length the distance. */ @FromAnyThread public static void movePoint( @NotNull Vector3f first, @NotNull Vector3f second, @NotNull Vector3f store, int length ) { store.x = first.x + (second.x - first.x) * length; store.y = first.y + (second.y - first.y) * length; store.z = first.z + (second.z - first.z) * length; } /** * Convert unix time to string presentation. * * @param time the unix time. * @return the string presentation. */ @FromAnyThread public static @NotNull String timeFormat(long time) { var format = LOCATE_DATE_FORMAT.get(); return format.format(new Date(time)); } /** * Get the path to the file from the asset folder. * * @param assetFolder the asset folder. * @param file the file. * @return the relative path. */ @FromAnyThread public static @NotNull Path getAssetFile(@NotNull Path assetFolder, @NotNull Path file) { return assetFolder.relativize(file); } /** * Get the path to the file from the current asset folder. * * @param file the file. * @return the relative path. */ @FromAnyThread public static @Nullable Path getAssetFile(@NotNull Path file) { var editorConfig = EditorConfig.getInstance(); var currentAsset = editorConfig.getCurrentAsset(); if (currentAsset == null) { return null; } try { return currentAsset.relativize(file); } catch (IllegalArgumentException e) { LOGGER.warning("Can't create asset file of the " + file + " for asset folder " + currentAsset); LOGGER.warning(e); return null; } } /** * Get the absolute path to the file in the current asset. * * @param assetFile the file. * @return the absolute path to the file. */ @FromAnyThread public static @Nullable Path getRealFile(@NotNull Path assetFile) { var editorConfig = EditorConfig.getInstance(); var currentAsset = editorConfig.getCurrentAsset(); if (currentAsset == null) { return null; } return currentAsset.resolve(assetFile); } /** * Get the absolute path to the file in the current asset. * * @param assetFile the asset path to file. * @return the absolute path to the file. */ @FromAnyThread public static @Nullable Path getRealFile(@NotNull String assetFile) { var editorConfig = EditorConfig.getInstance(); var currentAsset = editorConfig.getCurrentAsset(); if (currentAsset == null) { return null; } return currentAsset.resolve(assetFile); } /** * To asset path string. * * @param path the path * @return the valid asset path for the file. */ @FromAnyThread public static @NotNull String toAssetPath(@NotNull Path path) { if (File.separatorChar == '/') { return path.toString(); } return path.toString().replace("\\", "/"); } /** * Handle exception. * * @param logger the logger. * @param owner the owner. * @param e the exception. */ @FromAnyThread public static void handleException(@Nullable Logger logger, @Nullable Object owner, @NotNull Exception e) { handleException(logger, owner, e, null); } /** * Handle exception. * * @param logger the logger. * @param owner the owner. * @param e the exception. * @param callback the callback. */ @FromAnyThread public static void handleException( @Nullable Logger logger, @Nullable Object owner, @NotNull Exception e, @Nullable Runnable callback ) { if (logger == null) { logger = LOGGER; } if (owner == null) { logger.warning(e); } else { logger.warning(owner, e); } var executorManager = ExecutorManager.getInstance(); executorManager.addFxTask(() -> { GAnalytics.sendException(e, false); var localizedMessage = e.getLocalizedMessage(); var stackTrace = buildStackTrace(e); var alert = UiUtils.createErrorAlert(e, localizedMessage, stackTrace); alert.show(); alert.setWidth(500); alert.setHeight(220); if (callback != null) { alert.setOnHidden(event -> callback.run()); } }); } /** * Build the stack trace of the exception. * * @param exception the exception. * @return the built stack trace. */ @FromAnyThread public static String buildStackTrace(@NotNull Exception exception) { var writer = new StringWriter(); var printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); var stackTrace = writer.toString(); var level = 0; for (var cause = exception.getCause(); cause != null && level < 6; cause = cause.getCause(), level++) { writer = new StringWriter(); printWriter = new PrintWriter(writer); cause.printStackTrace(printWriter); stackTrace += "\n caused by " + writer.toString(); } return stackTrace; } /** * Open the file in an external editor. * * @param path the path */ @FromAnyThread public static void openFileInExternalEditor(@NotNull Path path) { var platform = JmeSystem.getPlatform(); var commands = new ArrayList<String>(); if (platform == Platform.MacOSX64 || platform == Platform.MacOSX_PPC64) { commands.add("open"); } else if (platform == Platform.Windows32 || platform == Platform.Windows64) { commands.add("cmd"); commands.add("/c"); commands.add("start"); } else if (platform == Platform.Linux32|| platform == Platform.Linux64) { commands.add("xdg-open"); } if (commands.isEmpty()) { return; } String url; try { url = path.toUri().toURL().toString(); } catch (MalformedURLException e) { handleException(LOGGER, null, e); return; } commands.add(url); var processBuilder = new ProcessBuilder(); processBuilder.command(commands); try { processBuilder.start(); } catch (IOException e) { handleException(LOGGER, null, e); } } /** * Open the file in a system explorer. * * @param path the path */ @FromAnyThread public static void openFileInSystemExplorer(@NotNull Path path) { var platform = JmeSystem.getPlatform(); var commands = new ArrayList<String>(); if (platform == Platform.MacOSX64 || platform == Platform.MacOSX_PPC64) { commands.add("open"); commands.add("-R"); } else if (platform == Platform.Windows32 || platform == Platform.Windows64) { commands.add("explorer"); commands.add("/select,"); } else if (platform == Platform.Linux32 || platform == Platform.Linux64) { if (isAppExists("nautilus -v")) { commands.add("nautilus"); } else if (isAppExists("dolphin -v")) { commands.add("dolphin"); commands.add("--select"); } else { commands.add("xdg-open"); if (!Files.isDirectory(path)) { path = path.getParent(); } } } if (commands.isEmpty()) { return; } String url; try { url = path.toUri().toURL().toString(); } catch (MalformedURLException e) { handleException(LOGGER, null, e); return; } commands.add(url); var processBuilder = new ProcessBuilder(); processBuilder.command(commands); try { processBuilder.start(); } catch (IOException e) { handleException(LOGGER, null, e); } } @FromAnyThread private static boolean isAppExists(@NotNull String command) { var runtime = Runtime.getRuntime(); int result; try { var exec = runtime.exec(command); result = exec.waitFor(); } catch (InterruptedException | IOException e) { return false; } return result >= 0; } /** * Convert the object to byte array. * * @param object the object * @return the byte array. */ @FromAnyThread public static @NotNull byte[] serialize(@NotNull Serializable object) { var bout = new ByteArrayOutputStream(); try (var out = new ObjectOutputStream(bout)) { out.writeObject(object); } catch (IOException e) { LOGGER.warning(e); } return bout.toByteArray(); } /** * Convert the byte array to object. * * @param <T> the type parameter * @param bytes the byte array. * @return the result object. */ @FromAnyThread public static <T> @NotNull T deserialize(@NotNull byte[] bytes) { var bin = new ByteArrayInputStream(bytes); try (var in = new ExtObjectInputStream(bin)) { return unsafeCast(in.readObject()); } catch (ClassNotFoundException | IOException e) { throw new RuntimeException(e); } } /** * Format the float number. * * @param value the value * @param mod the mod * @return the float */ @FromAnyThread public static float clipNumber(float value, float mod) { return (int) (value * mod) / mod; } /** * Get an array of available enum values by an enum value. * * @param <E> the type parameter * @param value the enum value. * @return the array of enum values. */ @FromAnyThread public static <E extends Enum<?>> @NotNull E[] getAvailableValues(@NotNull E value) { var valueClass = value.getClass(); if (!valueClass.isEnum()) { throw new RuntimeException("The class " + valueClass + " isn't enum."); } var enumConstants = valueClass.getEnumConstants(); return unsafeCast(enumConstants); } /** * Try to create an user object using asset classpath and additional classpath. * * @param <T> the type parameter * @param owner the requester. * @param className the classname. * @param resultType the result type. * @return the new instance or null. */ @FromAnyThread public static <T> @Nullable T tryToCreateUserObject( @NotNull Object owner, @NotNull String className, @NotNull Class<T> resultType ) { var resourceManager = ResourceManager.getInstance(); var classpathManager = ClasspathManager.getInstance(); Object newExample = null; try { newExample = ClassUtils.newInstance(className); } catch (RuntimeException e) { var classLoaders = resourceManager.getClassLoaders(); for (var classLoader : classLoaders) { try { var targetClass = classLoader.loadClass(className); newExample = ClassUtils.newInstance(targetClass); } catch (ClassNotFoundException ex) { LOGGER.warning(owner, e); } } var librariesLoader = classpathManager.getLibrariesLoader(); if (librariesLoader != null) { try { var targetClass = librariesLoader.loadClass(className); newExample = ClassUtils.newInstance(targetClass); } catch (final ClassNotFoundException ex) { LOGGER.warning(owner, e); } } } return cast(resultType, newExample); } /** * Get a default layer of the change consumer. * * @param consumer the change consumer. * @return the default layer or null. */ @FromAnyThread public static @Nullable SceneLayer getDefaultLayer(@NotNull ChangeConsumer consumer) { if (!(consumer instanceof SceneChangeConsumer)) { return null; } var sceneNode = ((SceneChangeConsumer) consumer).getCurrentModel(); var layers = sceneNode.getLayers(); if (layers.isEmpty()) { return null; } return layers.get(0); } /** * Return true if the asset key is null or empty. * * @param assetKey the asset key. * @return true if the asset key is null or empty. */ public static boolean isEmpty(@Nullable AssetKey<?> assetKey) { return assetKey == null || StringUtils.isEmpty(assetKey.getName()); } /** * Open the asset resource in an editor. * * @param assetKey the asset key. */ @FromAnyThread public static void openInEditor(@Nullable AssetKey<?> assetKey) { if (assetKey == null) { return; } var assetPath = assetKey.getName(); if (StringUtils.isEmpty(assetPath)) { return; } var assetFile = Paths.get(assetPath); var realFile = notNull(getRealFile(assetFile)); if (!Files.exists(realFile)) { return; } FxEventManager.getInstance() .notify(new RequestedOpenFileEvent(realFile)); } /** * Get the list of files in the current dragboard. * * @param dragboard the current dragboard. * @return the list of files. */ @FromAnyThread public static @NotNull List<File> getFiles(@NotNull Dragboard dragboard) { List<File> files = unsafeCast(dragboard.getContent(DataFormat.FILES)); return files == null ? Collections.emptyList() : files; } /** * Get an array of enum constants by the class. * * @param enumType the enum's class. * @param <T> the enum's type. * @return the array of enum's constants. */ @FromAnyThread public static <T> T[] getEnumValues(@NotNull Class<?> enumType) { if(!enumType.isEnum()) { throw new IllegalArgumentException("The type " + enumType + " isn't a enum."); } return unsafeCast(ENUM_VALUES_LOCAL.get() .get(enumType, type -> (Enum<?>[]) type.getEnumConstants())); } /** * Find a root key of the spatial. * * @param spatial the spatial. * @return the root key or null. */ public static @Nullable String findRootKey(@Nullable Spatial spatial) { if(spatial == null) { return null; } return NodeUtils.<Spatial>findParentOpt(spatial, sp -> sp.getKey() != null) .map(Spatial::getKey) .map(AssetKey::getName) .orElse(null); } }
yonetatuu/kamonohashi
web-pages/src/icon/kqi-notebook.js
import Icon from 'vue-awesome/components/Icon' import 'vue-awesome/icons/book' Icon.register({ 'pl-notebook': Icon.icons['book'], })
sarang-apps/darshan_browser
components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/signin/core/browser/dice_account_reconcilor_delegate.h" #include <vector> #include "components/prefs/pref_registry_simple.h" #include "components/signin/public/base/account_consistency_method.h" #include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/base/test_signin_client.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_auth_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace signin { TEST(DiceAccountReconcilorDelegateTest, RevokeTokens) { sync_preferences::TestingPrefServiceSyncable pref_service; TestSigninClient client(&pref_service); gaia::ListedAccount gaia_account; gaia_account.id = CoreAccountId("other"); DiceAccountReconcilorDelegate delegate(&client, /*migration_completed=*/true); EXPECT_EQ( signin::AccountReconcilorDelegate::RevokeTokenOption::kRevokeIfInError, delegate.ShouldRevokeSecondaryTokensBeforeReconcile( std::vector<gaia::ListedAccount>())); } TEST(DiceAccountReconcilorDelegateTest, ShouldRevokeTokensBasedOnCookies) { sync_preferences::TestingPrefServiceSyncable pref_service; TestSigninClient client(&pref_service); { // Dice is enabled, revoke tokens when Gaia cookie is deleted. DiceAccountReconcilorDelegate delegate(&client, /*migration_completed=*/true); EXPECT_EQ(true, delegate.ShouldRevokeTokensOnCookieDeleted()); EXPECT_EQ(false, delegate.ShouldRevokeTokensNotInCookies()); } { // Dice is enabled, migration not completed, revoke tokens when // Gaia cookie is deleted. DiceAccountReconcilorDelegate delegate(&client, /*migration_completed=*/false); EXPECT_EQ(true, delegate.ShouldRevokeTokensOnCookieDeleted()); EXPECT_EQ(true, delegate.ShouldRevokeTokensNotInCookies()); } } } // namespace signin
ilscipio/erp
framework/base/src/com/ilscipio/scipio/ce/util/servlet/ServletMapEntryAdapters.java
package com.ilscipio.scipio.ce.util.servlet; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpSession; import com.ilscipio.scipio.ce.util.collections.MapEntryAdapter; /** * Servlet API adapters for the {@link com.ilscipio.scipio.ce.util.collections.MapEntryAdapter} * ({@link Map.Entry}) interface. * <p> * NOTE: See also {@link com.ilscipio.scipio.ce.util.collections.MapEntryAdapters}. */ @SuppressWarnings("deprecation") public final class ServletMapEntryAdapters { private ServletMapEntryAdapters() { } /** * Returns a full-featured, best-possible-correctness request map entry adapter. */ public static RequestMapEntryAdapter getAdapter(ServletRequest request, String key) { return new StdRequestMapEntryAdapter(request, key); } /** * Returns a full-featured, best-possible-correctness session map entry adapter. */ public static SessionMapEntryAdapter getAdapter(HttpSession session, String key) { return new StdSessionMapEntryAdapter(session, key); } /** * Returns a full-featured, best-possible-correctness servlet context map entry adapter. */ public static ServletContextMapEntryAdapter getAdapter(ServletContext servletContext, String key) { return new StdServletContextMapEntryAdapter(servletContext, key); } /** * Returns an optimized request map entry adapter <strong>that makes {@link java.util.Map.Entry} * interface violations</strong>. * <p> * Characteristics: * <ul> * <li>{@link StdServletMapEntryAdapter#setValue} intentionally breaks the Map contract and does NOT return the previous/old value; * it may returns null or a dummy default instead.</li> * </ul> */ public static RequestMapEntryAdapter getFastAdapter(ServletRequest request, String key) { return new FastRequestMapEntryAdapter(request, key); } /** * Returns an optimized session map entry adapter <strong>that makes {@link java.util.Map.Entry} * interface violations</strong>. * <p> * Characteristics: * <ul> * <li>{@link StdServletMapEntryAdapter#setValue} intentionally breaks the Map contract and does NOT return the previous/old value; * it may returns null or a dummy default instead.</li> * </ul> */ public static SessionMapEntryAdapter getFastAdapter(HttpSession session, String key) { return new FastSessionMapEntryAdapter(session, key); } /** * Returns an optimized session map entry adapter <strong>that makes {@link java.util.Map.Entry} * interface violations</strong>. * <p> * Characteristics: * <ul> * <li>{@link StdServletMapEntryAdapter#setValue} intentionally breaks the Map contract and does NOT return the previous/old value; * it may returns null or a dummy default instead.</li> * </ul> */ public static ServletContextMapEntryAdapter getFastAdapter(ServletContext servletContext, String key) { return new FastServletContextMapEntryAdapter(servletContext, key); } public interface ServletMapEntryAdapter extends MapEntryAdapter<String, Object>, ServletAttrContainer { @Override public default void setValueOnly(Object value) { setAttribute(getKey(), value); } @Override public default void removeValueOnly() { removeAttribute(getKey()); } } public interface RequestMapEntryAdapter extends ServletMapEntryAdapter { } public interface SessionMapEntryAdapter extends ServletMapEntryAdapter { } public interface ServletContextMapEntryAdapter extends ServletMapEntryAdapter { } public interface StdServletMapEntryAdapter extends ServletMapEntryAdapter { @Override public default Object getValue() { return getAttribute(getKey()); } @Override public default Object setValue(Object value) { Object oldValue = getAttribute(getKey()); setValueOnly(value); return oldValue; } @Override public default Object removeValue() { Object oldValue = getAttribute(getKey()); removeValueOnly(); return oldValue; } } public static class StdRequestMapEntryAdapter implements StdServletMapEntryAdapter, ServletAttrContainer.RequestAdapter, RequestMapEntryAdapter { private final ServletRequest request; private final String key; public StdRequestMapEntryAdapter(ServletRequest request, String key) { this.request = request; this.key = key; } @Override public String getKey() { return key; } @Override public ServletRequest getAdapted() { return request; } } public static class StdSessionMapEntryAdapter implements StdServletMapEntryAdapter, ServletAttrContainer.SessionAdapter, SessionMapEntryAdapter { private final HttpSession session; private final String key; public StdSessionMapEntryAdapter(HttpSession session, String key) { this.session = session; this.key = key; } @Override public String getKey() { return key; } @Override public HttpSession getAdapted() { return session; } } public static class StdServletContextMapEntryAdapter implements StdServletMapEntryAdapter, ServletAttrContainer.ServletContextAdapter, ServletContextMapEntryAdapter { private final ServletContext servletContext; private final String key; public StdServletContextMapEntryAdapter(ServletContext servletContext, String key) { this.servletContext = servletContext; this.key = key; } @Override public String getKey() { return key; } @Override public ServletContext getAdapted() { return servletContext; } } public interface FastServletMapEntryAdapter extends StdServletMapEntryAdapter { @Override public default Object setValue(Object value) { setValueOnly(value); return null; } @Override public default Object removeValue() { removeValueOnly(); return null; } } public static class FastRequestMapEntryAdapter extends StdRequestMapEntryAdapter implements FastServletMapEntryAdapter { public FastRequestMapEntryAdapter(ServletRequest request, String key) { super(request, key); } @Override public Object setValue(Object value) { setValueOnly(value); return null; } @Override public Object removeValue() { removeValueOnly(); return null; } } public static class FastSessionMapEntryAdapter extends StdSessionMapEntryAdapter implements FastServletMapEntryAdapter { public FastSessionMapEntryAdapter(HttpSession session, String key) { super(session, key); } @Override public Object setValue(Object value) { setValueOnly(value); return null; } @Override public Object removeValue() { removeValueOnly(); return null; } } public static class FastServletContextMapEntryAdapter extends StdServletContextMapEntryAdapter implements FastServletMapEntryAdapter { public FastServletContextMapEntryAdapter(ServletContext servletContext, String key) { super(servletContext, key); } @Override public Object setValue(Object value) { setValueOnly(value); return null; } @Override public Object removeValue() { removeValueOnly(); return null; } } }
gpaganini/PadroesdeProjetos
TemplateMethod/src/com/company/Shelf.java
package com.company; import java.util.ArrayList; public class Shelf { protected ArrayList<Ebook> biblioteca; protected TemplateOrdenador ordenador; public Shelf(OrdemDeLeitura ordem) { biblioteca = new ArrayList<Ebook>(); switch (ordem) { case porAno: ordenador = new OrderByYear(); break; case porAutor: ordenador = new OrderByAuthor(); break; case porRating: ordenador = new OrderByRating(); break; case porNome: ordenador = new OrderByName(); break; case porEditora: ordenador = new OrderByEditora(); break; default: break; } } public void setOrdemDeLeitura(OrdemDeLeitura ordem) { ordenador = null; switch (ordem) { case porAno: ordenador = new OrderByYear(); break; case porAutor: ordenador = new OrderByAuthor(); break; case porRating: ordenador = new OrderByRating(); break; case porNome: ordenador = new OrderByName(); break; case porEditora: ordenador = new OrderByEditora(); break; default: break; } } public void adicionarEbook(String nome, String autor, String ano, String editora, int rating) { biblioteca.add(new Ebook(nome, autor, ano, editora, rating)); } public void mostrarListaDeLeitura() { ArrayList<Ebook> novaLista = new ArrayList<Ebook>(); novaLista = ordenador.ordernarEbook(biblioteca); for (Ebook ebook : novaLista) { System.out.println(ebook.nome + " - " + ebook.autor + "\nAno: " + ebook.anoPublicacao + "\nRating: " + ebook.rating + "\nEditora: " + ebook.editora + "\n" ); } } }
jstokes/secure-data-service
sli/admin-tools/admin-rails/app/models/admin_delegation.rb
<filename>sli/admin-tools/admin-rails/app/models/admin_delegation.rb class AdminDelegation < SessionResource self.site = APP_CONFIG['api_base'] self.collection_name = 'adminDelegation' schema do string 'localEdOrgId' boolean 'viewSecurityEventsEnabled' end end
MicrochipTech/aws-iot-winc1500-secure-wifi-board-included-source-files
mcu-firmware/saml21g18b_sensor_board_demo/src/cryptoauthlib/docs/html/a00131.js
<filename>mcu-firmware/saml21g18b_sensor_board_demo/src/cryptoauthlib/docs/html/a00131.js var a00131 = [ [ "atcab_random", "a00427.html#ga4fa442396dfbb89e59dfca837b565cec", null ] ];
liuzikai/klc3
test/Feature/IsSymbolic.c
// RUN: %clang %s -emit-llvm %O0opt -c -o %t1.bc // RUN: rm -rf %t.klee-out // RUN: %klee --output-dir=%t.klee-out %t1.bc #include <assert.h> int main() { int x, y, z = 0; klee_make_symbolic(&x, sizeof x, "x"); klee_make_symbolic(&y, sizeof y, "y"); if (x) { assert(klee_is_symbolic(y)); } else { assert(!klee_is_symbolic(z)); } return 0; }
EnglishLesson/dc_procxls
model/tkeyword.rb
<reponame>EnglishLesson/dc_procxls<filename>model/tkeyword.rb require_relative 'entity' class TKeywordModel < Entity def getName @name end def setName(name) @name = name end def to_s return "(code, name)" end end
JLLeitschuh/TIPL
spark/src/main/scala/tipl/spark/DTImgOps.scala
<filename>spark/src/main/scala/tipl/spark/DTImgOps.scala /** * */ package tipl.spark import org.apache.spark.SparkContext._ import org.apache.spark.api.java.JavaPairRDD import org.apache.spark.rdd.RDD import tipl.formats.TImgRO import tipl.spark.DSImg.D3IntSlicePartitioner import tipl.tools.BaseTIPLPluginIn import tipl.util.TIPLOps._ import tipl.util.{D3float, D3int, TImgSlice, TImgTools} import tipl.util.TImgTools.HasDimensions import scala.reflect.ClassTag import scala.util.Sorting.stableSort import scala.{specialized => spec} /** * A collection of useful functions for DTImg classes to allow more complicated analyses * * @author mader * */ object DTImgOps { def DTImgToKVStrict[T, V](inImg: DTImg[T], paddingVal: V)(implicit V: ClassTag[V]): KVImg[V] = { val outImg = DTImgToKVRDD(inImg).mapValues { cValue => cValue.asInstanceOf[V] } new KVImg[V](inImg, inImg.getImageType, outImg, paddingVal) } private[spark] def DTImgToKVRDD(inImg: DTImg[_]) = { val imgType = inImg.getImageType DTrddToKVrdd(inImg.getBaseImg.rdd, imgType, inImg.getPos, inImg.getDim) } private[spark] def DTrddToKVrdd[V](inImg: RDD[(D3int, TImgSlice[V])], imgType: Int, pos: D3int, dim: D3int) = { inImg.flatMap { cPoint => val pos = cPoint._1 val dim = new D3int(cPoint._2.getDim, 1) val obj = cPoint._2.get val outArr = TypeMacros.castArr(obj, imgType) for {z <- 0 until dim.z y <- 0 until dim.y x <- 0 until dim.x } yield (new D3int(pos.x + x, pos.y + y, pos.z + z), outArr((z * dim.y + y) * dim.x + x)) }.partitionBy(new D3IntSlicePartitioner(pos, dim)) //val onImg = TypeMacros.correctlyTypeDTImg(inImg) } /** * A smarter conversion function */ def fromTImgRO(inImg: TImgRO) = { val imClass = TImgTools.imageTypeToClass(inImg.getImageType) inImg match { case dImg: DTImg[_] if imClass == TImgTools.IMAGECLASS_LABEL => dImg.asDTLong case dImg: DTImg[_] if imClass == TImgTools.IMAGECLASS_VALUE => dImg.asDTDouble case dImg: DTImg[_] if imClass == TImgTools.IMAGECLASS_BINARY => dImg.asDTBool case normImg: TImgRO if imClass == TImgTools.IMAGECLASS_LABEL => DTImg.ConvertTImg[Array[Long]](SparkGlobal.getContext("DTImgOps"), normImg, TImgTools.IMAGETYPE_LONG) case normImg: TImgRO if imClass == TImgTools.IMAGECLASS_VALUE => DTImg.ConvertTImg[Array[Double]](SparkGlobal.getContext("DTImgOps"), normImg, TImgTools.IMAGETYPE_DOUBLE) case normImg: TImgRO if imClass == TImgTools.IMAGECLASS_BINARY => DTImg.ConvertTImg[Array[Boolean]](SparkGlobal.getContext("DTImgOps"), normImg, TImgTools.IMAGETYPE_BOOL) case normImg: TImgRO if imClass == TImgTools.IMAGECLASS_OTHER => throw new IllegalArgumentException(" Image Type Other is not supported yet inside Resize:Spark :" + inImg.getImageType) } } implicit class RichDtRDD[A](srd: RDD[(D3int, TImgSlice[A])]) extends NeighborhoodOperation[TImgSlice[A], TImgSlice[A]] { /** * Wrap a RDD as a DTImg * * @param elSize the size of the voxels */ def wrap(elSize: D3float = new D3float(1.0)): DTImg[A] = { val fele = srd.first val sPos = fele._1 val odim = fele._2.getDim val ndim = new D3int(odim, srd.count.asInstanceOf[Int]) val baseImg = TImgTools.SimpleDimensions(ndim, elSize, sPos) val imgtype = TImgTools.identifySliceType(fele._2.get) wrap(baseImg, imgtype) } /** * Wrap a RDD as a DTImg * * @param baseObj the image to mirror * @param imtype the type of the image */ def wrap(baseObj: HasDimensions, imtype: Int): DTImg[A] = { DTImg.WrapRDD[A](baseObj, JavaPairRDD.fromRDD(srd), imtype) } /** * simple apply a function to a slice */ def apply[B](mapFun: (Double => B))(implicit B: ClassTag[B]) = { srd.mapValues { inBlock => val outArray = (for (cval <- inBlock.getAsDouble()) yield mapFun(cval)).toArray new TImgSlice[Array[B]](outArray, inBlock) } } def blockOperation(windSize: D3int, kernel: Option[BaseTIPLPluginIn.morphKernel], mapFun: (Iterable[TImgSlice[A]] => TImgSlice[A])): RDD[(D3int, TImgSlice[A])] = { val spread = srd.spreadSlices(windSize).collectSlices(windSize, kernel, mapFun) spread } def spreadSlices(windSize: D3int): (RDD[(D3int, Iterable[TImgSlice[A]])]) = { var curOut = srd.mapValues(p => Iterable(p)) for (curOffset <- 1 to windSize.z) { val upSet = new D3int(0, 0, +curOffset) val up1 = srd.map(blockShift(upSet)) val downSet = new D3int(0, 0, -curOffset) val down1 = srd.map(blockShift(downSet)) val tempOut = curOut.join(up1.join(down1)) curOut = tempOut.mapValues { p => p._1 ++ Iterable(p._2._1, p._2._2) } } curOut } private[RichDtRDD] def blockShift(offset: D3int) = { (p: (D3int, TImgSlice[A])) => { val nPos = p._1 + offset (nPos, new TImgSlice[A](p._2.getClone(), nPos, offset)) } } } /** * A class of a spread RDD image (after a flatMap/spread operation) */ implicit class SpreadRDD[A](srd: RDD[(D3int, Iterable[TImgSlice[A]])]) extends Serializable { def collectSlices(windSize: D3int, kernel: Option[BaseTIPLPluginIn.morphKernel], coFun: (Iterable[TImgSlice[A]] => TImgSlice[A])) = { srd.mapValues(coFun) } } implicit class RichDTImg[A](ip: DTImg[A]) extends Serializable { val srd = ip.getBaseImg.rdd /** a much simpler version of spreadSlices taking advantage of Scala's language features * */ def spreadSlices(windSize: D3int) = srd.spreadSlices(windSize) def +[B](inImg: DTImg[B]) = combineImages(inImg, _ + _) /** * generic implementation of an operator * * @param inImg to combine with the ip image forming the classes * @param combFunc function to use to combine the two images * */ def combineImages[B](inImg: DTImg[B], combFunc: ((Double, Double) => Double)): DTImg[Array[Double]] = { sizeCheck(inImg) val aImg = ip.getBaseImg.rdd val bImg = inImg.getBaseImg.rdd val jImg = aImg.join(bImg).mapValues { inImages => val aArr = inImages._1.getAsDouble() val bArr = inImages._2.getAsDouble() val outArray = new Array[Double](aArr.length) for (i <- 0 until aArr.length) outArray(i) = combFunc(aArr(i), bArr(i)) new TImgSlice[Array[Double]](outArray, inImages._1) // inherit from first block } DTImg.WrapRDD[Array[Double]](ip, JavaPairRDD.fromRDD(jImg), TImgTools.IMAGETYPE_DOUBLE) } def sizeCheck(inImg: HasDimensions) = { if (!TImgTools.CheckSizes2(ip, inImg)) throw new IllegalArgumentException("Image sizes must" + " match! d1:" + ip.getDim + ", p1:" + ip.getPos + "\t d2:" + inImg.getDim + " p2:" + inImg.getPos) } def -[B](inImg: DTImg[B]) = combineImages(inImg, _ - _) def *[B](inImg: DTImg[B]) = combineImages(inImg, _ * _) def /[B](inImg: DTImg[B]) = combineImages(inImg, _ / _) } def fromKVImg[T](inImg: KVImg[T])(implicit T: ClassTag[T]): DTImg[Array[T]] = { val dim = inImg.getDim val pos = inImg.getPos val elSize = inImg.getElSize val sliceSize = dim.x * dim.y var rddObj = inImg.getBaseImg().map { posVal => ((posVal._1.z, (posVal._1.y - pos.y) * dim.x + posVal._1.x - pos.x), posVal._2) } if (inImg.getBaseImg.count.toInt != dim.prod) { // fill in holes since voxels are missing val allPix = rddObj.sparkContext.parallelize(0 until dim.z).flatMap { cPoint => val emptySlice = new Array[T](sliceSize) Array.fill(sliceSize)(cPoint).zip(0 until sliceSize).zip(emptySlice) } val missingPixels = allPix.subtractByKey(rddObj) rddObj = rddObj.union(missingPixels) } val slices = rddObj.map { posVal => (new D3int(pos.x, pos.y, pos.z + posVal._1._1), (posVal._1._2, posVal._2)) }.groupByKey val sslices = slices.map { imgVec => val sList = stableSort(imgVec._2.toList, (e1: (Int, T), e2: (Int, T)) => e1._1 < e2._1).map { _._2 } (imgVec._1, new TImgSlice[Array[T]](sList, imgVec._1, dim)) } DTImg.WrapRDD[Array[T]](inImg, JavaPairRDD.fromRDD(sslices), inImg.getImageType()) } private[spark] def DTrddToKVrdd[@spec(Boolean, Byte, Short, Int, Long, Float, Double) T](inImg: RDD[(D3int, TImgSlice[Array[T]])], pos: D3int, dim: D3int)( implicit tct: ClassTag[T]): RDD[(D3int, T)] = { inImg.flatMap { cPoint => val pos = cPoint._1 val dim = new D3int(cPoint._2.getDim, 1) val obj = cPoint._2.get val outArr = obj for {z <- 0 until dim.z y <- 0 until dim.y x <- 0 until dim.x } yield (new D3int(pos.x + x, pos.y + y, pos.z + z), outArr((z * dim.y + y) * dim.x + x)) }.partitionBy(new D3IntSlicePartitioner(pos, dim)) //val onImg = TypeMacros.correctlyTypeDTImg(inImg) } }
icyerasor/rome-modules
src/main/java/com/rometools/modules/sle/SortStrategy.java
<reponame>icyerasor/rome-modules package com.rometools.modules.sle; import com.rometools.modules.sle.io.ModuleParser; import com.rometools.modules.sle.types.EntryValue; import com.rometools.modules.sle.types.Sort; import com.rometools.rome.feed.module.Extendable; class SortStrategy implements ValueStrategy { @Override public EntryValue getValue(final Extendable extendable, final Object value) { try { final String uri = ModuleParser.TEMP.getURI(); final SleEntry entry = (SleEntry) extendable.getModule(uri); final Sort sort = (Sort) value; return entry.getSortByElement(sort); } catch (final NullPointerException npe) { return null; } } }
MarkStega/CQC
Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_CMLWSockBaseClass_.hpp
// // FILE NAME: CQCKit_CMLWSockBaseClass_.hpp // // AUTHOR: <NAME> // // CREATED: 09/17/2014 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (<NAME>.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for the CQCKit_CMLWSockBaseClass.cpp file, which implements a // CML abstract base class that all websocket handlers derive from. The CQC web server // uses this abstract interface to interact with websocket handlers on behalf of // the websocket clients. // // CAVEATS/GOTCHAS: // // LOG: // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TCMLWSockBaseInfo // PREFIX: meci // --------------------------------------------------------------------------- class CQCWEBSRVCEXP TCMLWSockBaseInfo : public TMEngClassInfo { public : // ------------------------------------------------------------------- // Public, static methods // ------------------------------------------------------------------- static const TString& strPath(); // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TCMLWSockBaseInfo ( TCIDMacroEngine& meOwner ); TCMLWSockBaseInfo(const TCMLWSockBaseInfo&) = delete; TCMLWSockBaseInfo(TCMLWSockBaseInfo&&) = delete; ~TCMLWSockBaseInfo(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TCMLWSockBaseInfo& operator=(const TCMLWSockBaseInfo&) = delete; TCMLWSockBaseInfo& operator=(TCMLWSockBaseInfo&&) = delete; // ------------------------------------------------------------------- // Public, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid Init ( TCIDMacroEngine& meOwner ) final; TMEngClassVal* pmecvMakeStorage ( const TString& strName , TCIDMacroEngine& meOwner , const tCIDMacroEng::EConstTypes eConst ) const final; protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TBoolean bInvokeMethod ( TCIDMacroEngine& meOwner , const TMEngMethodInfo& methiTarget , TMEngClassVal& mecvInstance ) final; private : // ------------------------------------------------------------------- // Private, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TVoid ProcessSimReq ( TCIDDataSrcJan& janSrc , TCIDMacroEngine& meOwner , TMEngClassVal& mecvInstance , const TString& strURL , const tCIDLib::TKVPList& colHdrLines , const TString& strType , const TString& strClassPath ); tCIDLib::TVoid ReplaceTokens ( TCIDMacroEngine& meOwner , TString& strMsg , const tCIDLib::TCard4 c4Tokens , const tCIDLib::TCard4 c4FirstInd ); tCIDLib::TVoid Simulate ( TCIDMacroEngine& meOwner , TMEngClassVal& mecvInstance , const tCIDLib::TIPPortNum ippnPort , const TString& strClassPath , const TString& strCertInfo ); tCIDLib::TVoid ThrowAnErr ( TCIDMacroEngine& meOwner , const tCIDLib::TCard4 c4ToThrow , const TString& strText ) const; tCIDLib::TVoid ThrowAnErr ( TCIDMacroEngine& meOwner , const tCIDLib::TCard4 c4ToThrow , const TError& errCaught ) const; // ------------------------------------------------------------------- // Private data members // // m_c2EnumId_XXX // Class ids for some nested enumerated types // // m_c2MethId_XXX // To speed up dispatch, we store the ids of the methods that we set up // during init. // // m_pmeciXXX // Info objects for any nested or external classes we want to interact // with directly. // ------------------------------------------------------------------- tCIDLib::TCard2 m_c2EnumId_Errors; tCIDLib::TCard2 m_c2MethId_Connected; tCIDLib::TCard2 m_c2MethId_DefCtor; tCIDLib::TCard2 m_c2MethId_Disconnected; tCIDLib::TCard2 m_c2MethId_EnableMsgLog; tCIDLib::TCard2 m_c2MethId_FieldChanged; tCIDLib::TCard2 m_c2MethId_LogMsg; tCIDLib::TCard2 m_c2MethId_LogMsg1; tCIDLib::TCard2 m_c2MethId_LogMsg2; tCIDLib::TCard2 m_c2MethId_ProcessMsg; tCIDLib::TCard2 m_c2MethId_SendMsg; tCIDLib::TCard2 m_c2MethId_SetFieldList; tCIDLib::TCard2 m_c2MethId_Simulate; tCIDLib::TCard2 m_c2MethId_StartShutdown; tCIDLib::TCard2 m_c2MethId_ValidateCreds; tCIDLib::TCard2 m_c2MethId_WriteField; tCIDLib::TCard2 m_c2MethId_WriteField2; tCIDLib::TCard4 m_c4ErrId_FieldWrite; tCIDLib::TCard4 m_c4ErrId_Simulate; TMEngEnumInfo* m_pmeciErrors; TMEngVectorInfo* m_pmeciStrList; // ------------------------------------------------------------------- // Do any needed magic macros // ------------------------------------------------------------------- RTTIDefs(TCMLWSockBaseInfo,TMEngClassInfo) }; #pragma CIDLIB_POPPACK
Fabian95qw/SF-Modulefunctions
src/letsencrypt/authorization/TriggerChallenge.java
package si.module.letsencryptv3.authorization; import org.apache.commons.logging.Log; import org.shredzone.acme4j.Status; import org.shredzone.acme4j.challenge.Dns01Challenge; import org.shredzone.acme4j.challenge.Http01Challenge; import org.shredzone.acme4j.exception.AcmeServerException; import de.starface.core.component.StarfaceComponentProvider; import de.vertico.starface.module.core.model.VariableType; import de.vertico.starface.module.core.model.Visibility; import de.vertico.starface.module.core.runtime.IBaseExecutable; import de.vertico.starface.module.core.runtime.IRuntimeEnvironment; import de.vertico.starface.module.core.runtime.annotations.Function; import de.vertico.starface.module.core.runtime.annotations.InputVar; import de.vertico.starface.module.core.runtime.annotations.OutputVar; import si.module.letsencryptv3.utility.LogHelper; import si.module.letsencryptv3.utility.Storage; import si.module.letsencryptv3.utility.EnumHelper.Challenge; @Function(visibility=Visibility.Private, rookieFunction=false, description="Authorizes a Domain") public class TriggerChallenge implements IBaseExecutable { //########################################################################################## @InputVar(label="ChallengeType", description="", valueByReferenceAllowed=true) public Challenge C = Challenge.NONE; @OutputVar(label="Success", description="",type=VariableType.BOOLEAN) public Boolean Success = false; @OutputVar(label="Retry", description="",type=VariableType.BOOLEAN) public Boolean Retry = false; StarfaceComponentProvider componentProvider = StarfaceComponentProvider.getInstance(); //########################################################################################## //################### Code Execution ############################ @Override public void execute(IRuntimeEnvironment context) throws Exception { Log log = context.getLog(); if(Storage.A != null && Storage.A.getStatus().equals(Status.VALID)) { log.debug("No Challenge triggered..."); Success=true; return; } log.debug("Triggering Challenge"); try { switch(C) { case NONE: break; case DNS: Dns01Challenge DNS = Storage.DNS; DNS.trigger(); while(DNS.getStatus() != Status.VALID && DNS.getStatus() != Status.INVALID) { log.debug("Challenge State: " + DNS.getStatus().toString()); Thread.sleep(5000); DNS.update(); } if(DNS.getStatus() == Status.VALID) { log.debug("Challenge Succeeded!"); Success = true; return; } log.debug("Challenge Failed. Returned: " + DNS.getStatus()); Storage.DNS=null; break; case HTTP: Http01Challenge HTTP = Storage.HTTP; HTTP.trigger(); while(HTTP.getStatus() != Status.VALID && HTTP.getStatus() != Status.INVALID) { log.debug("Challenge State: " + HTTP.getStatus().toString()); Thread.sleep(5000); HTTP.update(); } if(HTTP.getStatus() == Status.VALID) { log.debug("Challenge Succeeded!"); Success = true; return; } log.debug("Challenge Failed. Returned: " + HTTP.getStatus()); Storage.HTTP = null; break; } } catch(AcmeServerException e) { LogHelper.EtoStringLog(log, e); Retry = true; } catch(Exception e) { LogHelper.EtoStringLog(log, e); } Success = false; }//END OF EXECUTION }
AntoniosKalattas/Ping_rep
gui/node_modules/lodash/_isLaziable.js
version https://git-lfs.github.com/spec/v1 oid sha256:6863f63c866527fb17eba2b8abd81f04cdde2057c76201f3ac190494d319bd33 size 712
akrosinc/opensrp-client-core
opensrp-app/src/test/java/org/smartregister/repository/FormsVersionRepositoryTest.java
<filename>opensrp-app/src/test/java/org/smartregister/repository/FormsVersionRepositoryTest.java package org.smartregister.repository; import android.content.ContentValues; import junit.framework.Assert; import net.sqlcipher.MatrixCursor; import net.sqlcipher.database.SQLiteDatabase; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.smartregister.BaseUnitTest; import org.smartregister.domain.FormDefinitionVersion; import org.smartregister.domain.SyncStatus; import java.util.HashMap; /** * Created by kaderchowdhury on 19/11/17. */ public class FormsVersionRepositoryTest extends BaseUnitTest { private FormsVersionRepository formsVersionRepository; @Mock private SQLiteDatabase sqLiteDatabase; @Mock private Repository repository; private static final String ID_COLUMN = "id"; public static final String FORM_NAME_COLUMN = "formName"; public static final String VERSION_COLUMN = "formDataDefinitionVersion"; public static final String FORM_DIR_NAME_COLUMN = "formDirName"; public static final String SYNC_STATUS_COLUMN = "syncStatus"; @Before public void setUp() { MockitoAnnotations.initMocks(this); formsVersionRepository = new FormsVersionRepository(); formsVersionRepository.updateMasterRepository(repository); Mockito.when(repository.getWritableDatabase()).thenReturn(sqLiteDatabase); Mockito.when(repository.getReadableDatabase()).thenReturn(sqLiteDatabase); Mockito.when(sqLiteDatabase.query(Mockito.anyString(), Mockito.any(String[].class), Mockito.anyString(), Mockito.any(String[].class), Mockito.isNull(String.class), Mockito.isNull(String.class), Mockito.isNull(String.class))).thenReturn(getCursor()); Mockito.when(sqLiteDatabase.update(Mockito.anyString(), Mockito.any(ContentValues.class), Mockito.anyString(), Mockito.any(String[].class))).thenReturn(1); } public MatrixCursor getCursor() { String[] columns = {ID_COLUMN, FORM_NAME_COLUMN, FORM_DIR_NAME_COLUMN, VERSION_COLUMN, SYNC_STATUS_COLUMN}; MatrixCursor cursor = new MatrixCursor(columns); cursor.addRow(new Object[]{"1", "name", "dir", "1.0", SyncStatus.PENDING}); return cursor; } @Test public void assertConstructorNotNull() { Assert.assertNotNull(formsVersionRepository); } @Test public void assertOnCreateCallsDatabaseExec() { formsVersionRepository.onCreate(sqLiteDatabase); Mockito.verify(sqLiteDatabase, Mockito.times(1)).execSQL(Mockito.anyString()); } @Test public void assertFetchVersionByFormName() { Assert.assertNotNull(formsVersionRepository.fetchVersionByFormName("")); } @Test public void assertFetchVersionByFormDirName() { Assert.assertNotNull(formsVersionRepository.fetchVersionByFormDirName("")); } @Test public void assertGetVersion() { Assert.assertNotNull(formsVersionRepository.getVersion("")); } @Test public void assertgetAllFormWithSyncStatus() { Assert.assertNotNull(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)); } @Test public void assertgetAllFormWithSyncStatusAsMap() { Assert.assertNotNull(formsVersionRepository.getAllFormWithSyncStatusAsMap(SyncStatus.PENDING)); } @Test public void assertgetFormByFormDirName() { Assert.assertNotNull(formsVersionRepository.getFormByFormDirName("")); } @Test public void assertAddFormVersion() { HashMap<String, String> data = new HashMap<String, String>(); data.put(FORM_NAME_COLUMN, "form_name"); data.put(VERSION_COLUMN, "1.0"); data.put(FORM_DIR_NAME_COLUMN, "dir"); data.put(SYNC_STATUS_COLUMN, SyncStatus.PENDING.value()); formsVersionRepository.addFormVersion(data); Mockito.verify(sqLiteDatabase, Mockito.times(1)).insert(Mockito.anyString(), Mockito.isNull(String.class), Mockito.any(ContentValues.class)); } @Test public void assertAddFormVersionFromObject() { FormDefinitionVersion fd = new FormDefinitionVersion("", "", ""); fd.setSyncStatus(SyncStatus.PENDING); formsVersionRepository.addFormVersionFromObject(fd); Mockito.verify(sqLiteDatabase, Mockito.times(1)).insert(Mockito.anyString(), Mockito.isNull(String.class), Mockito.any(ContentValues.class)); } @Test public void assertformExistsReturnsTrue() { Assert.assertEquals(formsVersionRepository.formExists(""), true); } @Test public void assertDeleteAllCallsDatabaseDelete() { formsVersionRepository.deleteAll(); Mockito.verify(sqLiteDatabase, Mockito.times(1)).delete(Mockito.anyString(), Mockito.isNull(String.class), Mockito.isNull(String[].class)); } @Test public void assertupdateServerVersion() { formsVersionRepository.updateServerVersion("", ""); Mockito.verify(sqLiteDatabase, Mockito.times(1)).update(Mockito.anyString(), Mockito.any(ContentValues.class), Mockito.anyString(), Mockito.any(String[].class)); } @Test public void assertupdateFormName() { formsVersionRepository.updateFormName("", ""); Mockito.verify(sqLiteDatabase, Mockito.times(1)).update(Mockito.anyString(), Mockito.any(ContentValues.class), Mockito.anyString(), Mockito.any(String[].class)); } @Test public void assertupdateSyncStatus() { formsVersionRepository.updateSyncStatus("", SyncStatus.PENDING); Mockito.verify(sqLiteDatabase, Mockito.times(1)).update(Mockito.anyString(), Mockito.any(ContentValues.class), Mockito.anyString(), Mockito.any(String[].class)); } }
kStoykow/Technology-Fundamentals-with-JS
Lab/Data-Types-and-Variables/01-concatenateNames.js
function printNames(firstName, secondName, delimiter) { return `${firstName}${delimiter}${secondName}`; }
Gouzhong1223/Dubhe
dubhe-server/dubhe-data/src/main/java/org/dubhe/data/course/domain/dto/CourseUpdateDTO.java
<reponame>Gouzhong1223/Dubhe package org.dubhe.data.course.domain.dto; import lombok.AllArgsConstructor; import lombok.Data; import javax.validation.constraints.NotNull; /** * @Author : Gouzhong * @Blog : www.gouzhong1223.com * @Description : * @Date : create by QingSong in 2021-12-05 21:10 * @Email : <EMAIL> * @Since : JDK 1.8 * @PackageName : org.dubhe.course.domain.dto * @ProjectName : Dubhe * @Version : 1.0.0 */ @AllArgsConstructor @Data @NotNull @NotNull public class CourseUpdateDTO { @NotNull(message = "课程 ID 不能为空") private Long courseId; @NotNull(message = "课程名字不能为空") private String courseName; @NotNull(message = "课程类型主键不能为空") private Long courseTypeId; @NotNull(message = "课程简介不能为空") private String introduction; @NotNull(message = "课程封面图 ID 不能为空") private Long coverImageId; @NotNull(message = "课程状态码不能为空") private Integer status; }
joevansteen/AF-WP-Plugin-Core
af-wp-plugin/public/js/afX3D/pocGames/AF_SpaceVis_110_Canvas_and_MPG/server.js
//npm install -g connect //npm install -g socket.io var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello World!'); res.end(); }); server.listen(4000);
cr0wbar/bananarama
bananarama-core/src/main/java/org/bananarama/util/StringUtils.java
/* * Copyright 2016 BananaRama. * * 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.bananarama.util; import java.util.StringJoiner; import java.util.stream.Stream; /** * * @author <NAME> */ public class StringUtils { public static String getNMarkerSeparatedChars(char c,char del,int n){ char buf[] = new char[2*n-1]; char pattern[] = {c,del}; for(int i=0;i<buf.length;i++) buf[i] = pattern[i%2]; return new String(buf); } public static String getNMarkerSeparatedChars(String c,String del,int n){ char buf[] = new char[n*c.length() + (n-1)*del.length()]; final int patternLen = c.length() + del.length(); char pattern[] = new char[patternLen]; System.arraycopy(c.toCharArray(), 0, pattern, 0, c.length()); System.arraycopy(del.toCharArray(), 0, pattern, c.length(), del.length()); for(int i=0;i<buf.length;i++) buf[i] = pattern[i%patternLen]; return new String(buf); } public static String mkString(Stream<String> items,String prefix,String delimiter,String suffix){ StringJoiner joiner = new StringJoiner(delimiter); items.forEach(joiner::add); return prefix + joiner.toString() + suffix; } }
frhumanes/consulting
web/src/illness/forms.py
<reponame>frhumanes/consulting # -*- encoding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from cal.models import Appointment from illness.models import Illness from userprofile.models import Profile class IllnessSelectionForm(forms.Form): def __init__(self, *args, **kwargs): if 'id_appointment' in kwargs: id_appointment = kwargs.pop('id_appointment') super(IllnessSelectionForm, self).__init__(*args, **kwargs) appointment = Appointment.objects.get(id=id_appointment) #illnesses = appointment.patient.get_profile().illnesses.all()\ # .order_by('code') illnesses = Illness.objects.exclude(surveys__isnull=True) choices = [('', '--------')] choices.extend( [(illness.code, illness.name) for illness in illnesses]) self.fields['illness'].choices = choices else: super(IllnessSelectionForm, self).__init__(*args, **kwargs) illness = forms.ChoiceField(label=_(u"Diagnóstico"), widget=forms.Select( attrs={'class': 'input-medium search-query span12'})) class IllnessAddPatientForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(IllnessAddPatientForm, self).__init__(*args, **kwargs) illnesses = Illness.objects.all().order_by('code') choices = [] choices.extend( [(illness.id, illness.name) for illness in illnesses]) self.fields['illnesses'].choices = choices illnesses = forms.MultipleChoiceField(label=_(u"Enfermedades"), widget=forms.CheckboxSelectMultiple()) class Meta: model = Profile fields = ('illnesses', 'created_by')
leonardocouy/accent
webapp/app/pods/components/phoenix-channel-listener/component.js
<gh_stars>0 import {inject as service} from '@ember/service'; import Component from '@ember/component'; export default Component.extend({ session: service(), phoenix: service(), init() { this._super(...arguments); if (!this.session.credentials.isAuthenticated || !this.project) return; const phoenixService = this.phoenix; const token = `Bearer ${this.session.credentials.token}`; phoenixService .getChannel(`projects:${this.project.id}`, {token}) .then(phoenixService.joinChannel) .then(channel => phoenixService.bindChannelEvents(channel, this.session.credentials.user.id)) .then(channel => this.set('channel', channel)); }, willDestroyElement() { this._super(...arguments); this.phoenix.leaveChannel(this.channel); } });
zeesh49/tutorials
spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java
<reponame>zeesh49/tutorials package org.baeldung.spring43.defaultmethods; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; public interface ITransactionalUnitTest { Logger log = LoggerFactory.getLogger(ITransactionalUnitTest.class); @BeforeTransaction default void beforeTransaction() { log.info("Opening transaction"); } @AfterTransaction default void afterTransaction() { log.info("Closing transaction"); } }
joywa/graph-notebook
test/integration/DataDrivenSparqlTest.py
<filename>test/integration/DataDrivenSparqlTest.py """ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 """ import logging from graph_notebook.authentication.iam_credentials_provider.credentials_factory import IAMAuthCredentialsProvider from graph_notebook.seed.load_query import get_queries from graph_notebook.request_param_generator.factory import create_request_generator from graph_notebook.sparql.query import do_sparql_query from test.integration import IntegrationTest logger = logging.getLogger('DataDrivenSparqlTest') class DataDrivenSparqlTest(IntegrationTest): @classmethod def setUpClass(cls): super().setUpClass() cls.request_generator = create_request_generator(cls.auth_mode, IAMAuthCredentialsProvider.ENV) airport_queries = get_queries('sparql', 'epl') for q in airport_queries: try: # we are deciding to try except because we do not know if the database we are connecting to has a partially complete set of airports data or not. do_sparql_query(q['content'], cls.host, cls.port, cls.ssl, cls.request_generator) except Exception as e: logger.error(f'query {q["content"]} failed due to {e}') continue
wenfeifei/miniblink49
third_party/npapi/npspy/extern/nspr/prvrsion.h
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is the Netscape Portable Runtime (NSPR). * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1998-2000 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL"), in which case the provisions of the GPL are applicable * instead of those above. If you wish to allow use of your * version of this file only under the terms of the GPL and not to * allow others to use your version of this file under the MPL, * indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by * the GPL. If you do not delete the provisions above, a recipient * may use your version of this file under either the MPL or the * GPL. */ /* author: jstewart */ #if defined(_PRVERSION_H) #else #define _PRVERSION_H #include "prtypes.h" PR_BEGIN_EXTERN_C /* All components participating in the PR version protocol must expose * a structure and a function. The structure is defined below and named * according to the naming conventions outlined further below. The function * is called libVersionPoint and returns a pointer to this structure. */ /* on NT, always pack the structure the same. */ #ifdef _WIN32 #pragma pack(push, 8) #endif typedef struct { /* * The first field defines which version of this structure is in use. * At this time, only version 2 is specified. If this value is not * 2, you must read no further into the structure. */ PRInt32 version; /* for Version 2, this is the body format. */ PRInt64 buildTime; /* 64 bits - usecs since midnight, 1/1/1970 */ char * buildTimeString;/* a human readable version of the time */ PRUint8 vMajor; /* Major version of this component */ PRUint8 vMinor; /* Minor version of this component */ PRUint8 vPatch; /* Patch level of this component */ PRBool beta; /* true if this is a beta component */ PRBool debug; /* true if this is a debug component */ PRBool special; /* true if this component is a special build */ char * filename; /* The original filename */ char * description; /* description of this component */ char * security; /* level of security in this component */ char * copyright; /* The copyright for this file */ char * comment; /* free form field for misc usage */ char * specialString; /* the special variant for this build */ } PRVersionDescription; /* on NT, restore the previous packing */ #ifdef _WIN32 #pragma pack(pop) #endif /* * All components must define an entrypoint named libVersionPoint which * is of type versionEntryPointType. * * For example, for a library named libfoo, we would have: * * PRVersionDescription prVersionDescription_libfoo = * { * ... * }; * * PR_IMPLEMENT(const PRVersionDescription*) libVersionPoint(void) * { * return &prVersionDescription_libfoo; * } */ typedef const PRVersionDescription *(*versionEntryPointType)(void); /* * Where you declare your libVersionPoint, do it like this: * PR_IMPLEMENT(const PRVersionDescription *) libVersionPoint(void) { * fill it in... * } */ /* * NAMING CONVENTION FOR struct * * all components should also expose a static PRVersionDescription * The name of the struct should be calculated as follows: * Take the value of filename. (If filename is not specified, calculate * a short, unique string.) Convert all non-alphanumeric characters * to '_'. To this, prepend "PRVersionDescription_". Thus for libfoo.so, * the symbol name is "PRVersionDescription_libfoo_so". * so the file should have * PRVersionDescription PRVersionDescription_libfoo_so { fill it in }; * on NT, this file should be declspec export. */ PR_END_EXTERN_C #endif /* defined(_PRVERSION_H) */ /* prvrsion.h */
buddhika75/hims
src/main/java/com/divudi/bean/common/CreditCompanyDueController.java
<filename>src/main/java/com/divudi/bean/common/CreditCompanyDueController.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.divudi.bean.common; import com.divudi.data.BillType; import com.divudi.data.PaymentMethod; import com.divudi.data.dataStructure.DealerDueDetailRow; import com.divudi.data.dataStructure.InstitutionBills; import com.divudi.data.dataStructure.InstitutionEncounters; import com.divudi.data.table.String1Value5; import com.divudi.ejb.CommonFunctions; import com.divudi.ejb.CreditBean; import com.divudi.entity.Bill; import com.divudi.entity.BillItem; import com.divudi.entity.BilledBill; import com.divudi.entity.Institution; import com.divudi.entity.PatientEncounter; import com.divudi.entity.inward.Admission; import com.divudi.entity.inward.AdmissionType; import com.divudi.facade.AdmissionFacade; import com.divudi.facade.BillFacade; import com.divudi.facade.InstitutionFacade; import com.divudi.facade.PatientEncounterFacade; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.TemporalType; /** * * @author safrin */ @Named @SessionScoped public class CreditCompanyDueController implements Serializable { private Date fromDate; private Date toDate; Admission patientEncounter; boolean withOutDueUpdate; Institution creditCompany; //////////// private List<InstitutionBills> items; private List<InstitutionEncounters> institutionEncounters; List<PatientEncounter> patientEncounters; private List<String1Value5> creditCompanyAge; private List<String1Value5> filteredList; @EJB private InstitutionFacade institutionFacade; @EJB private BillFacade billFacade; @EJB private CommonFunctions commonFunctions; @EJB AdmissionFacade admissionFacade; @Inject CommonController commonController; double finalTotal; double finalPaidTotal; double finalPaidTotalPatient; double finalTransPaidTotal; double finalTransPaidTotalPatient; public List<PatientEncounter> getPatientEncounters() { return patientEncounters; } public void setPatientEncounters(List<PatientEncounter> patientEncounters) { this.patientEncounters = patientEncounters; } public void makeNull() { fromDate = null; toDate = null; items = null; institutionEncounters = null; creditCompanyAge = null; filteredList = null; } public void createAgeTable() { Date startTime = new Date(); Date fromDate = null; Date toDate = null; makeNull(); Set<Institution> setIns = new HashSet<>(); List<Institution> list = getCreditBean().getCreditCompanyFromBills(true); setIns.addAll(list); creditCompanyAge = new ArrayList<>(); for (Institution ins : setIns) { if (ins == null) { continue; } String1Value5 newRow = new String1Value5(); newRow.setString(ins.getName()); setValues(ins, newRow); if (newRow.getValue1() != 0 || newRow.getValue2() != 0 || newRow.getValue3() != 0 || newRow.getValue4() != 0) { creditCompanyAge.add(newRow); } } commonController.printReportDetails(fromDate, toDate, startTime, "Payments/Receieve/Credit Company/Due age(/faces/credit/credit_company_opd_due_age.xhtml)"); } public void createAgeTablePharmacy() { Date startTime = new Date(); Date fromDate = null; Date toDate = null; makeNull(); Set<Institution> setIns = new HashSet<>(); List<Institution> list = getCreditBean().getCreditCompanyFromBillsPharmacy(true); setIns.addAll(list); creditCompanyAge = new ArrayList<>(); for (Institution ins : setIns) { if (ins == null) { continue; } String1Value5 newRow = new String1Value5(); newRow.setString(ins.getName()); setValuesPharmacy(ins, newRow); if (newRow.getValue1() != 0 || newRow.getValue2() != 0 || newRow.getValue3() != 0 || newRow.getValue4() != 0) { creditCompanyAge.add(newRow); } } commonController.printReportDetails(fromDate, toDate, startTime, "Payments/Receieve/Credit Company/Due age(/faces/credit/credit_company_opd_due_age.xhtml)"); } public void createAgeAccessTable() { Date startTime = new Date(); makeNull(); Set<Institution> setIns = new HashSet<>(); List<Institution> list = getCreditBean().getCreditCompanyFromBills(false); setIns.addAll(list); creditCompanyAge = new ArrayList<>(); for (Institution ins : setIns) { if (ins == null) { continue; } String1Value5 newRow = new String1Value5(); newRow.setString(ins.getName()); setValuesAccess(ins, newRow); if (newRow.getValue1() != 0 || newRow.getValue2() != 0 || newRow.getValue3() != 0 || newRow.getValue4() != 0) { creditCompanyAge.add(newRow); } } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/OPD Dues and Access/OPD credit excess/Excess age(/faces/credit/credit_company_opd_access_age.xhtml)"); } public void createInwardAgeTable() { Date startTime = new Date(); makeNull(); Set<Institution> setIns = new HashSet<>(); List<Institution> list = getCreditBean().getCreditCompanyFromBht(true, PaymentMethod.Credit); setIns.addAll(list); creditCompanyAge = new ArrayList<>(); for (Institution ins : setIns) { if (ins == null) { continue; } String1Value5 newRow = new String1Value5(); newRow.setInstitution(ins); setInwardValues(ins, newRow, PaymentMethod.Credit); if (newRow.getValue1() != 0 || newRow.getValue2() != 0 || newRow.getValue3() != 0 || newRow.getValue4() != 0) { creditCompanyAge.add(newRow); } } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/Inward Dues And Access/Dues/Due Age(/faces/credit/inward_due_age.xhtml)"); } List<DealerDueDetailRow> dealerDueDetailRows; public List<DealerDueDetailRow> getDealerDueDetailRows() { return dealerDueDetailRows; } public void setDealerDueDetailRows(List<DealerDueDetailRow> dealerDueDetailRows) { this.dealerDueDetailRows = dealerDueDetailRows; } public void createInwardAgeDetailAnalysis() { Date startTime = new Date(); dealerDueDetailRows = new ArrayList<>(); createInwardAgeTable(); Institution dealer = null; for (String1Value5 s : creditCompanyAge) { DealerDueDetailRow row = new DealerDueDetailRow(); if (dealer == null || dealer != s.getInstitution()) { dealer = s.getInstitution(); row.setDealer(dealer); row.setZeroToThirty(s.getValue1()); row.setThirtyToSixty(s.getValue2()); row.setSixtyToNinty(s.getValue3()); row.setMoreThanNinty(s.getValue4()); dealerDueDetailRows.add(row); } int rowsForDealer = 0; if (rowsForDealer < s.getValue1PatientEncounters().size()) { rowsForDealer = s.getValue1PatientEncounters().size(); } if (rowsForDealer < s.getValue2PatientEncounters().size()) { rowsForDealer = s.getValue2PatientEncounters().size(); } if (rowsForDealer < s.getValue3PatientEncounters().size()) { rowsForDealer = s.getValue3PatientEncounters().size(); } if (rowsForDealer < s.getValue4PatientEncounters().size()) { rowsForDealer = s.getValue4PatientEncounters().size(); } for (int i = 0; i < rowsForDealer; i++) { DealerDueDetailRow rowi = new DealerDueDetailRow(); if (s.getValue1PatientEncounters().size() > i) { rowi.setZeroToThirtyEncounter(s.getValue1PatientEncounters().get(i)); } if (s.getValue2PatientEncounters().size() > i) { rowi.setThirtyToSixtyEncounter(s.getValue2PatientEncounters().get(i)); } if (s.getValue3PatientEncounters().size() > i) { rowi.setSixtyToNintyEncounter(s.getValue3PatientEncounters().get(i)); } if (s.getValue4PatientEncounters().size() > i) { rowi.setMoreThanNintyEncounter(s.getValue4PatientEncounters().get(i)); } dealerDueDetailRows.add(rowi); } } creditCompanyAge = new ArrayList<>(); commonController.printReportDetails(fromDate, toDate, startTime, "Reports/Inward Dues And Access/Dues/Due age detail(/faces/credit/inward_due_age_credit_company_detail.xhtml)"); } public void createInwardCashAgeTable() { makeNull(); Set<Institution> setIns = new HashSet<>(); List<Institution> list = getCreditBean().getCreditCompanyFromBht(true, PaymentMethod.Cash); setIns.addAll(list); creditCompanyAge = new ArrayList<>(); for (Institution ins : setIns) { if (ins == null) { continue; } String1Value5 newRow = new String1Value5(); newRow.setString(ins.getName()); setInwardValues(ins, newRow, PaymentMethod.Cash); if (newRow.getValue1() != 0 || newRow.getValue2() != 0 || newRow.getValue3() != 0 || newRow.getValue4() != 0) { creditCompanyAge.add(newRow); } } } public void createInwardAgeTableAccess() { Date startTime = new Date(); makeNull(); Set<Institution> setIns = new HashSet<>(); List<Institution> list = getCreditBean().getCreditCompanyFromBht(false, PaymentMethod.Credit); setIns.addAll(list); creditCompanyAge = new ArrayList<>(); for (Institution ins : setIns) { if (ins == null) { continue; } String1Value5 newRow = new String1Value5(); newRow.setString(ins.getName()); setInwardValuesAccess(ins, newRow, PaymentMethod.Credit); if (newRow.getValue1() != 0 || newRow.getValue2() != 0 || newRow.getValue3() != 0 || newRow.getValue4() != 0) { creditCompanyAge.add(newRow); } } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/Inward Dues And Access/excess/excess age (/faces/credit/credit_company_inward_access_age.xhtml)"); } public void createInwardCashAgeTableAccess() { Date startTime = new Date(); makeNull(); Set<Institution> setIns = new HashSet<>(); List<Institution> list = getCreditBean().getCreditCompanyFromBht(false, PaymentMethod.Cash); setIns.addAll(list); creditCompanyAge = new ArrayList<>(); for (Institution ins : setIns) { if (ins == null) { continue; } String1Value5 newRow = new String1Value5(); newRow.setString(ins.getName()); setInwardValuesAccess(ins, newRow, PaymentMethod.Cash); if (newRow.getValue1() != 0 || newRow.getValue2() != 0 || newRow.getValue3() != 0 || newRow.getValue4() != 0) { creditCompanyAge.add(newRow); } } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/Inward Dues And Access/excess/excess age (/faces/credit/cash_inward_access_age.xhtml)"); } private void setValues(Institution inst, String1Value5 dataTable5Value) { List<Bill> lst = getCreditBean().getCreditBills(inst, true); for (Bill b : lst) { Long dayCount = getCommonFunctions().getDayCountTillNow(b.getCreatedAt()); double finalValue = (b.getNetTotal() + b.getPaidAmount()); System.err.println("DayCount " + dayCount); if (dayCount < 30) { dataTable5Value.setValue1(dataTable5Value.getValue1() + finalValue); } else if (dayCount < 60) { dataTable5Value.setValue2(dataTable5Value.getValue2() + finalValue); } else if (dayCount < 90) { dataTable5Value.setValue3(dataTable5Value.getValue3() + finalValue); } else { dataTable5Value.setValue4(dataTable5Value.getValue4() + finalValue); } } } private void setValuesPharmacy(Institution inst, String1Value5 dataTable5Value) { List<Bill> lst = getCreditBean().getCreditBillsPharmacy(inst, true); for (Bill b : lst) { Long dayCount = getCommonFunctions().getDayCountTillNow(b.getCreatedAt()); double finalValue = (b.getNetTotal() + b.getPaidAmount()); System.err.println("DayCount " + dayCount); if (dayCount < 30) { dataTable5Value.setValue1(dataTable5Value.getValue1() + finalValue); } else if (dayCount < 60) { dataTable5Value.setValue2(dataTable5Value.getValue2() + finalValue); } else if (dayCount < 90) { dataTable5Value.setValue3(dataTable5Value.getValue3() + finalValue); } else { dataTable5Value.setValue4(dataTable5Value.getValue4() + finalValue); } } } private void setValuesAccess(Institution inst, String1Value5 dataTable5Value) { List<Bill> lst = getCreditBean().getCreditBills(inst, false); for (Bill b : lst) { Long dayCount = getCommonFunctions().getDayCountTillNow(b.getCreatedAt()); double finalValue = (b.getNetTotal() + b.getPaidAmount()); System.err.println("DayCount " + dayCount); if (dayCount < 30) { dataTable5Value.setValue1(dataTable5Value.getValue1() + finalValue); } else if (dayCount < 60) { dataTable5Value.setValue2(dataTable5Value.getValue2() + finalValue); } else if (dayCount < 90) { dataTable5Value.setValue3(dataTable5Value.getValue3() + finalValue); } else { dataTable5Value.setValue4(dataTable5Value.getValue4() + finalValue); } } } private void setInwardValues(Institution inst, String1Value5 dataTable5Value, PaymentMethod paymentMethod) { List<PatientEncounter> lst = getCreditBean().getCreditPatientEncounters(inst, true, paymentMethod); for (PatientEncounter b : lst) { Long dayCount = getCommonFunctions().getDayCountTillNow(b.getCreatedAt()); b.setTransDayCount(dayCount); double finalValue = b.getFinalBill().getNetTotal() - (Math.abs(b.getFinalBill().getPaidAmount()) + Math.abs(b.getCreditPaidAmount())); if (dayCount < 30) { dataTable5Value.setValue1(dataTable5Value.getValue1() + finalValue); dataTable5Value.getValue1PatientEncounters().add(b); } else if (dayCount < 60) { dataTable5Value.setValue2(dataTable5Value.getValue2() + finalValue); dataTable5Value.getValue2PatientEncounters().add(b); } else if (dayCount < 90) { dataTable5Value.setValue3(dataTable5Value.getValue3() + finalValue); dataTable5Value.getValue3PatientEncounters().add(b); } else { dataTable5Value.setValue4(dataTable5Value.getValue4() + finalValue); dataTable5Value.getValue4PatientEncounters().add(b); } } } private void setInwardValuesAccess(Institution inst, String1Value5 dataTable5Value, PaymentMethod paymentMethod) { List<PatientEncounter> lst = getCreditBean().getCreditPatientEncounters(inst, false, paymentMethod); for (PatientEncounter b : lst) { Long dayCount = getCommonFunctions().getDayCountTillNow(b.getCreatedAt()); double finalValue = (Math.abs(b.getCreditUsedAmount()) - Math.abs(b.getCreditPaidAmount())); if (dayCount < 30) { dataTable5Value.setValue1(dataTable5Value.getValue1() + finalValue); } else if (dayCount < 60) { dataTable5Value.setValue2(dataTable5Value.getValue2() + finalValue); } else if (dayCount < 90) { dataTable5Value.setValue3(dataTable5Value.getValue3() + finalValue); } else { dataTable5Value.setValue4(dataTable5Value.getValue4() + finalValue); } } } public CreditCompanyDueController() { } public Date getFromDate() { if (fromDate == null) { fromDate = com.divudi.java.CommonFunctions.getStartOfMonth(new Date()); } return fromDate; } public void setFromDate(Date fromDate) { this.fromDate = fromDate; } public Date getToDate() { if (toDate == null) { toDate = getCommonFunctions().getEndOfDay(new Date()); } return toDate; } public void setToDate(Date toDate) { this.toDate = toDate; } @EJB private CreditBean creditBean; public void createOpdCreditDue() { Date startTime = new Date(); List<Institution> setIns = getCreditBean().getCreditInstitution(BillType.OpdBill, getFromDate(), getToDate(), true); items = new ArrayList<>(); for (Institution ins : setIns) { List<Bill> bills = getCreditBean().getCreditBills(ins, BillType.OpdBill, getFromDate(), getToDate(), true); InstitutionBills newIns = new InstitutionBills(); newIns.setInstitution(ins); newIns.setBills(bills); for (Bill b : bills) { newIns.setTotal(newIns.getTotal() + b.getNetTotal()); newIns.setPaidTotal(newIns.getPaidTotal() + b.getPaidAmount()); } items.add(newIns); } commonController.printReportDetails(fromDate, toDate, startTime, "Payments/Receieve/Credit Company/OPD/Due search(/faces/credit/credit_company_opd_due.xhtml)"); } public void createPharmacyCreditDue() { Date startTime = new Date(); List<Institution> setIns = getCreditBean().getCreditInstitutionPharmacy(Arrays.asList(new BillType[]{BillType.PharmacyWholeSale, BillType.PharmacySale}), getFromDate(), getToDate(), true); items = new ArrayList<>(); for (Institution ins : setIns) { List<Bill> bills = getCreditBean().getCreditBillsPharmacy(ins, Arrays.asList(new BillType[]{BillType.PharmacyWholeSale, BillType.PharmacySale}), getFromDate(), getToDate(), true); InstitutionBills newIns = new InstitutionBills(); newIns.setInstitution(ins); newIns.setBills(bills); for (Bill b : bills) { newIns.setTotal(newIns.getTotal() + b.getNetTotal()); newIns.setPaidTotal(newIns.getPaidTotal() + b.getPaidAmount()); } items.add(newIns); } commonController.printReportDetails(fromDate, toDate, startTime, "Payments/Receieve/Credit Company/OPD/Due search(/faces/credit/credit_company_opd_due.xhtml)"); } public void createOpdCreditDueBillItem() { Date startTime = new Date(); List<Institution> setIns = new ArrayList<>(); if (creditCompany != null) { setIns.add(creditCompany); } else { setIns.addAll(getCreditBean().getCreditInstitution(BillType.OpdBill, getFromDate(), getToDate(), true)); } items = new ArrayList<>(); for (Institution ins : setIns) { List<BillItem> billItems = getCreditBean().getCreditBillItems(ins, BillType.OpdBill, getFromDate(), getToDate(), true); InstitutionBills newIns = new InstitutionBills(); newIns.setInstitution(ins); newIns.setBillItems(billItems); for (BillItem bi : billItems) { newIns.setTotal(newIns.getTotal() + bi.getNetValue()); } items.add(newIns); } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/OPD Dues and Access/OPD Dues and Access/Due Search(Bill item)(/faces/credit/credit_company_opd_due_by_bill_item.xhtml)"); } public void createOpdCreditAccess() { Date startTime = new Date(); List<Institution> setIns = getCreditBean().getCreditInstitution(BillType.OpdBill, getFromDate(), getToDate(), false); items = new ArrayList<>(); for (Institution ins : setIns) { List<Bill> bills = getCreditBean().getCreditBills(ins, BillType.OpdBill, getFromDate(), getToDate(), false); InstitutionBills newIns = new InstitutionBills(); newIns.setInstitution(ins); newIns.setBills(bills); for (Bill b : bills) { newIns.setTotal(newIns.getTotal() + b.getNetTotal()); newIns.setPaidTotal(newIns.getPaidTotal() + b.getPaidAmount()); } items.add(newIns); } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/OPD Dues and Access/OPD credit excess/Excess search(/faces/credit/credit_company_opd_access.xhtml)"); } public void createInwardCreditDue() { Date startTime = new Date(); List<Institution> setIns = getCreditBean().getCreditInstitutionByPatientEncounter(getFromDate(), getToDate(), PaymentMethod.Credit, true); institutionEncounters = new ArrayList<>(); finalTotal = 0.0; finalPaidTotal = 0.0; finalPaidTotalPatient = 0.0; finalTransPaidTotal = 0.0; finalTransPaidTotalPatient = 0.0; for (Institution ins : setIns) { List<PatientEncounter> lst = getCreditBean().getCreditPatientEncounter(ins, getFromDate(), getToDate(), PaymentMethod.Credit, true); InstitutionEncounters newIns = new InstitutionEncounters(); newIns.setInstitution(ins); newIns.setPatientEncounters(lst); for (PatientEncounter b : lst) { b.setTransPaidByPatient(createInwardPaymentTotal(b, getFromDate(), getToDate(), BillType.InwardPaymentBill)); b.setTransPaidByCompany(createInwardPaymentTotalCredit(b, getFromDate(), getToDate(), BillType.CashRecieveBill)); newIns.setTotal(newIns.getTotal() + b.getFinalBill().getNetTotal()); newIns.setPaidTotalPatient(newIns.getPaidTotalPatient() + b.getFinalBill().getPaidAmount()); newIns.setTransPaidTotalPatient(newIns.getTransPaidTotalPatient() + b.getTransPaidByPatient()); newIns.setPaidTotal(newIns.getPaidTotal() + b.getPaidByCreditCompany()); newIns.setTransPaidTotal(newIns.getTransPaidTotal() + b.getTransPaidByCompany()); } finalTotal += newIns.getTotal(); finalPaidTotal += newIns.getPaidTotal(); finalPaidTotalPatient += newIns.getPaidTotalPatient(); finalTransPaidTotal += newIns.getTransPaidTotal(); finalTransPaidTotalPatient += newIns.getTransPaidTotalPatient(); institutionEncounters.add(newIns); } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/Inward Dues And Access/Inward Dues And Access/Due search(Credit company)(/faces/credit/inward_due_search_credit_company.xhtml)"); } public double createInwardPaymentTotal(PatientEncounter pe, Date fd, Date td, BillType bt) { String sql; Map m = new HashMap(); sql = "select sum(b.netTotal) from BilledBill b where " + " b.billType=:billType " + " and b.createdAt between :fromDate and :toDate " + " and b.retired=false " + " and b.refunded=false " + " and b.cancelled=false " + " and b.patientEncounter=:pe "; m.put("pe", pe); m.put("billType", bt); m.put("toDate", td); m.put("fromDate", fd); return getBillFacade().findDoubleByJpql(sql, m, TemporalType.TIMESTAMP); } public double createInwardPaymentTotalCredit(PatientEncounter pe, Date fd, Date td, BillType bt) { String sql; Map m = new HashMap(); sql = "select sum(bi.netValue) from BillItem bi where " + " bi.bill.billType=:billType " + " and type(bi.bill)=:cl " + " and bi.bill.createdAt between :fromDate and :toDate " + " and bi.bill.retired=false " + " and bi.bill.refunded=false " + " and bi.bill.cancelled=false " + " and bi.patientEncounter=:pe "; m.put("pe", pe); m.put("billType", bt); m.put("toDate", td); m.put("fromDate", fd); m.put("cl", BilledBill.class); // System.out.println("sql = " + sql); return getBillFacade().findDoubleByJpql(sql, m, TemporalType.TIMESTAMP); } AdmissionType admissionType; PaymentMethod paymentMethod; @EJB PatientEncounterFacade patientEncounterFacade; public AdmissionType getAdmissionType() { return admissionType; } public void setAdmissionType(AdmissionType admissionType) { this.admissionType = admissionType; } public PaymentMethod getPaymentMethod() { return paymentMethod; } public void setPaymentMethod(PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; } public PatientEncounterFacade getPatientEncounterFacade() { return patientEncounterFacade; } public void setPatientEncounterFacade(PatientEncounterFacade patientEncounterFacade) { this.patientEncounterFacade = patientEncounterFacade; } public void createInwardCashDue() { Date startTime = new Date(); HashMap m = new HashMap(); String sql = " Select b from PatientEncounter b" + " where b.retired=false " + " and b.paymentFinalized=true " + " and b.dateOfDischarge between :fd and :td " + " and (abs(b.finalBill.netTotal)-(abs(b.finalBill.paidAmount)+abs(b.creditPaidAmount))) > 0.1 "; if (admissionType != null) { sql += " and b.admissionType =:ad "; m.put("ad", admissionType); } if (institution != null) { sql += " and b.creditCompany =:ins "; m.put("ins", institution); } if (paymentMethod != null) { sql += " and b.paymentMethod =:pm "; m.put("pm", paymentMethod); } sql += " order by b.dateOfDischarge"; m.put("fd", fromDate); m.put("td", toDate); patientEncounters = patientEncounterFacade.findBySQL(sql, m, TemporalType.TIMESTAMP); if (patientEncounters == null) { return; } billed = 0; paidByPatient = 0; paidByCompany = 0; for (PatientEncounter p : patientEncounters) { billed += p.getFinalBill().getNetTotal(); paidByPatient += p.getFinalBill().getPaidAmount(); paidByCompany += p.getPaidByCreditCompany(); } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/Inward Dues And Access/Dues/Due search(/faces/credit/inward_due_search.xhtml)"); } double billed; double paidByPatient; double paidByCompany; public double getBilled() { return billed; } public void setBilled(double billed) { this.billed = billed; } public double getPaidByPatient() { return paidByPatient; } public void setPaidByPatient(double paidByPatient) { this.paidByPatient = paidByPatient; } public double getPaidByCompany() { return paidByCompany; } public void setPaidByCompany(double paidByCompany) { this.paidByCompany = paidByCompany; } public void createInwardCreditAccess() { Date startTime = new Date(); List<Institution> setIns = getCreditBean().getCreditInstitutionByPatientEncounter(getFromDate(), getToDate(), PaymentMethod.Credit, false); institutionEncounters = new ArrayList<>(); for (Institution ins : setIns) { List<PatientEncounter> lst = getCreditBean().getCreditPatientEncounter(ins, getFromDate(), getToDate(), PaymentMethod.Credit, false); InstitutionEncounters newIns = new InstitutionEncounters(); newIns.setInstitution(ins); newIns.setPatientEncounters(lst); for (PatientEncounter b : lst) { // newIns.setTotal(newIns.getTotal() + b.getCreditUsedAmount()); // newIns.setPaidTotal(newIns.getPaidTotal() + b.getCreditPaidAmount()); b.getFinalBill().setNetTotal(com.divudi.java.CommonFunctions.round(b.getFinalBill().getNetTotal())); b.setCreditPaidAmount(Math.abs(b.getCreditPaidAmount())); b.setCreditPaidAmount(com.divudi.java.CommonFunctions.round(b.getCreditPaidAmount())); b.getFinalBill().setPaidAmount(com.divudi.java.CommonFunctions.round(b.getFinalBill().getPaidAmount())); b.setTransPaid(b.getFinalBill().getPaidAmount()+b.getCreditPaidAmount()); System.out.println("b.getTransPaid() = " + b.getTransPaid()); b.setTransPaid(com.divudi.java.CommonFunctions.round(b.getTransPaid())); System.out.println("b.getTransPaid() = " + b.getTransPaid()); System.out.println("b.getFinalBill().getNetTotal() = " + b.getFinalBill().getNetTotal()); newIns.setTotal(newIns.getTotal() + b.getFinalBill().getNetTotal()); // newIns.setPaidTotal(newIns.getPaidTotal() + (Math.abs(b.getCreditPaidAmount()) + Math.abs(b.getFinalBill().getPaidAmount()))); newIns.setPaidTotal(newIns.getPaidTotal() + b.getTransPaid()); } newIns.setTotal(com.divudi.java.CommonFunctions.round(newIns.getTotal())); newIns.setPaidTotal(com.divudi.java.CommonFunctions.round(newIns.getPaidTotal())); institutionEncounters.add(newIns); } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/Inward Dues And Access/excess/excess Search(/faces/credit/credit_company_inward_access.xhtml)"); } public void createInwardCashAccess() { Date startTime = new Date(); List<Institution> setIns = getCreditBean().getCreditInstitutionByPatientEncounter(getFromDate(), getToDate(), PaymentMethod.Cash, false); institutionEncounters = new ArrayList<>(); for (Institution ins : setIns) { List<PatientEncounter> lst = getCreditBean().getCreditPatientEncounter(ins, getFromDate(), getToDate(), PaymentMethod.Cash, false); InstitutionEncounters newIns = new InstitutionEncounters(); newIns.setInstitution(ins); newIns.setPatientEncounters(lst); for (PatientEncounter b : lst) { newIns.setTotal(newIns.getTotal() + b.getCreditUsedAmount()); newIns.setPaidTotal(newIns.getPaidTotal() + b.getCreditPaidAmount()); } institutionEncounters.add(newIns); } commonController.printReportDetails(fromDate, toDate, startTime, "Reports/Inward Dues And Access/excess/excess Search(/faces/credit/cash_inward_access.xhtml)"); } public List<InstitutionBills> getItems() { return items; } private Institution institution; public List<Bill> getItems2() { String sql; HashMap hm; sql = "Select b From Bill b where b.retired=false and b.createdAt " + " between :frm and :to and b.creditCompany=:cc " + " and b.paymentMethod= :pm and b.billType=:tp"; hm = new HashMap(); hm.put("frm", getFromDate()); hm.put("to", getToDate()); hm.put("cc", getInstitution()); hm.put("pm", PaymentMethod.Credit); hm.put("tp", BillType.OpdBill); return getBillFacade().findBySQL(sql, hm, TemporalType.TIMESTAMP); } public double getCreditTotal() { String sql; HashMap hm; sql = "Select sum(b.netTotal) From Bill b where b.retired=false and b.createdAt " + " between :frm and :to and b.creditCompany=:cc " + " and b.paymentMethod= :pm and b.billType=:tp"; hm = new HashMap(); hm.put("frm", getFromDate()); hm.put("to", getToDate()); hm.put("cc", getInstitution()); hm.put("pm", PaymentMethod.Credit); hm.put("tp", BillType.OpdBill); return getBillFacade().findDoubleByJpql(sql, hm, TemporalType.TIMESTAMP); } // public List<Admission> completePatientDishcargedNotFinalized(String query) { // List<Admission> suggestions; // String sql; // HashMap h = new HashMap(); // if (query == null) { // suggestions = new ArrayList<>(); // } else { // sql = "select c from Admission c where c.retired=false and " // + " ( c.paymentFinalized is null or c.paymentFinalized=false )" // + " and ( (upper(c.bhtNo) like :q )or (upper(c.patient.person.name)" // + " like :q) ) order by c.bhtNo"; // ////System.out.println(sql); // // h.put("btp", BillType.InwardPaymentBill); // h.put("q", "%" + query.toUpperCase() + "%"); // //suggestions = admissionFacade().findBySQL(sql, h); // } // //return suggestions; // } public void setItems(List<InstitutionBills> items) { this.items = items; } public InstitutionFacade getInstitutionFacade() { return institutionFacade; } public void setInstitutionFacade(InstitutionFacade institutionFacade) { this.institutionFacade = institutionFacade; } public BillFacade getBillFacade() { return billFacade; } public void setBillFacade(BillFacade billFacade) { this.billFacade = billFacade; } public Institution getInstitution() { return institution; } public void setInstitution(Institution institution) { this.institution = institution; } public CommonFunctions getCommonFunctions() { return commonFunctions; } public void setCommonFunctions(CommonFunctions commonFunctions) { this.commonFunctions = commonFunctions; } public CreditBean getCreditBean() { return creditBean; } public void setCreditBean(CreditBean creditBean) { this.creditBean = creditBean; } public List<String1Value5> getCreditCompanyAge() { return creditCompanyAge; } public void setCreditCompanyAge(List<String1Value5> creditCompanyAge) { this.creditCompanyAge = creditCompanyAge; } public List<String1Value5> getFilteredList() { return filteredList; } public void setFilteredList(List<String1Value5> filteredList) { this.filteredList = filteredList; } public List<InstitutionEncounters> getInstitutionEncounters() { return institutionEncounters; } public void setInstitutionEncounters(List<InstitutionEncounters> institutionEncounters) { this.institutionEncounters = institutionEncounters; } public Admission getPatientEncounter() { return patientEncounter; } public void setPatientEncounter(Admission patientEncounter) { this.patientEncounter = patientEncounter; } public AdmissionFacade getAdmissionFacade() { return admissionFacade; } public void setAdmissionFacade(AdmissionFacade admissionFacade) { this.admissionFacade = admissionFacade; } public boolean isWithOutDueUpdate() { return withOutDueUpdate; } public void setWithOutDueUpdate(boolean withOutDueUpdate) { this.withOutDueUpdate = withOutDueUpdate; } public Institution getCreditCompany() { return creditCompany; } public void setCreditCompany(Institution creditCompany) { this.creditCompany = creditCompany; } public double getFinalTotal() { return finalTotal; } public void setFinalTotal(double finalTotal) { this.finalTotal = finalTotal; } public double getFinalPaidTotal() { return finalPaidTotal; } public void setFinalPaidTotal(double finalPaidTotal) { this.finalPaidTotal = finalPaidTotal; } public double getFinalPaidTotalPatient() { return finalPaidTotalPatient; } public void setFinalPaidTotalPatient(double finalPaidTotalPatient) { this.finalPaidTotalPatient = finalPaidTotalPatient; } public double getFinalTransPaidTotal() { return finalTransPaidTotal; } public void setFinalTransPaidTotal(double finalTransPaidTotal) { this.finalTransPaidTotal = finalTransPaidTotal; } public double getFinalTransPaidTotalPatient() { return finalTransPaidTotalPatient; } public void setFinalTransPaidTotalPatient(double finalTransPaidTotalPatient) { this.finalTransPaidTotalPatient = finalTransPaidTotalPatient; } public CommonController getCommonController() { return commonController; } public void setCommonController(CommonController commonController) { this.commonController = commonController; } }
xaviergthiago/NetBeansProjects
Aula_2020_05_25_Noite/src/aula_2020_05_25_noite/Vetor4.java
<filename>Aula_2020_05_25_Noite/src/aula_2020_05_25_noite/Vetor4.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aula_2020_05_25_noite; /** * * @author sicsu */ public class Vetor4 { public static void main(String[] args) { int vetor[] = new int[10]; int auxiliar; for(int i=0; i<10; i++) { vetor[i]= (20- i*2);// cria na ordem descrescente vetor[i]= (i*2);// cria na ordem crescente } System.out.println("Vetor antes da ordenação:"); for(int i=0; i<10; i++) { System.out.println(vetor[i]); } for (int i=0; i<9; i++) { for (int j=i+1; j<10; j++) { //if(vetor[i] > vetor[j]) {// coloca na ordem crescente if(vetor[i] < vetor[j]) {// coloca na ordem decrescente auxiliar = vetor[i]; vetor[i] = vetor[j]; vetor[j] = auxiliar; } } } System.out.println("Vetor depois da ordenação:"); for(int i=0; i<10; i++) { System.out.println(vetor[i]); } } }
Biocodr/TomP2P
benchmark/src/main/java/net/tomp2p/Server.java
package net.tomp2p; import java.io.IOException; import java.util.Scanner; import net.tomp2p.p2p.Peer; import net.tomp2p.peers.PeerAddress; import net.tomp2p.utils.InteropRandom; public class Server { public static void setup() throws InterruptedException, IOException { Peer server = null; try { Peer[] peers = BenchmarkUtil.createNodes(1, new InteropRandom(456), 5432, false, false); server = peers[0]; server.rawDataReply(new ServerRawDataReply()); PeerAddress pa = server.peerAddress(); System.out.println(String.format("Server Peer: %s.", pa)); System.out.println("--------------------------------------------------------------------------------------"); System.out.println(String.format("Copy Arguments: %s %s %s %s.", pa.peerId(), pa.inetAddress(), pa.tcpPort(), pa.udpPort())); System.out.println("--------------------------------------------------------------------------------------"); System.out.println("Press Enter to shut server down..."); Scanner scanner = new Scanner(System.in); scanner.nextLine(); scanner.close(); } finally { if (server != null) { server.shutdown().await(); } } } }
redhat-openstack/manila
manila/tests/integrated/test_extensions.py
<gh_stars>1-10 # Copyright 2011 <NAME> # 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. from oslo_config import cfg from oslo_log import log import six from manila.tests.integrated import integrated_helpers CONF = cfg.CONF LOG = log.getLogger(__name__) class ExtensionsTest(integrated_helpers._IntegratedTestBase): def _get_flags(self): f = super(ExtensionsTest, self)._get_flags() f['osapi_share_extension'] = CONF.osapi_share_extension[:] f['osapi_share_extension'].append( 'manila.tests.api.extensions.foxinsocks.Foxinsocks') return f def test_get_foxnsocks(self): """Simple check that fox-n-socks works.""" response = self.api.api_request('/foxnsocks') foxnsocks = response.read() LOG.debug("foxnsocks: %s" % foxnsocks) self.assertEqual(six.b('Try to say this Mr. Knox, sir...'), foxnsocks)
sstromick/financial-app
resources/js/store/modules/creditAccounts/actions.js
<filename>resources/js/store/modules/creditAccounts/actions.js import api from "@/api"; const getCreditAccounts = context => { api.getUrl(context, "/api/credit-accounts", "CREDIT_ACCOUNTS_UPDATED"); }; const getCreditAccount = context => { api.getUrl(context, "/api/credit-account", "CREDIT_ACCOUNT_UPDATED"); }; const createCreditAccount = (context, payload) => { api.postUrl( context, "/api/credit-accounts", payload, "CREDIT_ACCOUNT_UPDATED" ); }; const updateCreditAccount = (context, payload) => { api.patchUrl( context, "/api/credit-accounts/" + payload.id, payload, "CREDIT_ACCOUNT_UPDATED" ); }; const getCreditAccountDebtTypes = context => { api.getUrl( context, "/api/credit-account-types", "CREDIT_ACCOUNT_DEBT_TYPES_UPDATED" ); }; const resetCreditAccount = context => { context.commit("RESET_CREDIT_ACCOUNT"); }; const deleteCreditAccount = (context, payload) => { api.deleteUrl( context, "/api/credit-accounts/" + payload.id, "CREDIT_ACCOUNT_DELETED" ); }; const creditPull = async (context, payload) => { return await api.postUrl( context, "/api/credit-pull", payload, "CREDIT_ACCOUNTS_UPDATED" ); }; export default { getCreditAccounts, getCreditAccount, createCreditAccount, updateCreditAccount, getCreditAccountDebtTypes, resetCreditAccount, deleteCreditAccount, creditPull };
EstevaoNaval/URI_repository
solutions/tier_03/python/uri_1241_encaixa_ou_nao_ii.py
<gh_stars>0 # -*- coding: utf-8 -*- qntCasos = int(input()) for indiceCaso in range(qntCasos): listInputNum = list(map(str, input().split())) print("encaixa" if listInputNum[0][len(listInputNum[0]) - len(listInputNum[1]):] == listInputNum[1] else "nao encaixa")
Superomeg4/pyleecan
Methods/Machine/LamSlotWind/comp_volumes.py
<filename>Methods/Machine/LamSlotWind/comp_volumes.py # -*- coding: utf-8 -*- """@package Methods.Machine.LamSlotWind.comp_volumes Lamination with winding computation of all volumes method @date Created on Mon Jan 12 17:09:42 2015 @copyright (C) 2015-2016 EOMYS ENGINEERING. @author pierre_b """ from numpy import pi from pyleecan.Classes.LamSlot import LamSlot def comp_volumes(self): """Compute the Lamination volumes (Vlam, Vvent, Vslot, Vwind) Parameters ---------- self : LamSlotWind A LamSlotWind object Returns ------- V_dict: dict Lamination volume dictionnary (Vlam, Vvent, Vslot, Vwind) [m**3] """ V_dict = LamSlot.comp_volumes(self) Lf = self.comp_length() # Include radial ventilation ducts V_dict["Vwind"] = Lf * self.slot.Zs * self.slot.comp_surface_wind() return V_dict
rohankumardubey/Android-demo-app
Chapter5_Sample_Earthquake/src/com/paad/earthquake/Earthquake.java
<gh_stars>0 package com.paad.earthquake; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.location.Location; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class Earthquake extends Activity { static final private int QUAKE_DIALOG = 1; static final private int MENU_UPDATE = Menu.FIRST; ListView earthquakeListView; ArrayAdapter<Quake> aa; ArrayList<Quake> earthquakes = new ArrayList<Quake>(); Quake selectedQuake; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); earthquakeListView = (ListView)this.findViewById(R.id.earthquakeListView); earthquakeListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> _av, View _v, int _index, long _id) { selectedQuake = earthquakes.get(_index); showDialog(QUAKE_DIALOG); } }); aa = new ArrayAdapter<Quake>(getApplicationContext(), android.R.layout.simple_list_item_1, earthquakes); earthquakeListView.setAdapter(aa); refreshEarthquakes(); } /** Refresh data from the earthquake feed */ private void refreshEarthquakes() { // Get the XML URL url; try { String quakeFeed = getString(R.string.quake_feed); url = new URL(quakeFeed); URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); // Parse the earthquake feed. Document dom = db.parse(in); Element docEle = dom.getDocumentElement(); // Clear the old earthquakes earthquakes.clear(); // Get a list of each earthquake entry. NodeList nl = docEle.getElementsByTagName("entry"); if (nl != null && nl.getLength() > 0) { for (int i = 0 ; i < nl.getLength(); i++) { Element entry = (Element)nl.item(i); Element title = (Element)entry.getElementsByTagName("title").item(0); Element g = (Element)entry.getElementsByTagName("georss:point").item(0); Element when = (Element)entry.getElementsByTagName("updated").item(0); Element link = (Element)entry.getElementsByTagName("link").item(0); String details = title.getFirstChild().getNodeValue(); String hostname = "http://earthquake.usgs.gov"; String linkString = hostname + link.getAttribute("href"); String point = g.getFirstChild().getNodeValue(); String dt = when.getFirstChild().getNodeValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); Date qdate = new GregorianCalendar(0,0,0).getTime(); try { qdate = sdf.parse(dt); } catch (ParseException e) { e.printStackTrace(); } String[] location = point.split(" "); Location l = new Location("dummyGPS"); l.setLatitude(Double.parseDouble(location[0])); l.setLongitude(Double.parseDouble(location[1])); String magnitudeString = details.split(" ")[1]; int end = magnitudeString.length()-1; double magnitude = Double.parseDouble(magnitudeString.substring(0, end)); details = details.split(",")[1].trim(); Quake quake = new Quake(qdate, details, l, magnitude, linkString); // Process a newly found earthquake addNewQuake(quake); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } finally { } } /** Add a new earthquake */ private void addNewQuake(Quake _quake) { // Add the new quake to our list of earthquakes. earthquakes.add(_quake); // Notify the array adapter of a change. aa.notifyDataSetChanged(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_UPDATE, Menu.NONE, R.string.menu_update); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case (MENU_UPDATE): { refreshEarthquakes(); return true; } } return false; } @Override public Dialog onCreateDialog(int id) { switch(id) { case (QUAKE_DIALOG) : LayoutInflater li = LayoutInflater.from(this); View quakeDetailsView = li.inflate(R.layout.quake_details, null); AlertDialog.Builder quakeDialog = new AlertDialog.Builder(this); quakeDialog.setTitle("Quake Time"); quakeDialog.setView(quakeDetailsView); return quakeDialog.create(); } return null; } @Override public void onPrepareDialog(int id, Dialog dialog) { switch(id) { case (QUAKE_DIALOG) : SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); String dateString = sdf.format(selectedQuake.getDate()); String quakeText = "Mangitude " + selectedQuake.getMagnitude() + "\n" + selectedQuake.getDetails() + "\n" + selectedQuake.getLink(); AlertDialog quakeDialog = (AlertDialog)dialog; quakeDialog.setTitle(dateString); TextView tv = (TextView)quakeDialog.findViewById(R.id.quakeDetailsTextView); if (tv != null) tv.setText(quakeText); break; } } }